@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.
- package/backend/auth/permissions.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +31 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +8 -1
- 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/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +78 -22
- package/backend/engine/adapters/copilot/stream.ts +97 -53
- package/backend/engine/adapters/cursor/stream.ts +75 -35
- 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 +92 -59
- 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 +47 -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/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +224 -0
- package/backend/git/nested-repos.ts +386 -0
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +23 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +309 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/db-client/connections.ts +1 -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/files/watch.ts +5 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/index.ts +4 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
- package/dist/assets/main-BbwWLJRN.js +1057 -0
- package/dist/assets/main-CCvRMXlP.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +1 -0
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-VgdjTBLR.css +0 -1
- package/dist/assets/main-r0iv2PDz.js +0 -1044
|
@@ -36,6 +36,7 @@ import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
|
36
36
|
import { artifactFilter } from '$backend/profiles';
|
|
37
37
|
import { resolvePermissionsFromDb, isToolAllowed, hasAnyRestriction, syncPermissions } from '$backend/permissions';
|
|
38
38
|
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
39
|
+
import { EngineRuns } from '../run-registry';
|
|
39
40
|
import type { EngineModel } from '$shared/types/unified';
|
|
40
41
|
import { CLAUDE_CODE_MODELS } from './models';
|
|
41
42
|
|
|
@@ -46,6 +47,20 @@ interface PendingUserAnswer {
|
|
|
46
47
|
resolve: (result: PermissionResult) => void;
|
|
47
48
|
removeAbortListener: () => void;
|
|
48
49
|
input: Record<string, unknown>;
|
|
50
|
+
/** The run that asked — cancelling one run must not abandon another's questions. */
|
|
51
|
+
run: ClaudeRun;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* One stream in flight on this instance. This engine instance is shared by every
|
|
56
|
+
* chat session of a project, so the SDK query has to be held per run: a single
|
|
57
|
+
* field holds only the most recently started stream, and cancelling any chat
|
|
58
|
+
* would then close another chat's query.
|
|
59
|
+
*/
|
|
60
|
+
interface ClaudeRun {
|
|
61
|
+
/** Identity of the run — the controller the caller passed to streamQuery. */
|
|
62
|
+
controller: AbortController;
|
|
63
|
+
query: Query | null;
|
|
49
64
|
}
|
|
50
65
|
|
|
51
66
|
/** Merge the SDK stream with Workflow transcript polling without blocking either producer. */
|
|
@@ -78,8 +93,7 @@ class EventQueue<T> {
|
|
|
78
93
|
export class ClaudeCodeEngine implements AIEngine {
|
|
79
94
|
readonly name = 'claude-code' as const;
|
|
80
95
|
private _isInitialized = false;
|
|
81
|
-
private
|
|
82
|
-
private activeQuery: Query | null = null;
|
|
96
|
+
private runs = new EngineRuns<ClaudeRun>();
|
|
83
97
|
private pendingUserAnswers = new Map<string, PendingUserAnswer>();
|
|
84
98
|
|
|
85
99
|
get isInitialized(): boolean {
|
|
@@ -87,7 +101,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
87
101
|
}
|
|
88
102
|
|
|
89
103
|
get isActive(): boolean {
|
|
90
|
-
return this.
|
|
104
|
+
return this.runs.isActive;
|
|
91
105
|
}
|
|
92
106
|
|
|
93
107
|
async initialize(): Promise<void> {
|
|
@@ -101,7 +115,8 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
101
115
|
}
|
|
102
116
|
|
|
103
117
|
async dispose(): Promise<void> {
|
|
104
|
-
|
|
118
|
+
// Shutdown/retirement: every run on this instance goes.
|
|
119
|
+
await this.stopRuns(this.runs.all());
|
|
105
120
|
this.pendingUserAnswers.clear();
|
|
106
121
|
this._isInitialized = false;
|
|
107
122
|
}
|
|
@@ -140,10 +155,9 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
140
155
|
debug.log('chat', "Claude Code - Stream Query");
|
|
141
156
|
debug.log('chat', { prompt });
|
|
142
157
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const streamController = this.activeController;
|
|
158
|
+
const streamController = abortController || new AbortController();
|
|
159
|
+
const run: ClaudeRun = { controller: streamController, query: null };
|
|
160
|
+
this.runs.add(run);
|
|
147
161
|
|
|
148
162
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
149
163
|
|
|
@@ -244,6 +258,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
244
258
|
canUseToolOptions.signal.addEventListener('abort', onAbort, { once: true });
|
|
245
259
|
|
|
246
260
|
this.pendingUserAnswers.set(canUseToolOptions.toolUseID, {
|
|
261
|
+
run,
|
|
247
262
|
resolve: (result: PermissionResult) => {
|
|
248
263
|
canUseToolOptions.signal.removeEventListener('abort', onAbort);
|
|
249
264
|
resolve(result);
|
|
@@ -289,7 +304,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
289
304
|
...(maxTurns && { maxTurns }),
|
|
290
305
|
...(includePartialMessages && { includePartialMessages }),
|
|
291
306
|
forwardSubagentText: true,
|
|
292
|
-
abortController:
|
|
307
|
+
abortController: streamController,
|
|
293
308
|
...(Object.keys(mcpServers).length > 0 && { mcpServers }),
|
|
294
309
|
...(allowedMcpTools.length > 0 && { allowedTools: allowedMcpTools })
|
|
295
310
|
};
|
|
@@ -306,7 +321,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
306
321
|
options: sdkOptions,
|
|
307
322
|
});
|
|
308
323
|
|
|
309
|
-
|
|
324
|
+
run.query = queryInstance;
|
|
310
325
|
|
|
311
326
|
// Per-query stateful converter so block-stop reasoning tracking persists
|
|
312
327
|
// across the stream of SDK messages.
|
|
@@ -335,9 +350,9 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
335
350
|
const observedVersion = workflowTranscripts.changeVersion;
|
|
336
351
|
for (const output of await workflowTranscripts.drain()) events.push(output);
|
|
337
352
|
|
|
338
|
-
if (
|
|
353
|
+
if (streamController.signal.aborted) break;
|
|
339
354
|
if (sdkStreamDone && !await workflowTranscripts.hasActiveWorkflows()) break;
|
|
340
|
-
await workflowTranscripts.waitForChange(observedVersion,
|
|
355
|
+
await workflowTranscripts.waitForChange(observedVersion, streamController.signal);
|
|
341
356
|
}
|
|
342
357
|
// The terminal status event is authoritative; drain once more for writes
|
|
343
358
|
// already queued by the filesystem before closing the merged stream.
|
|
@@ -363,62 +378,87 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
363
378
|
} catch (error) {
|
|
364
379
|
handleStreamError(error);
|
|
365
380
|
} finally {
|
|
366
|
-
|
|
367
|
-
|
|
381
|
+
// Retire THIS run only — a concurrent stream of another chat session in
|
|
382
|
+
// the same project is still using the instance.
|
|
383
|
+
this.forgetRun(run);
|
|
368
384
|
}
|
|
369
385
|
}
|
|
370
386
|
|
|
371
387
|
/**
|
|
372
|
-
*
|
|
388
|
+
* Drop a finished run and the questions only it could have answered.
|
|
373
389
|
*/
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
// already killed the subprocess, this write throws "Operation aborted" as
|
|
379
|
-
// an unhandled error, crashing the server. By removing listeners and not
|
|
380
|
-
// resolving, the promises are safely abandoned when close() terminates the
|
|
381
|
-
// process and the async generator completes.
|
|
382
|
-
for (const [, pending] of this.pendingUserAnswers) {
|
|
383
|
-
pending.removeAbortListener();
|
|
390
|
+
private forgetRun(run: ClaudeRun): void {
|
|
391
|
+
this.runs.remove(run);
|
|
392
|
+
for (const [toolUseId, pending] of this.pendingUserAnswers) {
|
|
393
|
+
if (pending.run === run) this.pendingUserAnswers.delete(toolUseId);
|
|
384
394
|
}
|
|
385
|
-
|
|
395
|
+
run.query = null;
|
|
396
|
+
}
|
|
386
397
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
398
|
+
/**
|
|
399
|
+
* Cancel the run whose AbortController is `owner`, and only that run.
|
|
400
|
+
*/
|
|
401
|
+
async cancel(owner: AbortController): Promise<void> {
|
|
402
|
+
await this.stopRuns(this.runs.select(owner));
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Tear down the given runs. `cancel` passes the one run it was asked to
|
|
407
|
+
* stop; `dispose` passes them all. Nothing else may reach this.
|
|
408
|
+
*/
|
|
409
|
+
private async stopRuns(targets: ClaudeRun[]): Promise<void> {
|
|
410
|
+
for (const run of targets) {
|
|
411
|
+
// Remove abort listeners from this run's pending AskUserQuestion promises
|
|
412
|
+
// WITHOUT resolving them. Resolving causes the SDK to call
|
|
413
|
+
// handleControlRequest → write() to send the permission result to the
|
|
414
|
+
// subprocess. If close() has already killed the subprocess, this write
|
|
415
|
+
// throws "Operation aborted" as an unhandled error, crashing the server.
|
|
416
|
+
// By removing listeners and not resolving, the promises are safely
|
|
417
|
+
// abandoned when close() terminates the process and the async generator
|
|
418
|
+
// completes. Questions parked by OTHER runs stay put — their subprocess
|
|
419
|
+
// is still alive and still waiting for an answer.
|
|
420
|
+
for (const [, pending] of this.pendingUserAnswers) {
|
|
421
|
+
if (pending.run === run) pending.removeAbortListener();
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Use close() to forcefully terminate the query process and clean up
|
|
425
|
+
// all resources (docs: "Forcefully ends the query and cleans up all
|
|
426
|
+
// resources"). Unlike interrupt() which can hang indefinitely when the
|
|
427
|
+
// subprocess is unresponsive, close() is synchronous and guaranteed to
|
|
428
|
+
// complete — making cancel deterministic.
|
|
429
|
+
if (run.query && typeof run.query.close === 'function') {
|
|
430
|
+
try {
|
|
431
|
+
run.query.close();
|
|
432
|
+
} catch {
|
|
433
|
+
// Ignore close errors — process may already be dead
|
|
434
|
+
}
|
|
397
435
|
}
|
|
398
|
-
}
|
|
399
436
|
|
|
400
|
-
|
|
401
|
-
this.
|
|
437
|
+
if (!run.controller.signal.aborted) run.controller.abort();
|
|
438
|
+
this.forgetRun(run);
|
|
402
439
|
}
|
|
403
|
-
this.activeController = null;
|
|
404
|
-
this.activeQuery = null;
|
|
405
440
|
}
|
|
406
441
|
|
|
407
442
|
/**
|
|
408
|
-
* Interrupt
|
|
443
|
+
* Interrupt a run (soft stop). Targeted like `cancel`.
|
|
409
444
|
*/
|
|
410
|
-
async interrupt(): Promise<void> {
|
|
411
|
-
|
|
412
|
-
|
|
445
|
+
async interrupt(owner: AbortController): Promise<void> {
|
|
446
|
+
const targets = this.runs.select(owner);
|
|
447
|
+
for (const run of targets) {
|
|
448
|
+
if (run.query && typeof run.query.interrupt === 'function') {
|
|
449
|
+
await run.query.interrupt();
|
|
450
|
+
}
|
|
413
451
|
}
|
|
414
452
|
}
|
|
415
453
|
|
|
416
454
|
/**
|
|
417
|
-
* Change permission mode for
|
|
455
|
+
* Change permission mode for one run's query.
|
|
418
456
|
*/
|
|
419
|
-
async setPermissionMode(mode: PermissionMode): Promise<void> {
|
|
420
|
-
|
|
421
|
-
|
|
457
|
+
async setPermissionMode(mode: PermissionMode, owner: AbortController): Promise<void> {
|
|
458
|
+
for (const run of this.runs.select(owner)) {
|
|
459
|
+
if (run.query && typeof run.query.setPermissionMode === 'function') {
|
|
460
|
+
await run.query.setPermissionMode(mode);
|
|
461
|
+
}
|
|
422
462
|
}
|
|
423
463
|
}
|
|
424
464
|
|
|
@@ -34,6 +34,7 @@ import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engin
|
|
|
34
34
|
import { artifactFilter } from '$backend/profiles';
|
|
35
35
|
import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
|
|
36
36
|
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
37
|
+
import { EngineRuns } from '../run-registry';
|
|
37
38
|
import { subagentQueries } from '$backend/database/queries';
|
|
38
39
|
import { readSubagentMd } from '$backend/subagents/store';
|
|
39
40
|
import { getClineAccountForProvider, parseClineCredential, resolveClineAuth } from './credential';
|
|
@@ -85,12 +86,24 @@ class EventQueue<T> {
|
|
|
85
86
|
}
|
|
86
87
|
}
|
|
87
88
|
|
|
89
|
+
/**
|
|
90
|
+
* One stream in flight on this instance. This engine instance is shared by every
|
|
91
|
+
* chat session of a project, so the agent belongs here, not in an instance field
|
|
92
|
+
* — a field would hold only the most recently started stream, and cancelling any
|
|
93
|
+
* chat would then abort another chat's agent.
|
|
94
|
+
*/
|
|
95
|
+
interface ClineRun {
|
|
96
|
+
/** Identity of the run — the controller the caller passed to streamQuery. */
|
|
97
|
+
controller: AbortController;
|
|
98
|
+
agent: ClineAgent | null;
|
|
99
|
+
}
|
|
100
|
+
|
|
88
101
|
export class ClineEngine implements AIEngine {
|
|
89
102
|
readonly name = 'cline' as const;
|
|
90
103
|
private _isInitialized = false;
|
|
91
|
-
private
|
|
92
|
-
|
|
93
|
-
private pendingAsks = new Map<string, PendingAsk>();
|
|
104
|
+
private runs = new EngineRuns<ClineRun>();
|
|
105
|
+
/** Parked AskUserQuestion callbacks → the run that asked. */
|
|
106
|
+
private pendingAsks = new Map<string, PendingAsk & { owner: ClineRun }>();
|
|
94
107
|
/**
|
|
95
108
|
* In-memory transcript keyed by the SDK session id EMITTED for each turn.
|
|
96
109
|
* Every turn stores its resulting transcript under a fresh id and never
|
|
@@ -101,7 +114,7 @@ export class ClineEngine implements AIEngine {
|
|
|
101
114
|
private sessions = new Map<string, AgentMessage[]>();
|
|
102
115
|
|
|
103
116
|
get isInitialized(): boolean { return this._isInitialized; }
|
|
104
|
-
get isActive(): boolean { return this.
|
|
117
|
+
get isActive(): boolean { return this.runs.isActive; }
|
|
105
118
|
|
|
106
119
|
async initialize(): Promise<void> {
|
|
107
120
|
if (this._isInitialized) return;
|
|
@@ -110,7 +123,7 @@ export class ClineEngine implements AIEngine {
|
|
|
110
123
|
}
|
|
111
124
|
|
|
112
125
|
async dispose(): Promise<void> {
|
|
113
|
-
await this.
|
|
126
|
+
await this.stopRuns(this.runs.all());
|
|
114
127
|
this.pendingAsks.clear();
|
|
115
128
|
this.sessions.clear();
|
|
116
129
|
this._isInitialized = false;
|
|
@@ -145,7 +158,9 @@ export class ClineEngine implements AIEngine {
|
|
|
145
158
|
const provider = parseClineCredential(account.credential)?.provider ?? providerSlug;
|
|
146
159
|
const auth = await resolveClineAuth(account);
|
|
147
160
|
|
|
148
|
-
|
|
161
|
+
const controller = abortController || new AbortController();
|
|
162
|
+
const run: ClineRun = { controller, agent: null };
|
|
163
|
+
this.runs.add(run);
|
|
149
164
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
150
165
|
|
|
151
166
|
// ── Active Profile scoping + artifact materialization ──
|
|
@@ -169,7 +184,7 @@ export class ClineEngine implements AIEngine {
|
|
|
169
184
|
enableSubmitAndExit: false,
|
|
170
185
|
});
|
|
171
186
|
const askTool = await createAskUserQuestionTool({
|
|
172
|
-
register: (id, entry) => this.pendingAsks.set(id, entry),
|
|
187
|
+
register: (id, entry) => this.pendingAsks.set(id, { ...entry, owner: run }),
|
|
173
188
|
unregister: (id) => this.pendingAsks.delete(id),
|
|
174
189
|
});
|
|
175
190
|
const mcpTools = await buildClineMcpTools(options.mcpContext, mcpProfileFilter);
|
|
@@ -278,7 +293,7 @@ export class ClineEngine implements AIEngine {
|
|
|
278
293
|
toolPolicies,
|
|
279
294
|
maxIterations: options.maxTurns ?? 100,
|
|
280
295
|
});
|
|
281
|
-
|
|
296
|
+
run.agent = agent;
|
|
282
297
|
if (priorMessages?.length) agent.restore(priorMessages);
|
|
283
298
|
|
|
284
299
|
const engineMeta: MessageEngine = {
|
|
@@ -300,7 +315,7 @@ export class ClineEngine implements AIEngine {
|
|
|
300
315
|
|
|
301
316
|
// Abort wiring: cancelling the stream aborts the Cline run.
|
|
302
317
|
const onAbort = () => { agent.abort('Cancelled'); };
|
|
303
|
-
|
|
318
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
304
319
|
|
|
305
320
|
// Build the user turn (text + image attachments).
|
|
306
321
|
const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
|
|
@@ -348,29 +363,52 @@ export class ClineEngine implements AIEngine {
|
|
|
348
363
|
} catch (error) {
|
|
349
364
|
handleStreamError(error);
|
|
350
365
|
} finally {
|
|
351
|
-
|
|
366
|
+
controller.signal.removeEventListener('abort', onAbort);
|
|
352
367
|
unsubscribe();
|
|
353
|
-
|
|
354
|
-
this.
|
|
355
|
-
this.
|
|
368
|
+
// Retire THIS run only — another chat session of the same project may
|
|
369
|
+
// still be streaming on this instance.
|
|
370
|
+
this.forgetRun(run);
|
|
356
371
|
}
|
|
357
372
|
}
|
|
358
373
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
374
|
+
/** Drop a finished run and the asks only it could answer. */
|
|
375
|
+
private forgetRun(run: ClineRun): void {
|
|
376
|
+
this.runs.remove(run);
|
|
377
|
+
for (const [id, pending] of this.pendingAsks) {
|
|
378
|
+
if (pending.owner === run) this.pendingAsks.delete(id);
|
|
362
379
|
}
|
|
363
|
-
|
|
364
|
-
|
|
380
|
+
run.agent = null;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Cancel the run whose AbortController is `owner`, and only that run.
|
|
385
|
+
*/
|
|
386
|
+
async cancel(owner: AbortController): Promise<void> {
|
|
387
|
+
await this.stopRuns(this.runs.select(owner));
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Tear down the given runs. `cancel` passes the one run it was asked to
|
|
392
|
+
* stop; `dispose` passes them all. Nothing else may reach this.
|
|
393
|
+
*/
|
|
394
|
+
private async stopRuns(targets: ClineRun[]): Promise<void> {
|
|
395
|
+
for (const run of targets) {
|
|
396
|
+
if (!run.controller.signal.aborted) run.controller.abort();
|
|
397
|
+
const agent = run.agent;
|
|
398
|
+
// Drop only this run's parked asks; another run's are still live.
|
|
399
|
+
this.forgetRun(run);
|
|
400
|
+
if (agent) {
|
|
401
|
+
try { agent.abort('Cancelled'); } catch { /* may already be idle */ }
|
|
402
|
+
}
|
|
365
403
|
}
|
|
366
|
-
this.pendingAsks.clear();
|
|
367
|
-
this.activeAgent = null;
|
|
368
|
-
this.activeController = null;
|
|
369
404
|
}
|
|
370
405
|
|
|
371
|
-
async interrupt(): Promise<void> {
|
|
372
|
-
|
|
373
|
-
|
|
406
|
+
async interrupt(owner: AbortController): Promise<void> {
|
|
407
|
+
const targets = this.runs.select(owner);
|
|
408
|
+
for (const run of targets) {
|
|
409
|
+
if (run.agent) {
|
|
410
|
+
try { run.agent.abort('Interrupted'); } catch { /* ignore */ }
|
|
411
|
+
}
|
|
374
412
|
}
|
|
375
413
|
}
|
|
376
414
|
|
|
@@ -77,7 +77,7 @@ import type {
|
|
|
77
77
|
} from '@openai/codex-sdk';
|
|
78
78
|
import { resolveOpenCodeToolName } from '../../../mcp';
|
|
79
79
|
import { readLastTokenUsageFromRollout } from './usage-rollout';
|
|
80
|
-
import {
|
|
80
|
+
import { readFileChangeSetsFromRollout, findMatchingFileChangeSet } from './patch-rollout';
|
|
81
81
|
|
|
82
82
|
// ============================================================================
|
|
83
83
|
// Engine Identity
|
|
@@ -469,29 +469,35 @@ function buildFileChangePair(item: FileChangeItem, state: CodexStreamState): Eng
|
|
|
469
469
|
const baseId = item.id;
|
|
470
470
|
const isFailed = item.status === 'failed';
|
|
471
471
|
|
|
472
|
-
// SDK doesn't carry
|
|
473
|
-
// rollout JSONL's
|
|
474
|
-
// after text
|
|
475
|
-
|
|
476
|
-
const
|
|
477
|
-
|
|
478
|
-
|
|
472
|
+
// SDK doesn't carry file content on FileUpdateChange — pull it from the
|
|
473
|
+
// rollout JSONL's `patch_apply_end` event so Edit blocks render the real
|
|
474
|
+
// before/after text and Write blocks the real file body. Falls back to
|
|
475
|
+
// empty strings if the rollout isn't readable.
|
|
476
|
+
const changedPaths = item.changes.map(change => change.path);
|
|
477
|
+
const matchedChangeSet = findMatchingFileChangeSet(
|
|
478
|
+
readFileChangeSetsFromRollout(state.sessionId),
|
|
479
|
+
changedPaths,
|
|
480
|
+
);
|
|
479
481
|
|
|
480
482
|
item.changes.forEach((change, idx) => {
|
|
481
483
|
const toolId = `${baseId}:${idx}`;
|
|
482
484
|
let toolName: string;
|
|
483
485
|
let input: Record<string, unknown>;
|
|
484
486
|
|
|
487
|
+
const recovered = matchedChangeSet?.get(change.path);
|
|
488
|
+
|
|
485
489
|
if (change.kind === 'add') {
|
|
486
490
|
toolName = 'Write';
|
|
487
|
-
input = {
|
|
491
|
+
input = {
|
|
492
|
+
filePath: change.path,
|
|
493
|
+
content: recovered?.content ?? '',
|
|
494
|
+
} satisfies WriteInput as unknown as Record<string, unknown>;
|
|
488
495
|
} else if (change.kind === 'update') {
|
|
489
496
|
toolName = 'Edit';
|
|
490
|
-
const diff = matchedPatch?.get(change.path);
|
|
491
497
|
input = {
|
|
492
498
|
filePath: change.path,
|
|
493
|
-
oldString:
|
|
494
|
-
newString:
|
|
499
|
+
oldString: recovered?.oldString ?? '',
|
|
500
|
+
newString: recovered?.newString ?? '',
|
|
495
501
|
} satisfies EditInput as unknown as Record<string, unknown>;
|
|
496
502
|
} else {
|
|
497
503
|
// delete → no canonical UI; map to Bash `rm <path>` so the user
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import type { FileChangeSet } from './patch-rollout';
|
|
3
|
+
import { parseUnifiedDiff, findMatchingFileChangeSet } from './patch-rollout';
|
|
4
|
+
|
|
5
|
+
describe('parseUnifiedDiff', () => {
|
|
6
|
+
test('splits a single hunk into before/after text', () => {
|
|
7
|
+
const diff = [
|
|
8
|
+
'@@ -1,4 +1,4 @@',
|
|
9
|
+
' :root {',
|
|
10
|
+
'- --accent: #1d4ed8;',
|
|
11
|
+
'+ --accent: #7c3aed;',
|
|
12
|
+
' }',
|
|
13
|
+
''
|
|
14
|
+
].join('\n');
|
|
15
|
+
|
|
16
|
+
expect(parseUnifiedDiff(diff)).toEqual({
|
|
17
|
+
oldString: ':root {\n --accent: #1d4ed8;\n}\n',
|
|
18
|
+
newString: ':root {\n --accent: #7c3aed;\n}\n'
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('concatenates every hunk so the Edit block shows all changes', () => {
|
|
23
|
+
const diff = [
|
|
24
|
+
'@@ -1,2 +1,2 @@',
|
|
25
|
+
'-first old',
|
|
26
|
+
'+first new',
|
|
27
|
+
' shared',
|
|
28
|
+
'@@ -9,2 +9,2 @@',
|
|
29
|
+
'-second old',
|
|
30
|
+
'+second new',
|
|
31
|
+
''
|
|
32
|
+
].join('\n');
|
|
33
|
+
|
|
34
|
+
const { oldString, newString } = parseUnifiedDiff(diff);
|
|
35
|
+
expect(oldString).toBe('first old\nshared\nsecond old\n');
|
|
36
|
+
expect(newString).toBe('first new\nshared\nsecond new\n');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('ignores headers before the first hunk but keeps dashes inside one', () => {
|
|
40
|
+
const diff = [
|
|
41
|
+
'--- a/notes.md',
|
|
42
|
+
'+++ b/notes.md',
|
|
43
|
+
'@@ -1,2 +1,2 @@',
|
|
44
|
+
'---',
|
|
45
|
+
'+++',
|
|
46
|
+
''
|
|
47
|
+
].join('\n');
|
|
48
|
+
|
|
49
|
+
// Inside a hunk `---` is a removed line whose text is `--`, and `+++`
|
|
50
|
+
// an added line whose text is `++` — not file headers.
|
|
51
|
+
expect(parseUnifiedDiff(diff)).toEqual({ oldString: '--\n', newString: '++\n' });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('drops the no-newline annotation', () => {
|
|
55
|
+
const diff = ['@@ -1 +1 @@', '-old', '\', '+new'].join('\n');
|
|
56
|
+
expect(parseUnifiedDiff(diff)).toEqual({ oldString: 'old', newString: 'new' });
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('returns empty strings for an empty diff', () => {
|
|
60
|
+
expect(parseUnifiedDiff('')).toEqual({ oldString: '', newString: '' });
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe('findMatchingFileChangeSet', () => {
|
|
65
|
+
const changeSetFor = (...paths: string[]): FileChangeSet =>
|
|
66
|
+
new Map(paths.map(path => [path, { kind: 'update' as const, oldString: path, newString: path, content: '' }]));
|
|
67
|
+
|
|
68
|
+
test('prefers the newest change set that covers every wanted path', () => {
|
|
69
|
+
const older = changeSetFor('/repo/a.ts');
|
|
70
|
+
const newer = changeSetFor('/repo/a.ts', '/repo/b.ts');
|
|
71
|
+
|
|
72
|
+
expect(findMatchingFileChangeSet([older, newer], ['/repo/a.ts'])).toBe(newer);
|
|
73
|
+
expect(findMatchingFileChangeSet([older, newer], ['/repo/a.ts', '/repo/b.ts'])).toBe(newer);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('skips change sets that miss one of the wanted paths', () => {
|
|
77
|
+
const matching = changeSetFor('/repo/a.ts', '/repo/b.ts');
|
|
78
|
+
const partial = changeSetFor('/repo/a.ts');
|
|
79
|
+
|
|
80
|
+
expect(findMatchingFileChangeSet([matching, partial], ['/repo/a.ts', '/repo/b.ts'])).toBe(matching);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('returns null when nothing matches or nothing is wanted', () => {
|
|
84
|
+
expect(findMatchingFileChangeSet([changeSetFor('/repo/a.ts')], ['/repo/c.ts'])).toBeNull();
|
|
85
|
+
expect(findMatchingFileChangeSet([changeSetFor('/repo/a.ts')], [])).toBeNull();
|
|
86
|
+
expect(findMatchingFileChangeSet([], ['/repo/a.ts'])).toBeNull();
|
|
87
|
+
});
|
|
88
|
+
});
|