Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
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
6 changes: 4 additions & 2 deletions packages/channels/base/src/AcpBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,14 @@ export class AcpBridge extends EventEmitter {

async loadSession(sessionId: string, cwd: string): Promise<string> {
const conn = this.ensureConnection();
const response = await conn.loadSession({
await conn.loadSession({
sessionId,
cwd,
mcpServers: [],
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] 行为契约从「返回 agent 报告的 session ID」改成了「直接回显调用者传入的 sessionId,信任 ACP agent 用同样的 ID 加载」。这是正确的——LoadSessionResponse 规范里就没这个字段——但建议加一行注释,避免未来 reader 觉得「这看起来像 bug」又把它改回去:

// LoadSessionResponse has no sessionId field — the ACP agent loads the
// session under the caller-supplied ID, so we just echo it back.
return sessionId;

return response.sessionId;
// LoadSessionResponse has no sessionId field — the ACP agent loads
// the session under the caller-supplied ID, so we echo it back.
return sessionId;
}

async prompt(
Expand Down
359 changes: 359 additions & 0 deletions packages/channels/base/src/SessionRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,67 @@ describe('SessionRouter', () => {
expect(router.hasSession('ch', 'alice', 'chat1')).toBe(false);
expect(router.getAll()).toEqual([]);
});

it('preserves persist file for restoration on next start', async () => {
const { writeFileSync, rmSync, readFileSync, existsSync, mkdtempSync } =
await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-clearAll-persist-'));

const persistFile = join(tmpDir, 'sessions.json');
const originalEntries = {
'telegram:alice:chat1': {
sessionId: 'session-xyz',
target: {
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
},
cwd: '/workspace',
},
};

try {
// Create a router, write a session, then clearAll
const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);
await router.resolve('telegram', 'alice', 'chat1');

// Populate the persist file with known data
writeFileSync(persistFile, JSON.stringify(originalEntries, null, 2));

router.clearAll();

// Memory should be cleared
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(false);
expect(router.getAll()).toEqual([]);

// Persist file should still exist with original content
expect(existsSync(persistFile)).toBe(true);
const onDisk = JSON.parse(readFileSync(persistFile, 'utf-8'));
expect(onDisk).toEqual(originalEntries);

// A fresh router should be able to restore from it
const freshRouter = new SessionRouter(
bridge,
'/tmp',
'user',
persistFile,
);
const result = await freshRouter.restoreSessions();

expect(result.restored).toBe(1);
expect(result.failed).toBe(0);
expect(freshRouter.hasSession('telegram', 'alice', 'chat1')).toBe(true);
expect(freshRouter.getTarget('session-xyz')).toEqual({
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
});
} finally {
rmSync(tmpDir, { recursive: true });
}
});
});

describe('setBridge', () => {
Expand All @@ -229,4 +290,302 @@ describe('SessionRouter', () => {
expect(bridge.newSession).not.toHaveBeenCalled();
});
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] describe('restoreSessions') 下的 3 个新测试直接调用 rmSync 清理临时目录,没有 try/finally 包裹。若测试中途失败(断言异常等),/tmp/test-restore-* 目录会残留。建议与同文件中 preserves persist file 测试保持一致,使用 try { ... } finally { rmSync(tmpDir, { recursive: true }) } 包裹测试体。

— deepseek-v4-pro via Qwen Code /review

describe('restoreSessions', () => {
it('restores sessions from persist file', async () => {
const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-'));

try {
const persistFile = join(tmpDir, 'sessions.json');
const entries = {
'telegram:alice:chat1': {
sessionId: 'old-session-1',
target: {
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
},
cwd: '/workspace',
},
'telegram:bob:chat2': {
sessionId: 'old-session-2',
target: {
channelName: 'telegram',
senderId: 'bob',
chatId: 'chat2',
},
cwd: '/workspace',
},
};
writeFileSync(persistFile, JSON.stringify(entries, null, 2));

const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);
const result = await router.restoreSessions();

expect(result.restored).toBe(2);
expect(result.failed).toBe(0);
expect(bridge.loadSession).toHaveBeenCalledTimes(2);
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true);
expect(router.hasSession('telegram', 'bob', 'chat2')).toBe(true);

const target = router.getTarget('old-session-1');
expect(target).toEqual({
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
});
} finally {
rmSync(tmpDir, { recursive: true });
}
});

it('skips entries whose loadSession throws', async () => {
const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-fail-'));

try {
const persistFile = join(tmpDir, 'sessions.json');
const entries = {
'telegram:alice:chat1': {
sessionId: 'good-session',
target: {
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
},
cwd: '/workspace',
},
'telegram:bob:chat2': {
sessionId: 'stale-session',
target: {
channelName: 'telegram',
senderId: 'bob',
chatId: 'chat2',
},
cwd: '/workspace',
},
};
writeFileSync(persistFile, JSON.stringify(entries, null, 2));

// Make loadSession throw for the stale session
(bridge.loadSession as ReturnType<typeof vi.fn>).mockImplementation(
(id: string) => {
if (id === 'stale-session') {
throw new Error('Session not found');
}
return id;
},
);

const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);
const result = await router.restoreSessions();

expect(result.restored).toBe(1);
expect(result.failed).toBe(1);
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true);
expect(router.hasSession('telegram', 'bob', 'chat2')).toBe(false);

// Persist file should be updated to remove the failed entry
const { readFileSync } = await import('node:fs');
const updated = JSON.parse(readFileSync(persistFile, 'utf-8'));
expect(Object.keys(updated)).toEqual(['telegram:alice:chat1']);
} finally {
rmSync(tmpDir, { recursive: true });
}
});

it('removes stale in-memory mappings on failed restore (crash recovery)', async () => {
const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-crash-'));

try {
const persistFile = join(tmpDir, 'sessions.json');
const entries = {
'telegram:alice:chat1': {
sessionId: 'will-fail',
target: {
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
},
cwd: '/workspace',
},
};
writeFileSync(persistFile, JSON.stringify(entries, null, 2));

// Simulate pre-crash in-memory state: the router already has a mapping
// for this key from before the bridge crash.
const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);
(bridge.newSession as ReturnType<typeof vi.fn>).mockResolvedValueOnce(
'will-fail',
);
await router.resolve(
'telegram',
'alice',
'chat1',
undefined,
'/workspace',
);
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true);

// Now make loadSession throw so restoreSessions hits the catch path.
(bridge.loadSession as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
new Error('Session not found'),
);

const result = await router.restoreSessions();
expect(result.restored).toBe(0);
expect(result.failed).toBe(1);
// The stale in-memory mapping should be cleaned up
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(false);
} finally {
rmSync(tmpDir, { recursive: true });
}
});

