Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,10 @@ export function AcpChatPane({
],
);

const agentSessionId = agent?.sessionId;
// A pane adopted in the background never saw the stream report the agent
// session, so recovery takes it from the host's row instead.
const agentSessionId =
agent?.sessionId ?? stored?.session?.harnessSessionId ?? undefined;
// Resuming when there is a session to resume, and a plain new one when the
// pane was opened straight onto the chat and no agent has run yet.
useEffect(() => {
Expand Down
11 changes: 5 additions & 6 deletions packages/chat-runtime/src/commands/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,16 +359,15 @@ export function createCommands(options: CommandsOptions): ChatCommands {

getSession(input) {
const parsed: GetSessionInput = getSessionInputSchema.parse(input);
const seq = options.sessions.get(parsed.sessionId)
? options.journal.cursor(parsed.sessionId).seq
: null;
// Reading the cursor can backfill the row, so read the row after it.
const session = options.sessions.get(parsed.sessionId);
return {
live: options.live.get(parsed.sessionId) !== null,
session,
cursor: session
? {
epoch: session.epoch,
seq: options.journal.cursor(parsed.sessionId).seq,
}
: null,
cursor: session && seq !== null ? { epoch: session.epoch, seq } : null,
};
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,33 @@ describe("ClaudeAdapter", () => {
).toBe(true);
});

test("reports the session id the stream carries, once", async () => {
const harness = createHarness();
const reported: string[] = [];
const collect = async () => {
for (let index = 0; index < 20; index += 1) {
const next = await harness.iterator.next();
if (next.done) return;
if (next.value.kind === "turn") return;
if (
next.value.kind === "session" &&
next.value.session.harnessSessionId
)
reported.push(next.value.session.harnessSessionId);
}
};

harness.adapter.prompt([{ type: "text", text: "first" }]);
harness.emit({ type: "system", subtype: "init", session_id: "session-1" });
harness.emit({
...(messageStart("msg_1") as object),
session_id: "session-1",
});
await collect();

expect(reported).toEqual(["session-1"]);
});

test("dispose aborts the underlying session", async () => {
const harness = createHarness();
harness.adapter.prompt([{ type: "text", text: "first" }]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ export class ClaudeAdapter implements HarnessAdapter {
private readonly abortController = new AbortController();
private translator: ClaudeTranslator | null = null;
private session: ClaudeSession | null = null;
private sessionId: string | null = null;
private modeId: ClaudePermissionMode = "default";
private pump: Promise<void> | null = null;
private disposed = false;
Expand Down Expand Up @@ -325,6 +326,7 @@ export class ClaudeAdapter implements HarnessAdapter {
try {
for await (const message of stream) {
if (this.disposed) return;
this.reportSessionId(message);
for (const event of translator.translate(message)) {
this.events.push(event);
}
Expand All @@ -336,6 +338,17 @@ export class ClaudeAdapter implements HarnessAdapter {
}
}

private reportSessionId(message: unknown): void {
if (typeof message !== "object" || message === null) return;
const sessionId = (message as { session_id?: unknown }).session_id;
if (typeof sessionId !== "string" || sessionId === this.sessionId) return;
this.sessionId = sessionId;
this.events.push({
kind: "session",
session: { harnessSessionId: sessionId },
});
}

private requestApproval(
input: Record<string, unknown>,
toolUseId: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ describe("codexAdapter fixtures", () => {
expect(sessionStates[0]).toEqual({ status: "starting" });
expect(sessionStates[1]).toMatchObject({
status: "idle",
harnessSessionId: "019fd2fb-7896-7791-b199-a568c89d4986",
modeId: "full-access",
modelId: "gpt-5.5",
availableModes: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ export class CodexAdapter implements HarnessAdapter {

this.emitSession({
status: "idle",
harnessSessionId: this.threadId,
modeId: this.modeId,
availableModes: [...CODEX_MODES],
...(this.modelId ? { modelId: this.modelId } : {}),
Expand Down
24 changes: 23 additions & 1 deletion packages/chat-runtime/src/journal/journal/journal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { chatJournal } from "../../db";
import {
readSessionRow,
removeSessionRow,
setHarnessSessionId,
writeSessionProjection,
} from "../../projection";
import { readSince } from "../../replay";
Expand Down Expand Up @@ -45,11 +46,13 @@ type SessionCache = {
queuedItemIds: Set<string>;
status: SessionStatus;
title: string | null;
harnessSessionId: string | null;
};

type NextProjection = {
status: SessionStatus;
title: string | null;
harnessSessionId: string | null;
queuedItemIds: Set<string>;
};

Expand Down Expand Up @@ -87,6 +90,7 @@ export class ChatJournal {
const listingChanged =
next.status !== cache.status ||
next.title !== cache.title ||
next.harnessSessionId !== cache.harnessSessionId ||
next.queuedItemIds.size !== cache.queuedItemIds.size;

this.db.transaction(() => {
Expand All @@ -103,6 +107,7 @@ export class ChatJournal {
writeSessionProjection(this.db, sessionId, {
status: next.status,
title: next.title,
harnessSessionId: next.harnessSessionId,
queuedCount: next.queuedItemIds.size,
updatedAt: ts,
});
Expand All @@ -111,6 +116,7 @@ export class ChatJournal {
cache.lastSeq = seq;
cache.status = next.status;
cache.title = next.title;
cache.harnessSessionId = next.harnessSessionId;
cache.queuedItemIds = next.queuedItemIds;
if (listingChanged) this.notify(sessionId, cache.scopeId, ts);

Expand Down Expand Up @@ -168,6 +174,8 @@ export class ChatJournal {
return {
status: event.session.status,
title: event.session.title ?? cache.title,
harnessSessionId:
event.session.harnessSessionId ?? cache.harnessSessionId,
queuedItemIds: cache.queuedItemIds,
};
}
Expand All @@ -179,12 +187,18 @@ export class ChatJournal {
} else {
queuedItemIds.delete(event.item.id);
}
return { status: cache.status, title: cache.title, queuedItemIds };
return {
status: cache.status,
title: cache.title,
harnessSessionId: cache.harnessSessionId,
queuedItemIds,
};
}

return {
status: cache.status,
title: cache.title,
harnessSessionId: cache.harnessSessionId,
queuedItemIds: cache.queuedItemIds,
};
}
Expand All @@ -208,12 +222,14 @@ export class ChatJournal {
let lastSeq = 0;
let status = row.status;
let title = row.title;
let harnessSessionId = row.harnessSessionId;
for (const envelope of replay.envelopes) {
lastSeq = envelope.cursor.seq;
const event = envelope.event;
if (event.type === "session") {
status = event.session.status;
title = event.session.title ?? title;
harnessSessionId = event.session.harnessSessionId ?? harnessSessionId;
continue;
}
if (event.type !== "item" || event.item.kind !== "user_message") continue;
Expand All @@ -224,13 +240,19 @@ export class ChatJournal {
}
}

// Rows written before the projection kept this id have it only in the journal.
if (harnessSessionId !== row.harnessSessionId) {
setHarnessSessionId(this.db, sessionId, harnessSessionId);
}

const cache: SessionCache = {
scopeId: row.scopeId,
epoch,
lastSeq,
queuedItemIds,
status,
title,
harnessSessionId,
};
this.sessions.set(sessionId, cache);
return cache;
Expand Down
1 change: 1 addition & 0 deletions packages/chat-runtime/src/projection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export {
readSessionRow,
removeSessionRow,
resetSessionForEpoch,
setHarnessSessionId,
setSessionEpoch,
writeSessionProjection,
} from "./projection";
31 changes: 25 additions & 6 deletions packages/chat-runtime/src/projection/projection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, test } from "bun:test";
import type { ChatRuntime } from "../index";
import { sessionState } from "../testing/fixtures";
import { createTestRuntime } from "../testing/testRuntime";
import { setHarnessSessionId } from "./projection";

describe("ChatSessionStore", () => {
let runtime: ChatRuntime;
Expand Down Expand Up @@ -32,15 +33,33 @@ describe("ChatSessionStore", () => {
).toEqual(["codex"]);
});

test("keeps the harness session id in its own column", () => {
runtime.sessions.setHarnessSessionId("s1", "claude-abc");
const row = runtime.sessions.get("s1");
expect(row).toMatchObject({
sessionId: "s1",
harnessSessionId: "claude-abc",
test("keeps the harness session id the agent reports", () => {
runtime.journal.append("s1", {
type: "session",
session: sessionState({ harnessSessionId: "agent-session-1" }),
});
runtime.journal.append("s1", {
type: "session",
session: sessionState({ status: "running" }),
});
expect(runtime.sessions.get("s1")).toMatchObject({
harnessSessionId: "agent-session-1",
});
});

test("backfills a harness session id that only the journal has", () => {
runtime.journal.append("s1", {
type: "session",
session: sessionState({ harnessSessionId: "agent-session-1" }),
});
setHarnessSessionId(runtime.db, "s1", null);
runtime.journal.forget("s1");

const { session } = runtime.commands.getSession({ sessionId: "s1" });

expect(session?.harnessSessionId).toBe("agent-session-1");
});

test("reflects journal projection writes", () => {
runtime.journal.append("s1", {
type: "session",
Expand Down
23 changes: 12 additions & 11 deletions packages/chat-runtime/src/projection/projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type SessionRowInsert = typeof chatSessionsLocal.$inferInsert;
export type SessionProjection = {
status: SessionStatus;
title: string | null;
harnessSessionId: string | null;
queuedCount: number;
updatedAt: number;
};
Expand Down Expand Up @@ -54,6 +55,17 @@ export function resetSessionForEpoch(
.run();
}

export function setHarnessSessionId(
db: ChatDb,
sessionId: string,
harnessSessionId: string | null,
): void {
db.update(chatSessionsLocal)
.set({ harnessSessionId })
.where(eq(chatSessionsLocal.sessionId, sessionId))
.run();
}

export function removeSessionRow(db: ChatDb, sessionId: string): void {
db.delete(chatSessionsLocal)
.where(eq(chatSessionsLocal.sessionId, sessionId))
Expand Down Expand Up @@ -94,15 +106,4 @@ export class ChatSessionStore {
.orderBy(desc(chatSessionsLocal.updatedAt))
.all();
}

setHarnessSessionId(
sessionId: string,
harnessSessionId: string | null,
): void {
this.db
.update(chatSessionsLocal)
.set({ harnessSessionId, updatedAt: Date.now() })
.where(eq(chatSessionsLocal.sessionId, sessionId))
.run();
}
}
Loading