Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
159002d
feat(daemon): worktree-isolated sessions for parallel tasks
wenshao Jul 19, 2026
738b6aa
Merge remote-tracking branch 'origin/main' into feat/webshell-worktre…
wenshao Jul 19, 2026
f7951df
feat(daemon): restore worktree isolation on session load/resume
wenshao Jul 19, 2026
c4b8b22
Merge remote-tracking branch 'origin/main' into feat/worktree-restore…
wenshao Jul 20, 2026
f184757
fix(daemon): use restoreWorktreeContext for load/resume worktree restore
wenshao Jul 20, 2026
0d24900
fix(daemon): durable worktree membership + pre-read sidecar before load
wenshao Jul 20, 2026
8fa7125
fix(daemon): read sidecar after load, reorder membership checks
wenshao Jul 20, 2026
dc1a551
test(daemon): worktree membership + load/resume restore tests
wenshao Jul 20, 2026
505edb3
fix(test): use bracket notation for path.sep in strict tsconfig
wenshao Jul 20, 2026
c62b15e
fix(daemon): symlink-safe containment, nested worktree membership, te…
wenshao Jul 20, 2026
2bc4147
test(daemon): add containment guard rejection test
wenshao Jul 20, 2026
af19e30
fix(daemon): realpath-based containment for worktree restore
wenshao Jul 20, 2026
2260f42
fix(daemon): containment uses workspaceCwd root, canonical path, nati…
wenshao Jul 20, 2026
94c882e
fix(daemon): monorepo worktree containment via repo top-level fallback
wenshao Jul 20, 2026
5a6b69d
fix(daemon): close TOCTOU with allowedRoots containment at sessionCd …
wenshao Jul 20, 2026
0d4aab9
fix(daemon): wrap getRepoTopLevel in try-catch for worktree create path
wenshao Jul 20, 2026
5efdb97
fix(daemon): narrow allowedRoots to .qwen/worktrees, containment befo…
wenshao Jul 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5624,6 +5624,13 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
return { sessionId, ...result };
},

setSessionWorktree(sessionId, worktree) {
const entry = byId.get(sessionId);
if (entry) {
entry.worktree = worktree;
}
},

async closeSession(sessionId, context, closeOpts) {
return closeSessionImpl(sessionId, context, closeOpts);
},
Expand Down
11 changes: 11 additions & 0 deletions packages/acp-bridge/src/bridgeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,17 @@ export interface AcpSessionBridge {
context?: BridgeClientRequestContext,
): Promise<ChangeSessionCwdResult>;

/**
* Set worktree metadata on an existing session entry. Used when
* restoring a worktree session after daemon restart — the sidecar
* file provides the metadata, and this populates the in-memory entry
* so `getSessionSummary` returns it.
*/
setSessionWorktree(
sessionId: string,
worktree: { slug: string; path: string; branch: string },
): void;

