Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: number reopened chat turns on from the earlier ones

ogsamrataaa26ed10a57
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index 3e0bb227..65861aee 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -79,7 +79,8 @@ export type CaptureService = {
status(): { mode: CaptureMode; since: Date; restarts: number };
/** Whether the session uploader is tracking this session (started and not finished). */
hasSession(sessionId: string): boolean;
- startSession(sessionId: string, workspaceId: string, root: string): void;
+ /** `turnsBefore`: the turns a reopened chat already had (its turn numbers carry on from them). */
+ startSession(sessionId: string, workspaceId: string, root: string, turnsBefore?: number): void;
/** The chat's prompts run in its project's Linux sandbox (box/service.ts), or no longer (null); before startSession. */
boxSession(sessionId: string, box: BoxCaptureInfo | null): void;
recordTrace(sessionId: string, type: string, data?: unknown): void;
@@ -191,9 +192,9 @@ class CaptureClient implements CaptureService {
return this.sessions.get(sessionId) === true;
}
- startSession(sessionId: string, workspaceId: string, root: string): void {
+ startSession(sessionId: string, workspaceId: string, root: string, turnsBefore = 0): void {
if (this.uploadEnabled && SESSION_ID_PATTERN.test(sessionId) && !this.sessions.has(sessionId)) this.sessions.set(sessionId, true);
- this.send({ kind: "call", id: null, method: "startSession", args: [sessionId, workspaceId, root] });
+ this.send({ kind: "call", id: null, method: "startSession", args: [sessionId, workspaceId, root, turnsBefore] });
}
boxSession(sessionId: string, box: BoxCaptureInfo | null): void {
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index 38cb5063..840dcc6b 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -211,9 +211,9 @@ export class CaptureHost {
this.archive.start();
}
- startSession(sessionId: string, workspaceId: string, root: string): void {
+ startSession(sessionId: string, workspaceId: string, root: string, turnsBefore = 0): void {
this.sessionRoots.set(sessionId, root);
- this.sessionUploader.startSession(sessionId, workspaceId, root);
+ this.sessionUploader.startSession(sessionId, workspaceId, root, { turnsBefore });
}
/** The chat's prompts run in its project's box (or no longer: null); sent before its startSession. */
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index e620fba6..51e17d96 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -17,7 +17,7 @@ export type CaptureStopOptions = { archiveFinals: boolean };
/** CaptureHost methods callable from the main thread, with their arguments. */
export type CaptureCalls = {
- startSession: [sessionId: string, workspaceId: string, root: string];
+ startSession: [sessionId: string, workspaceId: string, root: string, turnsBefore?: number];
boxSession: [sessionId: string, box: BoxCaptureInfo | null];
recordTrace: [sessionId: string, type: string, data?: unknown];
flushTrace: [sessionId: string, finalTrace?: unknown];
diff --git a/apps/server/src/reopened-chat-turns.test.ts b/apps/server/src/reopened-chat-turns.test.ts
new file mode 100644
index 00000000..cec85e1e
--- /dev/null
+++ b/apps/server/src/reopened-chat-turns.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { createServer, type Server } from "node:http";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { CaptureHost } from "./capture-host.js";
+import { SessionUploader } from "./session-uploader.js";
+import { turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";
+
+// A chat reopened after the app restarted: its turns are numbered on from the
+// turns it already had (context.install / context.env_turn), not from 1.
+
+const cleanups: Array<() => unknown> = [];
+afterEach(async () => {
+ for (const fn of cleanups.splice(0).reverse()) await fn();
+});
+
+const user = (id: string) => ({ info: { id, role: "user", time: { created: 1 } }, parts: [{ type: "text", text: "go" }] });
+const reply = (id: string) => ({ info: { id, role: "assistant", finish: "stop", time: { created: 2, completed: 3 } }, parts: [{ type: "step-finish" }] });
+
+async function engineWith(messages: unknown[]): Promise<EngineTarget> {
+ const server: Server = createServer((req, res) => {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify((req.url ?? "").includes("/message") ? messages : { id: "ses_reopened_0001" }));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ cleanups.push(() => server.close());
+ const address = server.address();
+ return { baseUrl: `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`, headers: [], search: "", engine: "v1" } as EngineTarget;
+}
+
+describe("a reopened chat", () => {
+ test("its earlier completed turns are counted from the engine, once, before the capture starts it", async () => {
+ const engine = await engineWith([user("u1"), reply("a1"), user("u2"), reply("a2")]);
+ expect(await turnsBeforeCapture({ hasSession: () => false }, "ses_reopened_0001", engine)).toBe(2);
+ expect(await turnsBeforeCapture({ hasSession: () => true }, "ses_reopened_0001", engine)).toBe(0);
+ expect(await turnsBeforeCapture({ hasSession: () => false }, "ses_new_000001", await engineWith([]))).toBe(0);
+ });
+
+ test("the capture host hands the count to the capture context (which numbers on from it: install-log.test.ts)", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omnirush-reopened-"));
+ cleanups.push(() => rmSync(root, { recursive: true, force: true }));
+ const uploader = new SessionUploader({ upload: async () => Response.json({ ok: true }, { status: 201 }), changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ cleanups.push(() => uploader.stop());
+ const started: Array<[string, number | undefined]> = [];
+ (uploader as unknown as { contextOf: () => unknown }).contextOf = () => ({
+ sessionStarted: (id: string, _root: string, _after: unknown, turnsBefore?: number) => started.push([id, turnsBefore]),
+ turnStarted: () => undefined,
+ turnEnded: () => undefined,
+ turnMessages: () => undefined,
+ sessionEnded: () => undefined,
+ settled: async () => undefined,
+ });
+ const host = Object.create(CaptureHost.prototype) as CaptureHost & { sessionRoots: Map<string, string>; sessionUploader: SessionUploader };
+ host.sessionRoots = new Map();
+ host.sessionUploader = uploader;
+ host.startSession("ses_reopened_0001", "ws", root, 2);
+ host.startSession("ses_new_000001", "ws", root);
+ expect(started).toEqual([["ses_reopened_0001", 2], ["ses_new_000001", 0]]);
+ });
+});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 60304401..3e8a8774 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -201,7 +201,7 @@ import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview
import { sessionUploaderEnabled } from "./session-uploader.js";
import { startCaptureService, type CaptureService } from "./capture-client.js";
import type { LateWritesGate } from "./capture-host.js";
-import { buildOpencodeProxyUrl, engineTarget, type EngineTarget } from "./session-upload-observer.js";
+import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
import { awaitOmniRushModelCatalogSettled, startOmniRushModelCatalogSync } from "./omnirush-model-catalog-sync.js";
import { OmniRushVoiceService, voiceProjectContext } from "./omnirush-voice.js";
@@ -1813,7 +1813,7 @@ export async function proxyOpencodeV2Request(input: {
// capture v2's session-start manifest is taken before the prompt reaches the engine (at most about 3 s).
await capture.archiveStartGate(uploadedSessionId, input.workspace.path, lateWritesGate(input.workspace));
capture.boxSession(uploadedSessionId, boxInfo);
- capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path);
+ capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path, await turnsBeforeCapture(capture, uploadedSessionId, engine));
capture.recordPrompt(uploadedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });
capture.captureSnapshot(uploadedSessionId, "prompt");
capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);
@@ -2187,7 +2187,7 @@ export async function proxyOpencodeRequest(input: {
// capture v2's session-start manifest is taken before the prompt reaches the engine (at most about 3 s).
if (promptDispatch) await capture.archiveStartGate(uploadedSessionId, workspace.path, lateWritesGate(workspace, pool?.snapshot().generations.map((generation) => generation.pid) ?? []));
if (promptDispatch) capture.boxSession(uploadedSessionId, boxInfo);
- capture.startSession(uploadedSessionId, workspace.id, workspace.path);
+ capture.startSession(uploadedSessionId, workspace.id, workspace.path, promptDispatch ? await turnsBeforeCapture(capture, uploadedSessionId, engineTarget(baseUrl, headers, search)) : 0);
capture.recordPrompt(uploadedSessionId, {
method,
path: normalizeOpencodeProxyPath(proxyPath),
diff --git a/apps/server/src/session-upload-observer.ts b/apps/server/src/session-upload-observer.ts
index c4937ca6..461bdae1 100644
--- a/apps/server/src/session-upload-observer.ts
+++ b/apps/server/src/session-upload-observer.ts
@@ -8,7 +8,7 @@
* named by plain data (EngineTarget) so the target can cross threads.
*/
import { loopbackFetch } from "./server-fetch.js";
-import { isFinishedAssistantMessage, isPromptMessage, type ArchiveEngineReads, type ProjectArchiveLifecycle } from "./session-archive/lifecycle.js";
+import { completedTurnCount, isFinishedAssistantMessage, isPromptMessage, type ArchiveEngineReads, type ProjectArchiveLifecycle } from "./session-archive/lifecycle.js";
import { MAX_UPLOAD_CHILD_SESSION_DEPTH, type UploadSessionModel, type SessionUploader } from "./session-uploader.js";
import { recordTurnFiles, type TurnFilesInput } from "./session-archive/turn-files.js";
import { watchToolCallEnds } from "./session-archive/files-used.js";
@@ -1409,3 +1409,17 @@ export function followContextToolEvents(input: {
if (map.get(input.sessionId) === controller) map.delete(input.sessionId);
});
}
+
+/**
+ * The turns a chat had before this app run started capturing it (a chat
+ * reopened after a restart), so its turn numbers carry on from them; 0 for a
+ * chat already started here, or when the engine does not answer in 5 s.
+ */
+export async function turnsBeforeCapture(capture: { hasSession(sessionId: string): boolean }, sessionId: string, engine: EngineTarget): Promise<number> {
+ if (capture.hasSession(sessionId)) return 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), 5_000); });
+ const outline = await Promise.race([projectArchiveEngineReads(engine, sessionId).messages().catch(() => null), timeout]);
+ clearTimeout(timer);
+ return completedTurnCount(outline) ?? 0;
+}
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 2d799b5e..a4534f79 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -5048,7 +5048,8 @@ export class SessionUploader {
return this.traceSchemaCache?.features ?? NO_UPLOAD_FEATURES;
}
- startSession(sessionId: string, workspaceId: string, root: string): void {
+ /** `turnsBefore`: the turns a reopened chat already had, so capture context numbers its turns on from them. */
+ startSession(sessionId: string, workspaceId: string, root: string, options: { turnsBefore?: number } = {}): void {
if (!this.enabled || this.sessions.has(sessionId) || !/^[A-Za-z0-9._:-]{8,128}$/.test(sessionId)) return;
// toolchain.ts: collected in the background (a box chat's in its box).
void (this.boxes.has(sessionId) ? this.boxToolchains : this.toolchains)?.get(root).catch(() => null);
@@ -5060,7 +5061,7 @@ export class SessionUploader {
let startSnapshotDone: () => void = () => undefined;
const startSnapshot = new Promise<void>((resolveStart) => (startSnapshotDone = resolveStart));
// A box chat: its own context (this machine's packages, services, processes and network are not the chat's).
- this.contextOf(sessionId)?.sessionStarted(sessionId, root, startSnapshot);
+ this.contextOf(sessionId)?.sessionStarted(sessionId, root, startSnapshot, options.turnsBefore ?? 0);
this.enqueue(state, async () => {
await state.ready;
try {