@myrialabs/clopen 0.4.31 → 0.4.33

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.
Files changed (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. 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 only own the per-project `Query` lifecycle, an
7
- * `AbortController`, and the single-slot `pendingAskUserQuestion` for the
8
- * blocking AskUserQuestion flow.
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 activeController: AbortController | null = null;
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.activeController !== null;
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
- await this.cancel();
101
- this.pendingAskUserQuestion = null;
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
- this.activeController = abortController || new AbortController();
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;
@@ -147,7 +162,7 @@ export class QwenEngine implements AIEngine {
147
162
  // Refresh the synthetic skills preamble in the Qwen memory file.
148
163
  await syncSkills('qwen', profileId);
149
164
  await syncEngineArtifacts('qwen', profileId);
150
- const mcpConfig = getQwenMcpConfig(mcpProfileFilter);
165
+ const mcpConfig = getQwenMcpConfig(mcpProfileFilter, options.mcpContext);
151
166
 
152
167
  // Resolve the permission policy once per stream; canUseTool enforces it
153
168
  // (Qwen otherwise auto-allows everything). Tool names arrive snake_cased.
@@ -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: this.activeController,
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
- this.pendingAskUserQuestion = null;
291
+ run.pendingAskUserQuestion = null;
277
292
  };
278
293
  ctx.signal.addEventListener('abort', onAbort, { once: true });
279
294
 
280
- this.pendingAskUserQuestion = {
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
- this.activeQuery = queryInstance;
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 (this.pendingAskUserQuestion && this.pendingAskUserQuestion.toolUseId === null) {
321
- this.pendingAskUserQuestion.toolUseId = toolUseId;
335
+ if (run.pendingAskUserQuestion && run.pendingAskUserQuestion.toolUseId === null) {
336
+ run.pendingAskUserQuestion.toolUseId = toolUseId;
322
337
  }
323
338
  },
324
339
  });
325
- this.activeConverter = converter;
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
- this.activeController = null;
333
- this.activeQuery = null;
334
- this.activeConverter = null;
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
- async cancel(): Promise<void> {
339
- // Drop the pending AskUserQuestion handler — same pattern as Claude
340
- // (don't resolve, just abandon, otherwise the SDK tries to write to
341
- // a subprocess that's about to die).
342
- if (this.pendingAskUserQuestion) {
343
- this.pendingAskUserQuestion.removeAbortListener();
344
- this.pendingAskUserQuestion = null;
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
- if (this.activeQuery && typeof this.activeQuery.close === 'function') {
348
- try {
349
- await this.activeQuery.close();
350
- } catch {
351
- /* subprocess may already be dead */
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
- if (this.activeController && !this.activeController.signal.aborted) {
356
- this.activeController.abort();
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
- if (this.activeQuery && typeof this.activeQuery.interrupt === 'function') {
365
- try {
366
- await this.activeQuery.interrupt();
367
- } catch {
368
- /* fall through to cancel */
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
- const pending = this.pendingAskUserQuestion;
457
- if (!pending) {
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
- this.activeConverter?.recordUserAnswer(toolUseId, answers);
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
- this.pendingAskUserQuestion = null;
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>; // hard cancel
16
- interrupt(): Promise<void>; // soft stop
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.** Because `getProjectEngine`
35
- returns one instance per `(projectId, engineType)`, the abort controller,
36
- active query, `pendingUserAnswers`, and session ID are automatically
37
- isolated per-project.
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 — isolated per-project |
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
@@ -165,6 +190,13 @@ interface EngineQueryOptions {
165
190
  **cannot** write into project B. Always forward it: see `claude/stream.ts`
166
191
  calling `getEnabledMcpServers(options.mcpContext)`.
167
192
 
193
+ Engines that reach MCP over the HTTP bridge instead of in-process forward the
194
+ same context to their config builder — `getCodexMcpConfig(filter, mcpContext)`
195
+ and friends — which writes it into the bridge URL for `handleMcpRequest` to bind.
196
+ Skipping it does not fail loudly: the handler falls back to the most recently
197
+ started stream, so tool calls land in whichever project the user most recently
198
+ prompted in. See `backend/mcp/README.md` → "Who is calling".
199
+
168
200
  `reasoningEffort` is an **opaque, native-per-engine token** — there is no
169
201
  cross-engine normalization. The adapter that produced the level in
170
202
  `models.ts` is the one that consumes it in `stream.ts`; every other layer
@@ -280,10 +312,16 @@ Important conventions:
280
312
  - Tool names **must** be canonicalised via `toCanonicalToolName(...)`
281
313
  (`shared/types/unified/tool.ts`) so the frontend renders the same UI for
282
314
  tools that have different names across SDKs.
315
+ - `cancel()` targeting: act **only** on `this.runs.select(owner)`. Never fall
316
+ back to "the runs that are left" when the owner is gone — the caller named a
317
+ stream that already ended, and the runs that are left belong to other chats
318
+ (see invariant 2 and `adapters/run-registry.test.ts`).
283
319
  - `cancel()` ordering: **abort the local controller first**, **then** RPC
284
320
  to the SDK/server. RPCs can hang; the local abort cuts the `for await`
285
- loop deterministically. See `OpenCodeEngine.cancel`,
286
- `ClaudeCodeEngine.cancel`, `CopilotEngine.cancel`.
321
+ loop deterministically. Release shared resources (OpenCode's pool hold)
322
+ **after** the RPC, or the server can be reaped mid-call. See
323
+ `OpenCodeEngine.stopRuns`, `ClaudeCodeEngine.stopRuns`,
324
+ `CopilotEngine.stopRuns`.
287
325
  - Dynamic-catalog fetchers in `models.ts` MUST return `EngineModel[]` and
288
326
  use `[]` as the failure sentinel (network, auth, parse error). Do **not**
289
327
  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