@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
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Wraps `@qwen-code/sdk` into the AIEngine interface. The SDK manages a
|
|
5
5
|
* `qwen` subprocess per `query()` call (CLI is bundled with the SDK from
|
|
6
|
-
* v0.1.1+). We
|
|
7
|
-
* `
|
|
8
|
-
*
|
|
6
|
+
* v0.1.1+). We own the `Query` lifecycle, an `AbortController` and the
|
|
7
|
+
* `pendingAskUserQuestion` slot of the blocking AskUserQuestion flow — all of
|
|
8
|
+
* it per RUN, since one instance serves every chat session of a project and
|
|
9
|
+
* several of them can be streaming at the same time.
|
|
9
10
|
*
|
|
10
11
|
* Auth: paste-token only. `engine_accounts.credential` stores the
|
|
11
12
|
* OpenAI-compatible API key; the active account is read on every stream
|
|
@@ -46,6 +47,7 @@ import { handleStreamError } from './error-handler';
|
|
|
46
47
|
import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
|
|
47
48
|
import { fetchQwenModels } from './models';
|
|
48
49
|
import { getQwenMcpConfig } from '../../../mcp';
|
|
50
|
+
import { EngineRuns } from '../run-registry';
|
|
49
51
|
import { artifactFilter } from '$backend/profiles';
|
|
50
52
|
import { syncSkills } from '$backend/skills';
|
|
51
53
|
import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
@@ -65,29 +67,40 @@ interface PendingAskUserQuestion {
|
|
|
65
67
|
toolUseId: string | null;
|
|
66
68
|
}
|
|
67
69
|
|
|
70
|
+
/**
|
|
71
|
+
* One stream in flight on this instance. All of it used to be instance fields,
|
|
72
|
+
* which only held the most recently started stream — so a second chat in the
|
|
73
|
+
* same project silently took over the first one's query, converter and parked
|
|
74
|
+
* question, and cancelling either one tore down the wrong stream.
|
|
75
|
+
*/
|
|
76
|
+
interface QwenRun {
|
|
77
|
+
/** Identity of the run — the controller the caller passed to streamQuery. */
|
|
78
|
+
controller: AbortController;
|
|
79
|
+
query: Query | null;
|
|
80
|
+
/**
|
|
81
|
+
* Live converter for this run — used by `resolveUserAnswer` to push the
|
|
82
|
+
* user's answers into the converter state so the eventual AUQ tool_result
|
|
83
|
+
* can be rewritten with the actual answers (the Qwen SDK's `canUseTool` →
|
|
84
|
+
* AUQ tool execution path drops `answers` on the floor; see the comment
|
|
85
|
+
* block at the top of `message-converter.ts` and the analysis in
|
|
86
|
+
* `qwen/stream.ts::canUseTool` for AskUserQuestion).
|
|
87
|
+
*/
|
|
88
|
+
converter: SdkMessageConverter | null;
|
|
89
|
+
pendingAskUserQuestion: PendingAskUserQuestion | null;
|
|
90
|
+
}
|
|
91
|
+
|
|
68
92
|
export class QwenEngine implements AIEngine {
|
|
69
93
|
readonly name = 'qwen' as const;
|
|
70
94
|
|
|
71
95
|
private _isInitialized = false;
|
|
72
|
-
private
|
|
73
|
-
private activeQuery: Query | null = null;
|
|
74
|
-
private pendingAskUserQuestion: PendingAskUserQuestion | null = null;
|
|
75
|
-
/**
|
|
76
|
-
* Live converter for the current stream — used by `resolveUserAnswer` to
|
|
77
|
-
* push the user's answers into the converter state so the eventual AUQ
|
|
78
|
-
* tool_result can be rewritten with the actual answers (the Qwen SDK's
|
|
79
|
-
* `canUseTool` → AUQ tool execution path drops `answers` on the floor; see
|
|
80
|
-
* the comment block at the top of `message-converter.ts` and the analysis
|
|
81
|
-
* in `qwen/stream.ts::canUseTool` for AskUserQuestion).
|
|
82
|
-
*/
|
|
83
|
-
private activeConverter: SdkMessageConverter | null = null;
|
|
96
|
+
private runs = new EngineRuns<QwenRun>();
|
|
84
97
|
|
|
85
98
|
get isInitialized(): boolean {
|
|
86
99
|
return this._isInitialized;
|
|
87
100
|
}
|
|
88
101
|
|
|
89
102
|
get isActive(): boolean {
|
|
90
|
-
return this.
|
|
103
|
+
return this.runs.isActive;
|
|
91
104
|
}
|
|
92
105
|
|
|
93
106
|
async initialize(): Promise<void> {
|
|
@@ -97,8 +110,8 @@ export class QwenEngine implements AIEngine {
|
|
|
97
110
|
}
|
|
98
111
|
|
|
99
112
|
async dispose(): Promise<void> {
|
|
100
|
-
|
|
101
|
-
this.
|
|
113
|
+
// Shutdown/retirement: every run on this instance goes.
|
|
114
|
+
await this.stopRuns(this.runs.all());
|
|
102
115
|
this._isInitialized = false;
|
|
103
116
|
}
|
|
104
117
|
|
|
@@ -139,7 +152,9 @@ export class QwenEngine implements AIEngine {
|
|
|
139
152
|
}
|
|
140
153
|
const { env } = resolution;
|
|
141
154
|
|
|
142
|
-
|
|
155
|
+
const controller = abortController || new AbortController();
|
|
156
|
+
const run: QwenRun = { controller, query: null, converter: null, pendingAskUserQuestion: null };
|
|
157
|
+
this.runs.add(run);
|
|
143
158
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
144
159
|
// Active Profile for this stream — scopes artifacts + connectors.
|
|
145
160
|
const profileId = options.mcpContext?.profileId;
|
|
@@ -194,7 +209,7 @@ export class QwenEngine implements AIEngine {
|
|
|
194
209
|
// "Qwen OAuth free tier was discontinued" even though we've
|
|
195
210
|
// supplied OPENAI_API_KEY / OPENAI_BASE_URL.
|
|
196
211
|
authType: 'openai',
|
|
197
|
-
abortController:
|
|
212
|
+
abortController: controller,
|
|
198
213
|
includePartialMessages,
|
|
199
214
|
stderr: (msg: string) => {
|
|
200
215
|
const trimmed = msg.replace(/\s+$/, '');
|
|
@@ -273,11 +288,11 @@ export class QwenEngine implements AIEngine {
|
|
|
273
288
|
// Claude (see claude/stream.ts cancel()). Resolving
|
|
274
289
|
// would prompt the SDK to write the result to a
|
|
275
290
|
// subprocess that's about to die.
|
|
276
|
-
|
|
291
|
+
run.pendingAskUserQuestion = null;
|
|
277
292
|
};
|
|
278
293
|
ctx.signal.addEventListener('abort', onAbort, { once: true });
|
|
279
294
|
|
|
280
|
-
|
|
295
|
+
run.pendingAskUserQuestion = {
|
|
281
296
|
resolve: (result) => {
|
|
282
297
|
ctx.signal.removeEventListener('abort', onAbort);
|
|
283
298
|
resolve(result);
|
|
@@ -308,7 +323,7 @@ export class QwenEngine implements AIEngine {
|
|
|
308
323
|
|
|
309
324
|
const { query } = await loadEngineSdk<typeof import('@qwen-code/sdk')>('qwen', '@qwen-code/sdk');
|
|
310
325
|
const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
|
|
311
|
-
|
|
326
|
+
run.query = queryInstance;
|
|
312
327
|
|
|
313
328
|
const converter = createSdkMessageConverter(modelId, {
|
|
314
329
|
onAskUserQuestionEmitted: (toolUseId: string) => {
|
|
@@ -317,55 +332,68 @@ export class QwenEngine implements AIEngine {
|
|
|
317
332
|
// the pending slot here unblocks `resolveUserAnswer` even
|
|
318
333
|
// when the frontend gets the toolUseId before our slot was
|
|
319
334
|
// populated (rare but possible if the SDK queues events).
|
|
320
|
-
if (
|
|
321
|
-
|
|
335
|
+
if (run.pendingAskUserQuestion && run.pendingAskUserQuestion.toolUseId === null) {
|
|
336
|
+
run.pendingAskUserQuestion.toolUseId = toolUseId;
|
|
322
337
|
}
|
|
323
338
|
},
|
|
324
339
|
});
|
|
325
|
-
|
|
340
|
+
run.converter = converter;
|
|
326
341
|
for await (const sdkMessage of queryInstance) {
|
|
327
342
|
yield* converter.convert(sdkMessage);
|
|
328
343
|
}
|
|
329
344
|
} catch (error) {
|
|
330
345
|
handleStreamError(error, stderrLines.join('\n'));
|
|
331
346
|
} finally {
|
|
332
|
-
|
|
333
|
-
this.
|
|
334
|
-
this.
|
|
347
|
+
// Retire THIS run only — another chat session of the same project may
|
|
348
|
+
// still be streaming on this instance.
|
|
349
|
+
this.runs.remove(run);
|
|
335
350
|
}
|
|
336
351
|
}
|
|
337
352
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
353
|
+
/**
|
|
354
|
+
* Cancel the run whose AbortController is `owner`, and only that run.
|
|
355
|
+
*/
|
|
356
|
+
async cancel(owner: AbortController): Promise<void> {
|
|
357
|
+
await this.stopRuns(this.runs.select(owner));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Tear down the given runs. `cancel` passes the one run it was asked to
|
|
362
|
+
* stop; `dispose` passes them all. Nothing else may reach this.
|
|
363
|
+
*/
|
|
364
|
+
private async stopRuns(targets: QwenRun[]): Promise<void> {
|
|
365
|
+
for (const run of targets) {
|
|
366
|
+
// Drop this run's pending AskUserQuestion handler — same pattern as
|
|
367
|
+
// Claude (don't resolve, just abandon, otherwise the SDK tries to write
|
|
368
|
+
// to a subprocess that's about to die). Another run's parked question
|
|
369
|
+
// is left alone; its subprocess is still alive and still waiting.
|
|
370
|
+
if (run.pendingAskUserQuestion) {
|
|
371
|
+
run.pendingAskUserQuestion.removeAbortListener();
|
|
372
|
+
run.pendingAskUserQuestion = null;
|
|
373
|
+
}
|
|
346
374
|
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
375
|
+
if (run.query && typeof run.query.close === 'function') {
|
|
376
|
+
try {
|
|
377
|
+
await run.query.close();
|
|
378
|
+
} catch {
|
|
379
|
+
/* subprocess may already be dead */
|
|
380
|
+
}
|
|
352
381
|
}
|
|
353
|
-
}
|
|
354
382
|
|
|
355
|
-
|
|
356
|
-
this.
|
|
383
|
+
if (!run.controller.signal.aborted) run.controller.abort();
|
|
384
|
+
this.runs.remove(run);
|
|
357
385
|
}
|
|
358
|
-
this.activeController = null;
|
|
359
|
-
this.activeQuery = null;
|
|
360
|
-
this.activeConverter = null;
|
|
361
386
|
}
|
|
362
387
|
|
|
363
|
-
async interrupt(): Promise<void> {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
388
|
+
async interrupt(owner: AbortController): Promise<void> {
|
|
389
|
+
const targets = this.runs.select(owner);
|
|
390
|
+
for (const run of targets) {
|
|
391
|
+
if (run.query && typeof run.query.interrupt === 'function') {
|
|
392
|
+
try {
|
|
393
|
+
await run.query.interrupt();
|
|
394
|
+
} catch {
|
|
395
|
+
/* fall through to cancel */
|
|
396
|
+
}
|
|
369
397
|
}
|
|
370
398
|
}
|
|
371
399
|
}
|
|
@@ -453,8 +481,13 @@ export class QwenEngine implements AIEngine {
|
|
|
453
481
|
}
|
|
454
482
|
|
|
455
483
|
resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
|
|
456
|
-
|
|
457
|
-
|
|
484
|
+
// Find the run that parked this question: the one that already recorded
|
|
485
|
+
// this toolUseId, else the one still waiting for its id to arrive.
|
|
486
|
+
const running = this.runs.all();
|
|
487
|
+
const run = running.find(r => r.pendingAskUserQuestion?.toolUseId === toolUseId)
|
|
488
|
+
?? running.find(r => r.pendingAskUserQuestion && r.pendingAskUserQuestion.toolUseId === null);
|
|
489
|
+
const pending = run?.pendingAskUserQuestion ?? null;
|
|
490
|
+
if (!run || !pending) {
|
|
458
491
|
debug.warn('engine', 'Qwen resolveUserAnswer: no pending question');
|
|
459
492
|
return false;
|
|
460
493
|
}
|
|
@@ -474,13 +507,13 @@ export class QwenEngine implements AIEngine {
|
|
|
474
507
|
// tool_result body is `"User has provided the following answers:\n\n"`
|
|
475
508
|
// (empty). The converter intercepts that tool_result and replaces its
|
|
476
509
|
// content with the proper formatted answers we just stored.
|
|
477
|
-
|
|
510
|
+
run.converter?.recordUserAnswer(toolUseId, answers);
|
|
478
511
|
|
|
479
512
|
pending.resolve({
|
|
480
513
|
behavior: 'allow',
|
|
481
514
|
updatedInput: { ...pending.input, answers },
|
|
482
515
|
});
|
|
483
|
-
|
|
516
|
+
run.pendingAskUserQuestion = null;
|
|
484
517
|
return true;
|
|
485
518
|
}
|
|
486
519
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { EngineRuns } from './run-registry';
|
|
4
|
+
|
|
5
|
+
// One engine instance serves every chat session of a project, so a cancel has to
|
|
6
|
+
// name the stream it means. These cases are the difference between "Stop this
|
|
7
|
+
// chat" and "Stop whatever this engine happens to be doing" — the second one
|
|
8
|
+
// interrupted a different chat mid-answer.
|
|
9
|
+
|
|
10
|
+
interface Run {
|
|
11
|
+
controller: AbortController;
|
|
12
|
+
label: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function registry(...labels: string[]) {
|
|
16
|
+
const runs = new EngineRuns<Run>();
|
|
17
|
+
const byLabel: Record<string, Run> = {};
|
|
18
|
+
for (const label of labels) {
|
|
19
|
+
byLabel[label] = runs.add({ controller: new AbortController(), label });
|
|
20
|
+
}
|
|
21
|
+
return { runs, byLabel };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe('EngineRuns', () => {
|
|
25
|
+
test('an owner selects its own run and leaves the others alone', () => {
|
|
26
|
+
const { runs, byLabel } = registry('a', 'b');
|
|
27
|
+
|
|
28
|
+
expect(runs.select(byLabel.a.controller).map(r => r.label)).toEqual(['a']);
|
|
29
|
+
expect(runs.select(byLabel.b.controller).map(r => r.label)).toEqual(['b']);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('an owner that already finished selects nothing', () => {
|
|
33
|
+
const { runs, byLabel } = registry('a', 'b');
|
|
34
|
+
runs.remove(byLabel.a);
|
|
35
|
+
|
|
36
|
+
// The tempting fallback — "target not found, so stop what's left" — is
|
|
37
|
+
// exactly the bug: it would take down 'b', a chat the user never stopped.
|
|
38
|
+
expect(runs.select(byLabel.a.controller)).toEqual([]);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('all() returns every run, for dispose and shutdown', () => {
|
|
42
|
+
const { runs } = registry('a', 'b');
|
|
43
|
+
|
|
44
|
+
expect(runs.all().map(r => r.label).sort()).toEqual(['a', 'b']);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('isActive stays true until the LAST run ends', () => {
|
|
48
|
+
const { runs, byLabel } = registry('a', 'b');
|
|
49
|
+
|
|
50
|
+
expect(runs.isActive).toBe(true);
|
|
51
|
+
runs.remove(byLabel.a);
|
|
52
|
+
// An engine retired mid-stream is disposed once it goes idle. Reporting
|
|
53
|
+
// idle here would dispose it out from under 'b'.
|
|
54
|
+
expect(runs.isActive).toBe(true);
|
|
55
|
+
runs.remove(byLabel.b);
|
|
56
|
+
expect(runs.isActive).toBe(false);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('removing a run twice is not an error', () => {
|
|
60
|
+
const { runs, byLabel } = registry('a');
|
|
61
|
+
|
|
62
|
+
// cancel() and the stream's own `finally` both retire the run.
|
|
63
|
+
runs.remove(byLabel.a);
|
|
64
|
+
runs.remove(byLabel.a);
|
|
65
|
+
expect(runs.isActive).toBe(false);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('an empty registry is not an error', () => {
|
|
69
|
+
const runs = new EngineRuns<Run>();
|
|
70
|
+
|
|
71
|
+
expect(runs.all()).toEqual([]);
|
|
72
|
+
expect(runs.select(new AbortController())).toEqual([]);
|
|
73
|
+
expect(runs.isActive).toBe(false);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The runs an engine instance is currently serving.
|
|
3
|
+
*
|
|
4
|
+
* One instance is shared by every chat session of a project (see
|
|
5
|
+
* `getProjectEngine`), so at any moment it can be streaming several chats at
|
|
6
|
+
* once. Everything a single stream owns — its abort controller, its SDK query
|
|
7
|
+
* or session, its pooled server, its parked questions — therefore belongs to a
|
|
8
|
+
* RUN and not to the instance. An instance field holds only the most recently
|
|
9
|
+
* started stream, which is how "Stop this chat" came to abort a different chat
|
|
10
|
+
* of the same project.
|
|
11
|
+
*
|
|
12
|
+
* A run is identified by the AbortController its caller passed to
|
|
13
|
+
* `streamQuery`. That is the same object `StreamState.abortController` holds,
|
|
14
|
+
* so it is the one handle the stream-manager and the adapter already agree on —
|
|
15
|
+
* no ids to mint, no bookkeeping to keep in sync.
|
|
16
|
+
*
|
|
17
|
+
* Adapters own the SHAPE of a run (each SDK exposes different handles) and this
|
|
18
|
+
* class owns the BOOKKEEPING, so the targeting rules live in one place instead
|
|
19
|
+
* of eight.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** The one field every adapter's run state must expose: its own controller. */
|
|
23
|
+
export interface EngineRun {
|
|
24
|
+
controller: AbortController;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class EngineRuns<T extends EngineRun> {
|
|
28
|
+
private byController = new Map<AbortController, T>();
|
|
29
|
+
|
|
30
|
+
/** True while at least ONE run is in flight — the answer `AIEngine.isActive` owes its callers. */
|
|
31
|
+
get isActive(): boolean {
|
|
32
|
+
return this.byController.size > 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Register a run for the duration of one `streamQuery` call. */
|
|
36
|
+
add(run: T): T {
|
|
37
|
+
this.byController.set(run.controller, run);
|
|
38
|
+
return run;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Unregister a finished run. Idempotent — cancel and the stream's own `finally` both call it. */
|
|
42
|
+
remove(run: T): void {
|
|
43
|
+
this.byController.delete(run.controller);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The run a targeted `cancel` / `interrupt` applies to.
|
|
48
|
+
*
|
|
49
|
+
* An owner that has already finished selects NOTHING. Falling back to "the
|
|
50
|
+
* runs that are left" is what made Stop in one chat kill another chat of the
|
|
51
|
+
* same project: the caller named a stream that had ended, and the engine
|
|
52
|
+
* helpfully tore down whichever one it still had.
|
|
53
|
+
*/
|
|
54
|
+
select(owner: AbortController): T[] {
|
|
55
|
+
const run = this.byController.get(owner);
|
|
56
|
+
return run ? [run] : [];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Every run — for `dispose()` and shutdown, the only places that may stop them all. */
|
|
60
|
+
all(): T[] {
|
|
61
|
+
return [...this.byController.values()];
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -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
|