Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

web-ui: pre-fork origin badge, author-labeled bubbles, real sidebar links

Regan Bellea1fa6176e02
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 9a4d275a0..de3ec466d 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -41,8 +41,13 @@ import {
entriesToMessages,
fetchEntry,
fetchTranscript,
+ currentEarlierCount,
+ forkOriginDetails,
forkCutSeq,
forkSession,
+ inheritedRefreshEntries,
+ inheritedTranscript,
+ loadInheritedTranscript,
makeCoreStreamFn,
makeOpenerStreamFn,
makeRunResumeStreamFn,
@@ -82,16 +87,19 @@ import { browserRenderableImage, formatBytes, icon, relTime } from "./ui";
import { adminSessionLogUrl, appState, can, renderSidebarTop, syncUrlFromState } from "./shell";
import {
addPendingSession,
+ dropPendingSession,
groupDmTitle,
refreshSessions,
renderList,
sessionsState,
sessionSlackUrl,
surfaceOf,
+ openSession,
} from "./sessions";
-import { backgroundLabel, clearWorking, conversationBackground, markWorking } from "./session-list";
+import { backgroundLabel, clearWorking, conversationBackground, isAbandonedNewChat, markWorking } from "./session-list";
import { liveTurnThreadRef } from "./working-dot";
import { newChatDraftKey, saveDraft, storedDraft } from "./drafts";
+import { createForkOriginController, forkOriginView } from "./fork-origin";
installMarkdownSanitizer();
@@ -122,8 +130,13 @@ export function markConnectorConnected(provider: string): void {
for (const hook of redrawHooks) hook();
}
-export function createChatSurface(ctx: ConvCtx): ChatSurface {
+export function createChatSurface(
+ ctx: ConvCtx,
+ dependencies: { fetchTranscript?: typeof fetchTranscript; openSession?: typeof openSession } = {},
+): ChatSurface {
const runSlot = createRunSlot();
+ const transcriptFetcher = dependencies.fetchTranscript ?? fetchTranscript;
+ const sessionOpener = dependencies.openSession ?? openSession;
const chatState = {
agent: null as Agent | null,
@@ -144,7 +157,37 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
transcriptAnchorSeq: null as number | null,
earlierCount: 0,
loadingEarlier: false,
+ forkSession: null as CoreSession | null,
+ inheritedMessages: [] as ReturnType<typeof entriesToMessages>,
+ inheritedExpanded: false,
+ inheritedLoaded: false,
};
+ const forkOriginController = createForkOriginController({
+ state: chatState,
+ load: async () => {
+ const session = chatState.forkSession;
+ if (!session) return [];
+ const entries = await loadInheritedTranscript(session, [], transcriptFetcher);
+ return entriesToMessages(entries, transcriptModel());
+ },
+ navigate: async () => {
+ const sourceId = chatState.forkSession?.forkedFrom?.sessionId;
+ if (!sourceId) return;
+ const listed = sessionsState.list.find((session) => session.id === sourceId);
+ const page = await transcriptFetcher(sourceId, { tailTurns: TAIL_TURNS });
+ const source = listed ?? page.session;
+ if (!source) throw new Error("missing source session");
+ await sessionOpener(source, Promise.resolve(page));
+ },
+ current: () => Boolean(chatState.forkSession && chatState.sessionId === chatState.forkSession.id),
+ redraw: () => {
+ if (chatState.agent) drawActiveChat();
+ else readonlyRedraw?.();
+ },
+ setError: (error) => {
+ ctx.composer.state.error = error;
+ },
+ });
let workTicker: ReturnType<typeof setInterval> | null = null;
let revealedTailLen = 0;
@@ -163,6 +206,7 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
let readOnlyView: { id: string; threadRef: string; session: CoreSession; anchorSeq: number | null } | null = null;
function teardownActiveChat(): void {
+ forkOriginController.invalidateRefresh();
readOnlyView = null;
preserveOutgoingWorkingDot(null);
detachActiveAgent();
@@ -183,6 +227,7 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
}
function resetChatState(): void {
+ dropAbandonedNewChat(null);
teardownActiveChat();
proactiveOpenerStarted = false;
chatState.rememberedThreadRef = null;
@@ -200,12 +245,29 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
const carried = storedDraft(newChatDraftKey(user));
if (carried) saveDraft(threadRef, carried);
ctx.composer.resetComposer();
+ forkOriginController.reset();
mountContinuable(threadRef, null, context?.scopeId ?? null, [], context?.name ?? null);
renderList();
ctx.composer.focusComposerEnd();
return threadRef;
}
+ function dropAbandonedNewChat(nextThreadRef: string | null): void {
+ const ref = chatState.threadRef;
+ if (
+ isAbandonedNewChat({
+ threadRef: ref,
+ nextThreadRef,
+ sessionId: chatState.sessionId,
+ pendingSend: chatState.pendingSend,
+ hasHumanMessage: (chatState.agent?.state.messages ?? []).some((m) => !(m as { opener?: boolean }).opener),
+ draft: ctx.composer.state.draft || storedDraft(ref ?? ""),
+ attachments: ctx.composer.state.attachments.length,
+ })
+ )
+ dropPendingSession(ref!);
+ }
+
function preserveOutgoingWorkingDot(nextThreadRef: string | null): void {
const live = liveTurnThreadRef({
mountedThreadRef: chatState.threadRef,
@@ -228,17 +290,25 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
scopeId: string | null,
messages: ReturnType<typeof entriesToMessages>,
contextName: string | null = null,
+ session?: CoreSession,
+ inheritedMessages: ReturnType<typeof entriesToMessages> = [],
): void {
const container = ctx.claimContainer();
if (!container) return;
readOnlyView = null;
preserveOutgoingWorkingDot(threadRef);
+ dropAbandonedNewChat(threadRef);
detachActiveAgent();
ctx.composer.resetComposer();
+ forkOriginController.reset();
chatState.threadRef = threadRef;
chatState.sessionId = sessionId;
chatState.scopeId = scopeId;
chatState.contextName = contextName;
+ chatState.forkSession = session ?? null;
+ chatState.inheritedMessages = inheritedMessages;
+ chatState.inheritedExpanded = false;
+ chatState.inheritedLoaded = !session?.forkedFrom;
chatState.rememberedThreadRef = threadRef;
chatState.rememberedSessionId = sessionId;
chatState.rememberedScopeId = scopeId;
@@ -377,18 +447,39 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
};
}
+ function inheritedHeader(): TemplateResult | typeof nothing {
+ const origin = chatState.forkSession
+ ? forkOriginDetails(chatState.forkSession, chatState.inheritedLoaded ? chatState.inheritedMessages.length : 0)
+ : null;
+ return forkOriginView(
+ origin
+ ? {
+ title: origin.title,
+ messageCount: origin.messageCount,
+ expanded: chatState.inheritedExpanded,
+ icon: icon(GitFork, 14),
+ navigate: () => void forkOriginController.navigate(),
+ toggle: () => void forkOriginController.toggle().catch(() => {}),
+ }
+ : null,
+ );
+ }
+
function onDelivery(threadRef: string): void {
const ro = readOnlyView;
if (ro && threadRef === ro.threadRef) {
void fetchTranscript(ro.id, ro.anchorSeq !== null ? { sinceSeq: ro.anchorSeq } : { tailTurns: TAIL_TURNS })
.then((page) => {
if (readOnlyView?.id !== ro.id) return;
- const earlier = page.earlierEntries ?? 0;
+ const split = inheritedTranscript(ro.session, page.entries ?? []);
+ const rawEarlier = page.earlierEntries ?? 0;
+ const earlier = currentEarlierCount(ro.session, rawEarlier);
mountReadOnly(
readOnlyView.session,
- entriesToMessages(page.entries ?? [], transcriptModel()),
+ entriesToMessages(split.current, transcriptModel()),
earlier,
- earlier > 0 ? (page.entries?.[0]?.seq ?? null) : null,
+ rawEarlier > 0 ? (page.entries?.[0]?.seq ?? null) : null,
+ entriesToMessages(split.inherited, transcriptModel()),
);
})
.catch(() => {});
@@ -480,13 +571,30 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
async function refreshTranscriptFromEntries(agent: Agent): Promise<void> {
const sessionId = chatState.sessionId;
if (!sessionId || agent !== chatState.agent || agent.state.isStreaming) return drawActiveChat(agent);
+ const generation = forkOriginController.beginRefresh();
const last = agent.state.messages[agent.state.messages.length - 1] as { stopReason?: string } | undefined;
if (last?.stopReason === "error" || last?.stopReason === "aborted") return drawActiveChat(agent);
try {
const anchor = chatState.transcriptAnchorSeq;
- const page = await fetchTranscript(sessionId, anchor !== null ? { sinceSeq: anchor } : undefined);
- if (agent !== chatState.agent || agent.state.isStreaming) return;
- const messages = entriesToMessages(page.entries ?? [], transcriptModel());
+ const page = await transcriptFetcher(sessionId, anchor !== null ? { sinceSeq: anchor } : undefined);
+ if (
+ !forkOriginController.isCurrentRefresh(generation) ||
+ sessionId !== chatState.sessionId ||
+ agent !== chatState.agent ||
+ agent.state.isStreaming
+ )
+ return;
+ const split = inheritedTranscript(chatState.forkSession ?? {}, page.entries ?? []);
+ const messages = entriesToMessages(split.current, transcriptModel());
+ const refreshedInherited = inheritedRefreshEntries(
+ chatState.forkSession ?? {},
+ page.entries ?? [],
+ chatState.inheritedLoaded,
+ );
+ forkOriginController.applyRefresh(
+ generation,
+ refreshedInherited ? entriesToMessages(refreshedInherited, transcriptModel()) : null,
+ );
try {
const r = await api<{ approvals: PendingApproval[] }>(
`/api/sessions/${encodeURIComponent(sessionId)}/approvals`,
@@ -495,10 +603,17 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
} catch {
void 0;
}
- if (agent !== chatState.agent || agent.state.isStreaming) return;
+ if (
+ !forkOriginController.isCurrentRefresh(generation) ||
+ sessionId !== chatState.sessionId ||
+ agent !== chatState.agent ||
+ agent.state.isStreaming
+ )
+ return;
agent.state.messages = messages;
- chatState.earlierCount = page.earlierEntries ?? 0;
- chatState.transcriptAnchorSeq = chatState.earlierCount > 0 ? (page.entries?.[0]?.seq ?? null) : null;
+ const rawEarlier = page.earlierEntries ?? 0;
+ chatState.earlierCount = currentEarlierCount(chatState.forkSession ?? {}, rawEarlier);
+ chatState.transcriptAnchorSeq = rawEarlier > 0 ? (page.entries?.[0]?.seq ?? null) : null;
} catch {
void 0;
}
@@ -627,18 +742,28 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
messages: ReturnType<typeof entriesToMessages>,
earlierCount = 0,
anchorSeq: number | null = null,
+ inheritedMessages: ReturnType<typeof entriesToMessages> = [],
): void {
const container = ctx.claimContainer();
if (!container) return;
preserveOutgoingWorkingDot(s.threadRef);
+ dropAbandonedNewChat(s.threadRef);
detachActiveAgent();
chatState.agent = null;
clearLiveWork();
chatState.host = null;
ctx.composer.resetComposer();
+ const sameSession = chatState.sessionId === s.id && chatState.threadRef === null;
+ if (!sameSession) forkOriginController.reset();
chatState.threadRef = null;
chatState.sessionId = s.id;
chatState.scopeId = s.scopeId;
+ chatState.forkSession = s;
+ if (!(sameSession && chatState.inheritedLoaded)) {
+ chatState.inheritedMessages = inheritedMessages;
+ chatState.inheritedLoaded = !s.forkedFrom;
+ }
+ if (!sameSession) chatState.inheritedExpanded = false;
syncLocation();
resetBackgroundPanel();
@@ -670,6 +795,7 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
${backgroundActivityStrip()}
<section class="chat-scroll readonly-scroll">
<div class="message-stack">
+ ${inheritedHeader()}
${
earlierCount > 0
? html`<div class="earlier-messages">
@@ -688,12 +814,18 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
const scroller = container?.querySelector<HTMLElement>(".chat-scroll");
const priorHeight = scroller?.scrollHeight ?? 0;
const priorTop = scroller?.scrollTop ?? 0;
- const remaining = page.earlierEntries ?? 0;
+ const rawRemaining = page.earlierEntries ?? 0;
+ const remaining = currentEarlierCount(s, rawRemaining);
+ const split = inheritedTranscript(s, page.entries ?? []);
mountReadOnly(
s,
- [...entriesToMessages(page.entries ?? [], transcriptModel()), ...messages],
+ [...entriesToMessages(split.current, transcriptModel()), ...messages],
remaining,
- remaining > 0 ? (page.entries?.[0]?.seq ?? null) : null,
+ rawRemaining > 0 ? (page.entries?.[0]?.seq ?? null) : null,
+ [
+ ...entriesToMessages(split.inherited, transcriptModel()),
+ ...chatState.inheritedMessages,
+ ],
);
requestAnimationFrame(() => {
const scrollerNow = container?.querySelector<HTMLElement>(".chat-scroll");
@@ -711,7 +843,14 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
</div>`
: nothing
}
- ${messages.length ? messages.map((m, i) => chatMessage(m, i)) : html`<div class="empty compact">No readable messages in this conversation.</div>`}
+ ${
+ (chatState.inheritedExpanded ? [...chatState.inheritedMessages, ...messages] : messages).length
+ ? (chatState.inheritedExpanded ? [...chatState.inheritedMessages, ...messages] : messages).map(
+ (m, i) => chatMessage(m, i),
+ )
+ : html`<div class="empty compact">No readable messages in this conversation.</div>`
+ }
+ ${ctx.composer.state.error ? html`<div class="composer-error inline">${ctx.composer.state.error}</div>` : nothing}
</div>
</section>
</div>
@@ -742,8 +881,8 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
`;
}
- function setTranscriptWindow(anchorSeq: number | null, earlierCount: number): void {
- chatState.transcriptAnchorSeq = earlierCount > 0 ? anchorSeq : null;
+ function setTranscriptWindow(anchorSeq: number | null, earlierCount: number, hasEarlier = earlierCount > 0): void {
+ chatState.transcriptAnchorSeq = hasEarlier ? anchorSeq : null;
chatState.earlierCount = earlierCount;
if (chatState.agent) drawActiveChat(chatState.agent);
}
@@ -770,14 +909,20 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
try {
const page = await fetchTranscript(sessionId, { beforeSeq: anchor, tailTurns: TAIL_TURNS });
if (agent !== chatState.agent || agent.state.isStreaming) return;
- const earlierMessages = entriesToMessages(page.entries ?? [], transcriptModel());
+ const split = inheritedTranscript(chatState.forkSession ?? {}, page.entries ?? []);
+ const earlierMessages = entriesToMessages(split.current, transcriptModel());
+ if (!chatState.inheritedLoaded)
+ chatState.inheritedMessages = [
+ ...entriesToMessages(split.inherited, transcriptModel()),
+ ...chatState.inheritedMessages,
+ ];
const scroller = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
const priorHeight = scroller?.scrollHeight ?? 0;
const priorTop = scroller?.scrollTop ?? 0;
agent.state.messages = [...earlierMessages, ...agent.state.messages];
- const remaining = page.earlierEntries ?? 0;
- chatState.transcriptAnchorSeq = remaining > 0 ? (page.entries?.[0]?.seq ?? null) : null;
- chatState.earlierCount = remaining;
+ const rawRemaining = page.earlierEntries ?? 0;
+ chatState.transcriptAnchorSeq = rawRemaining > 0 ? (page.entries?.[0]?.seq ?? null) : null;
+ chatState.earlierCount = currentEarlierCount(chatState.forkSession ?? {}, rawRemaining);
chatState.loadingEarlier = false;
drawActiveChat(agent);
requestAnimationFrame(() => {
@@ -847,12 +992,16 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
function drawActiveChat(agent = chatState.agent, opts: { forceScroll?: boolean } = {}): void {
if (!agent || agent !== chatState.agent || !chatState.host || appState.currentView !== "chats") return;
- const messages = visibleMessages(agent);
+ const currentMessages = visibleMessages(agent);
+ const messages = chatState.inheritedExpanded
+ ? [...chatState.inheritedMessages, ...currentMessages]
+ : currentMessages;
const isNewUser = sessionsState.list.filter((s) => s.id).length === 0;
let messageContent: Array<TemplateResult | typeof nothing> | TemplateResult | typeof nothing = nothing;
+ const inheritedOffset = chatState.inheritedExpanded ? chatState.inheritedMessages.length : 0;
if (messages.length) {
messageContent = messages.map((m, i) =>
- settledChatMessage(m, i, agent.state.isStreaming && m === agent.state.streamingMessage),
+ settledChatMessage(m, i - inheritedOffset, agent.state.isStreaming && m === agent.state.streamingMessage),
);
} else if (isNewUser) {
messageContent = welcomeGreeting();
@@ -880,8 +1029,9 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
glanceTier
? paneGlance(agent, messages, glanceTier)
: html`<section class="chat-scroll" @scroll=${onTranscriptScroll}>
- <div class="message-stack ${messages.length ? "" : "empty-stack"}">
- ${chatState.earlierCount > 0 ? earlierNotice(agent) : nothing} ${messageContent}
+ <div class="message-stack ${messages.length || chatState.forkSession ? "" : "empty-stack"}">
+ ${inheritedHeader()} ${chatState.earlierCount > 0 ? earlierNotice(agent) : nothing}
+ ${messageContent}
${showStateError(messages, agent.state.errorMessage) ? html`<div class="composer-error inline">${agent.state.errorMessage}</div>` : nothing}
</div>
</section>`
@@ -1078,7 +1228,7 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
const text = messageText(message).trim();
const ts = (message as { timestamp?: number }).timestamp;
if (!text && ts === undefined) return nothing;
- const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
+ const forkable = Boolean(index >= 0 && chatState.threadRef && chatState.sessionId && chatState.agent);
return html`
<div class="message-meta">
${ts !== undefined ? html`<span class="message-time">${formatClock(ts)}</span>` : nothing}
@@ -1132,13 +1282,16 @@ export function createChatSurface(ctx: ConvCtx): ChatSurface {
if (anchor !== null) userOrdinal += userMessagesBefore(entries ?? [], anchor);
const upToSeq = forkCutSeq(entries ?? [], userOrdinal, isUser);
const forked = await forkSession(sessionId, upToSeq);
+ const split = inheritedTranscript(forked.session, forked.entries ?? []);
ctx.composer.carryModelPick(sourceThreadRef, forked.session.threadRef);
mountContinuable(
forked.session.threadRef,
forked.session.id,
forked.session.scopeId,
- entriesToMessages(forked.entries ?? [], transcriptModel()),
+ entriesToMessages(split.current, transcriptModel()),
forked.session.channelName ?? null,
+ forked.session,
+ entriesToMessages(split.inherited, transcriptModel()),
);
await refreshSessions({ silent: true });
renderList();
diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.ts
index d9c1fffea..6ae240709 100644
--- a/plugins/web-ui/src/conv-types.ts
+++ b/plugins/web-ui/src/conv-types.ts
@@ -46,6 +46,10 @@ interface ChatState {
transcriptAnchorSeq: number | null;
earlierCount: number;
loadingEarlier: boolean;
+ forkSession: CoreSession | null;
+ inheritedMessages: ReturnType<typeof entriesToMessages>;
+ inheritedExpanded: boolean;
+ inheritedLoaded: boolean;
}
export interface ChatSurface {
@@ -61,16 +65,19 @@ export interface ChatSurface {
scopeId: string | null,
messages: ReturnType<typeof entriesToMessages>,
contextName?: string | null,
+ session?: CoreSession,
+ inheritedMessages?: ReturnType<typeof entriesToMessages>,
): void;
mountReadOnly(
s: CoreSession,
messages: ReturnType<typeof entriesToMessages>,
earlierCount?: number,
anchorSeq?: number | null,
+ inheritedMessages?: ReturnType<typeof entriesToMessages>,
): void;
mountLoadingPane(): void;
drawActiveChat(agent?: Agent | null, opts?: { forceScroll?: boolean }): void;
- setTranscriptWindow(anchorSeq: number | null, earlierCount: number): void;
+ setTranscriptWindow(anchorSeq: number | null, earlierCount: number, hasEarlier?: boolean): void;
requestBackgroundPanel(sessionId: string | null, threadRef: string | null): void;
activePendingApprovals(): PendingApproval[];
hasUnresolvedApproval(): boolean;
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index 9f6a55b15..2f40e288f 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -61,6 +61,68 @@ export interface CoreSession {
awaitingInput?: boolean;
backgroundJobs?: number;
watches?: number;
+ forkedFrom?: { sessionId: string; title?: string | null };
+ forkBoundarySeq?: number;
+}
+
+export function inheritedTranscript(
+ session: Pick<CoreSession, "forkedFrom" | "forkBoundarySeq">,
+ entries: SessionEntry[],
+): { inherited: SessionEntry[]; current: SessionEntry[] } {
+ if (!session.forkedFrom || session.forkBoundarySeq === undefined) return { inherited: [], current: entries };
+ const inherited: SessionEntry[] = [];
+ const current: SessionEntry[] = [];
+ for (const entry of entries)
+ (entry.seq !== undefined && entry.seq <= session.forkBoundarySeq ? inherited : current).push(entry);
+ return { inherited, current };
+}
+
+export function inheritedRefreshEntries(
+ session: Pick<CoreSession, "forkedFrom" | "forkBoundarySeq">,
+ entries: SessionEntry[],
+ inheritedLoaded: boolean,
+): SessionEntry[] | null {
+ const inherited = inheritedTranscript(session, entries).inherited;
+ return inherited.length && !inheritedLoaded ? inherited : null;
+}
+
+export function forkOriginDetails(
+ session: Pick<CoreSession, "forkedFrom" | "forkBoundarySeq">,
+ inheritedCount: number,
+): { sessionId: string; title: string; messageCount?: number } | null {
+ if (!session.forkedFrom || session.forkBoundarySeq === undefined) return null;
+ return {
+ sessionId: session.forkedFrom.sessionId,
+ title: session.forkedFrom.title?.trim() || "another conversation",
+ ...(inheritedCount > 0 ? { messageCount: inheritedCount } : {}),
+ };
+}
+
+export function currentEarlierCount(
+ session: Pick<CoreSession, "forkedFrom" | "forkBoundarySeq">,
+ earlierEntries: number,
+): number {
+ if (!session.forkedFrom || session.forkBoundarySeq === undefined) return earlierEntries;
+ return Math.max(0, earlierEntries - (session.forkBoundarySeq + 1));
+}
+
+export async function loadInheritedTranscript(
+ session: Pick<CoreSession, "id" | "forkedFrom" | "forkBoundarySeq">,
+ loaded: SessionEntry[],
+ fetcher: typeof fetchTranscript = fetchTranscript,
+): Promise<SessionEntry[]> {
+ if (loaded.length || !session.forkedFrom || session.forkBoundarySeq === undefined) return loaded;
+ let beforeSeq = session.forkBoundarySeq + 1;
+ let inherited: SessionEntry[] = [];
+ for (;;) {
+ const page = await fetcher(session.id, { beforeSeq, tailTurns: TAIL_TURNS });
+ const entries = inheritedTranscript(session, page.entries ?? []).inherited;
+ inherited = [...entries, ...inherited];
+ const earliestSeq = entries[0]?.seq;
+ if (!(page.earlierEntries ?? 0) || earliestSeq === undefined || earliestSeq <= 0 || earliestSeq >= beforeSeq) break;
+ beforeSeq = earliestSeq;
+ }
+ return inherited;
}
export interface SessionBackgroundView {
diff --git a/plugins/web-ui/src/crons.ts b/plugins/web-ui/src/crons.ts
index e9fc8d2cd..bfea1444b 100644
--- a/plugins/web-ui/src/crons.ts
+++ b/plugins/web-ui/src/crons.ts
@@ -7,7 +7,7 @@ import { listBackLink, listPageTpl } from "./list-page";
import { ensureContexts, scopeChip } from "./contexts";
import { appState } from "./shell";
import { mainConversation } from "./conversations";
-import { deepLinkPath, UI_BASE } from "./deep-link";
+import { deepLinkPath, isPlainLeftClick, UI_BASE } from "./deep-link";
import {
cronNextFire,
cronRunSummary,
@@ -340,7 +340,7 @@ function cronPageRow(c: CronView, mine: boolean): TemplateResult {
class="cron-row-main"
href=${deepLinkPath(UI_BASE, "crons", null, null, c.id)}
@click=${(event: MouseEvent) => {
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
+ if (!isPlainLeftClick(event)) return;
event.preventDefault();
openCron(c, { push: true });
}}
diff --git a/plugins/web-ui/src/deep-link.ts b/plugins/web-ui/src/deep-link.ts
index 659ec3bc4..336510b76 100644
--- a/plugins/web-ui/src/deep-link.ts
+++ b/plugins/web-ui/src/deep-link.ts
@@ -59,3 +59,8 @@ export function parseDeepLink(
export function sessionLink(origin: string, base: string, sessionId: string): string {
return `${origin}${deepLinkPath(base, "chats", sessionId)}`;
}
+
+/** True for an unmodified left click — the case an in-app link should handle itself (SPA nav). Modified clicks (cmd/ctrl/shift/alt, middle-click) fall through to the browser so "open in new tab" works. */
+export function isPlainLeftClick(e: MouseEvent): boolean {
+ return !(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0);
+}
diff --git a/plugins/web-ui/src/fork-origin.ts b/plugins/web-ui/src/fork-origin.ts
new file mode 100644
index 000000000..06cacb3cc
--- /dev/null
+++ b/plugins/web-ui/src/fork-origin.ts
@@ -0,0 +1,94 @@
+import { html, nothing, type TemplateResult } from "lit";
+
+export interface ForkOriginView {
+ title: string;
+ messageCount?: number;
+ expanded: boolean;
+ icon?: unknown;
+ navigate(): void;
+ toggle(): void;
+}
+
+export interface ForkOriginState<T> {
+ inheritedMessages: T[];
+ inheritedLoaded: boolean;
+ inheritedExpanded: boolean;
+}
+
+export function createForkOriginController<T>(options: {
+ state: ForkOriginState<T>;
+ load(): Promise<T[]>;
+ navigate(): Promise<void>;
+ current(): boolean;
+ redraw(): void;
+ setError(error: string): void;
+}) {
+ let refreshGeneration = 0;
+ let toggleGeneration = 0;
+ let loadingGeneration: number | null = null;
+ return {
+ reset() {
+ options.setError("");
+ toggleGeneration++;
+ loadingGeneration = null;
+ },
+ beginRefresh() {
+ return ++refreshGeneration;
+ },
+ invalidateRefresh() {
+ refreshGeneration++;
+ },
+ isCurrentRefresh(generation: number) {
+ return generation === refreshGeneration && options.current();
+ },
+ applyRefresh(generation: number, messages: T[] | null) {
+ if (generation !== refreshGeneration || !options.current()) return false;
+ if (messages) options.state.inheritedMessages = messages;
+ return true;
+ },
+ async navigate() {
+ try {
+ await options.navigate();
+ } catch {
+ options.setError("You no longer have access to the original conversation.");
+ options.redraw();
+ }
+ },
+ async toggle() {
+ if (loadingGeneration !== null) return;
+ options.setError("");
+ if (!options.state.inheritedExpanded && !options.state.inheritedLoaded) {
+ const generation = ++toggleGeneration;
+ loadingGeneration = generation;
+ try {
+ const messages = await options.load();
+ if (generation !== toggleGeneration || !options.current()) return;
+ options.state.inheritedMessages = messages;
+ options.state.inheritedLoaded = true;
+ } catch {
+ if (generation === toggleGeneration && options.current()) {
+ options.setError("Couldn't load the original conversation's history.");
+ options.redraw();
+ }
+ return;
+ } finally {
+ if (loadingGeneration === generation) loadingGeneration = null;
+ }
+ }
+ options.state.inheritedExpanded = !options.state.inheritedExpanded;
+ options.redraw();
+ },
+ };
+}
+
+export function forkOriginView(view: ForkOriginView | null): TemplateResult | typeof nothing {
+ if (!view) return nothing;
+ return html`<div class="fork-origin-row">
+ <button class="fork-origin-badge" type="button" @click=${view.navigate}>
+ ${view.icon ?? nothing}<span>Forked from ${view.title}</span>${
+ view.messageCount ? html`<span>· ${view.messageCount} messages</span>` : nothing
+ }
+ </button>
+ <button class="fork-origin-toggle" type="button" @click=${view.toggle}>${view.expanded ? "hide" : "show"}</button>
+ </div>`;
+}
diff --git a/plugins/web-ui/src/session-list.ts b/plugins/web-ui/src/session-list.ts
index 6bc352d7f..ab3bb21e8 100644
--- a/plugins/web-ui/src/session-list.ts
+++ b/plugins/web-ui/src/session-list.ts
@@ -97,6 +97,24 @@ export function withPendingSession(list: CoreSession[], pending: CoreSession): C
return [pending, ...list.filter((s) => s.threadRef !== pending.threadRef)];
}
+/** An unsent new chat the user walked away from, with nothing worth keeping. */
+export function isAbandonedNewChat(state: {
+ threadRef: string | null;
+ nextThreadRef: string | null;
+ sessionId: string | null;
+ pendingSend: string | null;
+ hasHumanMessage: boolean;
+ draft: string;
+ attachments: number;
+}): boolean {
+ const ref = state.threadRef;
+ if (!ref || ref === state.nextThreadRef) return false;
+ if (state.sessionId !== null || state.pendingSend === ref) return false;
+ if (state.hasHumanMessage) return false;
+ if (state.draft.trim() || state.attachments > 0) return false;
+ return true;
+}
+
export function withoutUnsentPending(list: CoreSession[], threadRef: string): CoreSession[] {
return list.filter((s) => s.id !== "" || s.threadRef !== threadRef);
}
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index bd8f6fd7b..738e164f0 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -28,6 +28,8 @@ import {
api,
attachPendingApprovals,
fetchTranscript,
+ currentEarlierCount,
+ inheritedTranscript,
isContinuable,
entriesToMessages,
regenerateTitle,
@@ -40,7 +42,7 @@ import {
type CoreProject,
type CoreSession,
} from "./core-bridge";
-import { sessionLink, UI_BASE } from "./deep-link";
+import { deepLinkPath, isPlainLeftClick, sessionLink, UI_BASE } from "./deep-link";
import {
activityOf,
chatBrowseStatusMatches,
@@ -617,7 +619,15 @@ function chatPageRow(s: CoreSession): TemplateResult {
class="list-row chat-row ${active ? "active" : ""} ${s.color ? "colored" : ""}"
style=${s.color ? `--session-color:${s.color}` : nothing}
>
- <button class="chat-row-open" type="button" @click=${() => void openSession(s)}>
+ <a
+ class="chat-row-open"
+ href=${deepLinkPath(UI_BASE, "chats", s.id)}
+ @click=${(e: MouseEvent) => {
+ if (!isPlainLeftClick(e)) return;
+ e.preventDefault();
+ void openSession(s);
+ }}
+ >
<span class="list-row-title">${statusMarks(s)}${groupDmTitle(s)}</span>
<span class="list-row-meta">
${scopeChip(s.scopeId, s.channelName ?? null)}
@@ -625,7 +635,7 @@ function chatPageRow(s: CoreSession): TemplateResult {
${readOnly ? html`<span class="ro-lock" title="Read-only">${icon(Lock, 12)}</span>` : nothing}
<span class="list-row-date">${listWhen(activityOf(s))}</span>
</span>
- </button>
+ </a>
${
s.id
? html`<span class="chat-row-actions">
@@ -782,14 +792,19 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
class="session-row ${active ? "active" : ""} ${menuOpen ? "menu-open" : ""} ${readOnly ? "read-only" : ""} ${refreshingTitle ? "title-refreshing" : ""} ${working ? "working" : ""} ${s.awaitingInput ? "awaiting-input" : ""} ${projectChild ? "project-child" : ""} ${s.color ? "colored" : ""}"
style=${s.color ? `--session-color:${s.color}` : nothing}
>
- <button
+ <a
class="session"
+ href=${saved ? deepLinkPath(UI_BASE, "chats", s.id) : nothing}
aria-busy=${refreshingTitle ? "true" : "false"}
aria-label=${ariaLabel}
draggable=${saved ? "true" : "false"}
@dragstart=${(e: DragEvent) => onSessionDragStart(e, s)}
@dragend=${() => endSessionDrag()}
- @click=${() => openSession(s)}
+ @click=${(e: MouseEvent) => {
+ if (saved && !isPlainLeftClick(e)) return;
+ e.preventDefault();
+ void openSession(s);
+ }}
@dblclick=${(e: Event) => {
if (!saved) return;
e.preventDefault();
@@ -802,7 +817,7 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
>${titleContent}</span
>${context ? html`<span class="row-context" title=${context}>${context}</span>` : nothing}
</div>
- </button>
+ </a>
${
saved
? html`<div class="session-menu">
@@ -1218,15 +1233,17 @@ export async function openSessionInto(
return;
}
- const messages = entriesToMessages(entriesRes.entries ?? [], transcriptModel());
- const earlier = entriesRes.earlierEntries ?? 0;
+ const split = inheritedTranscript(s, entriesRes.entries ?? []);
+ const messages = entriesToMessages(split.current, transcriptModel());
+ const inheritedMessages = entriesToMessages(split.inherited, transcriptModel());
+ const earlier = currentEarlierCount(s, entriesRes.earlierEntries ?? 0);
const anchorSeq = entriesRes.entries?.[0]?.seq ?? null;
if (continuable) {
attachPendingApprovals(messages, approvalsRes?.approvals ?? [], transcriptModel());
- conv.mountContinuable(s.threadRef, s.id, s.scopeId, messages, s.channelName ?? null);
- conv.setTranscriptWindow(anchorSeq, earlier);
+ conv.mountContinuable(s.threadRef, s.id, s.scopeId, messages, s.channelName ?? null, s, inheritedMessages);
+ conv.setTranscriptWindow(anchorSeq, earlier, (entriesRes.earlierEntries ?? 0) > 0);
} else {
- conv.mountReadOnly(s, messages, earlier, anchorSeq);
+ conv.mountReadOnly(s, messages, earlier, anchorSeq, inheritedMessages);
}
renderList();
}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 481762f00..e4f6fd67f 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -8,6 +8,9 @@
--radius-md: 10px;
--radius-lg: 16px;
--chat-pad: 22px;
+ /* Height reserved at the bottom of every chat message for its own hover footer; it doubles
+ as the rhythm between message blocks. */
+ --meta-lane: 18px;
--brand-accent: #4f46e5;
--dev-accent: #8a5a00;
--brand-mark: "A";
@@ -235,6 +238,11 @@ body.resizing-sidebar {
flex-direction: column;
gap: 1px;
}
+a.navrow,
+a.session,
+a.chat-row-open {
+ text-decoration: none;
+}
.navrow {
display: flex;
align-items: center;
@@ -1065,10 +1073,40 @@ body.resizing-sidebar {
min-height: 0;
overflow-y: auto;
- padding: 28px var(--chat-pad) 26px;
+ padding: 28px var(--chat-pad) 8px;
scroll-behavior: smooth;
}
+.fork-origin-row {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ margin: 8px 0 14px;
+}
+
+.fork-origin-badge,
+.fork-origin-toggle {
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--muted);
+ color: var(--muted-foreground);
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.fork-origin-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 5px 9px;
+}
+
+.fork-origin-toggle {
+ padding: 4px 7px;
+}
+
.earlier-messages {
display: flex;
justify-content: center;
@@ -1099,7 +1137,9 @@ body.resizing-sidebar {
display: flex;
flex-direction: column;
- gap: 14px;
+ /* The space between blocks lives in each row's reserved meta lane (see .message-row), so the
+ stack adds none of its own — a hover footer can never overhang the block below. */
+ gap: 0;
}
.empty-stack {
justify-content: center;
@@ -1118,6 +1158,11 @@ body.resizing-sidebar {
display: flex;
min-width: 0;
position: relative;
+ /* A lane at the bottom of every row that belongs to that row's own hover footer. It doubles
+ as the rhythm between blocks, so reserving it costs almost no height — and because the
+ footer paints inside its own row, it can never overlay the block below (most visibly a
+ collapsed 'Worked for Ns' header). Revealing the footer still changes no layout. */
+ padding-bottom: var(--meta-lane);
}
.user-row {
flex-direction: column;
@@ -1138,41 +1183,28 @@ body.resizing-sidebar {
border: 1px dashed var(--border);
}
+/* The hover footer (timestamp + copy/fork) sits in its row's reserved bottom lane: out of flow,
+ so revealing it never reflows, but inside the row's own box, so it never paints over the next
+ block and needs no opaque backing. The lane is part of the row, so no hover bridge is needed
+ to reach it either. pointer-events (not visibility) gates interaction, so the buttons stay
+ keyboard-focusable while hidden — that is what lets :focus-within reveal the footer. */
.message-meta {
position: absolute;
- top: 100%;
+ bottom: 0;
left: 0;
z-index: 2;
- margin-top: 2px;
display: flex;
align-items: center;
gap: 6px;
- height: 22px;
+ height: var(--meta-lane);
padding: 0 2px;
border-radius: 6px;
- background: var(--background);
color: var(--muted-foreground);
font-size: 11px;
opacity: 0;
pointer-events: none;
- /* The ::before bridge below is what keeps the footer reachable; the hide itself stays
- near-instant, because the footer overhangs the next row and any lingering paints on
- top of content the pointer has already moved on to. pointer-events (not visibility)
- gates interaction so the buttons stay keyboard-focusable while hidden, which is what
- lets :focus-within reveal the footer at all. */
transition: opacity 0.12s ease;
}
-/* Invisible hover bridge over the 2px gap between the row and the footer (plus a little
- slack), so crossing the gap never drops the row's :hover — while it's crossed, the
- footer is a hovered ancestor's child and stays interactive. */
-.message-meta::before {
- content: "";
- position: absolute;
- left: -4px;
- right: -4px;
- top: -4px;
- height: 4px;
-}
.user-row .message-meta {
left: auto;
right: 0;
@@ -1186,17 +1218,13 @@ body.resizing-sidebar {
pointer-events: auto;
}
+/* Hoverless (touch) devices can't reveal the footer, and a tap can't focus a control that
+ ignores pointer events — so there it simply stays visible in its lane. */
@media (hover: none) {
.message-meta {
- position: static;
- margin-top: 2px;
- background: transparent;
opacity: 1;
pointer-events: auto;
}
- .message-meta::before {
- display: none;
- }
}
.message-time {
white-space: nowrap;
@@ -4112,7 +4140,7 @@ body.resizing-sidebar {
padding: var(--surface-safe-top) max(10px, env(safe-area-inset-right)) 0 max(10px, env(safe-area-inset-left));
}
.message-stack {
- gap: 20px;
+ gap: 6px;
}
.chat-scroll {
padding-right: max(var(--chat-pad), env(safe-area-inset-right));
@@ -6654,10 +6682,13 @@ h3.ambient-field-label {
}
[data-density="compact"] .chat-scroll {
- padding: 14px 14px 18px;
+ padding: 14px 14px 4px;
+}
+[data-density="compact"] .message-row {
+ --meta-lane: 16px;
}
[data-density="compact"] .message-stack {
- gap: 10px;
+ gap: 0;
font-size: 13.5px;
}
[data-density="compact"] .live-work-detail {
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index ff4ce9a68..1f29ae2b8 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -33,7 +33,7 @@ import { markConnectorConnected } from "./chat";
import { clearSkillsCache, resyncModelSelection, seedRuntimeConfig } from "./composer";
import { ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";
import { clearAllDrafts, saveDraft, storedDraft } from "./drafts";
-import { deepLinkPath, parseDeepLink, UI_BASE } from "./deep-link";
+import { deepLinkPath, isPlainLeftClick, parseDeepLink, UI_BASE } from "./deep-link";
import {
addBlankPane,
canvasToast,
@@ -483,14 +483,14 @@ export function mountShell(): void {
export function renderSidebarTop(): void {
if (!appState.topEl) return;
const navRow = (v: View, glyph: IconNode, label: string) =>
- html`<button
+ html`<a
class="navrow ${appState.currentView === v ? "active" : ""}"
- type="button"
+ href=${deepLinkPath(UI_BASE, v, null)}
data-view=${v}
title=${label}
>
${icon(glyph, 17)}<span>${label}</span>
- </button>`;
+ </a>`;
const navGroup = (id: string, title: string, open: boolean, toggle: () => void, rows: TemplateResult) => html`
<button
class="nav-section-toggle"
@@ -559,12 +559,13 @@ export function renderSidebarTop(): void {
function onNavClick(e: Event): void {
const target = e.target as Element | null;
- const row = target?.closest<HTMLButtonElement>(".navrow[data-view]");
+ const row = target?.closest<HTMLAnchorElement>(".navrow[data-view]");
const view = row?.dataset.view;
- if (isView(view)) {
- switchView(view);
- closeSidebarOnNarrowView();
- }
+ if (!isView(view)) return;
+ if (e instanceof MouseEvent && !isPlainLeftClick(e)) return;
+ e.preventDefault();
+ switchView(view);
+ closeSidebarOnNarrowView();
}
export function switchView(v: View): void {
diff --git a/plugins/web-ui/test/chat-settled-row-cache.test.ts b/plugins/web-ui/test/chat-settled-row-cache.test.ts
index 182dd2caa..cc7b1d467 100644
--- a/plugins/web-ui/test/chat-settled-row-cache.test.ts
+++ b/plugins/web-ui/test/chat-settled-row-cache.test.ts
@@ -5,7 +5,7 @@ import test from "node:test";
const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
test("the transcript renders rows through the settled-row cache", () => {
- assert.match(chat, /messages\.map\(\(m, i\) =>\s*settledChatMessage\(m, i,/);
+ assert.match(chat, /messages\.map\(\(m, i\) =>\s*settledChatMessage\(m, i - inheritedOffset,/);
});
test("live or approval-paused rows bypass the cache (their render reads mutable state)", () => {
diff --git a/plugins/web-ui/test/crons-deep-link.test.ts b/plugins/web-ui/test/crons-deep-link.test.ts
index da567ba77..9203dbc84 100644
--- a/plugins/web-ui/test/crons-deep-link.test.ts
+++ b/plugins/web-ui/test/crons-deep-link.test.ts
@@ -15,7 +15,9 @@ test("a cron row is a real link to its own path", () => {
});
test("modified clicks fall through to the browser so open-in-tab and save-link still work", () => {
- assert.match(source, /event\.metaKey \|\| event\.ctrlKey \|\| event\.shiftKey \|\| event\.altKey \|\| event\.button/);
+ const deepLink = readFileSync(new URL("../src/deep-link.ts", import.meta.url), "utf8");
+ assert.match(deepLink, /e\.metaKey \|\| e\.ctrlKey \|\| e\.shiftKey \|\| e\.altKey \|\| e\.button !== 0/);
+ assert.match(source, /if \(!isPlainLeftClick\(event\)\) return;/);
});
test("opening a cron from the list pushes history, so Back returns to the list", () => {
diff --git a/plugins/web-ui/test/fork-remount-preserves-show.test.ts b/plugins/web-ui/test/fork-remount-preserves-show.test.ts
new file mode 100644
index 000000000..99d070fc6
--- /dev/null
+++ b/plugins/web-ui/test/fork-remount-preserves-show.test.ts
@@ -0,0 +1,15 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
+
+// A same-session readonly remount (delivery refresh, earlier pages) must not
+// reset the fork-origin controller: reset bumps the toggle generation and
+// discards an in-flight multi-page "show" load with no error.
+test("readonly remount resets the fork-origin controller only when the session changes", () => {
+ assert.match(
+ chat,
+ /const sameSession = chatState\.sessionId === s\.id && chatState\.threadRef === null;\s*if \(!sameSession\) forkOriginController\.reset\(\);/,
+ );
+});
diff --git a/plugins/web-ui/test/fork-transcript-anchor.test.ts b/plugins/web-ui/test/fork-transcript-anchor.test.ts
new file mode 100644
index 000000000..39cf19fe4
--- /dev/null
+++ b/plugins/web-ui/test/fork-transcript-anchor.test.ts
@@ -0,0 +1,34 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
+const sessions = readFileSync(new URL("../src/sessions.ts", import.meta.url), "utf8");
+
+// A fork whose only unloaded prefix is collapsed pre-fork history shows no
+// "earlier" button (adjusted count 0) but MUST keep its refresh anchor —
+// otherwise every settled turn refetches the transcript unbounded.
+test("the refresh anchor derives from raw earlier entries, not the fork-adjusted count", () => {
+ assert.match(chat, /const rawEarlier = page\.earlierEntries \?\? 0;/);
+ assert.match(
+ chat,
+ /chatState\.transcriptAnchorSeq = rawEarlier > 0 \? \(page\.entries\?\.\[0\]\?\.seq \?\? null\) : null;/,
+ );
+ assert.match(chat, /const rawRemaining = page\.earlierEntries \?\? 0;/);
+ assert.match(
+ chat,
+ /chatState\.transcriptAnchorSeq = rawRemaining > 0 \? \(page\.entries\?\.\[0\]\?\.seq \?\? null\) : null;/,
+ );
+ assert.match(
+ chat,
+ /setTranscriptWindow\(anchorSeq: number \| null, earlierCount: number, hasEarlier = earlierCount > 0\)/,
+ );
+ assert.match(sessions, /conv\.setTranscriptWindow\(anchorSeq, earlier, \(entriesRes\.earlierEntries \?\? 0\) > 0\);/);
+});
+
+// Badge navigation must probe access itself: a listed-but-unreadable origin
+// otherwise slips past the controller's error path into a torn-down view.
+test("origin navigation fetches the source transcript before opening it", () => {
+ assert.match(chat, /const page = await transcriptFetcher\(sourceId, \{ tailTurns: TAIL_TURNS \}\);/);
+ assert.match(chat, /await sessionOpener\(source, Promise\.resolve\(page\)\);/);
+});
diff --git a/plugins/web-ui/test/history.test.ts b/plugins/web-ui/test/history.test.ts
index 29a16da64..a136af0fc 100644
--- a/plugins/web-ui/test/history.test.ts
+++ b/plugins/web-ui/test/history.test.ts
@@ -1,14 +1,343 @@
import { test } from "node:test";
import assert from "node:assert/strict";
+import { JSDOM } from "jsdom";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
attachPendingApprovals,
+ currentEarlierCount,
entriesToMessages,
+ forkOriginDetails,
+ inheritedRefreshEntries,
+ inheritedTranscript,
+ loadInheritedTranscript,
type AssistantWork,
type PendingApproval,
type SessionEntry,
} from "../src/core-bridge.ts";
+test("fork provenance separates inherited entries at the boundary", () => {
+ const entries: SessionEntry[] = [
+ { type: "user", payload: { text: "old" }, createdAt: 1, seq: 1 },
+ { type: "assistant", payload: { text: "copied" }, createdAt: 2, seq: 2 },
+ { type: "user", payload: { text: "new" }, createdAt: 3, seq: 3 },
+ ];
+ const collapsed = inheritedTranscript(
+ { forkedFrom: { sessionId: "source", title: "Original" }, forkBoundarySeq: 2 },
+ entries,
+ );
+ assert.deepEqual(
+ collapsed.inherited.map((entry) => entry.seq),
+ [1, 2],
+ );
+ assert.deepEqual(
+ collapsed.current.map((entry) => entry.seq),
+ [3],
+ );
+ assert.deepEqual(inheritedTranscript({}, entries), { inherited: [], current: entries });
+});
+
+test("inherited transcript requires complete provenance and a defined entry sequence", () => {
+ const sequenced = { type: "user", payload: { text: "old" }, createdAt: 1, seq: 2 } as SessionEntry;
+ const unsequenced = { type: "assistant", payload: { text: "unknown" }, createdAt: 2 } as SessionEntry;
+ assert.deepEqual(inheritedTranscript({ forkedFrom: { sessionId: "source" } }, [sequenced]), {
+ inherited: [],
+ current: [sequenced],
+ });
+ assert.deepEqual(inheritedTranscript({ forkBoundarySeq: 2 }, [sequenced]), {
+ inherited: [],
+ current: [sequenced],
+ });
+ assert.deepEqual(inheritedTranscript({ forkedFrom: { sessionId: "source" }, forkBoundarySeq: 2 }, [unsequenced]), {
+ inherited: [],
+ current: [unsequenced],
+ });
+});
+
+test("inherited expansion pages backward to the start and preserves transcript order", async () => {
+ const session = { id: "fork", forkedFrom: { sessionId: "source" }, forkBoundarySeq: 50 };
+ const first = { type: "user", payload: { text: "first" }, createdAt: 1, seq: 1 } as SessionEntry;
+ const middle = { type: "assistant", payload: { text: "middle" }, createdAt: 2, seq: 25 } as SessionEntry;
+ const last = { type: "user", payload: { text: "last" }, createdAt: 3, seq: 50 } as SessionEntry;
+ const calls: unknown[] = [];
+ const fetcher = async (id: string, window?: { tailTurns?: number; beforeSeq?: number }) => {
+ calls.push({ id, window });
+ return window?.beforeSeq === 51
+ ? { entries: [middle, last], earlierEntries: 1 }
+ : { entries: [first], earlierEntries: 0 };
+ };
+ assert.deepEqual(await loadInheritedTranscript(session, [], fetcher), [first, middle, last]);
+ assert.deepEqual(calls, [
+ { id: "fork", window: { beforeSeq: 51, tailTurns: 25 } },
+ { id: "fork", window: { beforeSeq: 25, tailTurns: 25 } },
+ ]);
+ calls.length = 0;
+ assert.deepEqual(await loadInheritedTranscript(session, [last], fetcher), [last]);
+ assert.deepEqual(calls, []);
+});
+
+test("inherited expansion reaches entry seq 0 (0-based sequences)", async () => {
+ const session = { id: "fork", forkedFrom: { sessionId: "source" }, forkBoundarySeq: 2 };
+ const pages: Record<number, { entries: SessionEntry[]; earlierEntries: number }> = {
+ 3: {
+ entries: [{ type: "assistant", payload: { text: "two" }, createdAt: 3, seq: 2 } as SessionEntry],
+ earlierEntries: 2,
+ },
+ 2: {
+ entries: [{ type: "user", payload: { text: "one" }, createdAt: 2, seq: 1 } as SessionEntry],
+ earlierEntries: 1,
+ },
+ 1: {
+ entries: [{ type: "user", payload: { text: "zero" }, createdAt: 1, seq: 0 } as SessionEntry],
+ earlierEntries: 0,
+ },
+ };
+ const calls: number[] = [];
+ const fetcher = async (_id: string, window?: { beforeSeq?: number }) => {
+ calls.push(window?.beforeSeq ?? -1);
+ return pages[window?.beforeSeq ?? -1]!;
+ };
+ const inherited = await loadInheritedTranscript(session, [], fetcher as never);
+ assert.deepEqual(calls, [3, 2, 1]);
+ assert.deepEqual(
+ inherited.map((entry) => entry.seq),
+ [0, 1, 2],
+ );
+});
+
+test("currentEarlierCount hides inherited entries from the earlier-messages count", () => {
+ const fork = { forkedFrom: { sessionId: "source" }, forkBoundarySeq: 4 };
+ assert.equal(currentEarlierCount(fork, 12), 7);
+ assert.equal(currentEarlierCount(fork, 5), 0);
+ assert.equal(currentEarlierCount(fork, 3), 0);
+ assert.equal(currentEarlierCount({}, 12), 12);
+ assert.equal(currentEarlierCount({ forkedFrom: { sessionId: "source" } }, 12), 12);
+});
+
+test("a stale show load never lands on the next fork; reset revives the control", async () => {
+ const dom = new JSDOM("<!doctype html><main></main>");
+ Object.defineProperty(globalThis, "document", { configurable: true, value: dom.window.document });
+ Object.defineProperty(globalThis, "HTMLElement", { configurable: true, value: dom.window.HTMLElement });
+ Object.defineProperty(globalThis, "Event", { configurable: true, value: dom.window.Event });
+ const { createForkOriginController } = await import("../src/fork-origin.ts");
+ const state = { inheritedMessages: [] as SessionEntry[], inheritedLoaded: false, inheritedExpanded: false };
+ const pending: Array<(entries: SessionEntry[]) => void> = [];
+ const controller = createForkOriginController<SessionEntry>({
+ state,
+ load: () => new Promise((resolve) => pending.push(resolve)),
+ navigate: async () => {},
+ current: () => true,
+ redraw: () => {},
+ setError: () => {},
+ });
+ const firstToggle = controller.toggle();
+ assert.equal(pending.length, 1);
+ controller.reset(); // switched to another fork mid-load
+ const secondToggle = controller.toggle(); // new fork's control is live immediately
+ assert.equal(pending.length, 2, "reset frees the in-flight guard");
+ pending[0]!([{ type: "user", payload: { text: "fork A history" }, createdAt: 1, seq: 0 } as SessionEntry]);
+ await firstToggle;
+ assert.equal(state.inheritedLoaded, false, "stale load is discarded");
+ assert.equal(state.inheritedMessages.length, 0, "stale load is discarded");
+ pending[1]!([{ type: "user", payload: { text: "fork B history" }, createdAt: 2, seq: 0 } as SessionEntry]);
+ await secondToggle;
+ assert.equal(state.inheritedLoaded, true);
+ assert.equal(state.inheritedExpanded, true);
+ assert.equal((state.inheritedMessages[0]!.payload as { text: string }).text, "fork B history");
+});
+
+test("a failed show load surfaces an error instead of dying silently", async () => {
+ const { createForkOriginController } = await import("../src/fork-origin.ts");
+ const state = { inheritedMessages: [] as SessionEntry[], inheritedLoaded: false, inheritedExpanded: false };
+ let error = "";
+ let redraws = 0;
+ const controller = createForkOriginController<SessionEntry>({
+ state,
+ load: () => Promise.reject(new Error("boom")),
+ navigate: async () => {},
+ current: () => true,
+ redraw: () => {
+ redraws++;
+ },
+ setError: (value) => {
+ error = value;
+ },
+ });
+ await controller.toggle();
+ assert.equal(error, "Couldn't load the original conversation's history.");
+ assert.ok(redraws >= 1);
+ assert.equal(state.inheritedExpanded, false, "a failed load never expands");
+ assert.equal(state.inheritedLoaded, false);
+ // the control recovers: a later successful load works
+ const ok = createForkOriginController<SessionEntry>({
+ state,
+ load: async () => [{ type: "user", payload: { text: "old" }, createdAt: 1, seq: 0 } as SessionEntry],
+ navigate: async () => {},
+ current: () => true,
+ redraw: () => {},
+ setError: () => {},
+ });
+ await ok.toggle();
+ assert.equal(state.inheritedLoaded, true);
+ assert.equal(state.inheritedExpanded, true);
+});
+
+test("a successful show clears a prior error; an in-flight load survives non-reset redraws", async () => {
+ const { createForkOriginController } = await import("../src/fork-origin.ts");
+ const state = { inheritedMessages: [] as SessionEntry[], inheritedLoaded: false, inheritedExpanded: false };
+ let error = "sticky old failure";
+ let resolveLoad: ((entries: SessionEntry[]) => void) | null = null;
+ const controller = createForkOriginController<SessionEntry>({
+ state,
+ load: () => new Promise((resolve) => (resolveLoad = resolve)),
+ navigate: async () => {},
+ current: () => true,
+ redraw: () => {},
+ setError: (value) => {
+ error = value;
+ },
+ });
+ const toggling = controller.toggle();
+ assert.equal(error, "", "starting a new attempt clears the stale error");
+ // a same-session remount does NOT reset the controller, so the load lands
+ resolveLoad!([{ type: "user", payload: { text: "old" }, createdAt: 1, seq: 0 } as SessionEntry]);
+ await toggling;
+ assert.equal(state.inheritedLoaded, true);
+ assert.equal(state.inheritedExpanded, true);
+ assert.equal(error, "", "no error after a successful show");
+});
+
+test("fork origin remains visible when a deep-link tail contains only post-fork entries", () => {
+ const session = { forkedFrom: { sessionId: "source", title: "Original" }, forkBoundarySeq: 10 };
+ const postForkTail = Array.from({ length: 25 }, (_, index) => ({
+ type: "user" as const,
+ payload: { text: String(index) },
+ createdAt: index,
+ seq: 11 + index,
+ }));
+ assert.equal(inheritedTranscript(session, postForkTail).inherited.length, 0);
+ assert.deepEqual(forkOriginDetails(session, 0), { sessionId: "source", title: "Original" });
+ assert.deepEqual(forkOriginDetails(session, 3), {
+ sessionId: "source",
+ title: "Original",
+ messageCount: 3,
+ });
+});
+
+test("fork origin DOM navigates, reports access failure once, pages, toggles, survives refresh, and resets", async () => {
+ const dom = new JSDOM('<!doctype html><main id="chat"></main>');
+ Object.defineProperty(globalThis, "document", { configurable: true, value: dom.window.document });
+ Object.defineProperty(globalThis, "HTMLElement", { configurable: true, value: dom.window.HTMLElement });
+ Object.defineProperty(globalThis, "Event", { configurable: true, value: dom.window.Event });
+ const [{ render }, { createForkOriginController, forkOriginView }] = await Promise.all([
+ import("lit"),
+ import("../src/fork-origin.ts"),
+ ]);
+ const host = dom.window.document.querySelector<HTMLElement>("#chat")!;
+ const session = {
+ id: "fork",
+ forkedFrom: { sessionId: "source", title: "Original" },
+ forkBoundarySeq: 2,
+ };
+ const state = { inheritedMessages: [] as SessionEntry[], inheritedLoaded: false, inheritedExpanded: false };
+ let error = "";
+ let navigationFails = false;
+ let navigations = 0;
+ const calls: number[] = [];
+ const fetcher = async (_id: string, window?: { beforeSeq?: number }) => {
+ calls.push(window?.beforeSeq ?? 0);
+ return window?.beforeSeq === 3
+ ? {
+ entries: [{ type: "assistant" as const, payload: { text: "old two" }, createdAt: 2, seq: 2 }],
+ earlierEntries: 1,
+ }
+ : {
+ entries: [{ type: "user" as const, payload: { text: "old one" }, createdAt: 1, seq: 1 }],
+ earlierEntries: 0,
+ };
+ };
+ const controller = createForkOriginController({
+ state,
+ load: () => loadInheritedTranscript(session, [], fetcher as never),
+ navigate: async () => {
+ navigations++;
+ if (navigationFails) throw new Error("denied");
+ },
+ current: () => true,
+ redraw: () => draw(),
+ setError: (value) => {
+ error = value;
+ },
+ });
+ const draw = () => {
+ for (const node of host.querySelectorAll("article")) node.remove();
+ const origin = forkOriginDetails(session, state.inheritedLoaded ? state.inheritedMessages.length : 0);
+ render(
+ origin
+ ? forkOriginView({
+ ...origin,
+ expanded: state.inheritedExpanded,
+ navigate: () => void controller.navigate(),
+ toggle: () => void controller.toggle(),
+ })
+ : null,
+ host,
+ );
+ const existing = host.querySelector(".composer-error");
+ existing?.remove();
+ if (error) {
+ const node = dom.window.document.createElement("div");
+ node.className = "composer-error";
+ node.textContent = error;
+ host.append(node);
+ }
+ if (state.inheritedExpanded)
+ for (const entry of state.inheritedMessages) {
+ const node = dom.window.document.createElement("article");
+ node.textContent = (entry.payload as { text: string }).text;
+ host.append(node);
+ }
+ };
+ draw();
+ assert.match(host.textContent ?? "", /Forked from Original/);
+ assert.doesNotMatch(host.textContent ?? "", /messages/);
+ host.querySelector<HTMLButtonElement>(".fork-origin-badge")!.click();
+ assert.equal(navigations, 1);
+ navigationFails = true;
+ host.querySelector<HTMLButtonElement>(".fork-origin-badge")!.click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(host.textContent?.match(/You no longer have access to the original conversation\./g)?.length, 1);
+ controller.reset();
+ draw();
+ assert.doesNotMatch(host.textContent ?? "", /no longer have access/);
+ host.querySelector<HTMLButtonElement>(".fork-origin-toggle")!.click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.deepEqual(calls, [3, 2]);
+ assert.match(host.textContent ?? "", /old one/);
+ assert.match(host.textContent ?? "", /old two/);
+ assert.match(host.textContent ?? "", /2 messages/);
+ host.querySelector<HTMLButtonElement>(".fork-origin-toggle")!.click();
+ assert.doesNotMatch(host.textContent ?? "", /old one/);
+ const staleGeneration = controller.beginRefresh();
+ const generation = controller.beginRefresh();
+ const refresh = inheritedRefreshEntries(
+ session,
+ [{ type: "assistant", payload: { text: "new reply" }, createdAt: 3, seq: 3 }],
+ state.inheritedLoaded,
+ );
+ assert.equal(controller.applyRefresh(generation, refresh), true);
+ assert.equal(
+ controller.applyRefresh(staleGeneration, [{ type: "user", payload: { text: "stale" }, createdAt: 0, seq: 1 }]),
+ false,
+ );
+ host.querySelector<HTMLButtonElement>(".fork-origin-toggle")!.click();
+ assert.match(host.textContent ?? "", /old one/);
+ assert.equal(host.textContent?.match(/old one/g)?.length, 1);
+ const noOrigin = forkOriginDetails({}, 0);
+ render(noOrigin ? forkOriginView({ ...noOrigin, expanded: false, navigate() {}, toggle() {} }) : null, host);
+ assert.equal(host.querySelector(".fork-origin-badge"), null);
+ dom.window.close();
+});
+
const MODEL = { id: "m", api: "anthropic", provider: "anthropic" } as unknown as Parameters<
typeof entriesToMessages
>[1];
diff --git a/plugins/web-ui/test/session-list.test.ts b/plugins/web-ui/test/session-list.test.ts
index bf7899ece..cf2ad4f99 100644
--- a/plugins/web-ui/test/session-list.test.ts
+++ b/plugins/web-ui/test/session-list.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import {
activityOf,
applySessionState,
+ isAbandonedNewChat,
bumpActivity,
chatBrowseStatusMatches,
clearWorking,
@@ -411,3 +412,37 @@ test("conversationBackground: null when the conversation has nothing running, or
"nothing mounted",
);
});
+
+test("an untouched new chat is abandoned when you navigate away", () => {
+ const base = {
+ threadRef: "web:alice:t1",
+ nextThreadRef: "web:alice:t2",
+ sessionId: null,
+ pendingSend: null,
+ hasHumanMessage: false,
+ draft: "",
+ attachments: 0,
+ };
+ assert.equal(isAbandonedNewChat(base), true);
+ assert.equal(isAbandonedNewChat({ ...base, nextThreadRef: null }), true, "leaving the chats view abandons it too");
+});
+
+test("a new chat with anything worth keeping is not abandoned", () => {
+ const base = {
+ threadRef: "web:alice:t1",
+ nextThreadRef: "web:alice:t2",
+ sessionId: null,
+ pendingSend: null,
+ hasHumanMessage: false,
+ draft: "",
+ attachments: 0,
+ };
+ assert.equal(isAbandonedNewChat({ ...base, draft: "half-typed thought" }), false, "draft");
+ assert.equal(isAbandonedNewChat({ ...base, draft: " " }), true, "whitespace-only draft doesn't count");
+ assert.equal(isAbandonedNewChat({ ...base, attachments: 1 }), false, "attachment");
+ assert.equal(isAbandonedNewChat({ ...base, hasHumanMessage: true }), false, "already spoke");
+ assert.equal(isAbandonedNewChat({ ...base, pendingSend: "web:alice:t1" }), false, "send in flight");
+ assert.equal(isAbandonedNewChat({ ...base, sessionId: "s1" }), false, "saved session");
+ assert.equal(isAbandonedNewChat({ ...base, nextThreadRef: "web:alice:t1" }), false, "remounting the same chat");
+ assert.equal(isAbandonedNewChat({ ...base, threadRef: null }), false, "no chat mounted");
+});
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index 9502a5f7e..13aa15082 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -433,17 +433,25 @@ 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;
try {
for (const entry of copied) {
- await deps.sessions.append(lease, {
+ const appended = await deps.sessions.append(lease, {
type: entry.type,
payload: entry.payload,
scopeLabel: entry.scopeLabel,
});
+ forkBoundarySeq = appended.seq;
}
} finally {
await deps.sessions.releaseLease(lease);
}
+ if (forkBoundarySeq !== null) {
+ await deps.sessions.updateForkProvenance(forked.id, {
+ forkedFrom: { sessionId, title: source.title ?? null },
+ forkBoundarySeq,
+ });
+ }
const sourceTitle = source.title?.trim();
if (sourceTitle && projectMembers === undefined)
await deps.sessions.updateTitle(forked.id, `${sourceTitle} (fork)`);
diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.ts
index 79745801c..f1f1986ce 100644
--- a/src/sessions/memory-session-store.ts
+++ b/src/sessions/memory-session-store.ts
@@ -101,6 +101,11 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore
if (s) s.title = title;
},
+ async updateForkProvenance(sessionId, provenance) {
+ const s = sessions.get(sessionId);
+ if (s) Object.assign(s, provenance);
+ },
+
async acquireLease(sessionId, holder): Promise<LeaseAttempt> {
const held = leases.get(sessionId);
if (held && now() < held.expiresAt)
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index 7506f25b5..75942126b 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -36,7 +36,7 @@ import {
userMessagePreview,
} from "./session-store.ts";
-function rowToSession(r: Record<string, unknown>): Session {
+export function rowToSession(r: Record<string, unknown>): Session {
return {
id: r.id as string,
type: r.type as SessionType,
@@ -46,6 +46,15 @@ function rowToSession(r: Record<string, unknown>): Session {
createdAt: Number(r.created_at),
...(r.title != null ? { title: r.title as string } : {}),
...(r.channel_name != null ? { channelName: r.channel_name as string } : {}),
+ ...(r.forked_from_session_id != null && r.fork_boundary_seq != null
+ ? {
+ forkedFrom: {
+ sessionId: r.forked_from_session_id as string,
+ ...(r.forked_from_title != null ? { title: r.forked_from_title as string } : {}),
+ },
+ forkBoundarySeq: Number(r.fork_boundary_seq),
+ }
+ : {}),
};
}
@@ -169,6 +178,15 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
`ALTER TABLE sessions ADD COLUMN IF NOT EXISTS last_activity BIGINT`,
`ALTER TABLE sessions ADD COLUMN IF NOT EXISTS messages INT`,
`ALTER TABLE sessions ADD COLUMN IF NOT EXISTS turns INT`,
+ `ALTER TABLE sessions ADD COLUMN IF NOT EXISTS forked_from_session_id TEXT`,
+ `ALTER TABLE sessions ADD COLUMN IF NOT EXISTS forked_from_title TEXT`,
+ `ALTER TABLE sessions ADD COLUMN IF NOT EXISTS fork_boundary_seq INT`,
+ `DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'sessions_fork_provenance_pair') THEN
+ ALTER TABLE sessions ADD CONSTRAINT sessions_fork_provenance_pair
+ CHECK ((forked_from_session_id IS NULL) = (fork_boundary_seq IS NULL)) NOT VALID;
+ END IF;
+ END $$`,
`CREATE TABLE IF NOT EXISTS session_entries(
session_id TEXT NOT NULL, seq INT NOT NULL, parent_seq INT,
type TEXT NOT NULL, payload TEXT, scope_label TEXT NOT NULL, created_at BIGINT NOT NULL,
@@ -343,6 +361,13 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
await q("UPDATE sessions SET title = $2 WHERE id = $1", [sessionId, title]);
},
+ async updateForkProvenance(sessionId, provenance): Promise<void> {
+ await q(
+ "UPDATE sessions SET forked_from_session_id = $2, forked_from_title = $3, fork_boundary_seq = $4 WHERE id = $1",
+ [sessionId, provenance.forkedFrom.sessionId, provenance.forkedFrom.title ?? null, provenance.forkBoundarySeq],
+ );
+ },
+
async acquireLease(sessionId, holder): Promise<LeaseAttempt> {
const token = randomUUID();
const t = now();
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index 9b5a544d1..6f056d525 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -416,6 +416,10 @@ export interface SessionStore {
get(sessionId: string): Promise<Session | null>;
updateTitle(sessionId: string, title: string): Promise<void>;
+ updateForkProvenance(
+ sessionId: string,
+ provenance: { forkedFrom: { sessionId: string; title?: string | null }; forkBoundarySeq: number },
+ ): Promise<void>;
acquireLease(sessionId: string, holder?: LeaseHolder): Promise<LeaseAttempt>;
releaseLease(lease: Lease): Promise<void>;
diff --git a/src/types.ts b/src/types.ts
index 99d9aff7d..1f76af2d8 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -72,6 +72,8 @@ export interface Session {
archived?: boolean;
pinned?: boolean;
color?: string;
+ forkedFrom?: { sessionId: string; title?: string | null };
+ forkBoundarySeq?: number;
lastActivityAt?: number;
hasEntries?: boolean;
working?: boolean;
diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.ts
index d9e0b0912..2a3657b11 100644
--- a/test/postgres-store.test.ts
+++ b/test/postgres-store.test.ts
@@ -1,6 +1,6 @@
import { test, before } from "node:test";
import assert from "node:assert/strict";
-import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";
+import { createPostgresSessionStore, rowToSession } from "../src/sessions/postgres-session-store.ts";
import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";
import { scopeId, type Principal, type TurnResult } from "../src/types.ts";
import type { OrchestratorInput } from "../src/core/orchestrator.ts";
@@ -26,6 +26,33 @@ const turn = (text: string): OrchestratorInput => ({
text,
});
+test("pg session row mapping ignores incomplete fork provenance", () => {
+ const session = rowToSession({
+ id: "fork",
+ type: "dm",
+ scope_id: "personal:U1",
+ thread_ref: "thread",
+ created_at: 1,
+ forked_from_session_id: "source",
+ fork_boundary_seq: null,
+ });
+ assert.equal(session.forkedFrom, undefined);
+ assert.equal(session.forkBoundarySeq, undefined);
+});
+
+test("pg session store: fork provenance survives a store restart", { skip }, async () => {
+ const first = createPostgresSessionStore(URL!);
+ const session = await first.getOrCreateByThread("fork-provenance", "dm", scopeId("personal", "U1"));
+ await first.updateForkProvenance(session.id, {
+ forkedFrom: { sessionId: "source-session", title: "Original" },
+ forkBoundarySeq: 4,
+ });
+ const restarted = createPostgresSessionStore(URL!);
+ const loaded = await restarted.get(session.id);
+ assert.deepEqual(loaded?.forkedFrom, { sessionId: "source-session", title: "Original" });
+ assert.equal(loaded?.forkBoundarySeq, 4);
+});
+
test("pg session store: one-per-thread, TTL/fenced lease, monotonic log, visibility window", { skip }, async () => {
const s = createPostgresSessionStore(URL!, { leaseTtlMs: 50 });
const scope = scopeId("personal", "U1");
diff --git a/test/session-fork.test.ts b/test/session-fork.test.ts
index a273f6038..b3f205e2b 100644
--- a/test/session-fork.test.ts
+++ b/test/session-fork.test.ts
@@ -36,6 +36,8 @@ test("forking copies the transcript into a fresh independent web session", async
fork.entries.map((e) => [e.type, e.payload]),
source.entries.map((e) => [e.type, e.payload]),
);
+ assert.deepEqual(fork.session.forkedFrom, { sessionId: sid, title: source.session.title ?? null });
+ assert.equal(fork.session.forkBoundarySeq, fork.entries.at(-1)?.seq);
const mine = await app.listSessions("U1");
assert.ok(mine.some((s) => s.id === fork.session.id));
@@ -57,6 +59,33 @@ test("upToSeq truncates the copy at the cut point", async () => {
.map((e) => (e.payload as { text?: string }).text ?? "");
assert.ok(copiedTexts.some((t) => t.includes("Keep this turn")));
assert.ok(!copiedTexts.some((t) => t.includes("Drop this turn")));
+ assert.equal(fork.session.forkBoundarySeq, fork.entries.at(-1)?.seq);
+});
+
+test("a single-entry fork (boundary seq 0) still records provenance", async () => {
+ const { app } = freshApp();
+ const r = await app.turn(dm("Only the opening message survives the cut", "web:U1:seq0"));
+ const sid = r.sessionId!;
+ const first = (await app.getSession(sid))!.entries[0]!;
+ const fork = await app.forkSession(sid, "U1", { upToSeq: first.seq });
+ assert.ok(fork);
+ assert.equal(fork.entries.length, 1);
+ assert.equal(fork.entries[0]!.seq, 0, "entry seqs are 0-based");
+ assert.deepEqual(fork.session.forkedFrom, {
+ sessionId: sid,
+ title: (await app.getSession(sid))!.session.title ?? null,
+ });
+ assert.equal(fork.session.forkBoundarySeq, 0);
+});
+
+test("an empty fork has no provenance", async () => {
+ const { app } = freshApp();
+ const r = await app.turn(dm("Nothing before zero", "web:U1:empty"));
+ const fork = await app.forkSession(r.sessionId!, "U1", { upToSeq: -1 });
+ assert.ok(fork);
+ assert.equal(fork.entries.length, 0);
+ assert.equal(fork.session.forkedFrom, undefined);
+ assert.equal(fork.session.forkBoundarySeq, undefined);
});
test("the fork inherits a marked title and the original keeps its own history", async () => {
diff --git a/test/session-store.test.ts b/test/session-store.test.ts
index 7cbd88269..42855ce56 100644
--- a/test/session-store.test.ts
+++ b/test/session-store.test.ts
@@ -88,6 +88,18 @@ test("a blocked acquire names, dates, and times out the holder it lost to", asyn
const backends: Array<[string, () => SessionStore]> = [["memory", () => createMemorySessionStore()]];
for (const [name, make] of backends) {
+ test(`${name}: fork provenance is available through get and participant lists`, async () => {
+ const store = make();
+ const scope = scopeId("personal", "U1");
+ const session = await store.getOrCreateByThread("fork", "dm", scope);
+ await store.addParticipant(session.id, "U1");
+ const provenance = { forkedFrom: { sessionId: "source", title: "Original" }, forkBoundarySeq: 7 };
+ await store.updateForkProvenance(session.id, provenance);
+ assert.deepEqual(await store.get(session.id), { ...session, ...provenance });
+ assert.deepEqual((await store.listByParticipant("U1"))[0]?.forkedFrom, provenance.forkedFrom);
+ assert.equal((await store.listByParticipant("U1"))[0]?.forkBoundarySeq, 7);
+ });
+
test(`${name}: one session per thread (getOrCreateByThread is idempotent)`, async () => {
const store = make();
const scope = scopeId("personal", "U1");