Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Make conversation forks responsive and batch history copies (#2070)

Regan Bell485afd872faf
diff --git a/package.json b/package.json
index 61e22feb3..38e5323c9 100644
--- a/package.json
+++ b/package.json
@@ -46,7 +46,7 @@
"sandbox:local:build": "bash scripts/local-sandbox-build.sh",
"sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"",
"deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",
- "test:pg": "node scripts/run-pg-tests.mjs test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",
+ "test:pg": "node scripts/run-pg-tests.mjs test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",
"livetest": "node scripts/api-livetest.ts",
"bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts",
"prepare": "node .husky/install.mjs",
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 576f524ef..889357f65 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -166,6 +166,7 @@ import {
onSessionDragStart,
endSessionDrag,
dropPendingSession,
+ replacePendingSession,
groupDmTitle,
refreshSessions,
renderList,
@@ -223,6 +224,7 @@ interface SettledRowKey {
approvalDecision: unknown;
sendFailure: unknown;
forkable: boolean;
+ forking: boolean;
speakerLabel: string | undefined;
edited: boolean;
deleted: boolean;
@@ -268,6 +270,7 @@ export function createChatSurface(
const runSlot = createRunSlot((message) => {
ctx.composer.state.error = message;
});
+ let pendingFork: { index: number } | null = null;
const transcriptViewport = createTranscriptViewport();
let preserveConnectionScroll = isConnectionReturn();
let connectionReturnMessageCount: number | null = null;
@@ -1701,6 +1704,7 @@ export function createChatSurface(
(!work || ((work.status === "complete" || work.status === "failed") && !work.pendingApprovals?.length));
if (!cacheable) return chatMessage(message, index, isStreaming);
const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
+ const forking = pendingFork !== null;
const speakerLabel = speakerLabelFor(message);
const edited = Boolean((message as { edited?: boolean }).edited);
const deleted = Boolean((message as { deleted?: boolean }).deleted);
@@ -1719,6 +1723,7 @@ export function createChatSurface(
hit.approvalDecision === msg.approvalDecision &&
hit.sendFailure === msg.sendFailure &&
hit.forkable === forkable &&
+ hit.forking === forking &&
hit.speakerLabel === speakerLabel &&
hit.edited === edited &&
hit.deleted === deleted
@@ -1738,6 +1743,7 @@ export function createChatSurface(
approvalDecision: msg.approvalDecision,
sendFailure: msg.sendFailure,
forkable,
+ forking,
speakerLabel,
edited,
deleted,
@@ -1980,11 +1986,13 @@ export function createChatSurface(
? html`<button
class="msg-copy msg-fork"
type="button"
- ${tip("Fork conversation from here")}
- aria-label="Fork conversation from here"
+ ${tip(pendingFork ? "Forking..." : "Fork conversation from here")}
+ aria-label=${pendingFork?.index === index ? "Forking conversation…" : "Fork conversation from here"}
+ ?disabled=${pendingFork !== null}
+ aria-busy=${pendingFork?.index === index ? "true" : "false"}
@click=${() => void forkFromMessage(index)}
>
- ${icon(GitFork, 13)}
+ ${pendingFork?.index === index ? waveLoader({ width: 13, height: 13, label: "Forking" }) : icon(GitFork, 13)}
</button>`
: nothing
}
@@ -1996,15 +2004,24 @@ export function createChatSurface(
const agent = chatState.agent;
const sessionId = chatState.sessionId;
const sourceThreadRef = chatState.threadRef;
- if (!agent || !sessionId) return;
+ if (!agent || !sessionId || pendingFork) return;
const messages = agent.state.messages;
if (!messages[index]) return;
const floorSeq = Math.max(chatState.forkSession?.forkBoundarySeq ?? -1, (chatState.transcriptAnchorSeq ?? 0) - 1);
+ const pendingRef = `web:fork:${crypto.randomUUID()}`;
+ pendingFork = { index };
+ ctx.composer.state.error = "";
+ addPendingSession(pendingRef, chatState.scopeId, chatState.contextName, true);
+ if (chatState.scopeId) sessionsState.collapsedProjectScopes.delete(chatState.scopeId);
+ renderList();
+ drawActiveChat();
try {
const { entries } = await api<{ entries: SessionEntry[] }>(`/api/sessions/${encodeURIComponent(sessionId)}`);
const upToSeq = forkCutSeq(entries ?? [], messages, index, floorSeq);
if (upToSeq === undefined) throw new Error("That message is still saving. Try forking again in a moment.");
const forked = await forkSession(sessionId, upToSeq);
+ replacePendingSession(pendingRef, forked.session);
+ if (chatState.agent !== agent || chatState.sessionId !== sessionId) return;
const split = inheritedTranscript(forked.session, forked.entries ?? []);
ctx.composer.carryModelPick(sourceThreadRef, forked.session.threadRef);
mountContinuable(
@@ -2016,10 +2033,12 @@ export function createChatSurface(
forked.session,
entriesToMessages(split.inherited, transcriptModel()),
);
- await refreshSessions({ silent: true });
renderList();
} catch (err) {
ctx.composer.state.error = errMessage(err, "Could not fork the conversation.");
+ } finally {
+ pendingFork = null;
+ dropPendingSession(pendingRef);
drawActiveChat();
}
}
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index dcf312296..b363f2473 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -860,7 +860,14 @@ function chatPageRow(s: CoreSession): TemplateResult {
`;
}
-export function addPendingSession(threadRef: string, scopeId: string | null, channelName: string | null): void {
+const pendingForkThreads = new Set<string>();
+
+export function addPendingSession(
+ threadRef: string,
+ scopeId: string | null,
+ channelName: string | null,
+ pendingFork = false,
+): void {
const scope = scopeId ?? personalScopeId();
let type: CoreSession["type"] = "dm";
if (scope?.startsWith("group:")) type = "group";
@@ -871,15 +878,24 @@ export function addPendingSession(threadRef: string, scopeId: string | null, cha
scopeId: scope ?? "",
threadRef,
createdAt: Date.now(),
- title: null,
+ title: pendingFork ? "Forking…" : null,
channelName,
archived: false,
};
+ if (pendingFork) pendingForkThreads.add(threadRef);
sessionsState.list = withPendingSession(sessionsState.list, pending);
renderList();
}
+export function replacePendingSession(threadRef: string, session: CoreSession): void {
+ sessionPatchEpoch++;
+ pendingForkThreads.delete(threadRef);
+ sessionsState.list = withPendingSession(withoutUnsentPending(sessionsState.list, threadRef), session);
+ renderList();
+}
+
export function dropPendingSession(threadRef: string): void {
+ pendingForkThreads.delete(threadRef);
sessionsState.list = withoutUnsentPending(sessionsState.list, threadRef);
renderList();
}
@@ -961,7 +977,7 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
const working = sessionWorking(s);
const color = displaySessionColor(s.color);
let titleContent: string | TemplateResult = groupDmTitle(s);
- if (refreshingTitle) {
+ if (refreshingTitle || pendingForkThreads.has(s.threadRef)) {
titleContent = html`<span class="sheen-label title-sheen thinking-sheen" data-sheen=${title}>${title}</span>`;
} else if (untitledProjectChild) {
titleContent = title;
@@ -988,7 +1004,8 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
<a
class="session"
href=${saved ? deepLinkPath(UI_BASE, "chats", s.id) : nothing}
- aria-busy=${refreshingTitle ? "true" : "false"}
+ aria-busy=${refreshingTitle || pendingForkThreads.has(s.threadRef) ? "true" : "false"}
+ aria-disabled=${pendingForkThreads.has(s.threadRef) ? "true" : nothing}
aria-label=${ariaLabel}
aria-keyshortcuts="Space Shift+Space Control+Space Meta+Space"
draggable=${saved ? "true" : "false"}
@@ -1722,6 +1739,7 @@ export async function openSession(
entriesPrefetch?: Promise<TranscriptPage | null>,
approvalsPrefetch?: Promise<{ approvals: PendingApproval[] } | null>,
): Promise<void> {
+ if (pendingForkThreads.has(s.threadRef)) return;
if (appState.currentView !== "chats") {
appState.currentView = "chats";
appState.viewRenderSeq++;
@@ -1744,6 +1762,7 @@ export async function openSessionInto(
approvalsPrefetch?: Promise<{ approvals: PendingApproval[] } | null>,
tracked = conv === mainConversation(),
): Promise<void> {
+ if (pendingForkThreads.has(s.threadRef)) return;
if (!s.id) {
if (conv.state.threadRef !== s.threadRef) {
conv.mountContinuable(s.threadRef, null, s.scopeId || null, [], s.channelName ?? null);
diff --git a/plugins/web-ui/test/fork-feedback.test.ts b/plugins/web-ui/test/fork-feedback.test.ts
new file mode 100644
index 000000000..062158dcc
--- /dev/null
+++ b/plugins/web-ui/test/fork-feedback.test.ts
@@ -0,0 +1,100 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness } from "./deep-link-boot-fixture.ts";
+import type { CoreSession } from "../src/core-bridge.ts";
+
+async function until(check: () => boolean): Promise<void> {
+ for (let i = 0; i < 200; i++) {
+ if (check()) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ assert.fail("condition did not settle");
+}
+
+test("fork feedback survives delayed success, failure, and navigation", async () => {
+ const source: CoreSession = {
+ id: "source",
+ threadRef: "web:tester:source",
+ scopeId: "personal:tester",
+ type: "dm",
+ createdAt: Date.now(),
+ title: "Source conversation",
+ };
+ const entries = [{ seq: 0, type: "user", createdAt: Date.now(), payload: { text: "Fork this message" } }];
+ const h = await harness({ path: "/s/source", session: source, listSessions: [source], entries });
+ let finish: (response: Response) => void = () => {};
+ const anchorDescriptor = Object.getOwnPropertyDescriptor(globalThis, "HTMLAnchorElement");
+ try {
+ h.releaseSessions();
+ await h.boot();
+ await h.sessionsReady();
+ Object.defineProperty(globalThis, "HTMLAnchorElement", { configurable: true, value: window.HTMLAnchorElement });
+ const baseFetch = globalThis.fetch;
+ for (const outcome of ["success", "failure", "navigate"] as const) {
+ await h.openSession(source);
+ await until(() => document.querySelector(".msg-fork") !== null);
+ const response = new Promise<Response>((resolve) => (finish = resolve));
+ let requests = 0;
+ globalThis.fetch = (input, init) => {
+ if (String(input).endsWith("/fork")) {
+ requests++;
+ return response;
+ }
+ return baseFetch(input, init);
+ };
+ const button = document.querySelector<HTMLButtonElement>(".msg-fork")!;
+ button.click();
+ assert.equal(button.disabled, true);
+ assert.equal(button.getAttribute("aria-busy"), "true");
+ button.dispatchEvent(new window.MouseEvent("mouseenter"));
+ assert.equal(document.querySelector("[role=tooltip]")?.textContent, "Forking...");
+ button.dispatchEvent(new window.MouseEvent("mouseleave"));
+ assert.match(document.querySelector(".session[aria-busy=true]")?.textContent ?? "", /Forking/);
+ button.click();
+ await until(() => requests === 1);
+ await h.refreshSessions();
+ assert.match(document.querySelector(".session[aria-busy=true]")?.textContent ?? "", /Forking/);
+ const pending = h.sessionsState.list.find((session) => !session.id)!;
+ await h.openSession(pending as CoreSession);
+ assert.equal(h.visibleConversation().state.sessionId, source.id);
+ const conv = h.visibleConversation();
+ if (outcome === "navigate") conv.newChat();
+ const newThread = conv.state.threadRef;
+ const fork: CoreSession = {
+ ...source,
+ id: "fork",
+ threadRef: "web:tester:fork",
+ title: "Source conversation (fork)",
+ forkedFrom: { sessionId: source.id, title: source.title },
+ forkBoundarySeq: 0,
+ };
+ const refreshes = h.requests.filter((path) => path === "/api/sessions").length;
+ finish(
+ outcome === "failure"
+ ? Response.json({ error: "Could not copy history" }, { status: 500 })
+ : Response.json({ session: fork, entries }),
+ );
+ await until(() => !document.querySelector(".session[aria-busy=true]"));
+ assert.equal(requests, 1);
+ assert.equal(
+ h.sessionsState.list.some((session) => !session.id),
+ false,
+ );
+ if (outcome === "failure") {
+ assert.equal(conv.state.sessionId, source.id);
+ assert.equal(document.querySelector<HTMLButtonElement>(".msg-fork")?.disabled, false);
+ assert.match(h.mainText(), /Could not copy history/);
+ } else {
+ assert.equal(h.sessionsState.list.filter((session) => session.id === fork.id).length, 1);
+ assert.equal(h.requests.filter((path) => path === "/api/sessions").length, refreshes);
+ if (outcome === "navigate") assert.equal(conv.state.threadRef, newThread);
+ else assert.equal(conv.state.sessionId, fork.id);
+ }
+ }
+ } finally {
+ finish(Response.json({ error: "test ended" }, { status: 500 }));
+ await h.close();
+ if (anchorDescriptor) Object.defineProperty(globalThis, "HTMLAnchorElement", anchorDescriptor);
+ else Reflect.deleteProperty(globalThis, "HTMLAnchorElement");
+ }
+});
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index 4ad52cb1b..21f5f3d63 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -928,18 +928,13 @@ export function createSessionMethods(
);
const { lease } = await deps.sessions.acquireLease(forked.id, "fork");
if (!lease) throw new Error(`fork: could not lease fresh session ${forked.id}`);
- let forkBoundarySeq: number | null = null;
+ let forkBoundarySeq: number | null;
try {
- const copiedEntries = [];
- for (const entry of copied) {
- const appended = await deps.sessions.append(lease, {
- type: entry.type,
- payload: entry.payload,
- scopeLabel: entry.scopeLabel,
- });
- copiedEntries.push(appended);
- forkBoundarySeq = appended.seq;
- }
+ const copiedEntries = await deps.sessions.appendMany(
+ lease,
+ copied.map((entry) => ({ type: entry.type, payload: entry.payload, scopeLabel: entry.scopeLabel })),
+ );
+ forkBoundarySeq = copiedEntries.at(-1)?.seq ?? null;
if (forkBoundarySeq !== null) {
await appendCoverageImport(deps.sessions, lease, copiedEntries, source.scopeId).catch(
swallowAs("fork: tape import", undefined),
diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.ts
index 9473381c3..7bef5d19d 100644
--- a/src/sessions/memory-session-store.ts
+++ b/src/sessions/memory-session-store.ts
@@ -256,6 +256,10 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
},
async append(lease, entry: NewEntry): Promise<SessionEntry> {
+ return (await this.appendMany(lease, [entry]))[0]!;
+ },
+
+ async appendMany(lease, batch: readonly NewEntry[]): Promise<SessionEntry[]> {
const held = leases.get(lease.sessionId);
if (!held || held.token !== lease.token || now() >= held.expiresAt) {
throw new Error("append without a valid session lease");
@@ -263,34 +267,43 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
held.expiresAt = now() + leaseTtlMs;
const log = entries.get(lease.sessionId);
if (!log) throw new Error(`unknown session: ${lease.sessionId}`);
- const seq = log.length;
- const full: SessionEntry = {
- sessionId: lease.sessionId,
- seq,
- parentSeq: seq === 0 ? null : seq - 1,
- type: entry.type,
- payload: entry.payload,
- scopeLabel: entry.scopeLabel as ScopeId,
- createdAt: now(),
- };
- const mirrored = structuredClone(tapeTranscriptEntryRecord(full));
- log.push(full);
- const tapeLog = tape.get(lease.sessionId) ?? [];
- tapeLog.push({
- ...mirrored,
- sessionId: lease.sessionId,
- seq: tapeLog.length,
- createdAt: now(),
+ const copied = structuredClone(batch);
+ return copied.map((entry) => {
+ const seq = log.length;
+ const full: SessionEntry = {
+ sessionId: lease.sessionId,
+ seq,
+ parentSeq: seq === 0 ? null : seq - 1,
+ type: entry.type,
+ payload: entry.payload,
+ scopeLabel: entry.scopeLabel as ScopeId,
+ createdAt: now(),
+ };
+ const mirrored = structuredClone(tapeTranscriptEntryRecord(full));
+ log.push(full);
+ const tapeLog = tape.get(lease.sessionId) ?? [];
+ tapeLog.push({
+ ...mirrored,
+ sessionId: lease.sessionId,
+ seq: tapeLog.length,
+ createdAt: now(),
+ });
+ tape.set(lease.sessionId, tapeLog);
+ const text = SEARCHABLE_ENTRY_TYPES.has(full.type) ? entrySearchText(full.payload) : null;
+ if (text?.trim()) {
+ const index = searchIndex.get(full.sessionId) ?? [];
+ const author = entrySearchAuthor(full);
+ index.push({
+ seq: full.seq,
+ type: full.type,
+ text,
+ createdAt: full.createdAt,
+ ...(author ? { author } : {}),
+ });
+ searchIndex.set(full.sessionId, index);
+ }
+ return full;
});
- tape.set(lease.sessionId, tapeLog);
- const text = SEARCHABLE_ENTRY_TYPES.has(full.type) ? entrySearchText(full.payload) : null;
- if (text?.trim()) {
- const index = searchIndex.get(full.sessionId) ?? [];
- const author = entrySearchAuthor(full);
- index.push({ seq: full.seq, type: full.type, text, createdAt: full.createdAt, ...(author ? { author } : {}) });
- searchIndex.set(full.sessionId, index);
- }
- return full;
},
async getEntries(sessionId, opts?: GetEntriesOptions) {
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index 0482b0461..5eb3b1ed2 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -988,27 +988,56 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
},
async append(lease, entry: NewEntry): Promise<SessionEntry> {
+ return (await this.appendMany(lease, [entry]))[0]!;
+ },
+
+ async appendMany(lease, entries: readonly NewEntry[]): Promise<SessionEntry[]> {
return withLease(lease, "append without a valid session lease", async (client) => {
+ if (!entries.length) return [];
const max = await client.query(
"SELECT COALESCE(MAX(seq), -1) + 1 AS n FROM session_entries WHERE session_id = $1",
[lease.sessionId],
);
- const seq = Number(max.rows[0]!.n);
- const stored = jsonbSafeStringify(entry.payload ?? null);
- const full: SessionEntry = {
- sessionId: lease.sessionId,
- seq,
- parentSeq: seq === 0 ? null : seq - 1,
+ const startSeq = Number(max.rows[0]!.n);
+ const createdAt = now();
+ const full = entries.map((entry, index): SessionEntry => {
+ const seq = startSeq + index;
+ return {
+ sessionId: lease.sessionId,
+ seq,
+ parentSeq: seq === 0 ? null : seq - 1,
+ type: entry.type,
+ payload: JSON.parse(jsonbSafeStringify(entry.payload ?? null)),
+ scopeLabel: entry.scopeLabel as ScopeId,
+ createdAt,
+ };
+ });
+ const rows = full.map((entry) => ({
+ seq: entry.seq,
+ parent_seq: entry.parentSeq,
type: entry.type,
- payload: JSON.parse(stored),
- scopeLabel: entry.scopeLabel as ScopeId,
- createdAt: now(),
- };
+ payload: JSON.stringify(entry.payload),
+ scope_label: entry.scopeLabel,
+ created_at: entry.createdAt,
+ tape_payload: JSON.stringify(tapeTranscriptEntryRecord(entry).payload),
+ }));
+ const encoded = JSON.stringify(rows);
await client.query(
- "INSERT INTO session_entries(session_id, seq, parent_seq, type, payload, scope_label, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)",
- [full.sessionId, full.seq, full.parentSeq, full.type, stored, full.scopeLabel, full.createdAt],
+ `INSERT INTO session_entries(session_id, seq, parent_seq, type, payload, scope_label, created_at)
+ SELECT $1, e.seq, e.parent_seq, e.type, e.payload, e.scope_label, e.created_at
+ FROM jsonb_to_recordset($2::jsonb) AS e(
+ seq bigint, parent_seq bigint, type text, payload text, scope_label text, created_at bigint)
+ ORDER BY e.seq`,
+ [lease.sessionId, encoded],
+ );
+ await client.query(
+ `INSERT INTO session_tape(session_id, seq, kind, payload, scope_label, entry_seq, created_at)
+ SELECT $1, t.next_seq + e.seq - $3, 'annotation', e.tape_payload, e.scope_label, e.seq, e.created_at
+ FROM jsonb_to_recordset($2::jsonb) AS e(seq bigint, tape_payload text, scope_label text, created_at bigint)
+ CROSS JOIN (SELECT COALESCE(MAX(seq), -1) + 1 AS next_seq FROM session_tape WHERE session_id = $1) t
+ ORDER BY e.seq`,
+ [lease.sessionId, encoded, startSeq],
);
- await insertTapeRow(client, full.sessionId, tapeTranscriptEntryRecord(full));
await client.query(
`UPDATE sessions
SET last_activity = CASE WHEN last_activity >= $2::bigint - ${LAST_ACTIVITY_DEBOUNCE_MS}
@@ -1020,11 +1049,11 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
ELSE turns + $4 END
WHERE id = $1`,
[
- full.sessionId,
- full.createdAt,
- seq + 1,
- full.type === "user" && !stored.includes('"overheard":true') ? 1 : 0,
- seq,
+ lease.sessionId,
+ createdAt,
+ startSeq + full.length,
+ rows.filter((entry) => entry.type === "user" && !entry.payload.includes('"overheard":true')).length,
+ startSeq,
],
);
return full;
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index 0ddcd0e34..32189824f 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -729,6 +729,7 @@ export interface SessionStore {
forceReleaseLease(sessionId: string): Promise<void>;
append(lease: Lease, entry: NewEntry): Promise<SessionEntry>;
+ appendMany(lease: Lease, entries: readonly NewEntry[]): Promise<SessionEntry[]>;
getEntries(sessionId: string, opts?: GetEntriesOptions): Promise<SessionEntry[]>;
getTranscriptEntries(sessionId: string, opts?: GetEntriesOptions): Promise<SessionEntry[]>;
canReadTranscriptSuffix(sessionId: string, beforeSeq: number): Promise<boolean>;
diff --git a/test/projects.test.ts b/test/projects.test.ts
index cc185392c..5597866cd 100644
--- a/test/projects.test.ts
+++ b/test/projects.test.ts
@@ -499,7 +499,7 @@ test("Project routes use ordinary group sessions with the durable roster as auth
assert.match(JSON.stringify(forked.entries), /after joining/);
assert.equal((await built.sessions.get(forked.session.id))?.title ?? null, null);
- const appendForFork = built.sessions.append.bind(built.sessions);
+ const appendForFork = built.sessions.appendMany.bind(built.sessions);
let releaseForkCopy!: () => void;
const forkCopyReleased = new Promise<void>((resolve) => {
releaseForkCopy = resolve;
@@ -509,13 +509,13 @@ test("Project routes use ordinary group sessions with the durable roster as auth
forkCopyStarted = resolve;
});
let copyingSessionId: string | undefined;
- built.sessions.append = async (lease, entry) => {
+ built.sessions.appendMany = async (lease, entries) => {
if (!copyingSessionId && lease.sessionId !== first.id && lease.sessionId !== forked.session.id) {
copyingSessionId = lease.sessionId;
forkCopyStarted();
await forkCopyReleased;
}
- return appendForFork(lease, entry);
+ return appendForFork(lease, entries);
};
const racingForkPromise = built.app.forkSession(first.id, "owner");
await forkCopyStart;
@@ -527,7 +527,7 @@ test("Project routes use ordinary group sessions with the durable roster as auth
assert.equal(addSettled, false);
releaseForkCopy();
const [racingFork, addedDuringFork] = await Promise.all([racingForkPromise, addDuringFork]);
- built.sessions.append = appendForFork;
+ built.sessions.appendMany = appendForFork;
assert.ok(racingFork);
assert.equal(addedDuringFork.status, "ok");
assert.equal(racingFork.session.id, copyingSessionId);
diff --git a/test/session-append-many.test.ts b/test/session-append-many.test.ts
new file mode 100644
index 000000000..9e5b3cc9b
--- /dev/null
+++ b/test/session-append-many.test.ts
@@ -0,0 +1,81 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { randomUUID } from "node:crypto";
+import pg from "pg";
+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
+import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";
+import { scopeId } from "../src/types.ts";
+
+for (const backend of ["memory", "postgres"] as const) {
+ test(
+ `appendMany preserves ordering, tape, counters, and leases: ${backend}`,
+ {
+ skip: backend === "postgres" && !process.env.DATABASE_URL,
+ },
+ async () => {
+ const store =
+ backend === "memory" ? createMemorySessionStore() : createPostgresSessionStore(process.env.DATABASE_URL!);
+ const scope = scopeId("personal", "batch-test");
+ const session = await store.getOrCreateByThread(`web:batch-test:${randomUUID()}`, "dm", scope);
+ await store.addParticipant(session.id, "batch-test");
+ const { lease } = await store.acquireLease(session.id);
+ assert.ok(lease);
+ await store.append(lease, { type: "user", payload: { text: "Before batch" }, scopeLabel: scope });
+ await store.appendTape(lease, { kind: "context_event", payload: { event: "test" }, scopeLabel: scope });
+ const batch = await store.appendMany(lease, [
+ { type: "assistant", payload: { text: "First answer" }, scopeLabel: scope },
+ { type: "user", payload: { text: "Next question" }, scopeLabel: scope },
+ { type: "assistant", payload: { text: "Next answer" }, scopeLabel: scope },
+ ]);
+ assert.deepEqual(
+ batch.map((entry) => [entry.seq, entry.parentSeq]),
+ [
+ [1, 0],
+ [2, 1],
+ [3, 2],
+ ],
+ );
+ assert.deepEqual((await store.getTranscriptEntries(session.id)).slice(1), batch);
+ assert.deepEqual(
+ (await store.getTape(session.id)).map((entry) => entry.seq),
+ [0, 1, 2, 3, 4],
+ );
+ assert.deepEqual(await store.appendMany(lease, []), []);
+ const pool = backend === "postgres" ? new pg.Pool({ connectionString: process.env.DATABASE_URL }) : null;
+ try {
+ if (pool) {
+ const { rows } = await pool.query("SELECT messages, turns FROM sessions WHERE id = $1", [session.id]);
+ assert.equal(Number(rows[0].messages), 4);
+ assert.equal(Number(rows[0].turns), 2);
+ const constraint = `batch_failure_${randomUUID().replaceAll("-", "")}`;
+ await pool.query(
+ `ALTER TABLE session_tape ADD CONSTRAINT ${constraint} CHECK (session_id <> '${session.id}' OR entry_seq <> 5)`,
+ );
+ try {
+ await assert.rejects(
+ store.appendMany(lease, [
+ { type: "user", payload: { text: "Rolled back" }, scopeLabel: scope },
+ { type: "assistant", payload: { text: "Fails tape insert" }, scopeLabel: scope },
+ ]),
+ );
+ assert.equal((await store.getEntries(session.id)).length, 4);
+ assert.equal((await store.getTape(session.id)).length, 5);
+ const after = await pool.query("SELECT messages, turns FROM sessions WHERE id = $1", [session.id]);
+ assert.deepEqual(after.rows, rows);
+ } finally {
+ await pool.query(`ALTER TABLE session_tape DROP CONSTRAINT ${constraint}`);
+ }
+ }
+ await store.releaseLease(lease);
+ await assert.rejects(
+ store.appendMany(lease, [{ type: "user", payload: { text: "Rejected" }, scopeLabel: scope }]),
+ /lease/,
+ );
+ await assert.rejects(store.appendMany(lease, []), /lease/);
+ assert.equal((await store.getEntries(session.id)).length, 4);
+ } finally {
+ await pool?.end();
+ }
+ },
+ );
+}