@myrialabs/clopen 0.4.31 → 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 +27 -11
- 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 +45 -18
- 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 +511 -134
- 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/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/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- 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/ws/chat/stream.ts +24 -0
- package/backend/ws/engine/codex/accounts.ts +0 -12
- 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/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
|
@@ -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) |
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applying engine config changes without anyone pressing anything.
|
|
3
|
+
*
|
|
4
|
+
* This is the piece that replaced the "Restart Server" button. The button asked
|
|
5
|
+
* the user to understand something they should never have had to: that Open Code
|
|
6
|
+
* runs as a process which froze its configuration at boot, and that their edit
|
|
7
|
+
* would quietly do nothing until they told the server to start again. Worse, the
|
|
8
|
+
* button's only implementation was destructive — it aborted every running chat,
|
|
9
|
+
* which is why it had to ask for confirmation, which is why new users learned to
|
|
10
|
+
* be afraid of it.
|
|
11
|
+
*
|
|
12
|
+
* What happens instead, driven entirely by the config revision:
|
|
13
|
+
*
|
|
14
|
+
* nothing is streaming → a replacement server is spawned and health-checked
|
|
15
|
+
* NOW, and only once it is up does the old one go. The
|
|
16
|
+
* user's next message costs nothing.
|
|
17
|
+
*
|
|
18
|
+
* something is streaming → nothing is touched. The running turn finishes under
|
|
19
|
+
* the config it started with; the next stream resolves
|
|
20
|
+
* the new config on its own and binds to a new server,
|
|
21
|
+
* and the old one is reaped when its last stream lets
|
|
22
|
+
* go of it.
|
|
23
|
+
*
|
|
24
|
+
* Both cases are the same mechanism — the pool keys servers by a hash of the
|
|
25
|
+
* config they were spawned with — so this module only decides WHEN to pay the
|
|
26
|
+
* spawn cost, never whether the right config is used. That part cannot be got
|
|
27
|
+
* wrong by anything here.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { streamManager } from '../chat';
|
|
31
|
+
import { onEngineConfigChanged } from './config-revision';
|
|
32
|
+
import { retireAllEngines } from './index';
|
|
33
|
+
import {
|
|
34
|
+
acquireServer,
|
|
35
|
+
pooledScopeKeys,
|
|
36
|
+
reconcileServerHolders,
|
|
37
|
+
DEFAULT_SCOPE_KEY,
|
|
38
|
+
} from './adapters/opencode/server';
|
|
39
|
+
import { debug } from '$shared/utils/logger';
|
|
40
|
+
|
|
41
|
+
let started = false;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Re-warm the Open Code pool for the scopes that are actually in use.
|
|
45
|
+
*
|
|
46
|
+
* Only the default (no-Profile) scope can be warmed blind: a Profile scope's
|
|
47
|
+
* spec is built from that Profile's connector and subagent set at stream start,
|
|
48
|
+
* and reconstructing it here would duplicate that resolution. Profile servers
|
|
49
|
+
* therefore respawn lazily on their next stream, which is the correct trade —
|
|
50
|
+
* they are the rarer case, and the cost is one spawn on a turn that was going to
|
|
51
|
+
* talk to a server anyway.
|
|
52
|
+
*/
|
|
53
|
+
async function warmDefaultScope(): Promise<void> {
|
|
54
|
+
if (!pooledScopeKeys().includes(DEFAULT_SCOPE_KEY)) return;
|
|
55
|
+
try {
|
|
56
|
+
await acquireServer({});
|
|
57
|
+
debug.log('engine', 'Open Code default server re-warmed for the new config');
|
|
58
|
+
} catch (error) {
|
|
59
|
+
// Deliberately silent to the user. A config that cannot start is a real
|
|
60
|
+
// problem, but the honest place to report it is the turn that needs it —
|
|
61
|
+
// where the error is actionable and in context — not a background toast
|
|
62
|
+
// about a server the user was never told about.
|
|
63
|
+
debug.warn('engine', 'Open Code warm-up failed; keeping the current server until a turn needs the new config', error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Start reacting to engine config changes. Idempotent.
|
|
69
|
+
*/
|
|
70
|
+
export function startEngineHotReload(): void {
|
|
71
|
+
if (started) return;
|
|
72
|
+
started = true;
|
|
73
|
+
|
|
74
|
+
onEngineConfigChanged(revision => {
|
|
75
|
+
// Holder bookkeeping is reconciled against the live stream set first, so
|
|
76
|
+
// "is anything running" and "is this server still needed" are answered from
|
|
77
|
+
// the same source of truth rather than from two drifting counters.
|
|
78
|
+
const liveStreams = streamManager.getActiveStreams();
|
|
79
|
+
reconcileServerHolders(new Set(liveStreams.map(s => s.streamId)));
|
|
80
|
+
|
|
81
|
+
// Engines other than Open Code hold no baked config, but they DO cache
|
|
82
|
+
// credentialed clients. Retiring evicts those without touching a stream
|
|
83
|
+
// that is mid-answer.
|
|
84
|
+
retireAllEngines();
|
|
85
|
+
|
|
86
|
+
if (liveStreams.length > 0) {
|
|
87
|
+
debug.log(
|
|
88
|
+
'engine',
|
|
89
|
+
`Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
|
|
90
|
+
'applying it to the next turn and draining the old server behind them'
|
|
91
|
+
);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
void warmDefaultScope();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
debug.log('engine', 'Engine hot-reload active');
|
|
99
|
+
}
|
package/backend/engine/index.ts
CHANGED
|
@@ -8,10 +8,16 @@
|
|
|
8
8
|
* Used for non-streaming operations like models:list, settings, etc.
|
|
9
9
|
*
|
|
10
10
|
* - Per-project instances (getProjectEngine / initializeProjectEngine):
|
|
11
|
-
* Used by stream-manager for chat streaming.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Used by stream-manager for chat streaming. Cancelling Project A's stream
|
|
12
|
+
* never affects Project B.
|
|
13
|
+
*
|
|
14
|
+
* Per project, NOT per chat session: every chat session of a project shares
|
|
15
|
+
* one instance, and several of them stream at once. Isolation between those
|
|
16
|
+
* streams is the adapter's job, not this cache's — each keeps its per-stream
|
|
17
|
+
* state in an `EngineRuns` registry (backend/engine/adapters/run-registry.ts)
|
|
18
|
+
* and `cancel(owner)` stops exactly the run it was handed. Adding per-stream
|
|
19
|
+
* state to an adapter INSTANCE reintroduces "Stop this chat" stopping a
|
|
20
|
+
* different one.
|
|
15
21
|
*
|
|
16
22
|
* Adapters are loaded on first use, never at boot. This registry used to import
|
|
17
23
|
* all eight statically, which coupled every user's startup to every adapter: one
|
|
@@ -133,6 +139,84 @@ export async function disposeEngine(type: EngineType): Promise<void> {
|
|
|
133
139
|
}
|
|
134
140
|
}
|
|
135
141
|
|
|
142
|
+
// ============================================================================
|
|
143
|
+
// Retirement — replacing an engine without killing what it is doing
|
|
144
|
+
// ============================================================================
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Engines removed from a cache but still mid-stream, awaiting a quiet moment.
|
|
148
|
+
*
|
|
149
|
+
* Disposing an engine tears down its SDK process and aborts whatever query it is
|
|
150
|
+
* running. That is right at shutdown and wrong everywhere else: switching a
|
|
151
|
+
* Copilot account or editing a connector used to call `dispose()` immediately,
|
|
152
|
+
* which killed any chat that happened to be streaming at that moment — silently,
|
|
153
|
+
* from the user's point of view, since nothing in the UI connects "I changed a
|
|
154
|
+
* setting" to "that answer stopped halfway".
|
|
155
|
+
*
|
|
156
|
+
* Retiring instead evicts the instance from the cache so the next stream builds a
|
|
157
|
+
* fresh one, and disposes the old one once it goes idle. New work gets the new
|
|
158
|
+
* config; work already in flight finishes under the config it started with.
|
|
159
|
+
*/
|
|
160
|
+
const retired = new Set<AIEngine>();
|
|
161
|
+
/** How often retired instances are re-checked for idleness. */
|
|
162
|
+
const RETIRE_POLL_MS = 2000;
|
|
163
|
+
let retireTimer: ReturnType<typeof setInterval> | null = null;
|
|
164
|
+
|
|
165
|
+
function disposeWhenIdle(engine: AIEngine, label: string): void {
|
|
166
|
+
if (!engine.isActive) {
|
|
167
|
+
void engine.dispose().catch(error => debug.error('engine', `Error disposing ${label}:`, error));
|
|
168
|
+
debug.log('engine', `Engine disposed: ${label}`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
retired.add(engine);
|
|
173
|
+
debug.log('engine', `Engine retired while busy, will dispose when idle: ${label}`);
|
|
174
|
+
if (retireTimer) return;
|
|
175
|
+
|
|
176
|
+
retireTimer = setInterval(() => {
|
|
177
|
+
for (const candidate of [...retired]) {
|
|
178
|
+
if (candidate.isActive) continue;
|
|
179
|
+
retired.delete(candidate);
|
|
180
|
+
void candidate.dispose().catch(error => debug.error('engine', 'Error disposing retired engine:', error));
|
|
181
|
+
debug.log('engine', `Retired engine disposed after going idle: ${candidate.name}`);
|
|
182
|
+
}
|
|
183
|
+
if (retired.size === 0 && retireTimer) {
|
|
184
|
+
clearInterval(retireTimer);
|
|
185
|
+
retireTimer = null;
|
|
186
|
+
}
|
|
187
|
+
}, RETIRE_POLL_MS);
|
|
188
|
+
retireTimer.unref?.();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Evict every instance of an engine type — global and per-project — so the next
|
|
193
|
+
* stream rebuilds it, without interrupting any stream currently using one.
|
|
194
|
+
*
|
|
195
|
+
* This is what account switches, credential edits and config changes call.
|
|
196
|
+
*/
|
|
197
|
+
export function retireEnginesByType(type: EngineType): void {
|
|
198
|
+
const slot = engines.get(type);
|
|
199
|
+
if (slot) {
|
|
200
|
+
engines.delete(type);
|
|
201
|
+
if (slot.instance) disposeWhenIdle(slot.instance, `global ${type}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
for (const [projectId, projectMap] of projectEngines) {
|
|
205
|
+
const projectSlot = projectMap.get(type);
|
|
206
|
+
if (!projectSlot) continue;
|
|
207
|
+
projectMap.delete(type);
|
|
208
|
+
if (projectSlot.instance) disposeWhenIdle(projectSlot.instance, `${type} for project ${projectId.slice(0, 8)}`);
|
|
209
|
+
if (projectMap.size === 0) projectEngines.delete(projectId);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Evict every engine of every type, letting in-flight streams finish. */
|
|
214
|
+
export function retireAllEngines(): void {
|
|
215
|
+
for (const type of new Set<EngineType>([...engines.keys(), ...[...projectEngines.values()].flatMap(m => [...m.keys()])])) {
|
|
216
|
+
retireEnginesByType(type);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
136
220
|
/**
|
|
137
221
|
* Dispose all global engines (used on server shutdown).
|
|
138
222
|
*/
|
|
@@ -160,8 +244,10 @@ const projectEngines = new Map<string, Map<EngineType, EngineSlot>>();
|
|
|
160
244
|
|
|
161
245
|
/**
|
|
162
246
|
* Get (or create) an engine instance scoped to a specific project.
|
|
163
|
-
*
|
|
164
|
-
*
|
|
247
|
+
*
|
|
248
|
+
* Scoped per project, so one project's streams never reach another's. Within a
|
|
249
|
+
* project the instance is SHARED by every chat session — see the note at the
|
|
250
|
+
* top of this file for what that means for adapters.
|
|
165
251
|
*/
|
|
166
252
|
export async function getProjectEngine(projectId: string, type: EngineType): Promise<AIEngine> {
|
|
167
253
|
let engines = projectEngines.get(projectId);
|
|
@@ -241,26 +327,12 @@ export async function disposeProjectEngines(projectId: string): Promise<void> {
|
|
|
241
327
|
* Dispose all instances of a given engine type across all projects, plus the
|
|
242
328
|
* global singleton. Call when an account/credential change requires every
|
|
243
329
|
* client to re-initialise (e.g. Copilot account switch).
|
|
330
|
+
*
|
|
331
|
+
* Retires rather than tears down — see `retireEnginesByType`. Kept async so the
|
|
332
|
+
* many `await`ing call sites read unchanged.
|
|
244
333
|
*/
|
|
245
334
|
export async function disposeAllProjectEnginesByType(type: EngineType): Promise<void> {
|
|
246
|
-
|
|
247
|
-
const slot = engines.get(type);
|
|
248
|
-
if (slot) {
|
|
249
|
-
engines.delete(type);
|
|
250
|
-
try {
|
|
251
|
-
if (slot.instance) await slot.instance.dispose();
|
|
252
|
-
debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
|
|
253
|
-
} catch (error) {
|
|
254
|
-
debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
if (engines.size === 0) {
|
|
258
|
-
projectEngines.delete(projectId);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Also drop the global singleton so the next non-streaming op rebuilds it.
|
|
263
|
-
await disposeEngine(type);
|
|
335
|
+
retireEnginesByType(type);
|
|
264
336
|
}
|
|
265
337
|
|
|
266
338
|
/**
|
package/backend/engine/types.ts
CHANGED
|
@@ -81,13 +81,25 @@ export interface AIEngine {
|
|
|
81
81
|
*/
|
|
82
82
|
streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown>;
|
|
83
83
|
|
|
84
|
-
/**
|
|
85
|
-
|
|
84
|
+
/**
|
|
85
|
+
* Cancel ONE run — the stream whose AbortController is `owner`.
|
|
86
|
+
*
|
|
87
|
+
* One engine instance is shared by every chat session of a project, so it can
|
|
88
|
+
* be streaming several chats at once. `owner` is the controller that stream
|
|
89
|
+
* passed to `streamQuery`, and the same object `StreamState.abortController`
|
|
90
|
+
* holds — the handle both sides already agree on. Adapters must stop that run
|
|
91
|
+
* alone and leave the others streaming.
|
|
92
|
+
*
|
|
93
|
+
* The parameter is deliberately required: there is no "cancel whatever you
|
|
94
|
+
* are doing" for callers. Stopping every run is `dispose()`'s job, and only
|
|
95
|
+
* shutdown and engine retirement get to ask for it.
|
|
96
|
+
*/
|
|
97
|
+
cancel(owner: AbortController): Promise<void>;
|
|
86
98
|
|
|
87
|
-
/** Interrupt
|
|
88
|
-
interrupt(): Promise<void>;
|
|
99
|
+
/** Interrupt one run (soft stop). Targeted like `cancel`. */
|
|
100
|
+
interrupt(owner: AbortController): Promise<void>;
|
|
89
101
|
|
|
90
|
-
/**
|
|
102
|
+
/** True while at least ONE run is in flight — not just the most recent one. */
|
|
91
103
|
readonly isActive: boolean;
|
|
92
104
|
|
|
93
105
|
/** Return the list of models this engine supports */
|
|
@@ -13,14 +13,30 @@ export interface GitExecResult {
|
|
|
13
13
|
exitCode: number;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
export interface GitExecOptions {
|
|
17
|
+
/** Milliseconds before the process is killed. */
|
|
18
|
+
timeout?: number;
|
|
19
|
+
/** Piped to the command's stdin (e.g. `check-ignore --stdin` path lists). */
|
|
20
|
+
stdin?: string;
|
|
21
|
+
/**
|
|
22
|
+
* Exit codes that are a normal answer rather than a failure, so they are
|
|
23
|
+
* not logged as one — `check-ignore` exits 1 to say "nothing matched".
|
|
24
|
+
*/
|
|
25
|
+
okExitCodes?: number[];
|
|
26
|
+
}
|
|
27
|
+
|
|
16
28
|
/**
|
|
17
|
-
* Execute a git command in the given working directory
|
|
29
|
+
* Execute a git command in the given working directory.
|
|
30
|
+
* The third argument accepts a timeout in ms (legacy form) or an options object.
|
|
18
31
|
*/
|
|
19
32
|
export async function execGit(
|
|
20
33
|
args: string[],
|
|
21
34
|
cwd: string,
|
|
22
|
-
|
|
35
|
+
timeoutOrOptions: number | GitExecOptions = 30000
|
|
23
36
|
): Promise<GitExecResult> {
|
|
37
|
+
const options: GitExecOptions =
|
|
38
|
+
typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : timeoutOrOptions;
|
|
39
|
+
const { timeout = 30000, stdin, okExitCodes = [] } = options;
|
|
24
40
|
debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
|
|
25
41
|
|
|
26
42
|
const gitPath = resolveBinary('git');
|
|
@@ -29,6 +45,9 @@ export async function execGit(
|
|
|
29
45
|
const safeCwd = cwd.replace(/\\/g, '/');
|
|
30
46
|
const proc = Bun.spawn([gitPath, '-c', `safe.directory=${safeCwd}`, ...args], {
|
|
31
47
|
cwd,
|
|
48
|
+
// Commands that read a path list (`check-ignore --stdin`) get it here —
|
|
49
|
+
// far safer than argv, which has a length limit and quoting pitfalls.
|
|
50
|
+
stdin: stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin),
|
|
32
51
|
stdout: 'pipe',
|
|
33
52
|
stderr: 'pipe',
|
|
34
53
|
env: {
|
|
@@ -63,7 +82,7 @@ export async function execGit(
|
|
|
63
82
|
const exitCode = await proc.exited;
|
|
64
83
|
clearTimeout(timeoutId);
|
|
65
84
|
|
|
66
|
-
if (exitCode !== 0) {
|
|
85
|
+
if (exitCode !== 0 && !okExitCodes.includes(exitCode)) {
|
|
67
86
|
debug.warn('git', `Command failed (exit ${exitCode}): git ${args.join(' ')}\n${stderr}`);
|
|
68
87
|
}
|
|
69
88
|
|
|
@@ -36,7 +36,7 @@ import {
|
|
|
36
36
|
assertSafeGitRevish,
|
|
37
37
|
assertSafeGitShowRef
|
|
38
38
|
} from './git-spawn-validation';
|
|
39
|
-
import { findNestedRepoPaths, findSubmodulePaths } from '
|
|
39
|
+
import { findNestedRepoPaths, findSubmodulePaths } from './nested-repos';
|
|
40
40
|
import path from 'node:path';
|
|
41
41
|
|
|
42
42
|
export class GitService {
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { execGit } from './git-executor';
|
|
6
|
+
import { findNestedRepoPaths, findRepoForFile } from './nested-repos';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Sub-repo detection used to walk the whole tree and report every directory
|
|
10
|
+
* with a `.git` inside it. On an iOS project that meant Swift Package
|
|
11
|
+
* Manager's `build/…/SourcePackages/checkouts/*` — thousands of foreign
|
|
12
|
+
* changes in the Changes tab. These cover both sides of the policy: package
|
|
13
|
+
* caches stay out, repos the user actually embedded stay in.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
let root: string;
|
|
17
|
+
|
|
18
|
+
async function git(cwd: string, ...args: string[]) {
|
|
19
|
+
const result = await execGit(args, cwd);
|
|
20
|
+
if (result.exitCode !== 0 && args[0] !== 'check-ignore') {
|
|
21
|
+
throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
|
|
22
|
+
}
|
|
23
|
+
return result.stdout;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function initRepo(dir: string) {
|
|
27
|
+
await mkdir(dir, { recursive: true });
|
|
28
|
+
await git(dir, 'init', '-b', 'main', '.');
|
|
29
|
+
await git(dir, 'config', 'user.email', 'test@example.com');
|
|
30
|
+
await git(dir, 'config', 'user.name', 'Test');
|
|
31
|
+
await git(dir, 'config', 'commit.gpgsign', 'false');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Paths relative to the project root, for readable assertions. */
|
|
35
|
+
async function detected(): Promise<string[]> {
|
|
36
|
+
const paths = await findNestedRepoPaths(root);
|
|
37
|
+
return paths.map((p) => path.relative(root, p).replace(/\\/g, '/')).sort();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
beforeEach(async () => {
|
|
41
|
+
root = await mkdtemp(path.join(tmpdir(), 'clopen-nested-'));
|
|
42
|
+
await initRepo(root);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
afterEach(async () => {
|
|
46
|
+
await rm(root, { recursive: true, force: true });
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('findNestedRepoPaths', () => {
|
|
50
|
+
test('ignores package-manager checkouts under an ignored build dir', async () => {
|
|
51
|
+
await writeFile(path.join(root, '.gitignore'), 'build/\n');
|
|
52
|
+
for (const name of ['abseil-cpp-binary', 'firebase-ios-sdk', 'leveldb']) {
|
|
53
|
+
await initRepo(path.join(root, 'build/ios/SourcePackages/checkouts', name));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
expect(await detected()).toEqual([]);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('ignores dependency dirs by name even when they are committed', async () => {
|
|
60
|
+
// No .gitignore at all — the name alone must be enough.
|
|
61
|
+
await initRepo(path.join(root, 'node_modules/some-pkg'));
|
|
62
|
+
await initRepo(path.join(root, 'ios/Pods/SomePod'));
|
|
63
|
+
await initRepo(path.join(root, '.build/checkouts/some-dep'));
|
|
64
|
+
|
|
65
|
+
expect(await detected()).toEqual([]);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('detects a repo embedded in the project tree', async () => {
|
|
69
|
+
await initRepo(path.join(root, 'packages/widget'));
|
|
70
|
+
|
|
71
|
+
expect(await detected()).toEqual(['packages/widget']);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('detects a repo the outer repo ignores', async () => {
|
|
75
|
+
await writeFile(path.join(root, '.gitignore'), 'wp-content/themes/mytheme/\n');
|
|
76
|
+
await initRepo(path.join(root, 'wp-content/themes/mytheme'));
|
|
77
|
+
|
|
78
|
+
expect(await detected()).toEqual(['wp-content/themes/mytheme']);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('detects a repo sitting directly under an ignored parent', async () => {
|
|
82
|
+
await writeFile(path.join(root, '.gitignore'), 'themes/\n');
|
|
83
|
+
await initRepo(path.join(root, 'themes/mytheme'));
|
|
84
|
+
|
|
85
|
+
expect(await detected()).toEqual(['themes/mytheme']);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test('does not report repos generated deep inside an ignored tree', async () => {
|
|
89
|
+
await writeFile(path.join(root, '.gitignore'), 'themes/\n');
|
|
90
|
+
await initRepo(path.join(root, 'themes/mytheme'));
|
|
91
|
+
await initRepo(path.join(root, 'themes/cache/vendor/dep/checkout'));
|
|
92
|
+
|
|
93
|
+
expect(await detected()).toEqual(['themes/mytheme']);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('a nested repo is judged by its own ignore rules', async () => {
|
|
97
|
+
await initRepo(path.join(root, 'packages/widget'));
|
|
98
|
+
await writeFile(path.join(root, 'packages/widget/.gitignore'), 'build/\n');
|
|
99
|
+
await initRepo(path.join(root, 'packages/widget/build/x/y/dep'));
|
|
100
|
+
await initRepo(path.join(root, 'packages/widget/plugins/helper'));
|
|
101
|
+
|
|
102
|
+
expect(await detected()).toEqual(['packages/widget', 'packages/widget/plugins/helper']);
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe('findRepoForFile', () => {
|
|
107
|
+
test('routes a file to the deepest owning repo', async () => {
|
|
108
|
+
await initRepo(path.join(root, 'packages/widget'));
|
|
109
|
+
await initRepo(path.join(root, 'packages/widget/plugins/helper'));
|
|
110
|
+
|
|
111
|
+
const owner = await findRepoForFile(root, 'packages/widget/plugins/helper/src/a.ts');
|
|
112
|
+
expect(owner?.repoPath).toBe(path.join(root, 'packages/widget/plugins/helper'));
|
|
113
|
+
expect(owner?.relativeFilePath).toBe('src/a.ts');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test('leaves outer-repo files alone', async () => {
|
|
117
|
+
await initRepo(path.join(root, 'packages/widget'));
|
|
118
|
+
|
|
119
|
+
expect(await findRepoForFile(root, 'src/main.ts')).toBeNull();
|
|
120
|
+
});
|
|
121
|
+
});
|