Skip to content

Commit 45fc7e9

Browse files
samuelcoleclaude
andauthored
Delete the session registry's uncalled methods, and test its expiry and list filters (#164)
The session registry carried methods nothing called: getSessionsForOrigin, addToHistory, getHistory, destroySession, cloneSession, canUseLLM, canUseBrowser and getStats, plus a per-session history array that recordPrompt filled and nothing read. This deletes them, the history field on AgentSession, and the test mocks of createImplicitSession, which no longer exists. It adds tests for the registry's own behaviour: a session with ttlMinutes is usable until its lifetime ends, is then refused as expired and listed as terminated, and is terminated by the periodic cleanup even when nothing looks it up; a session without ttlMinutes never expires; listSessions filters by origin, status, activeOnly and type (an unknown type matches nothing) and lists the most recently active first. Each test loads a fresh registry on fake timers, and the session-handler tests now do the same, so no real cleanup intervals leak between tests. Fixes HBR-112 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 12b2811 commit 45fc7e9

9 files changed

Lines changed: 144 additions & 187 deletions

File tree

‎extension/src/handlers/__tests__/session-handlers.test.ts‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* the sidebar sends.
88
*/
99

10-
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
10+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
1111

1212
const mocks = vi.hoisted(() => ({
1313
hasPermission: vi.fn(),
@@ -18,8 +18,12 @@ vi.mock('../../page-api/handlers/permission-handlers', () => ({
1818
getPermissions: mocks.getPermissions,
1919
}));
2020

21-
import { handleSessionsCreate } from '../../page-api/handlers/session-handlers';
22-
import { SessionRegistry } from '../../sessions';
21+
type SessionsModule = typeof import('../../sessions');
22+
type PageSessionHandlers = typeof import('../../page-api/handlers/session-handlers');
23+
24+
// Each test loads a fresh module graph, so it gets its own empty registry.
25+
let SessionRegistry: SessionsModule['SessionRegistry'];
26+
let handleSessionsCreate: PageSessionHandlers['handleSessionsCreate'];
2327

2428
type Listener = (
2529
message: unknown,
@@ -31,22 +35,28 @@ const listeners: Listener[] = [];
3135
const ORIGIN = 'https://example.test';
3236
const SIDEBAR = { id: 'harbor-test', url: 'chrome-extension://harbor-test/sidebar.html' } as chrome.runtime.MessageSender;
3337

34-
beforeAll(async () => {
38+
beforeAll(() => {
3539
const chrome = (globalThis as unknown as { chrome: { runtime: { onMessage: { addListener: (l: Listener) => void } } } }).chrome;
3640
chrome.runtime.onMessage.addListener = (l: Listener) => {
3741
listeners.push(l);
3842
};
39-
const mod = await import('../session-handlers');
40-
mod.registerSessionHandlers();
4143
});
4244

43-
beforeEach(() => {
45+
beforeEach(async () => {
4446
vi.clearAllMocks();
4547
mocks.hasPermission.mockResolvedValue(true);
4648
mocks.getPermissions.mockResolvedValue({ scopes: {}, allowedTools: [] });
47-
for (const s of SessionRegistry.listSessions()) {
48-
SessionRegistry.destroySession(s.sessionId, s.origin);
49-
}
49+
// Each fresh registry starts a cleanup interval; keep it off the real clock.
50+
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
51+
vi.resetModules();
52+
listeners.length = 0;
53+
({ SessionRegistry } = await import('../../sessions'));
54+
({ handleSessionsCreate } = await import('../../page-api/handlers/session-handlers'));
55+
(await import('../session-handlers')).registerSessionHandlers();
56+
});
57+
58+
afterEach(() => {
59+
vi.useRealTimers();
5060
});
5161

5262
/** Send a runtime message the way the sidebar does and await the response. */

‎extension/src/page-api/__tests__/listener-origin-and-gate.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ vi.mock('../../sessions', () => ({
3636
SessionRegistry: {
3737
subscribe: vi.fn(),
3838
createExplicitSession: vi.fn(),
39-
createImplicitSession: vi.fn(),
4039
getSession: vi.fn(),
4140
getValidatedSession: vi.fn(),
4241
listSessions: vi.fn(() => []),

‎extension/src/page-api/__tests__/page-tools-port.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ vi.mock('../../sessions', () => ({
2929
SessionRegistry: {
3030
subscribe: vi.fn(),
3131
createExplicitSession: vi.fn(),
32-
createImplicitSession: vi.fn(),
3332
getSession: vi.fn(),
3433
getValidatedSession: vi.fn(),
3534
listSessions: vi.fn(() => []),

‎extension/src/page-api/__tests__/receiver-feature-flags.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ vi.mock('../../sessions', () => ({
3232
SessionRegistry: {
3333
subscribe: vi.fn(),
3434
createExplicitSession: vi.fn(),
35-
createImplicitSession: vi.fn(),
3635
getSession: vi.fn(),
3736
getValidatedSession: vi.fn(),
3837
listSessions: vi.fn(() => []),

‎extension/src/page-api/__tests__/revoked-grant-prompt.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ vi.mock('../../sessions', () => ({
4141
SessionRegistry: {
4242
subscribe: vi.fn(),
4343
createExplicitSession: vi.fn(),
44-
createImplicitSession: vi.fn(),
4544
getSession: vi.fn(),
4645
getValidatedSession: vi.fn(),
4746
listSessions: vi.fn(() => []),

‎extension/src/sessions/__tests__/label-flow.test.ts‎

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,25 @@ describe('session-owned flow state', () => {
1212
it('unions labels only within one validated session and keeps them out of summaries', () => {
1313
const first = create();
1414
const second = create();
15-
try {
16-
const flow = SessionRegistry.getLabelFlow(first, ORIGIN);
17-
flow.add(new LabelSet(['credentials']));
18-
flow.add(new LabelSet(['confidential']));
19-
expect(SessionRegistry.getLabelFlow(first, ORIGIN)).toBe(flow);
20-
expect(flow.labels.toArray()).toEqual(['confidential', 'credentials']);
21-
expect(SessionRegistry.getLabelFlow(second, ORIGIN).labels.isEmpty()).toBe(true);
22-
expect(SessionRegistry.listSessions({ origin: ORIGIN }).every(s => !('labelFlow' in s) && !('labels' in s))).toBe(true);
23-
expect(() => SessionRegistry.getLabelFlow(first, 'https://other.example')).toThrow('different origin');
24-
} finally {
25-
SessionRegistry.destroySession(first, ORIGIN);
26-
SessionRegistry.destroySession(second, ORIGIN);
27-
}
15+
const flow = SessionRegistry.getLabelFlow(first, ORIGIN);
16+
flow.add(new LabelSet(['credentials']));
17+
flow.add(new LabelSet(['confidential']));
18+
expect(SessionRegistry.getLabelFlow(first, ORIGIN)).toBe(flow);
19+
expect(flow.labels.toArray()).toEqual(['confidential', 'credentials']);
20+
expect(SessionRegistry.getLabelFlow(second, ORIGIN).labels.isEmpty()).toBe(true);
21+
expect(SessionRegistry.listSessions({ origin: ORIGIN }).every(s => !('labelFlow' in s) && !('labels' in s))).toBe(true);
22+
expect(() => SessionRegistry.getLabelFlow(first, 'https://other.example')).toThrow('different origin');
2823
});
2924

30-
it.each(['expired', 'terminated', 'destroyed'] as const)('refuses flow access for a %s session', (state) => {
25+
it.each(['expired', 'terminated'] as const)('refuses flow access for a %s session', (state) => {
3126
const id = create();
3227
SessionRegistry.getLabelFlow(id, ORIGIN).add(new LabelSet(['credentials']));
3328
if (state === 'expired') SessionRegistry.getValidatedSession(id, ORIGIN).capabilities.limits = { expiresAt: Date.now() - 1 };
3429
if (state === 'terminated') SessionRegistry.terminateSession(id, ORIGIN);
35-
if (state === 'destroyed') SessionRegistry.destroySession(id, ORIGIN);
3630
expect(() => SessionRegistry.getLabelFlow(id, ORIGIN)).toThrow();
37-
SessionRegistry.destroySession(id, ORIGIN);
31+
});
32+
33+
it('refuses flow access for a session id the registry never issued', () => {
34+
expect(() => SessionRegistry.getLabelFlow('no-such-session', ORIGIN)).toThrow('Session not found');
3835
});
3936
});
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**
2+
* The session registry's own behavior: a session's `ttlMinutes` lifetime and
3+
* `listSessions` filters. Each test loads a fresh registry module, so it
4+
* starts empty and its cleanup interval runs on this test's fake clock.
5+
*/
6+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7+
import type { SessionEvent } from '../types';
8+
9+
type Registry = typeof import('../registry')['SessionRegistry'];
10+
11+
const A = 'https://a.example';
12+
const B = 'https://b.example';
13+
const START = new Date('2026-12-04T12:00:00Z');
14+
15+
let registry: Registry;
16+
17+
beforeEach(async () => {
18+
vi.useFakeTimers();
19+
vi.setSystemTime(START);
20+
vi.resetModules();
21+
({ SessionRegistry: registry } = await import('../registry'));
22+
});
23+
24+
afterEach(() => {
25+
vi.useRealTimers();
26+
});
27+
28+
function create(origin: string, ttlMinutes?: number): string {
29+
const result = registry.createExplicitSession(origin, {
30+
capabilities: { llm: {} },
31+
...(ttlMinutes !== undefined ? { limits: { ttlMinutes } } : {}),
32+
});
33+
expect(result.success).toBe(true);
34+
return result.sessionId!;
35+
}
36+
37+
describe('a session with ttlMinutes', () => {
38+
it('is usable until its lifetime runs out, then refused as expired and listed as terminated', () => {
39+
const id = create(A, 5);
40+
41+
vi.setSystemTime(START.getTime() + 5 * 60_000 - 1);
42+
expect(registry.getValidatedSession(id, A).status).toBe('active');
43+
44+
vi.setSystemTime(START.getTime() + 5 * 60_000 + 1);
45+
expect(() => registry.getValidatedSession(id, A)).toThrow('Session has expired');
46+
expect(registry.listSessions({ origin: A })).toEqual([
47+
expect.objectContaining({ sessionId: id, status: 'terminated' }),
48+
]);
49+
// Once terminated, a later lookup says so rather than expiring it again.
50+
expect(() => registry.getValidatedSession(id, A)).toThrow('Session has been terminated');
51+
});
52+
53+
it('is terminated by the periodic cleanup even if nothing looks it up', () => {
54+
const id = create(A, 5);
55+
const events: SessionEvent[] = [];
56+
registry.subscribe((e) => events.push(e));
57+
58+
// Cleanup runs every 10 minutes; the session expired at 5.
59+
vi.advanceTimersByTime(10 * 60_000);
60+
61+
expect(registry.getSession(id)?.status).toBe('terminated');
62+
expect(events).toContainEqual({ type: 'session_terminated', sessionId: id, origin: A });
63+
});
64+
65+
it('without ttlMinutes has no expiry', () => {
66+
const id = create(A);
67+
expect(registry.getSession(id)?.capabilities.limits?.expiresAt).toBeUndefined();
68+
69+
vi.setSystemTime(START.getTime() + 24 * 60 * 60_000);
70+
expect(registry.getValidatedSession(id, A).status).toBe('active');
71+
});
72+
});
73+
74+
describe('listSessions', () => {
75+
it('filters by origin, status and activeOnly, and lists the most recently active first', () => {
76+
const a1 = create(A);
77+
vi.advanceTimersByTime(1_000);
78+
const a2 = create(A);
79+
vi.advanceTimersByTime(1_000);
80+
const b1 = create(B);
81+
registry.terminateSession(a1, A);
82+
vi.advanceTimersByTime(1_000);
83+
registry.touchSession(a1);
84+
85+
const ids = (opts?: Parameters<Registry['listSessions']>[0]) =>
86+
registry.listSessions(opts).map((s) => s.sessionId);
87+
88+
expect(ids()).toEqual([a1, b1, a2]);
89+
expect(ids({ origin: A })).toEqual([a1, a2]);
90+
expect(ids({ origin: B })).toEqual([b1]);
91+
expect(ids({ origin: 'https://none.example' })).toEqual([]);
92+
expect(ids({ status: 'terminated' })).toEqual([a1]);
93+
expect(ids({ status: 'active' })).toEqual([b1, a2]);
94+
expect(ids({ activeOnly: true })).toEqual([b1, a2]);
95+
expect(ids({ origin: A, activeOnly: true })).toEqual([a2]);
96+
// 'explicit' is the only session type the registry produces.
97+
expect(ids({ type: 'explicit' })).toEqual([a1, b1, a2]);
98+
// The type arrives untyped from runtime messages; an unknown type matches nothing.
99+
expect(ids({ type: 'implicit' as never })).toEqual([]);
100+
});
101+
102+
it('returns summaries, not the sessions themselves', () => {
103+
create(A);
104+
const [summary] = registry.listSessions();
105+
expect(Object.keys(summary).sort()).toEqual(
106+
['capabilities', 'createdAt', 'lastActiveAt', 'name', 'origin', 'sessionId', 'status', 'type', 'usage'].sort(),
107+
);
108+
expect(summary.capabilities).toEqual({ hasLLM: true, hasBrowserAccess: false });
109+
});
110+
});

0 commit comments

Comments
 (0)