/**
* Forward a prompt to the agent. Concurrent prompts against the same
* session FIFO-serialize through a per-session queue.
Expand Down
66 changes: 66 additions & 0 deletions packages/cli/src/serve/routes/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import {
APPROVAL_MODES,
Expand All @@ -23,6 +24,7 @@ import {
runWithoutDebugLogSession,
writeWorktreeSessionMarker,
writeWorktreeSession,
readWorktreeSession,
type ApprovalMode,
type SessionGroupColor,
type SessionGroupPresetColor,
Expand Down Expand Up @@ -1551,6 +1553,70 @@ export function registerSessionRoutes(
}
return;
}
// Restore worktree isolation. Read the sidecar AFTER load/resume
// so we inherit the ACP layer's verdict: #restoreWorktreeOnResume
// clears the sidecar on dead-worktree / containment-failure paths,
// so a post-read naturally skips those cases. On the healthy path
// the sidecar is untouched and we relocate + populate the entry.
// Note: the !res.writable early-return above skips this restore;
// a client that disconnects mid-load leaves the session parked in
// the main workspace (pre-existing shape, low frequency).
if (!session.worktree) {
Comment thread
wenshao marked this conversation as resolved.
Resolved
const sidecar = await readWorktreeSession(
new SessionService(workspaceCwd).getWorktreeSessionPath(sessionId),
).catch(() => null);
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
if (sidecar) {
// Defense-in-depth: resolve symlinks on both the target and
// the expected worktrees root, then verify containment. This
// defeats both `..` traversal and symlink escapes (e.g.
// .qwen/worktrees/escape -> /etc). The allowed root is always
// derived from workspaceCwd (never from the sidecar, which is
// attacker-writable). The canonical realTarget is passed to
// changeSessionCwd to eliminate the TOCTOU window between
// validation and relocation.
let realTarget: string | undefined;
try {
realTarget = fs.realpathSync(sidecar.worktreePath);
const realRoot = fs.realpathSync(
path.join(workspaceCwd, '.qwen', 'worktrees'),
Comment thread
wenshao marked this conversation as resolved.
Resolved
);
const rel = path.relative(realRoot, realTarget);
if (rel.startsWith('..') || path.isAbsolute(rel)) {
realTarget = undefined;
}
} catch {
realTarget = undefined;
}
if (!realTarget) {
daemonLog?.warn('worktree sidecar path failed containment', {
sessionId,
path: sidecar.worktreePath,
});
} else {
const wt = {
slug: sidecar.slug,
path: realTarget,
branch: sidecar.worktreeBranch,
};
try {
await runtime.bridge.changeSessionCwd(sessionId, {
path: wt.path,
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
});
runtime.bridge.setSessionWorktree(sessionId, wt);
session.worktree = wt;
} catch (restoreErr) {
daemonLog?.warn('worktree restore failed on load/resume', {
sessionId,
worktreePath: wt.path,
error:
restoreErr instanceof Error
? restoreErr.message
: String(restoreErr),
});
}
}
Comment thread
wenshao marked this conversation as resolved.
Resolved
}
}
res.status(200).json(session);
} catch (err) {
sendBridgeError(res, err, {
Expand Down
179 changes: 179 additions & 0 deletions packages/cli/src/serve/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,32 @@ import {
// `mockWt.impl` to control instance behaviour.
const mockWt = vi.hoisted(() => ({
impl: undefined as (() => Record<string, unknown>) | undefined,
readSidecar: undefined as (() => Promise<unknown>) | undefined,
realpath: undefined as ((p: string) => string) | undefined,
}));
vi.mock('node:fs', async (importOriginal) => {
const original = await importOriginal<typeof import('node:fs')>();
const wrapped = ((p: fs.PathLike) =>
mockWt.realpath
? mockWt.realpath(String(p))
: original.realpathSync(p)) as typeof original.realpathSync;
wrapped.native = original.realpathSync.native;
return {
...original,
realpathSync: wrapped,
};
});
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
const original =
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
return {
...original,
readWorktreeSession: (...args: unknown[]) =>
mockWt.readSidecar
? mockWt.readSidecar()
: (original.readWorktreeSession as (...a: unknown[]) => unknown)(
...args,
),
GitWorktreeService: class MockGitWorktreeService {
static validateUserWorktreeSlug =
original.GitWorktreeService.validateUserWorktreeSlug;
Expand Down Expand Up @@ -500,6 +520,15 @@ interface FakeBridgeOpts {
promptId: string,
) => { removed: boolean };
spawnImpl?: (req: BridgeSpawnRequest) => Promise<BridgeSession>;
changeSessionCwdImpl?: (
sessionId: string,
req: { path: string },
) => Promise<{
sessionId: string;
previousCwd: string;
newCwd: string;
warnings: string[];
}>;
loadImpl?: (
req: BridgeRestoreSessionRequest,
) => Promise<BridgeRestoredSession>;
Expand Down Expand Up @@ -754,6 +783,10 @@ interface FakeBridge extends AcpSessionBridge {
}>;
detachCalls: Array<{ sessionId: string; clientId?: string }>;
changeSessionCwdCalls: Array<{ sessionId: string; path: string }>;
setSessionWorktreeCalls: Array<{
sessionId: string;
worktree: { slug: string; path: string; branch: string };
}>;
enqueueMidTurnCalls: Array<{
sessionId: string;
message: string;
Expand Down Expand Up @@ -932,6 +965,10 @@ function fakeBridge(opts: FakeBridgeOpts = {}): FakeBridge {
}> = [];
const detachCalls: FakeBridge['detachCalls'] = [];
const changeSessionCwdCalls: Array<{ sessionId: string; path: string }> = [];
const setSessionWorktreeCalls: Array<{
sessionId: string;
worktree: { slug: string; path: string; branch: string };
}> = [];
const enqueueMidTurnCalls: FakeBridge['enqueueMidTurnCalls'] = [];
const enqueueMidTurnImpl =
opts.enqueueMidTurnImpl ?? (() => ({ accepted: true }));
Expand Down Expand Up @@ -1497,6 +1534,7 @@ function fakeBridge(opts: FakeBridgeOpts = {}): FakeBridge {
killCalls,
detachCalls,
changeSessionCwdCalls,
setSessionWorktreeCalls,
enqueueMidTurnCalls,
permissionVotes,
sessionPermissionVotes,
Expand Down Expand Up @@ -1976,13 +2014,19 @@ function fakeBridge(opts: FakeBridgeOpts = {}): FakeBridge {
},
async changeSessionCwd(sessionId, req) {
changeSessionCwdCalls.push({ sessionId, path: req.path });
if (opts.changeSessionCwdImpl) {
return opts.changeSessionCwdImpl(sessionId, req);
}
return {
sessionId,
previousCwd: '/fake/previous',
newCwd: req.path,
warnings: [],
};
},
setSessionWorktree(sessionId, worktree) {
setSessionWorktreeCalls.push({ sessionId, worktree });
},
isChannelLive() {
return false;
},
Expand Down Expand Up @@ -8842,6 +8886,141 @@ describe('createServeApp', () => {
// CI. The same constraint applies here. The cleanup behavior
// is exercised manually via the route handler closure shared
// between both routes in `restoreSessionHandler`.

it('restores worktree isolation on load when sidecar exists', async () => {
const bridge = fakeBridge();
const app = createServeApp(
{ ...baseOpts, workspace: WS_BOUND },
undefined,
{ bridge },
);
// Identity realpath so the containment check passes in the test env.
mockWt.realpath = (p) => p;
mockWt.readSidecar = () =>
Promise.resolve({
slug: 'my-task',
worktreePath: `${WS_BOUND}/.qwen/worktrees/my-task`,
worktreeBranch: 'worktree-my-task',
originalCwd: WS_BOUND,
originalBranch: 'main',
originalHeadCommit: 'abc123',
});

try {
const res = await request(app)
.post('/session/wt-session/load')
.set('Host', `127.0.0.1:${baseOpts.port}`)
.send({ cwd: WS_BOUND });

expect(res.status).toBe(200);
expect(res.body.worktree).toEqual({
slug: 'my-task',
path: `${WS_BOUND}/.qwen/worktrees/my-task`,
branch: 'worktree-my-task',
});
expect(bridge.changeSessionCwdCalls).toHaveLength(1);
expect(bridge.changeSessionCwdCalls[0].path).toBe(
`${WS_BOUND}/.qwen/worktrees/my-task`,
);
expect(bridge.setSessionWorktreeCalls).toHaveLength(1);
} finally {
mockWt.readSidecar = undefined;
mockWt.realpath = undefined;
}
});

it('skips worktree restore when no sidecar exists', async () => {
const bridge = fakeBridge();
const app = createServeApp(
{ ...baseOpts, workspace: WS_BOUND },
undefined,
{ bridge },
);
mockWt.readSidecar = () => Promise.resolve(null);

try {
const res = await request(app)
.post('/session/plain-session/load')
.set('Host', `127.0.0.1:${baseOpts.port}`)
.send({ cwd: WS_BOUND });

expect(res.status).toBe(200);
expect(res.body.worktree).toBeUndefined();
expect(bridge.changeSessionCwdCalls).toHaveLength(0);
expect(bridge.setSessionWorktreeCalls).toHaveLength(0);
} finally {
mockWt.readSidecar = undefined;
}
});

it('returns 200 without worktree when changeSessionCwd fails', async () => {
const bridge = fakeBridge({
changeSessionCwdImpl: async () => {
throw new Error('cd failed');
},
});
const app = createServeApp(
{ ...baseOpts, workspace: WS_BOUND },
undefined,
{ bridge },
);
mockWt.realpath = (p) => p;
mockWt.readSidecar = () =>
Promise.resolve({
slug: 'dead-task',
worktreePath: `${WS_BOUND}/.qwen/worktrees/dead-task`,
worktreeBranch: 'worktree-dead-task',
originalCwd: WS_BOUND,
originalBranch: 'main',
originalHeadCommit: 'abc123',
});

try {
const res = await request(app)
.post('/session/dead-session/load')
.set('Host', `127.0.0.1:${baseOpts.port}`)
.send({ cwd: WS_BOUND });

expect(res.status).toBe(200);
expect(res.body.worktree).toBeUndefined();
expect(bridge.setSessionWorktreeCalls).toHaveLength(0);
} finally {
mockWt.readSidecar = undefined;
mockWt.realpath = undefined;
}
});

it('skips restore when sidecar path fails containment check', async () => {
const bridge = fakeBridge();
const app = createServeApp(
{ ...baseOpts, workspace: WS_BOUND },
undefined,
{ bridge },
);
mockWt.readSidecar = () =>
Promise.resolve({
slug: 'escape',
worktreePath: '/etc/passwd',
worktreeBranch: 'worktree-escape',
originalCwd: WS_BOUND,
originalBranch: 'main',
originalHeadCommit: 'abc123',
});

try {
const res = await request(app)
.post('/session/escape-session/load')
.set('Host', `127.0.0.1:${baseOpts.port}`)
.send({ cwd: WS_BOUND });

expect(res.status).toBe(200);
expect(res.body.worktree).toBeUndefined();
expect(bridge.changeSessionCwdCalls).toHaveLength(0);
expect(bridge.setSessionWorktreeCalls).toHaveLength(0);
} finally {
mockWt.readSidecar = undefined;
}
});
});

describe('POST /session/:id/prompt', () => {
Expand Down
Loading
Loading