it('returns zeros when no persist file exists', async () => {
const router = new SessionRouter(
bridge,
'/tmp',
'user',
'/nonexistent/sessions.json',
);
const result = await router.restoreSessions();
expect(result).toEqual({ restored: 0, failed: 0 });
});

it('returns zeros when persist file is empty', async () => {
const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-empty-'));

try {
const persistFile = join(tmpDir, 'sessions.json');
writeFileSync(persistFile, '{}');

const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);
const result = await router.restoreSessions();

expect(result).toEqual({ restored: 0, failed: 0 });
expect(bridge.loadSession).not.toHaveBeenCalled();
} finally {
rmSync(tmpDir, { recursive: true });
}
});

it('times out when loadSession hangs and logs error to stderr', async () => {
const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-timeout-'));

vi.useFakeTimers();

try {
const persistFile = join(tmpDir, 'sessions.json');
const entries = {
'telegram:alice:chat1': {
sessionId: 'hanging-session',
target: {
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
},
cwd: '/workspace',
},
};
writeFileSync(persistFile, JSON.stringify(entries, null, 2));

// Make loadSession hang indefinitely (never resolves/rejects)
let hangingResolve: (value: string) => void;
const hangingPromise = new Promise<string>((resolve) => {
hangingResolve = resolve;
});
(bridge.loadSession as ReturnType<typeof vi.fn>).mockReturnValue(
hangingPromise,
);

const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);

// Start restoreSessions - it will hang waiting for loadSession
const resultPromise = router.restoreSessions();

// Advance time past the 30s timeout
await vi.advanceTimersByTimeAsync(30_000);

const result = await resultPromise;

// Should have recorded a failure due to timeout
expect(result.restored).toBe(0);
expect(result.failed).toBe(1);
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(false);

// The hanging loadSession should have a no-op catch attached
// to prevent unhandled rejection. Resolve it now to verify no crash.
hangingResolve!('hanging-session');
await Promise.resolve(); // let microtasks settle
} finally {
vi.useRealTimers();
rmSync(tmpDir, { recursive: true });
}
});

it('clears timeout when loadSession completes before timeout', async () => {
const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs');
const { join } = await import('node:path');
const { tmpdir } = await import('node:os');
const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-notimeout-'));

vi.useFakeTimers();

try {
const persistFile = join(tmpDir, 'sessions.json');
const entries = {
'telegram:alice:chat1': {
sessionId: 'fast-session',
target: {
channelName: 'telegram',
senderId: 'alice',
chatId: 'chat1',
},
cwd: '/workspace',
},
};
writeFileSync(persistFile, JSON.stringify(entries, null, 2));

// Make loadSession resolve quickly (within timeout)
(bridge.loadSession as ReturnType<typeof vi.fn>).mockImplementation(
(id: string) => Promise.resolve(id),
);

const router = new SessionRouter(bridge, '/tmp', 'user', persistFile);
const resultPromise = router.restoreSessions();

// Advance time a bit (but not past timeout)
await vi.advanceTimersByTimeAsync(1000);

const result = await resultPromise;

// Should have succeeded
expect(result.restored).toBe(1);
expect(result.failed).toBe(0);
expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true);

// Advance past the original timeout to ensure no stray timer fires
await vi.advanceTimersByTimeAsync(30_000);
// No error should occur (timeout was cleared)
} finally {
vi.useRealTimers();
rmSync(tmpDir, { recursive: true });
}
});
});
});
Loading