mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 07:23:11 +00:00
🛤️ feat: Route Linked Worktree Requests into Per-Worktree Lanes (#16477)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
* feat: Route Linked Worktree Requests into Per-Worktree Lanes Workers that advertise the git_linked_worktree workspace scope run each .worktrees/<name> of a registered checkout in its own scheduling lane. Accept the scope in worker status, map worktree-scoped paths and command working directories onto the worktree field, and restore the prefix on returned paths so tool output stays relative to the checkout. * fix: Advertise Worktree cwd Routing in Model-Facing Bash Definitions * refactor: Normalize the Lane Flag in TypeScript, Pass It Through /api Unchanged * feat: Gate Linked Worktree Lanes Behind an Environment configSchema Toggle * test: Give the Lane Toggle Fixture a Default Environment
This commit is contained in:
parent
a7662d2d26
commit
867fd5eac5
22 changed files with 651 additions and 8 deletions
|
|
@ -97,6 +97,7 @@ describe('getCodeBridgeWorkerStatus', () => {
|
|||
id: 'project-a',
|
||||
name: 'Project A',
|
||||
workspaceInstances: ['git_worktree'],
|
||||
workspaceScopes: ['git_linked_worktree'],
|
||||
},
|
||||
{ id: 'docs', operations: ['read_file'] },
|
||||
],
|
||||
|
|
@ -128,6 +129,7 @@ describe('getCodeBridgeWorkerStatus', () => {
|
|||
id: 'project-a',
|
||||
name: 'Project A',
|
||||
workspaceInstances: ['git_worktree'],
|
||||
workspaceScopes: ['git_linked_worktree'],
|
||||
},
|
||||
{ id: 'docs', operations: ['read_file'] },
|
||||
],
|
||||
|
|
@ -249,6 +251,53 @@ describe('getCodeBridgeWorkerStatus', () => {
|
|||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
online: true,
|
||||
ready: true,
|
||||
leaseExpiresInMs: 5_000,
|
||||
capabilities: {
|
||||
statefulWorkspace: true,
|
||||
sandboxProfile: 'native-srt',
|
||||
runtimes: ['bash'],
|
||||
workspaceTools: {
|
||||
protocolVersion: 1,
|
||||
operations: ['read_file'],
|
||||
workspaces: [{ id: 'project-a', workspaceScopes: ['subdirectory'] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
online: true,
|
||||
ready: true,
|
||||
leaseExpiresInMs: 5_000,
|
||||
capabilities: {
|
||||
statefulWorkspace: true,
|
||||
sandboxProfile: 'native-srt',
|
||||
runtimes: ['bash'],
|
||||
workspaceTools: {
|
||||
protocolVersion: 1,
|
||||
operations: ['read_file'],
|
||||
workspaces: [{ id: 'project-a', workspaceScopes: 'git_linked_worktree' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
online: true,
|
||||
ready: true,
|
||||
leaseExpiresInMs: 5_000,
|
||||
capabilities: {
|
||||
statefulWorkspace: true,
|
||||
sandboxProfile: 'native-srt',
|
||||
runtimes: ['bash'],
|
||||
workspaceTools: {
|
||||
protocolVersion: 1,
|
||||
operations: ['read_file'],
|
||||
workspaces: [
|
||||
{ id: 'project-a', workspaceScopes: ['git_linked_worktree', 'git_linked_worktree'] },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
])('rejects an invalid upstream status response: %p', async (invalid) => {
|
||||
const fetchImpl = jest
|
||||
.fn()
|
||||
|
|
|
|||
|
|
@ -282,6 +282,7 @@ function validWorkspaceCapabilities(value: unknown): value is {
|
|||
key !== 'name' &&
|
||||
key !== 'operations' &&
|
||||
key !== 'workspaceInstances' &&
|
||||
key !== 'workspaceScopes' &&
|
||||
key !== 'environment' &&
|
||||
key !== 'instructions',
|
||||
) ||
|
||||
|
|
@ -297,6 +298,10 @@ function validWorkspaceCapabilities(value: unknown): value is {
|
|||
(!Array.isArray(workspace.workspaceInstances) ||
|
||||
workspace.workspaceInstances.length !== 1 ||
|
||||
workspace.workspaceInstances[0] !== 'git_worktree')) ||
|
||||
(workspace.workspaceScopes !== undefined &&
|
||||
(!Array.isArray(workspace.workspaceScopes) ||
|
||||
workspace.workspaceScopes.length !== 1 ||
|
||||
workspace.workspaceScopes[0] !== 'git_linked_worktree')) ||
|
||||
(workspace.name !== undefined &&
|
||||
(typeof workspace.name !== 'string' ||
|
||||
workspace.name.trim().length === 0 ||
|
||||
|
|
|
|||
|
|
@ -461,6 +461,49 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
|
|||
expect(legacy.codeWorkspace).not.toHaveProperty('workspaceInstanceId');
|
||||
});
|
||||
|
||||
it('routes linked worktrees into lanes only when configured and no conversation instance owns the checkout', async () => {
|
||||
const workspaceInstanceId = 'c'.repeat(64);
|
||||
jest.spyOn(globalThis, 'fetch').mockImplementation(async () =>
|
||||
workspaceStatus([
|
||||
{
|
||||
id: 'lanes',
|
||||
workspaceInstances: ['git_worktree'],
|
||||
workspaceScopes: ['git_linked_worktree'],
|
||||
},
|
||||
{ id: 'legacy' },
|
||||
]),
|
||||
);
|
||||
const resolve = (workspaceId: string, instanceId?: string, linkedWorktrees = true) =>
|
||||
resolveCodeExecutionWorkspaceContext({
|
||||
context: {
|
||||
...context,
|
||||
codeEnvironmentConfigSchema: { workspaces: { linkedWorktrees } },
|
||||
...(instanceId ? { conversationWorkspaceInstanceId: instanceId } : {}),
|
||||
},
|
||||
requestedSelections: [{ environmentId: 'personal', workspaceId }],
|
||||
environments,
|
||||
getAppConfig,
|
||||
});
|
||||
|
||||
const lanes = await resolve('lanes');
|
||||
const disabled = await resolve('lanes', undefined, false);
|
||||
const unconfigured = await resolveCodeExecutionWorkspaceContext({
|
||||
context,
|
||||
requestedSelections: [{ environmentId: 'personal', workspaceId: 'lanes' }],
|
||||
environments,
|
||||
getAppConfig,
|
||||
});
|
||||
const instance = await resolve('lanes', workspaceInstanceId);
|
||||
const legacy = await resolve('legacy');
|
||||
|
||||
expect(lanes.codeWorkspace?.linkedWorktrees).toBe(true);
|
||||
expect(disabled.codeWorkspace).not.toHaveProperty('linkedWorktrees');
|
||||
expect(unconfigured.codeWorkspace).not.toHaveProperty('linkedWorktrees');
|
||||
expect(instance.codeWorkspace?.workspaceInstanceId).toBe(workspaceInstanceId);
|
||||
expect(instance.codeWorkspace).not.toHaveProperty('linkedWorktrees');
|
||||
expect(legacy.codeWorkspace).not.toHaveProperty('linkedWorktrees');
|
||||
});
|
||||
|
||||
it('admits native workspace tools without enabling programmatic runtime execution', async () => {
|
||||
jest
|
||||
.spyOn(globalThis, 'fetch')
|
||||
|
|
|
|||
|
|
@ -182,6 +182,14 @@ export async function resolveCodeExecutionWorkspaceContext({
|
|||
workspace.workspaceInstances?.includes('git_worktree')
|
||||
? { workspaceInstanceId: context.conversationWorkspaceInstanceId }
|
||||
: {}),
|
||||
...(context.codeEnvironmentConfigSchema?.workspaces?.linkedWorktrees === true &&
|
||||
workspace.workspaceScopes?.includes('git_linked_worktree') &&
|
||||
!(
|
||||
context.conversationWorkspaceInstanceId &&
|
||||
workspace.workspaceInstances?.includes('git_worktree')
|
||||
)
|
||||
? { linkedWorktrees: true }
|
||||
: {}),
|
||||
...(status.maxCommandTimeoutMs == null
|
||||
? {}
|
||||
: { maxCommandTimeoutMs: status.maxCommandTimeoutMs }),
|
||||
|
|
|
|||
|
|
@ -316,6 +316,23 @@ describe('createAttachedWorkspaceBashTool', () => {
|
|||
});
|
||||
});
|
||||
|
||||
test('runs a command whose working directory is a linked worktree in that lane', async () => {
|
||||
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
|
||||
const bashTool = createAttachedWorkspaceBashTool({
|
||||
baseUrl: 'https://code.example.com/v1',
|
||||
authHeaders: () => ({}),
|
||||
workspaceId: 'project-a',
|
||||
linkedWorktrees: true,
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
expect(JSON.stringify(bashTool.schema)).toContain('.worktrees/<name>');
|
||||
await bashTool.func({ command: 'npm test', cwd: '.worktrees/fix-a/api' }, undefined, {});
|
||||
|
||||
const request = JSON.parse(String((fetchImpl as jest.Mock).mock.calls[0][1]?.body));
|
||||
expect(request).toMatchObject({ command: 'npm test', cwd: 'api', worktree: 'fix-a' });
|
||||
});
|
||||
|
||||
test('forwards a bounded per-call execution timeout', async () => {
|
||||
const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse());
|
||||
const bashTool = createAttachedWorkspaceBashTool({
|
||||
|
|
|
|||
|
|
@ -173,9 +173,15 @@ export function resolveAttachedWorkspaceRequestTimeoutMs(
|
|||
return configured;
|
||||
}
|
||||
|
||||
const linkedWorktreeWorkingDirectorySchema: BoundedWorkingDirectorySchema = {
|
||||
...attachedWorkingDirectorySchema,
|
||||
description: `${attachedWorkingDirectorySchema.description} To work in a linked worktree, pass its directory here (for example ".worktrees/fix-auth") instead of running cd inside the command: commands in different .worktrees/<name> directories then run in parallel, while a cd from the workspace root waits for all of them.`,
|
||||
};
|
||||
|
||||
export function buildAttachedWorkspaceBashSchema(
|
||||
maxTimeoutMs: number = WORKSPACE_COMMAND_DEFAULT_TIMEOUT_MS,
|
||||
environment?: CodeWorkspaceDescriptor['environment'],
|
||||
linkedWorktrees = false,
|
||||
): NonNullable<LCTool['parameters']> {
|
||||
const effectiveMaxTimeoutMs = normalizeAttachedWorkspaceCommandTimeoutMax(maxTimeoutMs);
|
||||
return {
|
||||
|
|
@ -183,7 +189,10 @@ export function buildAttachedWorkspaceBashSchema(
|
|||
properties: {
|
||||
...bashSchema.properties,
|
||||
command: attachedCommandSchema,
|
||||
cwd: attachedWorkingDirectorySchema,
|
||||
cwd:
|
||||
linkedWorktrees === true
|
||||
? linkedWorktreeWorkingDirectorySchema
|
||||
: attachedWorkingDirectorySchema,
|
||||
timeoutMs: buildAttachedTimeoutSchema(effectiveMaxTimeoutMs),
|
||||
...(environment?.actions.length
|
||||
? {
|
||||
|
|
@ -322,12 +331,15 @@ export function createAttachedWorkspaceBashTool({
|
|||
codeApiMaxRetryWaitMs,
|
||||
maxRequestTimeoutMs,
|
||||
minCommandAdmissionMs,
|
||||
linkedWorktrees = false,
|
||||
fetchImpl,
|
||||
}: {
|
||||
baseUrl: string;
|
||||
authHeaders: () => Promise<Record<string, string>> | Record<string, string>;
|
||||
workspaceId: string;
|
||||
workspaceInstanceId?: string;
|
||||
/** The worker runs each `.worktrees/<name>` in its own lane; a matching `cwd` is routed there. */
|
||||
linkedWorktrees?: boolean;
|
||||
environment?: CodeWorkspaceDescriptor['environment'];
|
||||
gitIdentity?: AgentGitIdentity | null;
|
||||
/** Effective admin/upstream ceiling already intersected with the protocol hard cap. */
|
||||
|
|
@ -347,7 +359,7 @@ export function createAttachedWorkspaceBashTool({
|
|||
minCommandAdmissionMs,
|
||||
);
|
||||
const schema = structuredClone(
|
||||
buildAttachedWorkspaceBashSchema(effectiveMaxTimeoutMs, environment),
|
||||
buildAttachedWorkspaceBashSchema(effectiveMaxTimeoutMs, environment, linkedWorktrees),
|
||||
);
|
||||
const actions = environment?.actions ?? [];
|
||||
return tool(
|
||||
|
|
@ -405,6 +417,7 @@ export function createAttachedWorkspaceBashTool({
|
|||
baseURL: baseUrl,
|
||||
/** Passed as a supplier: a queued call outlives its minted token. */
|
||||
authHeaders,
|
||||
linkedWorktrees,
|
||||
request: {
|
||||
protocolVersion: 1,
|
||||
operation: 'execute_command',
|
||||
|
|
|
|||
183
packages/api/src/code/workspace.lanes.spec.ts
Normal file
183
packages/api/src/code/workspace.lanes.spec.ts
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import type { WorkspaceToolRequest, WorkspaceToolResult } from './workspace';
|
||||
import { fromLinkedWorktreeResult, toLinkedWorktreeRequest } from './workspace';
|
||||
|
||||
const base = { protocolVersion: 1, workspaceId: 'librechat' } as const;
|
||||
|
||||
describe('toLinkedWorktreeRequest', () => {
|
||||
it.each([
|
||||
['read_file', { operation: 'read_file', path: '.worktrees/fix-a/src/index.ts' }],
|
||||
['write_file', { operation: 'write_file', path: '.worktrees/fix-a/src/index.ts', content: '' }],
|
||||
['edit_file', { operation: 'edit_file', path: '.worktrees/fix-a/src/index.ts', edits: [] }],
|
||||
[
|
||||
'preview_edit',
|
||||
{ operation: 'preview_edit', path: '.worktrees/fix-a/src/index.ts', edits: [] },
|
||||
],
|
||||
])('routes a %s path into its worktree lane', (_operation, fields) => {
|
||||
const request = { ...base, ...fields } as WorkspaceToolRequest;
|
||||
expect(toLinkedWorktreeRequest(request)).toEqual({
|
||||
worktree: 'fix-a',
|
||||
request: { ...request, path: 'src/index.ts', worktree: 'fix-a' },
|
||||
});
|
||||
});
|
||||
|
||||
it('scopes searches and listings to the worktree, omitting the path at its root', () => {
|
||||
expect(
|
||||
toLinkedWorktreeRequest({
|
||||
...base,
|
||||
operation: 'search_text',
|
||||
query: 'TODO',
|
||||
path: '.worktrees/fix-a',
|
||||
}),
|
||||
).toEqual({
|
||||
worktree: 'fix-a',
|
||||
request: { ...base, operation: 'search_text', query: 'TODO', worktree: 'fix-a' },
|
||||
});
|
||||
expect(
|
||||
toLinkedWorktreeRequest({
|
||||
...base,
|
||||
operation: 'list_files',
|
||||
path: '.worktrees/fix-a/src',
|
||||
afterPath: '.worktrees/fix-a/src/a.ts',
|
||||
}),
|
||||
).toEqual({
|
||||
worktree: 'fix-a',
|
||||
request: {
|
||||
...base,
|
||||
operation: 'list_files',
|
||||
path: 'src',
|
||||
afterPath: 'src/a.ts',
|
||||
worktree: 'fix-a',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('runs a command whose cwd is inside a worktree in that lane', () => {
|
||||
expect(
|
||||
toLinkedWorktreeRequest({
|
||||
...base,
|
||||
operation: 'execute_command',
|
||||
command: 'npm test',
|
||||
cwd: '.worktrees/fix-a',
|
||||
}),
|
||||
).toEqual({
|
||||
worktree: 'fix-a',
|
||||
request: { ...base, operation: 'execute_command', command: 'npm test', worktree: 'fix-a' },
|
||||
});
|
||||
expect(
|
||||
toLinkedWorktreeRequest({
|
||||
...base,
|
||||
operation: 'execute_command',
|
||||
command: 'npx jest',
|
||||
cwd: '.worktrees/fix-a/packages/api',
|
||||
})?.request,
|
||||
).toMatchObject({ cwd: 'packages/api', worktree: 'fix-a' });
|
||||
});
|
||||
|
||||
it.each<[string, WorkspaceToolRequest]>([
|
||||
['a root path', { ...base, operation: 'read_file', path: 'src/index.ts' }],
|
||||
['the worktree directory itself', { ...base, operation: 'read_file', path: '.worktrees/a' }],
|
||||
['the worktrees container', { ...base, operation: 'list_files', path: '.worktrees' }],
|
||||
['an invalid name', { ...base, operation: 'read_file', path: '.worktrees/-bad/x.ts' }],
|
||||
['a lock name', { ...base, operation: 'read_file', path: '.worktrees/a.lock/x.ts' }],
|
||||
[
|
||||
'an instruction read',
|
||||
{
|
||||
...base,
|
||||
operation: 'read_file',
|
||||
path: '.worktrees/a/AGENTS.md',
|
||||
instructionSha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
[
|
||||
'a conversation instance',
|
||||
{
|
||||
...base,
|
||||
operation: 'read_file',
|
||||
path: '.worktrees/a/x.ts',
|
||||
workspaceInstanceId: 'b'.repeat(64),
|
||||
},
|
||||
],
|
||||
[
|
||||
'a listing cursor in another worktree',
|
||||
{
|
||||
...base,
|
||||
operation: 'list_files',
|
||||
path: '.worktrees/a',
|
||||
afterPath: '.worktrees/b/x.ts',
|
||||
},
|
||||
],
|
||||
[
|
||||
'a listing cursor at the worktree root',
|
||||
{ ...base, operation: 'list_files', path: '.worktrees/a', afterPath: '.worktrees/a' },
|
||||
],
|
||||
[
|
||||
'a command without cwd',
|
||||
{ ...base, operation: 'execute_command', command: 'cd .worktrees/a' },
|
||||
],
|
||||
[
|
||||
'an environment action',
|
||||
{
|
||||
...base,
|
||||
operation: 'execute_command',
|
||||
command: 'setup',
|
||||
cwd: '.worktrees/a',
|
||||
environmentAction: { name: 'setup', fingerprint: 'c'.repeat(64) },
|
||||
},
|
||||
],
|
||||
])('leaves %s root-scoped', (_case, request) => {
|
||||
expect(toLinkedWorktreeRequest(request)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromLinkedWorktreeResult', () => {
|
||||
it('restores the worktree prefix on every reported path', () => {
|
||||
const listing: WorkspaceToolResult = {
|
||||
...base,
|
||||
operation: 'list_files',
|
||||
paths: ['src/a.ts', 'src/b.ts'],
|
||||
truncated: true,
|
||||
nextAfterPath: 'src/b.ts',
|
||||
};
|
||||
expect(fromLinkedWorktreeResult(listing, 'fix-a')).toEqual({
|
||||
...listing,
|
||||
paths: ['.worktrees/fix-a/src/a.ts', '.worktrees/fix-a/src/b.ts'],
|
||||
nextAfterPath: '.worktrees/fix-a/src/b.ts',
|
||||
});
|
||||
|
||||
const search: WorkspaceToolResult = {
|
||||
...base,
|
||||
operation: 'search_text',
|
||||
matches: [{ path: 'src/a.ts', line: 3, column: 1, text: 'TODO' }],
|
||||
truncated: false,
|
||||
};
|
||||
expect(fromLinkedWorktreeResult(search, 'fix-a')).toEqual({
|
||||
...search,
|
||||
matches: [{ path: '.worktrees/fix-a/src/a.ts', line: 3, column: 1, text: 'TODO' }],
|
||||
});
|
||||
|
||||
const written: WorkspaceToolResult = {
|
||||
...base,
|
||||
operation: 'write_file',
|
||||
path: 'src/a.ts',
|
||||
created: true,
|
||||
bytesWritten: 1,
|
||||
};
|
||||
expect(fromLinkedWorktreeResult(written, 'fix-a')).toEqual({
|
||||
...written,
|
||||
path: '.worktrees/fix-a/src/a.ts',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns command results unchanged', () => {
|
||||
const result: WorkspaceToolResult = {
|
||||
...base,
|
||||
operation: 'execute_command',
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
exitCode: 0,
|
||||
timedOut: false,
|
||||
truncated: false,
|
||||
};
|
||||
expect(fromLinkedWorktreeResult(result, 'fix-a')).toBe(result);
|
||||
});
|
||||
});
|
||||
|
|
@ -2176,3 +2176,72 @@ describe('executeWorkspaceTool', () => {
|
|||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('linked worktree lanes', () => {
|
||||
const listing = (paths: string[]) =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
protocolVersion: 1,
|
||||
operation: 'list_files',
|
||||
workspaceId: 'librechat',
|
||||
paths,
|
||||
truncated: false,
|
||||
}),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
const request: WorkspaceToolRequest = {
|
||||
protocolVersion: 1,
|
||||
operation: 'list_files',
|
||||
workspaceId: 'librechat',
|
||||
path: '.worktrees/fix-a/src',
|
||||
};
|
||||
|
||||
test('sends a worktree request and reports paths relative to the checkout', async () => {
|
||||
const fetchImpl = jest.fn().mockResolvedValue(listing(['src/a.ts']));
|
||||
|
||||
await expect(
|
||||
executeWorkspaceTool({
|
||||
baseURL: 'https://code.example/v1',
|
||||
authHeaders: {},
|
||||
fetchImpl,
|
||||
request,
|
||||
linkedWorktrees: true,
|
||||
}),
|
||||
).resolves.toMatchObject({ paths: ['.worktrees/fix-a/src/a.ts'] });
|
||||
expect(JSON.parse(fetchImpl.mock.calls[0][1].body)).toEqual({
|
||||
protocolVersion: 1,
|
||||
operation: 'list_files',
|
||||
workspaceId: 'librechat',
|
||||
path: 'src',
|
||||
worktree: 'fix-a',
|
||||
});
|
||||
});
|
||||
|
||||
test('keeps the checkout-scoped request when the worker has no lanes', async () => {
|
||||
const fetchImpl = jest.fn().mockResolvedValue(listing(['.worktrees/fix-a/src/a.ts']));
|
||||
|
||||
await expect(
|
||||
executeWorkspaceTool({
|
||||
baseURL: 'https://code.example/v1',
|
||||
authHeaders: {},
|
||||
fetchImpl,
|
||||
request,
|
||||
}),
|
||||
).resolves.toMatchObject({ paths: ['.worktrees/fix-a/src/a.ts'] });
|
||||
expect(JSON.parse(fetchImpl.mock.calls[0][1].body)).toEqual(request);
|
||||
});
|
||||
|
||||
test('rejects lane results that escape the requested worktree scope', async () => {
|
||||
const fetchImpl = jest.fn().mockResolvedValue(listing(['lib/a.ts']));
|
||||
|
||||
await expect(
|
||||
executeWorkspaceTool({
|
||||
baseURL: 'https://code.example/v1',
|
||||
authHeaders: {},
|
||||
fetchImpl,
|
||||
request,
|
||||
linkedWorktrees: true,
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: 'invalid' });
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -858,6 +858,142 @@ function getWorkspaceAuthHeaders(
|
|||
});
|
||||
}
|
||||
|
||||
/** Linked worktrees live at `.worktrees/<name>` beneath a registered checkout. */
|
||||
const LINKED_WORKTREE_DIRECTORY = '.worktrees/';
|
||||
/** Mirrors Code API's single-segment worktree name rule. */
|
||||
const LINKED_WORKTREE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
||||
|
||||
export type LinkedWorktreeRequest = WorkspaceToolRequest & { worktree: string };
|
||||
|
||||
interface LinkedWorktreePath {
|
||||
worktree: string;
|
||||
/** Path relative to the worktree root; empty for the worktree root itself. */
|
||||
rest: string;
|
||||
}
|
||||
|
||||
function splitLinkedWorktreePath(path: string | undefined): LinkedWorktreePath | undefined {
|
||||
if (path == null || !path.startsWith(LINKED_WORKTREE_DIRECTORY)) return undefined;
|
||||
const remainder = path.slice(LINKED_WORKTREE_DIRECTORY.length);
|
||||
const slash = remainder.indexOf('/');
|
||||
const worktree = slash === -1 ? remainder : remainder.slice(0, slash);
|
||||
if (!LINKED_WORKTREE_NAME_PATTERN.test(worktree) || worktree.endsWith('.lock')) {
|
||||
return undefined;
|
||||
}
|
||||
return { worktree, rest: slash === -1 ? '' : remainder.slice(slash + 1) };
|
||||
}
|
||||
|
||||
function prefixed(worktree: string, path: string): string {
|
||||
return `${LINKED_WORKTREE_DIRECTORY}${worktree}/${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route a request that targets `.worktrees/<name>/…` into that worktree's own
|
||||
* scheduling lane, so work in sibling worktrees runs concurrently. Only
|
||||
* structural targets are routed: a file path, a search or listing scope, or a
|
||||
* command `cwd`. Anything else, including a command that `cd`s into a worktree
|
||||
* from the root, stays root-scoped because its reach cannot be bounded.
|
||||
*/
|
||||
export function toLinkedWorktreeRequest(
|
||||
request: WorkspaceToolRequest,
|
||||
): { request: LinkedWorktreeRequest; worktree: string } | undefined {
|
||||
if (request.workspaceInstanceId != null) return undefined;
|
||||
switch (request.operation) {
|
||||
case 'read_file':
|
||||
case 'write_file':
|
||||
case 'edit_file':
|
||||
case 'preview_edit': {
|
||||
if (request.operation === 'read_file' && request.instructionSha256 != null) return undefined;
|
||||
const target = splitLinkedWorktreePath(request.path);
|
||||
if (target == null || target.rest === '') return undefined;
|
||||
return {
|
||||
worktree: target.worktree,
|
||||
request: { ...request, path: target.rest, worktree: target.worktree },
|
||||
};
|
||||
}
|
||||
case 'search_text': {
|
||||
const target = splitLinkedWorktreePath(request.path);
|
||||
if (target == null) return undefined;
|
||||
const { path: _path, ...rest } = request;
|
||||
return {
|
||||
worktree: target.worktree,
|
||||
request: {
|
||||
...rest,
|
||||
...(target.rest === '' ? {} : { path: target.rest }),
|
||||
worktree: target.worktree,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'list_files': {
|
||||
const target = splitLinkedWorktreePath(request.path);
|
||||
if (target == null) return undefined;
|
||||
const after =
|
||||
request.afterPath == null ? undefined : splitLinkedWorktreePath(request.afterPath);
|
||||
if (
|
||||
request.afterPath != null &&
|
||||
(after == null || after.worktree !== target.worktree || after.rest === '')
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const { path: _path, afterPath: _afterPath, ...rest } = request;
|
||||
return {
|
||||
worktree: target.worktree,
|
||||
request: {
|
||||
...rest,
|
||||
...(target.rest === '' ? {} : { path: target.rest }),
|
||||
...(after == null ? {} : { afterPath: after.rest }),
|
||||
worktree: target.worktree,
|
||||
},
|
||||
};
|
||||
}
|
||||
case 'execute_command': {
|
||||
if (request.environmentAction != null) return undefined;
|
||||
const target = splitLinkedWorktreePath(request.cwd);
|
||||
if (target == null) return undefined;
|
||||
const { cwd: _cwd, ...rest } = request;
|
||||
return {
|
||||
worktree: target.worktree,
|
||||
request: {
|
||||
...rest,
|
||||
...(target.rest === '' ? {} : { cwd: target.rest }),
|
||||
worktree: target.worktree,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Restore the `.worktrees/<name>/` prefix on every path a lane result reports. */
|
||||
export function fromLinkedWorktreeResult(
|
||||
result: WorkspaceToolResult,
|
||||
worktree: string,
|
||||
): WorkspaceToolResult {
|
||||
switch (result.operation) {
|
||||
case 'read_file':
|
||||
case 'write_file':
|
||||
case 'edit_file':
|
||||
case 'preview_edit':
|
||||
return { ...result, path: prefixed(worktree, result.path) };
|
||||
case 'search_text':
|
||||
return {
|
||||
...result,
|
||||
matches: result.matches.map((match) => ({
|
||||
...match,
|
||||
path: prefixed(worktree, match.path),
|
||||
})),
|
||||
};
|
||||
case 'list_files':
|
||||
return {
|
||||
...result,
|
||||
paths: result.paths.map((path) => prefixed(worktree, path)),
|
||||
...(result.nextAfterPath == null
|
||||
? {}
|
||||
: { nextAfterPath: prefixed(worktree, result.nextAfterPath) }),
|
||||
};
|
||||
case 'execute_command':
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export async function executeWorkspaceTool({
|
||||
baseURL,
|
||||
authHeaders,
|
||||
|
|
@ -868,6 +1004,7 @@ export async function executeWorkspaceTool({
|
|||
codeApiMaxRetryWaitMs = CODE_API_RATE_LIMIT_WAIT_DEFAULT_MS,
|
||||
maxRequestTimeoutMs,
|
||||
deadlineAtMs,
|
||||
linkedWorktrees = false,
|
||||
}: {
|
||||
baseURL: string;
|
||||
authHeaders: WorkspaceToolAuthHeaders;
|
||||
|
|
@ -881,6 +1018,8 @@ export async function executeWorkspaceTool({
|
|||
maxRequestTimeoutMs?: number;
|
||||
/** Optional earlier caller deadline; a signal alone has no remaining-time value. */
|
||||
deadlineAtMs?: number;
|
||||
/** The worker runs each `.worktrees/<name>` in its own lane; route matching requests there. */
|
||||
linkedWorktrees?: boolean;
|
||||
}): Promise<WorkspaceToolResult> {
|
||||
if (
|
||||
!isValidRequest(request) ||
|
||||
|
|
@ -898,16 +1037,18 @@ export async function executeWorkspaceTool({
|
|||
) {
|
||||
throw new WorkspaceToolHttpError('invalid');
|
||||
}
|
||||
const executionBudgetMs = getWorkspaceExecutionBudgetMs(request);
|
||||
const lane = linkedWorktrees === true ? toLinkedWorktreeRequest(request) : undefined;
|
||||
const wireRequest: WorkspaceToolRequest = lane?.request ?? request;
|
||||
const executionBudgetMs = getWorkspaceExecutionBudgetMs(wireRequest);
|
||||
const completionReserveMs = executionBudgetMs + WORKSPACE_COMMAND_TRANSPORT_GRACE_MS;
|
||||
const perAttemptTimeoutMs = maxRequestTimeoutMs ?? getWorkspaceToolTimeoutMs(request);
|
||||
const perAttemptTimeoutMs = maxRequestTimeoutMs ?? getWorkspaceToolTimeoutMs(wireRequest);
|
||||
const callerDeadlineAt = Math.min(
|
||||
deadlineAtMs ?? Infinity,
|
||||
maxRequestTimeoutMs == null ? Infinity : Date.now() + maxRequestTimeoutMs,
|
||||
);
|
||||
const queueDeadlineAt = Date.now() + maxQueueWaitMs;
|
||||
const callerRetryDeadlineAt = callerDeadlineAt - completionReserveMs;
|
||||
const body = JSON.stringify(request);
|
||||
const body = JSON.stringify(wireRequest);
|
||||
let lastAdmissionRejection: WorkspaceToolHttpError | undefined;
|
||||
let lastRetryDeadlineAt = Infinity;
|
||||
let rateLimitWaitedMs = 0;
|
||||
|
|
@ -1011,10 +1152,10 @@ export async function executeWorkspaceTool({
|
|||
continue;
|
||||
}
|
||||
const result = await readBoundedJson(response, requestSignal);
|
||||
if (!isValidResult(request, result)) {
|
||||
if (!isValidResult(wireRequest, result)) {
|
||||
throw new WorkspaceToolHttpError('invalid');
|
||||
}
|
||||
return result;
|
||||
return lane ? fromLinkedWorktreeResult(result, lane.worktree) : result;
|
||||
} catch (error) {
|
||||
if (error instanceof WorkspaceToolHttpError) throw error;
|
||||
if (
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue