@myrialabs/clopen 0.4.30 → 0.4.32
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/backend/auth/permissions.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +28 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/engine/README.md +16 -0
- package/backend/engine/adapters/claude/stream.ts +89 -49
- package/backend/engine/adapters/cline/stream.ts +62 -24
- package/backend/engine/adapters/codex/stream.ts +51 -21
- package/backend/engine/adapters/copilot/stream.ts +96 -52
- package/backend/engine/adapters/cursor/stream.ts +74 -34
- package/backend/engine/adapters/opencode/server.ts +512 -126
- package/backend/engine/adapters/opencode/stream.ts +131 -79
- package/backend/engine/adapters/pi/stream.ts +63 -24
- package/backend/engine/adapters/qwen/stream.ts +91 -58
- package/backend/engine/adapters/run-registry.test.ts +75 -0
- package/backend/engine/adapters/run-registry.ts +63 -0
- package/backend/engine/bootstrap-default-engine.ts +67 -38
- package/backend/engine/config-revision.ts +150 -0
- package/backend/engine/docs/adapter-contract.md +40 -9
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/frontend-and-chat.md +39 -0
- package/backend/engine/docs/lessons-learned.md +70 -0
- package/backend/engine/docs/quick-reference.md +3 -1
- package/backend/engine/engine-cli.ts +313 -0
- package/backend/engine/engine-setup.ts +40 -3
- package/backend/engine/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- package/backend/engine/install-recipes.test.ts +99 -5
- package/backend/engine/install-recipes.ts +47 -11
- package/backend/engine/install-runner.ts +34 -16
- package/backend/engine/stack-project.ts +72 -0
- package/backend/engine/types.ts +17 -5
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +121 -0
- package/backend/git/nested-repos.ts +301 -0
- package/backend/index.ts +7 -0
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/utils/path-enrich.ts +2 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/engine/claude/accounts.ts +9 -4
- package/backend/ws/engine/codex/accounts.ts +8 -17
- package/backend/ws/engine/codex/status.ts +10 -17
- package/backend/ws/engine/copilot/accounts.ts +0 -10
- package/backend/ws/engine/cursor/accounts.ts +0 -10
- package/backend/ws/engine/index.ts +17 -2
- package/backend/ws/engine/opencode/providers.ts +0 -52
- package/backend/ws/files/read.ts +1 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/stack/access.ts +5 -2
- package/dist/assets/{index-DYwQ5bP8.js → index-DSvGoxp2.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-hu17G6tX.js} +1 -1
- package/dist/assets/main-BccclZsC.js +1031 -0
- package/dist/assets/{main-VgdjTBLR.css → main-Ciuw0wF0.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-r0iv2PDz.js +0 -1044
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine config revision — the signal that replaced the "Restart Server" button.
|
|
3
|
+
*
|
|
4
|
+
* Open Code is the only engine that runs as a persistent process, and that
|
|
5
|
+
* process freezes its MCP set, provider list and agent registry at spawn. Every
|
|
6
|
+
* other engine reads its config per turn and needs nothing from this module.
|
|
7
|
+
* Until now the gap was covered by asking the user to press a button, which
|
|
8
|
+
* meant the software only worked correctly for people who knew that a button
|
|
9
|
+
* existed and why.
|
|
10
|
+
*
|
|
11
|
+
* Two pieces live here:
|
|
12
|
+
*
|
|
13
|
+
* 1. `getEngineConfigRevision()` — reads the counter that migration 068's
|
|
14
|
+
* triggers maintain. Everything downstream keys its memoization on this, so
|
|
15
|
+
* correctness never depends on anyone NOTICING a change; a stale cache is
|
|
16
|
+
* impossible because the cache key came from the database.
|
|
17
|
+
*
|
|
18
|
+
* 2. `startEngineConfigWatcher()` — polls the counter so a change can also be
|
|
19
|
+
* ACTED on: warm a replacement server, tell open clients to refetch models.
|
|
20
|
+
* Polling looks unfashionable next to an event bus, but the alternatives are
|
|
21
|
+
* worse here. SQLite triggers cannot call into JS, and hooking the WS
|
|
22
|
+
* dispatch would only catch writes that arrive over WS — missing seeders,
|
|
23
|
+
* migrations, OAuth token refreshes and any future background writer. The
|
|
24
|
+
* query is a single-row read of a two-column table against an in-process
|
|
25
|
+
* SQLite handle; at one per second it is far below the noise floor of
|
|
26
|
+
* everything else this server does, and it cannot be defeated by a write path
|
|
27
|
+
* that forgot to announce itself.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { getDatabase } from '../database';
|
|
31
|
+
import { ws } from '$backend/utils/ws';
|
|
32
|
+
import { debug } from '$shared/utils/logger';
|
|
33
|
+
|
|
34
|
+
/** How often the counter is checked. Only affects reaction latency, never correctness. */
|
|
35
|
+
const POLL_MS = 1000;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Quiet period before a change is acted on.
|
|
39
|
+
*
|
|
40
|
+
* Settings edits arrive in bursts — a user toggling four connectors and adding a
|
|
41
|
+
* provider produces five bumps in as many seconds. Acting on each would spawn
|
|
42
|
+
* and discard four servers to arrive at the same place. Waiting for the burst to
|
|
43
|
+
* settle produces one.
|
|
44
|
+
*/
|
|
45
|
+
const SETTLE_MS = 1500;
|
|
46
|
+
|
|
47
|
+
type ConfigChangeListener = (revision: number) => void;
|
|
48
|
+
|
|
49
|
+
const listeners = new Set<ConfigChangeListener>();
|
|
50
|
+
let watcherTimer: ReturnType<typeof setInterval> | null = null;
|
|
51
|
+
let settleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
52
|
+
let lastSeenRevision: number | null = null;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The current revision, or 0 if the counter is unavailable.
|
|
56
|
+
*
|
|
57
|
+
* Returning 0 rather than throwing is deliberate: callers use this as a cache
|
|
58
|
+
* key, and a database that cannot answer must degrade into "rebuild the config"
|
|
59
|
+
* rather than into "fail the user's turn". A constant 0 makes every subsequent
|
|
60
|
+
* lookup miss, which is slow and correct.
|
|
61
|
+
*/
|
|
62
|
+
export function getEngineConfigRevision(): number {
|
|
63
|
+
try {
|
|
64
|
+
const row = getDatabase()
|
|
65
|
+
.prepare('SELECT revision FROM engine_config_revision WHERE id = 1')
|
|
66
|
+
.get() as { revision: number } | undefined;
|
|
67
|
+
return row?.revision ?? 0;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
debug.warn('engine', 'Could not read engine config revision; treating config as changed', error);
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Be told when engine-affecting config has settled after a change.
|
|
76
|
+
*
|
|
77
|
+
* Listeners run on the trailing edge of a burst, never per write. A listener
|
|
78
|
+
* that throws is logged and skipped — this is housekeeping, and one subscriber
|
|
79
|
+
* failing must not stop the others from reacting.
|
|
80
|
+
*/
|
|
81
|
+
export function onEngineConfigChanged(listener: ConfigChangeListener): () => void {
|
|
82
|
+
listeners.add(listener);
|
|
83
|
+
return () => listeners.delete(listener);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function fire(revision: number): void {
|
|
87
|
+
for (const listener of listeners) {
|
|
88
|
+
try {
|
|
89
|
+
listener(revision);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
debug.warn('engine', 'Engine config listener failed', error);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Tell open clients their view of engine config is stale. The payload is a
|
|
96
|
+
// doorbell, not a delivery — the model list is refetched over the existing
|
|
97
|
+
// `models:list` route rather than duplicated into this event. This is what
|
|
98
|
+
// used to happen as a side effect of the restart button's success path.
|
|
99
|
+
try {
|
|
100
|
+
ws.emit.global('engine:config-changed', { revision });
|
|
101
|
+
} catch (error) {
|
|
102
|
+
debug.warn('engine', 'Failed to broadcast engine:config-changed', error);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Start watching the counter. Idempotent — calling twice does not double-poll.
|
|
108
|
+
*
|
|
109
|
+
* The first observation only records a baseline: at startup the revision is
|
|
110
|
+
* whatever the last session left behind, and treating that as a change would
|
|
111
|
+
* spawn a replacement server for config nobody just edited.
|
|
112
|
+
*/
|
|
113
|
+
export function startEngineConfigWatcher(): void {
|
|
114
|
+
if (watcherTimer) return;
|
|
115
|
+
|
|
116
|
+
lastSeenRevision = getEngineConfigRevision();
|
|
117
|
+
|
|
118
|
+
watcherTimer = setInterval(() => {
|
|
119
|
+
const current = getEngineConfigRevision();
|
|
120
|
+
if (current === lastSeenRevision) return;
|
|
121
|
+
lastSeenRevision = current;
|
|
122
|
+
|
|
123
|
+
// Restart the settle window on every bump so a burst produces one event
|
|
124
|
+
// on its trailing edge.
|
|
125
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
126
|
+
settleTimer = setTimeout(() => {
|
|
127
|
+
settleTimer = null;
|
|
128
|
+
debug.log('engine', `Engine config settled at revision ${current}`);
|
|
129
|
+
fire(current);
|
|
130
|
+
}, SETTLE_MS);
|
|
131
|
+
settleTimer.unref?.();
|
|
132
|
+
}, POLL_MS);
|
|
133
|
+
// Housekeeping must never be the reason the process refuses to exit.
|
|
134
|
+
watcherTimer.unref?.();
|
|
135
|
+
|
|
136
|
+
debug.log('engine', `Engine config watcher started (revision ${lastSeenRevision})`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Stop watching. Used by tests and shutdown. */
|
|
140
|
+
export function stopEngineConfigWatcher(): void {
|
|
141
|
+
if (watcherTimer) {
|
|
142
|
+
clearInterval(watcherTimer);
|
|
143
|
+
watcherTimer = null;
|
|
144
|
+
}
|
|
145
|
+
if (settleTimer) {
|
|
146
|
+
clearTimeout(settleTimer);
|
|
147
|
+
settleTimer = null;
|
|
148
|
+
}
|
|
149
|
+
lastSeenRevision = null;
|
|
150
|
+
}
|
|
@@ -12,8 +12,8 @@ export interface AIEngine {
|
|
|
12
12
|
|
|
13
13
|
initialize(accountId?: number): Promise<void>; // lazy; idempotent
|
|
14
14
|
dispose(): Promise<void>; // called per-project & on shutdown
|
|
15
|
-
cancel(): Promise<void>;
|
|
16
|
-
interrupt(): Promise<void>;
|
|
15
|
+
cancel(owner: AbortController): Promise<void>; // hard cancel, ONE run
|
|
16
|
+
interrupt(owner: AbortController): Promise<void>; // soft stop, ONE run
|
|
17
17
|
|
|
18
18
|
streamQuery(options: EngineQueryOptions):
|
|
19
19
|
AsyncGenerator<EngineOutput, void, unknown>;
|
|
@@ -31,10 +31,35 @@ Four invariants:
|
|
|
31
31
|
1. **`streamQuery` is the only streaming output path.** It is an
|
|
32
32
|
`AsyncGenerator<EngineOutput>`. The adapter translates SDK events into
|
|
33
33
|
`EngineOutput` — that is all.
|
|
34
|
-
2. **Streaming state lives on the instance.**
|
|
35
|
-
returns one instance per `(projectId, engineType)`,
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
2. **Streaming state lives on the RUN, never on the instance.**
|
|
35
|
+
`getProjectEngine` returns one instance per `(projectId, engineType)`, so an
|
|
36
|
+
instance is isolated from other *projects* — and shared by every chat session
|
|
37
|
+
*within* one project. Several of them stream at the same time. An
|
|
38
|
+
`activeController` / `activeQuery` / `activeSessionId` field therefore holds
|
|
39
|
+
whichever chat started last, and the earlier one silently loses its handles.
|
|
40
|
+
That is not theoretical: it is how `cancel()` came to abort a different chat
|
|
41
|
+
than the one the user stopped, how a finished stream made `isActive` report
|
|
42
|
+
idle while another was still running (letting engine retirement dispose it
|
|
43
|
+
mid-answer), and how OpenCode leaked a pooled-server hold per overwritten
|
|
44
|
+
stream.
|
|
45
|
+
|
|
46
|
+
So every adapter keeps a `private runs = new EngineRuns<XxxRun>()`
|
|
47
|
+
([`adapters/run-registry.ts`](../adapters/run-registry.ts)) and puts each
|
|
48
|
+
stream's controller, SDK handle, session id, server binding and parked
|
|
49
|
+
questions in its own `XxxRun`. The registry keys runs by the AbortController
|
|
50
|
+
the caller passed to `streamQuery` — the same object
|
|
51
|
+
`StreamState.abortController` holds, so no id has to be minted or kept in
|
|
52
|
+
sync. `isActive` is `this.runs.isActive` (any run, not the latest one), the
|
|
53
|
+
stream's `finally` retires only its own run, and anything keyed by tool id
|
|
54
|
+
(`pendingUserAnswers`, `pendingAsks`, `pendingQuestions`) records which run
|
|
55
|
+
parked it so a cancel drops that run's entries alone.
|
|
56
|
+
|
|
57
|
+
`cancel(owner)` and `interrupt(owner)` take the run to stop, and the
|
|
58
|
+
parameter is required on purpose — there is no "cancel whatever you are
|
|
59
|
+
doing" for callers outside the adapter. Adapters implement the teardown once
|
|
60
|
+
in a private `stopRuns(targets)`, called with `this.runs.select(owner)` from
|
|
61
|
+
`cancel` and with `this.runs.all()` from `dispose()`. Stopping everything is
|
|
62
|
+
`dispose()`'s job; only shutdown and engine retirement get to ask for it.
|
|
38
63
|
3. **Init is lazy & concurrency-safe.** The first `streamQuery` /
|
|
39
64
|
`getAvailableModels` call triggers `initialize()`. Multiple parallel
|
|
40
65
|
callers **must** share a single init promise. See:
|
|
@@ -61,7 +86,7 @@ share one instance instead of racing to build two.
|
|
|
61
86
|
| Accessor | Kind | Used for |
|
|
62
87
|
|--------------------------------------|-------|-----------------------------------------------|
|
|
63
88
|
| `getEngine(type)` | async | Global singleton — `models:list`, settings |
|
|
64
|
-
| `getProjectEngine(projectId, type)` | async | Streaming chat —
|
|
89
|
+
| `getProjectEngine(projectId, type)` | async | Streaming chat — one instance per project, shared by its chat sessions |
|
|
65
90
|
| `findProjectEngine(projectId, type)` | sync | An engine that must already exist — cancel, answer routing |
|
|
66
91
|
|
|
67
92
|
`findProjectEngine` returns `undefined` rather than creating one: cancelling a
|
|
@@ -280,10 +305,16 @@ Important conventions:
|
|
|
280
305
|
- Tool names **must** be canonicalised via `toCanonicalToolName(...)`
|
|
281
306
|
(`shared/types/unified/tool.ts`) so the frontend renders the same UI for
|
|
282
307
|
tools that have different names across SDKs.
|
|
308
|
+
- `cancel()` targeting: act **only** on `this.runs.select(owner)`. Never fall
|
|
309
|
+
back to "the runs that are left" when the owner is gone — the caller named a
|
|
310
|
+
stream that already ended, and the runs that are left belong to other chats
|
|
311
|
+
(see invariant 2 and `adapters/run-registry.test.ts`).
|
|
283
312
|
- `cancel()` ordering: **abort the local controller first**, **then** RPC
|
|
284
313
|
to the SDK/server. RPCs can hang; the local abort cuts the `for await`
|
|
285
|
-
loop deterministically.
|
|
286
|
-
|
|
314
|
+
loop deterministically. Release shared resources (OpenCode's pool hold)
|
|
315
|
+
**after** the RPC, or the server can be reaped mid-call. See
|
|
316
|
+
`OpenCodeEngine.stopRuns`, `ClaudeCodeEngine.stopRuns`,
|
|
317
|
+
`CopilotEngine.stopRuns`.
|
|
287
318
|
- Dynamic-catalog fetchers in `models.ts` MUST return `EngineModel[]` and
|
|
288
319
|
use `[]` as the failure sentinel (network, auth, parse error). Do **not**
|
|
289
320
|
return `null` — both `fetchOpenCodeModels` and `fetchQwenModels` return
|
|
@@ -298,6 +298,14 @@ Then the minimum UI scenarios that must pass:
|
|
|
298
298
|
Active account: <name>`.
|
|
299
299
|
- [ ] Chat input → pick NewEngine + model → send a message → assistant
|
|
300
300
|
replies → cancel mid-stream → idle → send again → resume works.
|
|
301
|
+
- [ ] **Two chats of the SAME project streaming at once.** Start one, start a
|
|
302
|
+
second, switch back to the first and Stop it: only that one stops, the
|
|
303
|
+
other keeps streaming and keeps rendering. Then Stop the second. One
|
|
304
|
+
instance serves both, so per-stream state on the adapter class shows up
|
|
305
|
+
here and nowhere else (§10.26).
|
|
306
|
+
- [ ] With those two chats still streaming, change the engine's account or
|
|
307
|
+
config in Settings. Neither chat may be cut short — retirement waits for
|
|
308
|
+
`isActive`, which must count every run and not just the newest one.
|
|
301
309
|
- [ ] AskUserQuestion (if the SDK supports it) → appears in UI → submit
|
|
302
310
|
answer → stream continues.
|
|
303
311
|
- [ ] Reasoning effort (if the engine has a knob) → the pill appears for
|
|
@@ -299,6 +299,45 @@ Backend `chat:stream` then `streamManager.startStream(...)`, which:
|
|
|
299
299
|
> (`claude`, `copilot`) read this and override their per-stream credential
|
|
300
300
|
> accordingly.
|
|
301
301
|
|
|
302
|
+
### 6.3a Stop path → backend
|
|
303
|
+
|
|
304
|
+
Stop is `chatService.cancelRequest()` → `ws.emit('chat:cancel', { chatSessionId })`
|
|
305
|
+
→ `streamManager.cancelStream(streamId)` → `engine.cancel(streamState.abortController)`.
|
|
306
|
+
|
|
307
|
+
Every hop names a session or a run explicitly, because both halves once
|
|
308
|
+
resolved it from ambient state and both stopped the wrong chat:
|
|
309
|
+
|
|
310
|
+
- **The target is the session on screen** — `sessionState.currentSession`,
|
|
311
|
+
nothing else. The service used to prefer a `currentSessionId` remembered from
|
|
312
|
+
the last message this client *sent*, which is a different session the moment
|
|
313
|
+
two chats stream at once.
|
|
314
|
+
- **Stream bookkeeping is per session.** `processId`, `streamCompleted`, the
|
|
315
|
+
cancelled-processId set and the cancel safety timer live in a
|
|
316
|
+
`Map<sessionId, …>` inside `chat.service.ts`.
|
|
317
|
+
- **Every stream event carries its own `chatSessionId`** — `chat:connection`,
|
|
318
|
+
`chat:message`, `chat:partial`, `chat:complete`, `chat:error`,
|
|
319
|
+
`chat:cancelled` — and `chat.service.ts::ownerOf` credits it to that session.
|
|
320
|
+
Room membership looks like it would do the job (a client joins the room of the
|
|
321
|
+
session it views) but it does not: a switch points `currentSession` at the new
|
|
322
|
+
chat immediately, while the leave/join and the transcript reload are still in
|
|
323
|
+
flight. Attributing by "whatever is on screen" put the chat being left's
|
|
324
|
+
pending question onto the chat being opened, which then showed
|
|
325
|
+
"Waiting for your input..." while it was still working.
|
|
326
|
+
- **`sessionState.messagesSessionId` says whose transcript is loaded.**
|
|
327
|
+
`sessionState.messages` holds one session's messages, and `currentSession`
|
|
328
|
+
moves a round trip before they arrive. Anything that writes to the transcript
|
|
329
|
+
or derives from it — event handlers, `catchupActiveStream`,
|
|
330
|
+
`detectPendingInteractiveTools`, the cancel-time `finalizeStreamEvents` —
|
|
331
|
+
checks this marker, not `currentSession`.
|
|
332
|
+
- **The backend cancels one run**, identified by `StreamState.abortController`.
|
|
333
|
+
See invariant 2 in [adapter-contract](./adapter-contract.md) and §10.26 in
|
|
334
|
+
[lessons-learned](./lessons-learned.md).
|
|
335
|
+
|
|
336
|
+
Catchup (`ChatInput.svelte::catchupActiveStream` → `chatService.reconnectToStream`)
|
|
337
|
+
is keyed by `projectId:sessionId` for the same reason: a project-only key made an
|
|
338
|
+
intra-project session switch skip catchup, so the session switched to never
|
|
339
|
+
re-attached to its own live stream.
|
|
340
|
+
|
|
302
341
|
### 6.4 Reasoning, attachments, AskUserQuestion
|
|
303
342
|
|
|
304
343
|
- **Reasoning (output)**: an adapter must emit
|
|
@@ -1508,3 +1508,73 @@ The mechanical part of an upgrade is cheap; budget the time for the union
|
|
|
1508
1508
|
diffs. `/tmp`-installing the old and new versions side by side and diffing the
|
|
1509
1509
|
`type: "…"` literals in each SDK's event declarations found every item above in
|
|
1510
1510
|
minutes.
|
|
1511
|
+
|
|
1512
|
+
---
|
|
1513
|
+
|
|
1514
|
+
### 10.26 One engine instance, many chats — per-stream state cannot live on it
|
|
1515
|
+
|
|
1516
|
+
A user with two chats streaming in one project pressed **Stop** in one of them.
|
|
1517
|
+
Both stopped.
|
|
1518
|
+
|
|
1519
|
+
`getProjectEngine(projectId, type)` returns one instance per project, and the
|
|
1520
|
+
adapters read that as "one stream at a time". Every one of the eight kept the
|
|
1521
|
+
running stream's handles in instance fields:
|
|
1522
|
+
|
|
1523
|
+
```ts
|
|
1524
|
+
private activeController: AbortController | null = null;
|
|
1525
|
+
private activeQuery: Query | null = null; // opencode: activeSessionId,
|
|
1526
|
+
// activeServer, activeHolder
|
|
1527
|
+
```
|
|
1528
|
+
|
|
1529
|
+
Clopen's stream-manager has always allowed concurrent streams — one per
|
|
1530
|
+
`(project, chat session)`, not one per project. So the second chat to start
|
|
1531
|
+
overwrote the first chat's handles, and `cancel()` operated on whatever was in
|
|
1532
|
+
the fields:
|
|
1533
|
+
|
|
1534
|
+
- **Stop hit the wrong chat.** With chats A and B streaming, cancelling A ran
|
|
1535
|
+
`client.session.abort(activeSessionId)` — B's id. Both died. Before a
|
|
1536
|
+
frontend fix that made Stop target the *viewed* session, the mis-target on
|
|
1537
|
+
each side cancelled out and the bug read as "Stop needs two presses".
|
|
1538
|
+
- **`isActive` lied.** The first stream's `finally` nulled the shared fields,
|
|
1539
|
+
so the instance reported idle while the second was still running. Engine
|
|
1540
|
+
retirement (§10.14's successor: evict now, dispose once idle) took that at
|
|
1541
|
+
face value and disposed the engine mid-answer — the exact bug retirement was
|
|
1542
|
+
built to prevent.
|
|
1543
|
+
- **Resources leaked.** OpenCode's `activeHolder` is the pool hold that keeps a
|
|
1544
|
+
per-Profile server from being reaped. The second stream overwrote it, so the
|
|
1545
|
+
first stream's hold was never released and that server was pinned forever.
|
|
1546
|
+
- **Replies went to the wrong server.** Two chats on different Profiles sit on
|
|
1547
|
+
different pooled servers; permission and question replies read
|
|
1548
|
+
`this.activeServer`, so one chat's approval was POSTed into the other's
|
|
1549
|
+
server and its own tool call sat waiting.
|
|
1550
|
+
|
|
1551
|
+
The fix is structural, not a guard: per-stream state moved into an
|
|
1552
|
+
`EngineRuns<XxxRun>` registry ([`adapters/run-registry.ts`](../adapters/run-registry.ts))
|
|
1553
|
+
keyed by the AbortController the caller passed to `streamQuery` — the same
|
|
1554
|
+
object `StreamState.abortController` holds, so the stream-manager and the
|
|
1555
|
+
adapter already agree on it without minting an id. `isActive` counts runs, the
|
|
1556
|
+
stream's `finally` retires only its own, and each adapter implements teardown
|
|
1557
|
+
once in `stopRuns(targets)`.
|
|
1558
|
+
|
|
1559
|
+
Three details worth keeping:
|
|
1560
|
+
|
|
1561
|
+
- **`cancel(owner)` takes a required parameter.** An optional one invites
|
|
1562
|
+
`cancel()` at a call site that has a specific stream in mind, which is the
|
|
1563
|
+
original bug with a nicer signature. Stopping every run is `dispose()`'s job.
|
|
1564
|
+
- **An owner that has already finished cancels nothing.** The tempting fallback
|
|
1565
|
+
— "not found, so stop what's left" — reproduces the bug exactly: the runs that
|
|
1566
|
+
are left belong to other chats. This is the case `run-registry.test.ts` pins.
|
|
1567
|
+
- **Release shared resources after the RPC, not before.** OpenCode's hold is
|
|
1568
|
+
handed back only once `session.abort()` has returned; releasing first can let
|
|
1569
|
+
the server be reaped out from under that very call.
|
|
1570
|
+
|
|
1571
|
+
One boundary this does **not** cover: `isActive` counts streaming runs, so a
|
|
1572
|
+
`generateStructured` call in flight still reads as idle. Those run on the global
|
|
1573
|
+
singleton tier (`initializeEngine`), not the per-project one, so they are a
|
|
1574
|
+
separate problem — but if a future engine routes one-shot generation through a
|
|
1575
|
+
project engine, it has to register a run like everything else.
|
|
1576
|
+
|
|
1577
|
+
What made this survive so long is that the contract doc *taught* it: invariant 2
|
|
1578
|
+
used to read "Streaming state lives on the instance … automatically isolated
|
|
1579
|
+
per-project". It was true about projects and silently wrong about chat sessions.
|
|
1580
|
+
When an invariant is scoped, write down what it does **not** cover.
|
|
@@ -19,7 +19,9 @@
|
|
|
19
19
|
| Usage backfill (once-per-turn engines) | `backend/chat/stream-manager.ts::backfillUsageForStream` (Codex + Cursor; §10.20-I) |
|
|
20
20
|
| Context window unknown → "?" not 100% | `frontend/utils/context-manager.ts` (`unknown`) + `frontend/components/chat/widgets/ContextIndicator.svelte` (§10.20-J) |
|
|
21
21
|
| Reasoning stream lifecycle | `opencode/stream.ts::flushReasoning`, `copilot/message-converter.ts::convertReasoningDelta` |
|
|
22
|
-
|
|
|
22
|
+
| Per-stream state on a shared instance | `adapters/run-registry.ts::EngineRuns` (+ each adapter's `XxxRun`; §10.26) |
|
|
23
|
+
| Cancel exactly one chat's stream | `adapters/run-registry.ts::select` → `stream.ts::stopRuns`; stream-manager passes `streamState.abortController` |
|
|
24
|
+
| Cancel-before-RPC ordering | `opencode/stream.ts::stopRuns`, `claude/stream.ts::stopRuns`, `copilot/stream.ts::stopRuns` |
|
|
23
25
|
| Fork session (native vs. on-disk vs. in-memory) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state), `pi/session-fork.ts` (`SessionManager.forkFrom`), `cline/stream.ts` (**session-less** — fresh id per turn + in-memory copy-on-branch; see §10.10) |
|
|
24
26
|
| Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap`; **synthesized** `Agent` tool for bare-loop SDKs in `cline/agent-tool.ts` + `pi/agent-tool.ts` (see §10.15) |
|
|
25
27
|
| File-backed Workflow activity (event-driven) | `claude/workflow-transcript.ts` (filesystem watchers, byte offsets, terminal status) + `claude/stream.ts::EventQueue` merge; no interval polling (§10.15) |
|