ompchamber 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/index.html +1 -1
- package/dist/client/index.js +279 -280
- package/dist/client/static/js/index-01dv383b.css +1 -0
- package/dist/client/static/js/{index-qhzsybkn.js → index-1q6165r3.js} +641 -641
- package/package.json +1 -1
- package/src/cli/lib/output.js +15 -8
- package/src/client/components/common/Modal.tsx +14 -4
- package/src/client/components/{layout/session-sidebar/SubagentList.tsx → common/subagent-list/index.tsx} +8 -10
- package/src/client/components/layout/session-sidebar/CategoryItem.tsx +6 -30
- package/src/client/components/layout/session-sidebar/Toolbar.tsx +11 -5
- package/src/client/components/layout/session-sidebar/index.tsx +4 -2
- package/src/client/components/mobile/LayoutWrapper.tsx +6 -0
- package/src/client/components/mobile/SessionSidebar.tsx +4 -0
- package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +66 -29
- package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +50 -12
- package/src/client/components/mobile/mobile-session-sidebar/Toolbar.tsx +21 -1
- package/src/client/components/settings/Modal.tsx +35 -6
- package/src/client/components/settings/SettingsSidebarList.tsx +1 -1
- package/src/client/components/settings/categories/AgentSettings.tsx +45 -28
- package/src/client/components/settings/categories/CommandSettings.tsx +45 -28
- package/src/client/components/settings/categories/McpSettings.tsx +48 -31
- package/src/client/components/settings/categories/ProjectSettings.tsx +34 -19
- package/src/client/components/settings/categories/ProviderSettings.tsx +77 -53
- package/src/client/components/settings/categories/SkillSettings.tsx +34 -17
- package/src/client/components/settings/categories/UsageSettings.tsx +53 -39
- package/src/client/components/settings/categories/behavior-settings/Editor.tsx +7 -7
- package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +1 -1
- package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +1 -1
- package/src/client/components/settings/categories/project-settings/SidebarList.tsx +1 -1
- package/src/client/components/settings/categories/provider-settings/AuthSection.tsx +8 -3
- package/src/client/components/settings/categories/provider-settings/DeleteProviderModal.tsx +1 -1
- package/src/client/components/settings/categories/provider-settings/ModelsList.tsx +9 -4
- package/src/client/components/settings/categories/provider-settings/SidebarList.tsx +1 -1
- package/src/client/components/settings/categories/skill-catalog/AddSourceModal.tsx +1 -1
- package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +1 -1
- package/src/client/components/settings/categories/usage-settings/SidebarList.tsx +1 -1
- package/src/client/components/settings/master-detail/index.tsx +68 -0
- package/src/client/components/workspace/SearchPanel.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/SubagentView.tsx +7 -1
- package/src/client/components/workspace/chat-timeline/SystemNotice.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/TaskResultContent.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/index.tsx +1 -0
- package/src/client/components/workspace/chat-timeline/tool-renderers/hashline-patch/index.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/AstEdit.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Edit.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/SearchTool.tsx +2 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.tsx +2 -1
- package/src/client/components/workspace/diff-panel/SplitView.tsx +31 -5
- package/src/client/components/workspace/diff-panel/Toolbar.tsx +77 -6
- package/src/client/components/workspace/diff-panel/UnifiedView.tsx +18 -5
- package/src/client/components/workspace/diff-panel/index.tsx +36 -7
- package/src/client/components/workspace/editor/Toolbar.tsx +11 -4
- package/src/client/components/workspace/git-panel/commit-modal/CommitDiffViewer.tsx +2 -1
- package/src/client/hooks/chat/omp/session-list.tsx +31 -1
- package/src/client/hooks/chat/omp/session-sidebar-controller.ts +7 -1
- package/src/client/hooks/chat/subagent/index.ts +37 -11
- package/src/client/hooks/editor/use-file-editor.ts +1 -1
- package/src/client/hooks/settings/master-detail.ts +33 -0
- package/src/client/hooks/workspace/expanded-sessions.ts +62 -0
- package/src/server/lib/db/client.ts +5 -1
- package/src/server/lib/fs/git-diff.ts +34 -10
- package/src/server/lib/fs/git-repos.ts +81 -0
- package/src/server/lib/lifecycle/flock.ts +199 -0
- package/src/server/lib/lifecycle/identity.ts +5 -1
- package/src/server/lib/lifecycle/port-guard.ts +18 -3
- package/src/server/lib/lifecycle/proc/darwin.ts +52 -17
- package/src/server/lib/lifecycle/proc/linux.ts +29 -7
- package/src/server/lib/lifecycle/proc/ps.ts +7 -0
- package/src/server/lib/lifecycle/proc/types.ts +17 -0
- package/src/server/lib/lifecycle/proc/win32.ts +5 -0
- package/src/server/lib/observer-ws.ts +150 -0
- package/src/server/lib/omp/rpc/constants.ts +9 -0
- package/src/server/lib/omp/rpc/subagent-liveness.ts +2 -12
- package/src/server/lib/omp/session/file-scan.ts +7 -1
- package/src/server/lib/omp/session/files.ts +95 -96
- package/src/server/lib/omp/session/locator.ts +18 -8
- package/src/server/lib/omp/session/messages.ts +7 -7
- package/src/server/lib/omp/session/scan.ts +108 -0
- package/src/server/lib/omp/session/stats.ts +50 -50
- package/src/server/lib/omp/session/telemetry/scan.ts +89 -7
- package/src/server/lib/omp/session/telemetry-raw.ts +24 -8
- package/src/server/lib/omp/session/usage/aggregate.ts +170 -55
- package/src/server/lib/terminal/runtime.server.ts +3 -0
- package/src/server/lib/terminal/session.server.ts +30 -3
- package/src/server/routes/agent/command.test.ts +69 -0
- package/src/server/routes/agent/command.ts +14 -0
- package/src/server/routes/agent/ws.test.ts +159 -0
- package/src/server/routes/agent/ws.ts +22 -97
- package/src/server/routes/btw/ws.ts +22 -95
- package/src/server/routes/fs/git.ts +61 -70
- package/src/server/routes/omp/session-stats.ts +1 -1
- package/src/server/routes/telemetry/tokens.ts +6 -4
- package/src/server/routes/terminal/run.ts +4 -8
- package/src/server/routes/terminal/ws.ts +24 -2
- package/src/shared/lib/chat/omp/agent-events.test.ts +33 -1
- package/src/shared/lib/chat/omp/agent-events.ts +10 -0
- package/src/shared/lib/code/language.ts +146 -0
- package/src/shared/lib/code/syntax-highlight.test.ts +2 -1
- package/src/shared/lib/code/syntax-highlight.ts +0 -122
- package/src/shared/lib/fs/diff-parser.test.ts +5 -5
- package/src/shared/lib/fs/diff-parser.ts +67 -42
- package/src/shared/lib/omp/subagent/parse.test.ts +88 -0
- package/src/shared/lib/omp/subagent/parse.ts +17 -0
- package/src/shared/lib/omp/subagent/transcript-client.test.ts +100 -0
- package/src/shared/lib/omp/subagent/transcript-client.ts +17 -1
- package/src/shared/types/omp/subagent.ts +6 -0
- package/dist/client/static/js/index-5yfre1kw.css +0 -1
|
@@ -273,6 +273,9 @@ export function forgetTerminal(id: string): void {
|
|
|
273
273
|
if (!session) return;
|
|
274
274
|
sessions.delete(id);
|
|
275
275
|
clearPendingResize(id);
|
|
276
|
+
// Close each viewer's socket, not just forget it: the record is going away,
|
|
277
|
+
// so a socket left open would sit on a terminal that can never answer it.
|
|
278
|
+
for (const viewer of session.viewers) viewer.drop();
|
|
276
279
|
session.viewers.clear();
|
|
277
280
|
if (session.status === 'running') signalGroup(session, 'SIGKILL');
|
|
278
281
|
closeTerminalStream(session);
|
|
@@ -41,7 +41,15 @@ export const TERMINATION_GRACE_MS = 1000;
|
|
|
41
41
|
|
|
42
42
|
/** A socket attached to a terminal. Output is raw PTY bytes; control is JSON. */
|
|
43
43
|
export interface TerminalViewer {
|
|
44
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Deliver one frame. Returns false when the viewer could not accept it —
|
|
46
|
+
* the socket's send buffer is over its high-water mark — which the session
|
|
47
|
+
* treats as "this viewer is gone": a PTY producer cannot be paused, so the
|
|
48
|
+
* alternative is buffering unbounded output in a socket nobody is reading.
|
|
49
|
+
*/
|
|
50
|
+
send(frame: string | Uint8Array): boolean;
|
|
51
|
+
/** Detach this viewer. Called when `send` reports it cannot keep up. */
|
|
52
|
+
drop(): void;
|
|
45
53
|
}
|
|
46
54
|
|
|
47
55
|
export interface TerminalSession {
|
|
@@ -63,6 +71,25 @@ export interface TerminalSession {
|
|
|
63
71
|
lastActivity: number;
|
|
64
72
|
}
|
|
65
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Deliver `frame` to every viewer, dropping the ones that cannot keep up.
|
|
76
|
+
*
|
|
77
|
+
* `Bun.ServerWebSocket.send` returns the bytes queued, or `-1` when the socket
|
|
78
|
+
* is over its high-water mark and the frame was NOT sent (verified on 1.4.2:
|
|
79
|
+
* 40 sends of 1 MiB to a socket nobody reads all return `-1`). A viewer that
|
|
80
|
+
* reports `-1` is closed rather than skipped — skipping would leave xterm's
|
|
81
|
+
* parser mid-sequence, so the honest outcome is a reconnect that replays the
|
|
82
|
+
* scrollback. The PTY cannot be paused, so this is the only backpressure a
|
|
83
|
+
* terminal has.
|
|
84
|
+
*/
|
|
85
|
+
export function fanOut(session: TerminalSession, frame: string | Uint8Array): void {
|
|
86
|
+
for (const viewer of session.viewers) {
|
|
87
|
+
if (viewer.send(frame)) continue;
|
|
88
|
+
session.viewers.delete(viewer);
|
|
89
|
+
viewer.drop();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
66
93
|
/** A rejected attach, carrying the code the client shows to the user. */
|
|
67
94
|
export class TerminalRuntimeError extends Error {
|
|
68
95
|
constructor(
|
|
@@ -118,7 +145,7 @@ export async function createSession(request: AttachRequest): Promise<TerminalSes
|
|
|
118
145
|
data(_term, bytes) {
|
|
119
146
|
session.history.append(bytes);
|
|
120
147
|
session.lastActivity = Date.now();
|
|
121
|
-
|
|
148
|
+
fanOut(session, bytes);
|
|
122
149
|
},
|
|
123
150
|
});
|
|
124
151
|
session.term = term;
|
|
@@ -145,7 +172,7 @@ export async function createSession(request: AttachRequest): Promise<TerminalSes
|
|
|
145
172
|
session.signal = proc.signalCode ?? null;
|
|
146
173
|
session.lastActivity = Date.now();
|
|
147
174
|
const frame = JSON.stringify({ t: 'exit', exitCode: session.exitCode, signal: session.signal });
|
|
148
|
-
|
|
175
|
+
fanOut(session, frame);
|
|
149
176
|
});
|
|
150
177
|
|
|
151
178
|
return session;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The spawn guard on POST /api/agent/:sessionId.
|
|
8
|
+
*
|
|
9
|
+
* This route is the chamber's ONLY lazy-spawn path: a command posted for a
|
|
10
|
+
* session it does not manage starts an `omp` child for it. That is right for a
|
|
11
|
+
* prompt — the user asked for work — and wrong for a read. The sidebar renders
|
|
12
|
+
* a subagent roster row for every session in the list, and the roster probes
|
|
13
|
+
* `get_subagents` to seed itself, so an unguarded route booted a whole omp
|
|
14
|
+
* process per finished session merely LOOKED at (measured: the process count
|
|
15
|
+
* grew on a session whose liveness probe had just answered `running: false`).
|
|
16
|
+
*
|
|
17
|
+
* Both observer-only commands have RPC-free on-disk equivalents, which is what
|
|
18
|
+
* a finished session is served from, so refusing them for a dead session costs
|
|
19
|
+
* the client nothing.
|
|
20
|
+
*
|
|
21
|
+
* No module is mocked. The assertions are about which response comes back
|
|
22
|
+
* BEFORE the spawn path is reached, so the real registry (empty for these ids)
|
|
23
|
+
* and the real on-disk resolver are exactly the inputs that matter. The
|
|
24
|
+
* "prompt" case proves the guard is not a blanket refusal: it reaches the
|
|
25
|
+
* resolver and 404s for an id with no session file — a spawn was attempted.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { describe, expect, test } from 'bun:test';
|
|
29
|
+
import { sendCommand } from '@/server/routes/agent/command';
|
|
30
|
+
|
|
31
|
+
/** Ids that no chamber instance manages and no session file backs. */
|
|
32
|
+
const DEAD = 'spawn-guard-dead-session';
|
|
33
|
+
const UNKNOWN = 'spawn-guard-unknown-session';
|
|
34
|
+
|
|
35
|
+
function post(sessionId: string, body: Record<string, unknown>): Promise<Response> {
|
|
36
|
+
return sendCommand({
|
|
37
|
+
params: { sessionId },
|
|
38
|
+
request: new Request(`http://localhost/api/agent/${sessionId}`, {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: { 'Content-Type': 'application/json' },
|
|
41
|
+
body: JSON.stringify(body),
|
|
42
|
+
}),
|
|
43
|
+
} as never) as Promise<Response>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function payload(response: Response): Promise<Record<string, unknown>> {
|
|
47
|
+
return (await response.json()) as Record<string, unknown>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe('agent command spawn guard', () => {
|
|
51
|
+
test('refuses a roster snapshot for a session that is not running', async () => {
|
|
52
|
+
const response = await post(DEAD, { type: 'get_subagents' });
|
|
53
|
+
expect(response.status).toBe(409);
|
|
54
|
+
expect(await payload(response)).toMatchObject({ code: 'session_not_running' });
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('refuses a transcript page for a session that is not running', async () => {
|
|
58
|
+
const response = await post(DEAD, { type: 'get_subagent_messages', subagentId: 'child' });
|
|
59
|
+
expect(response.status).toBe(409);
|
|
60
|
+
expect(await payload(response)).toMatchObject({ code: 'session_not_running' });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('does not refuse a command that asks for work', async () => {
|
|
64
|
+
const response = await post(UNKNOWN, { type: 'prompt', message: 'hello' });
|
|
65
|
+
// It reached the spawn path and failed there (no session file on disk),
|
|
66
|
+
// which is the opposite of the guard's 409.
|
|
67
|
+
expect(response.status).not.toBe(409);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
@@ -5,6 +5,7 @@ import { WebRpcError, getRpcSession, resolveSpawnCwd, startRpcSession, type Agen
|
|
|
5
5
|
import { getSpawnApprovalMode, reconcileSpawnApprovalMode } from '@/server/lib/omp/rpc/session-registry';
|
|
6
6
|
import { isApprovalMode } from '@/shared/lib/omp/config/access-mode';
|
|
7
7
|
import { loadPersistedAccessMode } from '@/shared/lib/omp/config/access-mode.server';
|
|
8
|
+
import { OBSERVER_ONLY_COMMANDS } from '@/server/lib/omp/rpc/constants';
|
|
8
9
|
import { rpcErrorResponse } from '@/server/lib/omp/rpc/errors';
|
|
9
10
|
|
|
10
11
|
// POST /api/agent/:sessionId — send a command to an existing session (or spawn
|
|
@@ -39,6 +40,19 @@ export async function sendCommand({ params, request }: ActionFunctionArgs) {
|
|
|
39
40
|
}
|
|
40
41
|
}
|
|
41
42
|
|
|
43
|
+
// Observer-only reads must never boot an omp child. This route is the spawn
|
|
44
|
+
// path, so a roster snapshot (`get_subagents`) or a transcript page
|
|
45
|
+
// (`get_subagent_messages`) posted for a session the chamber is not
|
|
46
|
+
// managing would start a whole process just to answer a read — measured:
|
|
47
|
+
// opening a FINISHED session's roster row grew the omp process count, and
|
|
48
|
+
// the sidebar renders those rows for every session in the list. Both reads
|
|
49
|
+
// have RPC-free on-disk equivalents (`GET /api/sessions/:id/subagents[/:sub]`),
|
|
50
|
+
// which is what a dead session is served from; the live registry is only
|
|
51
|
+
// consulted while a process exists to answer for.
|
|
52
|
+
if (OBSERVER_ONLY_COMMANDS.has(body.type)) {
|
|
53
|
+
return json({ error: 'Session is not managed by the chamber', code: 'session_not_running' }, { status: 409 });
|
|
54
|
+
}
|
|
55
|
+
|
|
42
56
|
const resolved = await resolveSessionPathOr404(sessionId);
|
|
43
57
|
if ('response' in resolved) return resolved.response;
|
|
44
58
|
const { filePath, recordedCwd } = resolved;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Regression test for the observer WebSocket routes' connection state.
|
|
8
|
+
*
|
|
9
|
+
* The bug this pins: `agent/ws.ts` and `btw/ws.ts` kept per-connection state in
|
|
10
|
+
* a `WeakMap` keyed by the `ws` object. Elysia's Bun adapter builds a NEW
|
|
11
|
+
* `ElysiaWS` wrapper for every callback and hands `pong` the RAW socket, so
|
|
12
|
+
* every lookup missed — the pong never cleared `awaitingPong`, the second
|
|
13
|
+
* heartbeat tore down a socket the client was still reading, and `close` leaked
|
|
14
|
+
* the interval and the session subscription for the life of the process.
|
|
15
|
+
*
|
|
16
|
+
* These assertions run through a real listener on purpose: the failure lived in
|
|
17
|
+
* the framework's callback identity, which a unit-level fake of `ws` cannot
|
|
18
|
+
* reproduce. That also makes the heartbeat a REAL timer here — the property
|
|
19
|
+
* under test is "the socket outlives N keepalive cycles", so the clock is the
|
|
20
|
+
* thing being measured. The interval is shrunk to 60ms to keep it cheap.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
|
|
24
|
+
import { Elysia } from 'elysia';
|
|
25
|
+
|
|
26
|
+
/** Heartbeat for the test — several beats must fit inside a test timeout. */
|
|
27
|
+
const HEARTBEAT_MS = 60;
|
|
28
|
+
|
|
29
|
+
// The route reads the cadence constant at module scope, so the module is
|
|
30
|
+
// replaced BEFORE the route module is imported.
|
|
31
|
+
mock.module('@/shared/lib/workspace/refresh-cadence', () => ({
|
|
32
|
+
STREAM_HEARTBEAT_MS: HEARTBEAT_MS,
|
|
33
|
+
SIDEBAR_IDLE_REFRESH_MS: 30_000,
|
|
34
|
+
SIDEBAR_STREAM_POLL_MS: 8_000,
|
|
35
|
+
SIDEBAR_REVALIDATE_THROTTLE_MS: 1_000,
|
|
36
|
+
PANEL_REFRESH_MS: 5_000,
|
|
37
|
+
FILE_MUTATION_THROTTLE_MS: 500,
|
|
38
|
+
GIT_STATUS_POLL_MS: 15_000,
|
|
39
|
+
GIT_STATUS_EVENT_THROTTLE_MS: 1_000,
|
|
40
|
+
REPO_DISCOVERY_POLL_MS: 1_500,
|
|
41
|
+
TODO_REFRESH_EVENT_THROTTLE_MS: 400,
|
|
42
|
+
BROWSER_POLL_MS: 1_000,
|
|
43
|
+
SIDEBAR_DATA_TTL_MS: 4_000,
|
|
44
|
+
SESSION_META_RETRY_SCHEDULE_MS: [250],
|
|
45
|
+
}));
|
|
46
|
+
|
|
47
|
+
const { agentWsRoutes } = await import('@/server/routes/agent/ws');
|
|
48
|
+
|
|
49
|
+
/** The live session the route subscribes to; records its own lifecycle. */
|
|
50
|
+
interface SessionStub {
|
|
51
|
+
isAlive: () => boolean;
|
|
52
|
+
onEvent: (listener: (event: unknown) => void) => () => void;
|
|
53
|
+
listeners: Set<(event: unknown) => void>;
|
|
54
|
+
unsubscribes: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function makeSession(): SessionStub {
|
|
58
|
+
const stub: SessionStub = {
|
|
59
|
+
isAlive: () => true,
|
|
60
|
+
listeners: new Set(),
|
|
61
|
+
unsubscribes: 0,
|
|
62
|
+
onEvent(listener) {
|
|
63
|
+
stub.listeners.add(listener);
|
|
64
|
+
return () => {
|
|
65
|
+
stub.unsubscribes += 1;
|
|
66
|
+
stub.listeners.delete(listener);
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
return stub;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
let session = makeSession();
|
|
74
|
+
const app = new Elysia().use(agentWsRoutes);
|
|
75
|
+
let baseUrl = '';
|
|
76
|
+
|
|
77
|
+
beforeAll(async () => {
|
|
78
|
+
(globalThis as { __ompSessions?: unknown }).__ompSessions = {
|
|
79
|
+
get: (id: string) => (id === 'test-session' ? session : undefined),
|
|
80
|
+
};
|
|
81
|
+
await app.listen({ port: 0, hostname: '127.0.0.1' });
|
|
82
|
+
const port = (app.server as { port?: number } | null)?.port;
|
|
83
|
+
if (!port) throw new Error('test listener did not report a port');
|
|
84
|
+
baseUrl = `ws://127.0.0.1:${port}`;
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
afterAll(async () => {
|
|
88
|
+
await app.stop();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
92
|
+
|
|
93
|
+
/** One client, its received frames, and the promises for its lifecycle. */
|
|
94
|
+
function connect(sessionId: string) {
|
|
95
|
+
const frames: unknown[] = [];
|
|
96
|
+
const client = new WebSocket(`${baseUrl}/api/agent/${sessionId}/ws`);
|
|
97
|
+
const opened = Promise.withResolvers<void>();
|
|
98
|
+
const closed = Promise.withResolvers<number>();
|
|
99
|
+
client.onopen = () => opened.resolve();
|
|
100
|
+
client.onmessage = (event) => {
|
|
101
|
+
try {
|
|
102
|
+
frames.push(JSON.parse(String(event.data)));
|
|
103
|
+
} catch {
|
|
104
|
+
// A non-JSON frame would be a protocol bug; assertions read `frames`.
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
client.onclose = (event) => closed.resolve(event.code);
|
|
108
|
+
return { client, frames, opened: opened.promise, closed: closed.promise };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
describe('agent observer WebSocket', () => {
|
|
112
|
+
test('survives many heartbeats instead of being torn down by its own keepalive', async () => {
|
|
113
|
+
session = makeSession();
|
|
114
|
+
const { client, closed } = connect('test-session');
|
|
115
|
+
// Five beats: the old code closed the socket at the second one.
|
|
116
|
+
await sleep(HEARTBEAT_MS * 5);
|
|
117
|
+
expect(client.readyState).toBe(WebSocket.OPEN);
|
|
118
|
+
client.close();
|
|
119
|
+
await closed;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('delivers the connected greeting and live session frames', async () => {
|
|
123
|
+
session = makeSession();
|
|
124
|
+
const { client, frames, opened, closed } = connect('test-session');
|
|
125
|
+
await opened;
|
|
126
|
+
for (const listener of session.listeners) listener({ type: 'agent_start' });
|
|
127
|
+
await sleep(30);
|
|
128
|
+
expect(frames).toEqual([
|
|
129
|
+
{ type: 'connected', sessionId: 'test-session' },
|
|
130
|
+
{ type: 'agent_start' },
|
|
131
|
+
]);
|
|
132
|
+
client.close();
|
|
133
|
+
await closed;
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('releases the session subscription when the client disconnects', async () => {
|
|
137
|
+
session = makeSession();
|
|
138
|
+
const { client, opened, closed } = connect('test-session');
|
|
139
|
+
await opened;
|
|
140
|
+
expect(session.listeners.size).toBe(1);
|
|
141
|
+
client.close();
|
|
142
|
+
await closed;
|
|
143
|
+
await sleep(30);
|
|
144
|
+
expect(session.unsubscribes).toBe(1);
|
|
145
|
+
expect(session.listeners.size).toBe(0);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test('refuses a session the chamber does not manage', async () => {
|
|
149
|
+
const { opened, closed, client } = connect('unknown-session');
|
|
150
|
+
const outcome = await Promise.race([
|
|
151
|
+
opened.then(() => 'opened' as const),
|
|
152
|
+
closed.then(() => 'closed' as const),
|
|
153
|
+
sleep(400).then(() => 'timeout' as const),
|
|
154
|
+
]);
|
|
155
|
+
// The upgrade is rejected before `open` runs, so the client never opens.
|
|
156
|
+
expect(outcome).not.toBe('opened');
|
|
157
|
+
client.close();
|
|
158
|
+
});
|
|
159
|
+
});
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Same frame vocabulary (JSON objects with a `type`, first frame `connected`),
|
|
11
11
|
* same backpressure policy (replaceable `message_update` frames collapse to the
|
|
12
|
-
* latest one while the client is behind) — the policy itself
|
|
12
|
+
* latest one while the client is behind) — the policy itself lives in
|
|
13
13
|
* `createEventCoalescer`, shared with the SSE route — but carried by one duplex
|
|
14
14
|
* socket: no per-event HTTP framing, no browser reconnect storm, and
|
|
15
15
|
* protocol-level ping/pong keepalive instead of a comment frame every 30s.
|
|
@@ -17,18 +17,18 @@
|
|
|
17
17
|
* Transport-only by design. It reads the live session registry off `globalThis`
|
|
18
18
|
* (the map the server build populates) and duck-types the wrapper, so the
|
|
19
19
|
* registry contract survives any HTTP framework owning the port.
|
|
20
|
+
*
|
|
21
|
+
* **Per-connection state lives on `ws.data`, not in a `WeakMap` keyed by the
|
|
22
|
+
* `ws` object.** Elysia's Bun adapter builds a fresh wrapper per callback and
|
|
23
|
+
* hands `pong` the raw socket, so a WeakMap lookup always missed: the pong
|
|
24
|
+
* never cleared `awaitingPong` and the second heartbeat closed a healthy
|
|
25
|
+
* socket at 60s, while `close` leaked the interval and the session
|
|
26
|
+
* subscription. `attachObserverStream` owns the lifecycle; see
|
|
27
|
+
* `@/server/lib/observer-ws` for the measurements.
|
|
20
28
|
*/
|
|
21
29
|
|
|
22
30
|
import { Elysia, t } from 'elysia';
|
|
23
|
-
import {
|
|
24
|
-
import { STREAM_HEARTBEAT_MS } from '@/shared/lib/workspace/refresh-cadence';
|
|
25
|
-
|
|
26
|
-
/** Coalesce `message_update` frames once this many bytes sit unsent. */
|
|
27
|
-
const HIGH_WATER_BYTES = 256 * 1024;
|
|
28
|
-
|
|
29
|
-
/** Longest a coalesced frame may wait before it is flushed anyway, so a burst
|
|
30
|
-
* that ends while the socket is still busy never strands the newest update. */
|
|
31
|
-
const FLUSH_DELAY_MS = 50;
|
|
31
|
+
import { attachObserverStream, createObserverState, type ObserverConnectionState } from '@/server/lib/observer-ws';
|
|
32
32
|
|
|
33
33
|
interface AgentEventSession {
|
|
34
34
|
isAlive?: () => boolean;
|
|
@@ -48,15 +48,8 @@ function findAgentSession(sessionId: string): AgentEventSession | null {
|
|
|
48
48
|
return session;
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
unsubscribe: (() => void) | null;
|
|
54
|
-
heartbeat: ReturnType<typeof setInterval> | null;
|
|
55
|
-
awaitingPong: boolean;
|
|
56
|
-
coalescer: EventCoalescer | null;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const connections = new WeakMap<object, ConnectionState>();
|
|
51
|
+
/** Elysia's ws context, narrowed to the per-connection store this route adds. */
|
|
52
|
+
type AgentWsData = { params: { sessionId: string }; observer?: ObserverConnectionState };
|
|
60
53
|
|
|
61
54
|
export const agentWsRoutes = new Elysia({ prefix: '/api/agent' }).ws('/:sessionId/ws', {
|
|
62
55
|
params: t.Object({ sessionId: t.String() }),
|
|
@@ -68,81 +61,24 @@ export const agentWsRoutes = new Elysia({ prefix: '/api/agent' }).ws('/:sessionI
|
|
|
68
61
|
},
|
|
69
62
|
|
|
70
63
|
open(ws) {
|
|
71
|
-
const
|
|
64
|
+
const data = ws.data as unknown as AgentWsData;
|
|
65
|
+
const sessionId = data.params.sessionId;
|
|
72
66
|
const session = findAgentSession(sessionId);
|
|
73
67
|
if (!session) {
|
|
74
68
|
ws.close();
|
|
75
69
|
return;
|
|
76
70
|
}
|
|
77
71
|
|
|
78
|
-
const state
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
heartbeat: null,
|
|
82
|
-
awaitingPong: false,
|
|
83
|
-
coalescer: null,
|
|
84
|
-
};
|
|
85
|
-
connections.set(ws, state);
|
|
72
|
+
const state = createObserverState();
|
|
73
|
+
data.observer = state;
|
|
74
|
+
const { push } = attachObserverStream(state, ws);
|
|
86
75
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
state.closed = true;
|
|
90
|
-
state.coalescer?.dispose();
|
|
91
|
-
state.coalescer = null;
|
|
92
|
-
if (state.heartbeat !== null) {
|
|
93
|
-
clearInterval(state.heartbeat);
|
|
94
|
-
state.heartbeat = null;
|
|
95
|
-
}
|
|
96
|
-
if (state.unsubscribe) {
|
|
97
|
-
try {
|
|
98
|
-
state.unsubscribe();
|
|
99
|
-
} catch {
|
|
100
|
-
// Subscriber cleanup is best-effort.
|
|
101
|
-
}
|
|
102
|
-
state.unsubscribe = null;
|
|
103
|
-
}
|
|
104
|
-
try {
|
|
105
|
-
ws.close();
|
|
106
|
-
} catch {
|
|
107
|
-
// Already gone.
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
state.coalescer = createEventCoalescer({
|
|
112
|
-
send: (_event, data) => {
|
|
113
|
-
try {
|
|
114
|
-
ws.send(JSON.stringify(data));
|
|
115
|
-
} catch {
|
|
116
|
-
teardown();
|
|
117
|
-
}
|
|
118
|
-
},
|
|
119
|
-
isBackpressured: () => ((ws.raw as { bufferedAmount?: number }).bufferedAmount ?? 0) > HIGH_WATER_BYTES,
|
|
120
|
-
flushDelayMs: FLUSH_DELAY_MS,
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
// Protocol-level keepalive: a client that misses a full ping cycle is gone,
|
|
124
|
-
// and a live one answers without any application-level traffic.
|
|
125
|
-
state.heartbeat = setInterval(() => {
|
|
126
|
-
if (state.closed) return;
|
|
127
|
-
if (state.awaitingPong) {
|
|
128
|
-
teardown();
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
state.awaitingPong = true;
|
|
132
|
-
if (!state.coalescer?.flush()) return;
|
|
133
|
-
try {
|
|
134
|
-
(ws.raw as { ping?: () => void }).ping?.();
|
|
135
|
-
} catch {
|
|
136
|
-
teardown();
|
|
137
|
-
}
|
|
138
|
-
}, STREAM_HEARTBEAT_MS);
|
|
139
|
-
|
|
140
|
-
state.unsubscribe = session.onEvent((event) => state.coalescer?.push('', event));
|
|
141
|
-
state.coalescer.push('', { type: 'connected', sessionId });
|
|
76
|
+
state.unsubscribe = session.onEvent((event) => push('', event));
|
|
77
|
+
push('', { type: 'connected', sessionId });
|
|
142
78
|
},
|
|
143
79
|
|
|
144
80
|
pong(ws) {
|
|
145
|
-
const state =
|
|
81
|
+
const state = (ws.data as unknown as AgentWsData).observer;
|
|
146
82
|
if (state) state.awaitingPong = false;
|
|
147
83
|
},
|
|
148
84
|
|
|
@@ -151,18 +87,7 @@ export const agentWsRoutes = new Elysia({ prefix: '/api/agent' }).ws('/:sessionI
|
|
|
151
87
|
},
|
|
152
88
|
|
|
153
89
|
close(ws) {
|
|
154
|
-
const state =
|
|
155
|
-
if (
|
|
156
|
-
state.closed = true;
|
|
157
|
-
state.coalescer?.dispose();
|
|
158
|
-
state.coalescer = null;
|
|
159
|
-
if (state.heartbeat !== null) clearInterval(state.heartbeat);
|
|
160
|
-
if (state.unsubscribe) {
|
|
161
|
-
try {
|
|
162
|
-
state.unsubscribe();
|
|
163
|
-
} catch {
|
|
164
|
-
// Subscriber cleanup is best-effort.
|
|
165
|
-
}
|
|
166
|
-
}
|
|
90
|
+
const state = (ws.data as unknown as AgentWsData).observer;
|
|
91
|
+
if (state) state.teardown();
|
|
167
92
|
},
|
|
168
93
|
});
|
|
@@ -12,105 +12,43 @@
|
|
|
12
12
|
* A client that attaches replays nothing: the socket's first `btw_state` is
|
|
13
13
|
* the session's current history, so a reload lands on the same panel a live
|
|
14
14
|
* stream would have produced.
|
|
15
|
+
*
|
|
16
|
+
* **Per-connection state lives on `ws.data`, not in a `WeakMap` keyed by the
|
|
17
|
+
* `ws` object** — Elysia's Bun adapter hands `pong` the raw socket and a fresh
|
|
18
|
+
* wrapper to every other callback, so a WeakMap lookup always missed and the
|
|
19
|
+
* second heartbeat closed a healthy socket. See `@/server/lib/observer-ws`.
|
|
15
20
|
*/
|
|
16
21
|
|
|
17
22
|
import { Elysia, t } from 'elysia';
|
|
18
|
-
import {
|
|
19
|
-
import { STREAM_HEARTBEAT_MS } from '@/shared/lib/workspace/refresh-cadence';
|
|
23
|
+
import { attachObserverStream, createObserverState, type ObserverConnectionState } from '@/server/lib/observer-ws';
|
|
20
24
|
import { btwStateFor, subscribeBtw } from '@/server/lib/btw/registry.server';
|
|
21
25
|
import type { BtwFrame } from '@/shared/types';
|
|
22
26
|
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
/** Longest a coalesced frame may wait before it is flushed anyway. */
|
|
27
|
-
const FLUSH_DELAY_MS = 50;
|
|
28
|
-
|
|
29
|
-
interface ConnectionState {
|
|
30
|
-
closed: boolean;
|
|
31
|
-
unsubscribe: (() => void) | null;
|
|
32
|
-
heartbeat: ReturnType<typeof setInterval> | null;
|
|
33
|
-
awaitingPong: boolean;
|
|
34
|
-
coalescer: EventCoalescer | null;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const connections = new WeakMap<object, ConnectionState>();
|
|
27
|
+
/** Elysia's ws context, narrowed to the per-connection store this route adds. */
|
|
28
|
+
type BtwWsData = { params: { sessionId: string }; observer?: ObserverConnectionState };
|
|
38
29
|
|
|
39
30
|
export const btwWsRoutes = new Elysia({ prefix: '/api/btw' }).ws('/:sessionId/ws', {
|
|
40
31
|
params: t.Object({ sessionId: t.String() }),
|
|
41
32
|
|
|
42
33
|
open(ws) {
|
|
43
|
-
const
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (state.closed) return;
|
|
53
|
-
state.closed = true;
|
|
54
|
-
state.coalescer?.dispose();
|
|
55
|
-
state.coalescer = null;
|
|
56
|
-
if (state.heartbeat !== null) {
|
|
57
|
-
clearInterval(state.heartbeat);
|
|
58
|
-
state.heartbeat = null;
|
|
59
|
-
}
|
|
60
|
-
if (state.unsubscribe) {
|
|
61
|
-
try {
|
|
62
|
-
state.unsubscribe();
|
|
63
|
-
} catch {
|
|
64
|
-
// Subscriber cleanup is best-effort.
|
|
65
|
-
}
|
|
66
|
-
state.unsubscribe = null;
|
|
67
|
-
}
|
|
68
|
-
try {
|
|
69
|
-
ws.close();
|
|
70
|
-
} catch {
|
|
71
|
-
// Already gone.
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
state.coalescer = createEventCoalescer({
|
|
76
|
-
send: (_event, data) => {
|
|
77
|
-
try {
|
|
78
|
-
ws.send(JSON.stringify(data));
|
|
79
|
-
} catch {
|
|
80
|
-
teardown();
|
|
81
|
-
}
|
|
82
|
-
},
|
|
83
|
-
isBackpressured: () => (raw.bufferedAmount ?? 0) > HIGH_WATER_BYTES,
|
|
84
|
-
flushDelayMs: FLUSH_DELAY_MS,
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
state.heartbeat = setInterval(() => {
|
|
88
|
-
if (state.closed) return;
|
|
89
|
-
if (state.awaitingPong) {
|
|
90
|
-
teardown();
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
state.awaitingPong = true;
|
|
94
|
-
if (!state.coalescer?.flush()) return;
|
|
95
|
-
try {
|
|
96
|
-
raw.ping?.();
|
|
97
|
-
} catch {
|
|
98
|
-
teardown();
|
|
99
|
-
}
|
|
100
|
-
}, STREAM_HEARTBEAT_MS);
|
|
101
|
-
|
|
102
|
-
const push = (frame: BtwFrame) => state.coalescer?.push('', frame);
|
|
103
|
-
state.unsubscribe = subscribeBtw(sessionId, push);
|
|
104
|
-
push({ type: 'connected', sessionId });
|
|
34
|
+
const data = ws.data as unknown as BtwWsData;
|
|
35
|
+
const sessionId = data.params.sessionId;
|
|
36
|
+
const state = createObserverState();
|
|
37
|
+
data.observer = state;
|
|
38
|
+
const { push } = attachObserverStream(state, ws);
|
|
39
|
+
|
|
40
|
+
const send = (frame: BtwFrame) => push('', frame);
|
|
41
|
+
state.unsubscribe = subscribeBtw(sessionId, send);
|
|
42
|
+
send({ type: 'connected', sessionId });
|
|
105
43
|
void btwStateFor(sessionId)
|
|
106
|
-
.then((snapshot) =>
|
|
44
|
+
.then((snapshot) => send({ type: 'btw_state', state: snapshot }))
|
|
107
45
|
.catch((error: unknown) => {
|
|
108
|
-
|
|
46
|
+
send({ type: 'btw_error', topicId: null, message: error instanceof Error ? error.message : String(error) });
|
|
109
47
|
});
|
|
110
48
|
},
|
|
111
49
|
|
|
112
50
|
pong(ws) {
|
|
113
|
-
const state =
|
|
51
|
+
const state = (ws.data as unknown as BtwWsData).observer;
|
|
114
52
|
if (state) state.awaitingPong = false;
|
|
115
53
|
},
|
|
116
54
|
|
|
@@ -119,18 +57,7 @@ export const btwWsRoutes = new Elysia({ prefix: '/api/btw' }).ws('/:sessionId/ws
|
|
|
119
57
|
},
|
|
120
58
|
|
|
121
59
|
close(ws) {
|
|
122
|
-
const state =
|
|
123
|
-
if (
|
|
124
|
-
state.closed = true;
|
|
125
|
-
state.coalescer?.dispose();
|
|
126
|
-
state.coalescer = null;
|
|
127
|
-
if (state.heartbeat !== null) clearInterval(state.heartbeat);
|
|
128
|
-
if (state.unsubscribe) {
|
|
129
|
-
try {
|
|
130
|
-
state.unsubscribe();
|
|
131
|
-
} catch {
|
|
132
|
-
// Subscriber cleanup is best-effort.
|
|
133
|
-
}
|
|
134
|
-
}
|
|
60
|
+
const state = (ws.data as unknown as BtwWsData).observer;
|
|
61
|
+
if (state) state.teardown();
|
|
135
62
|
},
|
|
136
63
|
});
|