Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Fix prompt history session scoping

yxlyx841f26b6c8a2
diff --git a/gui/src/app/SessionProvider.test.tsx b/gui/src/app/SessionProvider.test.tsx
index ac27e73e..1580f070 100644
--- a/gui/src/app/SessionProvider.test.tsx
+++ b/gui/src/app/SessionProvider.test.tsx
@@ -138,7 +138,7 @@ mock.module("../hooks/useSessionBootstrap", () => ({
mock.module("../services/desktop/client", () => ({
setFast: async () => {},
savePastedImage: async () => "/tmp/pasted-image.png",
- imageThumbnail: async () => "data:image/jpeg;base64,",
+ imageThumbnail: async () => "data:image/jpeg;base64,", listCommands: async () => [],
openExternalUrl: async () => {},
openPathInTarget: async () => {},
ensureConversationView: async () => {
diff --git a/gui/src/app/sessionSnapshot.test.ts b/gui/src/app/sessionSnapshot.test.ts
new file mode 100644
index 00000000..2a3adeb5
--- /dev/null
+++ b/gui/src/app/sessionSnapshot.test.ts
@@ -0,0 +1,19 @@
+import { expect, test } from "bun:test";
+
+import { getPromptDraftKey, getWorkspaceDraftKey } from "./sessionSnapshot";
+
+test("conversation draft keys are scoped by workspace and conversation", () => {
+ const first = getPromptDraftKey("/workspace/first", "shared-id");
+ const second = getPromptDraftKey("/workspace/second", "shared-id");
+
+ expect(first).not.toBe(second);
+ expect(first).toBe("conversation:/workspace/first::shared-id");
+ expect(second).toBe("conversation:/workspace/second::shared-id");
+});
+
+test("workspace-only drafts retain their workspace scope", () => {
+ expect(getPromptDraftKey("/workspace/first", null)).toBe(
+ getWorkspaceDraftKey("/workspace/first"),
+ );
+ expect(getPromptDraftKey(null, null)).toBeNull();
+});
diff --git a/gui/src/app/sessionSnapshot.ts b/gui/src/app/sessionSnapshot.ts
index 0a0e0b2c..1402e1a1 100644
--- a/gui/src/app/sessionSnapshot.ts
+++ b/gui/src/app/sessionSnapshot.ts
@@ -6,8 +6,11 @@ import type {
export const LATEST_WORKSPACE_STORAGE_KEY = 'session:latest-workspace-path'
-function getConversationDraftKey(conversationId: string): string {
- return `conversation:${conversationId}`
+function getConversationDraftKey(
+ workspacePath: string | null | undefined,
+ conversationId: string,
+): string {
+ return `conversation:${workspacePath ?? ""}::${conversationId}`
}
export function getWorkspaceDraftKey(workspacePath: string): string {
@@ -19,7 +22,7 @@ export function getPromptDraftKey(
conversationId: string | null | undefined,
): string | null {
if (conversationId != null) {
- return getConversationDraftKey(conversationId)
+ return getConversationDraftKey(workspacePath, conversationId)
}
if (workspacePath != null) {
diff --git a/gui/src/app/sessionStore.test.ts b/gui/src/app/sessionStore.test.ts
index 1a79e0ff..a6c1e68f 100644
--- a/gui/src/app/sessionStore.test.ts
+++ b/gui/src/app/sessionStore.test.ts
@@ -112,6 +112,7 @@ mock.module("../services/desktop/client", () => ({
},
savePastedImage: async () => "/tmp/pasted-image.png",
imageThumbnail: async () => "data:image/jpeg;base64,",
+ listCommands: async () => [],
openExternalUrl: async () => {},
openPathInTarget: async () => {},
ensureConversationView: async (workspacePath: string, conversationId: string) => {
@@ -396,6 +397,43 @@ describe("sessionStore", () => {
).toBeUndefined();
});
+ test("attachment replacement removes the previous history entry atomically", () => {
+ const key = "conversation:history-attachments";
+ const previous = {
+ id: "/abs/previous.png",
+ path: "/abs/previous.png",
+ name: "previous.png",
+ ext: "png",
+ kind: "image" as const,
+ };
+ const next = [
+ {
+ id: "/abs/next-a.png",
+ path: "/abs/next-a.png",
+ name: "next-a.png",
+ ext: "png",
+ kind: "image" as const,
+ },
+ {
+ id: "/abs/next-b.png",
+ path: "/abs/next-b.png",
+ name: "next-b.png",
+ ext: "png",
+ kind: "image" as const,
+ },
+ ];
+
+ sessionStore.getState().addAttachments(key, [previous]);
+ sessionStore.getState().replaceAttachments(key, next);
+
+ expect(getAttachments(key)).toEqual(next);
+ expect(getAttachments(key)).not.toContainEqual(previous);
+
+ sessionStore.getState().replaceAttachments(key, []);
+ expect(getAttachments(key)).toEqual([]);
+ expect(sessionStore.getState().attachmentsByKey[key]).toBeUndefined();
+ });
+
test("workspace draft selection ignores a stale active conversation", () => {
sessionStore.getState().applySessionSnapshot(createSnapshot());
sessionStore.getState().setBoardSelection({
diff --git a/gui/src/app/sessionStoreState.ts b/gui/src/app/sessionStoreState.ts
index f49179cf..88d4c58a 100644
--- a/gui/src/app/sessionStoreState.ts
+++ b/gui/src/app/sessionStoreState.ts
@@ -152,6 +152,28 @@ export function createSessionStoreState(
};
});
},
+ replaceAttachments: (key, items) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => {
+ const nextByKey = { ...current.attachmentsByKey };
+ if (items.length === 0) {
+ delete nextByKey[key];
+ } else {
+ const paths = new Set<string>();
+ nextByKey[key] = items.filter((item) => {
+ if (paths.has(item.path)) {
+ return false;
+ }
+ paths.add(item.path);
+ return true;
+ });
+ }
+ return { attachmentsByKey: nextByKey };
+ });
+ },
removeAttachment: (key, id) => {
if (key == null) {
return;
diff --git a/gui/src/app/types/sessionStore.ts b/gui/src/app/types/sessionStore.ts
index 792de3bd..f380407a 100644
--- a/gui/src/app/types/sessionStore.ts
+++ b/gui/src/app/types/sessionStore.ts
@@ -57,6 +57,7 @@ export interface SessionStoreState {
workspacesByPath: Record<string, WorkspaceSession>;
applySessionSnapshot: (snapshot: SessionSnapshot) => void;
addAttachments: (key: string | null, items: Attachment[]) => void;
+ replaceAttachments: (key: string | null, items: Attachment[]) => void;
removeAttachment: (key: string | null, id: string) => void;
clearAttachments: (key: string | null) => void;
moveAttachments: (fromKey: string | null, toKey: string | null) => void;
diff --git a/gui/src/components/PromptInputCard.navigation.test.tsx b/gui/src/components/PromptInputCard.navigation.test.tsx
new file mode 100644
index 00000000..39ea0884
--- /dev/null
+++ b/gui/src/components/PromptInputCard.navigation.test.tsx
@@ -0,0 +1,260 @@
+import { afterAll, beforeAll, expect, test } from "bun:test";
+import { useState } from "react";
+
+import type { Attachment } from "./attachments/attachmentTypes";
+import type { ChatBinding } from "@/services/desktop/types/contracts";
+
+let createRoot: typeof import("react-dom/client").createRoot;
+let flushSync: typeof import("react-dom").flushSync;
+let PromptInputCard: typeof import("./PromptInputCard").PromptInputCard;
+let getPromptDraftKey: typeof import("@/app/sessionSnapshot").getPromptDraftKey;
+let resetSessionStore: typeof import("@/app/sessionStore").resetSessionStore;
+let sessionStore: typeof import("@/app/sessionStore").sessionStore;
+let unregisterDom: () => Promise<void>;
+
+beforeAll(async () => {
+ const { GlobalRegistrator } = await import("@happy-dom/global-registrator");
+ GlobalRegistrator.register();
+ unregisterDom = () => GlobalRegistrator.unregister();
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false;
+ Object.defineProperty(window, "__TAURI_INTERNALS__", {
+ configurable: true,
+ value: {
+ invoke: async (command: string) => {
+ if (command === "list_commands") return [];
+ if (command === "image_thumbnail") return "";
+ return null;
+ },
+ },
+ });
+ ({ createRoot } = await import("react-dom/client"));
+ ({ flushSync } = await import("react-dom"));
+ ({ PromptInputCard } = await import("./PromptInputCard"));
+ ({ getPromptDraftKey } = await import("@/app/sessionSnapshot"));
+ ({ resetSessionStore, sessionStore } = await import("@/app/sessionStore"));
+});
+
+afterAll(async () => {
+ await unregisterDom();
+});
+
+const workspacePath = "/workspace/history-tests";
+
+function ComposerHarness({
+ histories,
+ initialDrafts,
+ scope,
+}: {
+ histories: Record<string, string[]>;
+ initialDrafts: Record<string, string>;
+ scope: string;
+}) {
+ const [drafts, setDrafts] = useState(initialDrafts);
+ const binding: ChatBinding = { conversationId: scope, workspacePath };
+ const promptDraft = drafts[scope] ?? "";
+
+ return (
+ <PromptInputCard
+ binding={binding}
+ canCompose
+ isPlanningMode={false}
+ isRequestActive={false}
+ isSendingPrompt={false}
+ isUltraMode={false}
+ onCommandSelect={() => {}}
+ promptDraft={promptDraft}
+ promptHistory={histories[scope] ?? []}
+ promptSettings={null}
+ setPlanningMode={() => {}}
+ setPromptDraft={(value) => {
+ setDrafts((current) => ({ ...current, [scope]: value }));
+ }}
+ setUltraMode={() => {}}
+ stopPrompt={async () => {}}
+ submitPrompt={async () => {}}
+ updatePromptSettings={async () => {}}
+ workspacePath={workspacePath}
+ />
+ );
+}
+
+function mountComposer(input: {
+ histories: Record<string, string[]>;
+ initialAttachments?: Record<string, Attachment[]>;
+ initialDrafts: Record<string, string>;
+ scope: string;
+}) {
+ resetSessionStore();
+ for (const [conversationId, attachments] of Object.entries(
+ input.initialAttachments ?? {},
+ )) {
+ const key = getPromptDraftKey(workspacePath, conversationId)!;
+ sessionStore.getState().addAttachments(key, attachments);
+ }
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ let scope = input.scope;
+
+ const render = () => {
+ flushSync(() => {
+ root.render(
+ <ComposerHarness
+ histories={input.histories}
+ initialDrafts={input.initialDrafts}
+ scope={scope}
+ />,
+ );
+ });
+ };
+ render();
+
+ return {
+ container,
+ arrow(key: "ArrowUp" | "ArrowDown") {
+ const textarea = container.querySelector("textarea")!;
+ textarea.setSelectionRange(textarea.value.length, textarea.value.length);
+ flushSync(() => {
+ textarea.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ bubbles: true,
+ cancelable: true,
+ key,
+ }),
+ );
+ });
+ },
+ close() {
+ flushSync(() => root.unmount());
+ container.remove();
+ resetSessionStore();
+ },
+ switchScope(nextScope: string) {
+ scope = nextScope;
+ render();
+ },
+ textareaValue() {
+ return container.querySelector("textarea")!.value;
+ },
+ };
+}
+
+function image(path: string): Attachment {
+ return {
+ ext: "png",
+ id: path,
+ kind: "image",
+ name: path.split("/").at(-1)!,
+ path,
+ };
+}
+
+function attachmentTitles(container: HTMLElement) {
+ return Array.from(container.querySelectorAll<HTMLElement>("[title]"))
+ .map((element) => element.title)
+ .filter((title) => title.endsWith(".png"));
+}
+
+test("recalled multiline prompts keep navigating instead of trapping ArrowUp", () => {
+ const composer = mountComposer({
+ histories: {
+ chat: ["older prompt", "newest prompt\nwith a second line"],
+ },
+ initialDrafts: { chat: "draft" },
+ scope: "chat",
+ });
+
+ try {
+ composer.arrow("ArrowUp");
+ expect(composer.textareaValue()).toBe("newest prompt\nwith a second line");
+
+ composer.arrow("ArrowUp");
+ expect(composer.textareaValue()).toBe("older prompt");
+ } finally {
+ composer.close();
+ }
+});
+
+test("equal-length chat switches cannot restore another chat's draft or attachments", () => {
+ const firstAttachment = image("/images/first-live.png");
+ const secondAttachment = image("/images/second-live.png");
+ const composer = mountComposer({
+ histories: {
+ first: ["first old", "first new"],
+ second: ["second old", "second new"],
+ },
+ initialAttachments: {
+ first: [firstAttachment],
+ second: [secondAttachment],
+ },
+ initialDrafts: {
+ first: "first draft",
+ second: "second draft",
+ },
+ scope: "first",
+ });
+
+ try {
+ composer.arrow("ArrowUp");
+ expect(composer.textareaValue()).toBe("first new");
+
+ composer.switchScope("second");
+ expect(composer.textareaValue()).toBe("second draft");
+ expect(attachmentTitles(composer.container)).toEqual([
+ secondAttachment.path,
+ ]);
+
+ composer.arrow("ArrowDown");
+ expect(composer.textareaValue()).toBe("second draft");
+ expect(attachmentTitles(composer.container)).toEqual([
+ secondAttachment.path,
+ ]);
+
+ composer.arrow("ArrowUp");
+ expect(composer.textareaValue()).toBe("second new");
+ } finally {
+ composer.close();
+ }
+});
+
+test("each recalled prompt replaces attachments and exiting restores only the live draft", () => {
+ const live = image("/images/live.png");
+ const newest = image("/images/newest.png");
+ const older = [
+ image("/images/older-a.png"),
+ image("/images/older-b.png"),
+ image("/images/older-c.png"),
+ ];
+ const composer = mountComposer({
+ histories: {
+ chat: [
+ `older\n\nAttached files:\n${older.map((item) => `@[${item.path}]`).join("\n")}`,
+ `newest\n\nAttached files:\n@[${newest.path}]`,
+ ],
+ },
+ initialAttachments: { chat: [live] },
+ initialDrafts: { chat: "live draft" },
+ scope: "chat",
+ });
+
+ try {
+ composer.arrow("ArrowUp");
+ expect(composer.textareaValue()).toBe("newest");
+ expect(attachmentTitles(composer.container)).toEqual([newest.path]);
+
+ composer.arrow("ArrowUp");
+ expect(composer.textareaValue()).toBe("older");
+ expect(attachmentTitles(composer.container)).toEqual(
+ older.map((item) => item.path),
+ );
+
+ composer.arrow("ArrowDown");
+ expect(attachmentTitles(composer.container)).toEqual([newest.path]);
+
+ composer.arrow("ArrowDown");
+ expect(composer.textareaValue()).toBe("live draft");
+ expect(attachmentTitles(composer.container)).toEqual([live.path]);
+ } finally {
+ composer.close();
+ }
+});
diff --git a/gui/src/components/PromptInputCard.tsx b/gui/src/components/PromptInputCard.tsx
index 94c7347f..3e00da66 100644
--- a/gui/src/components/PromptInputCard.tsx
+++ b/gui/src/components/PromptInputCard.tsx
@@ -75,8 +75,13 @@ export function PromptInputCard({
// it — the highlight drifts away from the caret.
const commandOverlayRef = useRef<HTMLDivElement | null>(null);
const dropZoneRef = useRef<HTMLDivElement | null>(null);
- const { attachments, addAttachments, removeAttachment, replaceAttachments } =
- useAttachments(binding);
+ const {
+ attachmentScopeKey,
+ attachments,
+ addAttachments,
+ removeAttachment,
+ replaceAttachments,
+ } = useAttachments(binding);
const { isActive: isDropActive } = useDropZone(dropZoneRef, (paths) => {
const accepted = paths
.map((path) => classifyPath(path))
@@ -125,6 +130,7 @@ export function PromptInputCard({
const [attachmentsBeforeHistory, setAttachmentsBeforeHistory] = useState<
Attachment[]
>([]);
+ const promptHistoryScopeRef = useRef(attachmentScopeKey);
const promptHistoryLengthRef = useRef(promptHistory.length);
function resetHistoryNavigation() {
@@ -248,21 +254,42 @@ export function PromptInputCard({
return false;
}
- const textarea = event.currentTarget;
- if (direction === "previous" && !isCaretOnFirstLine(textarea)) {
- return false;
- }
- if (direction === "next" && !isCaretOnLastLine(textarea)) {
- return false;
- }
-
+ const didHistoryScopeChange =
+ promptHistoryScopeRef.current !== attachmentScopeKey;
const didHistoryLengthChange =
promptHistoryLengthRef.current !== promptHistory.length;
- const effectiveCursor = didHistoryLengthChange ? null : historyCursor;
- const effectiveDraftBeforeHistory = didHistoryLengthChange
+ const didHistoryChange = didHistoryScopeChange || didHistoryLengthChange;
+ const effectiveCursor = didHistoryChange ? null : historyCursor;
+ const effectiveDraftBeforeHistory = didHistoryChange
? ""
: draftBeforeHistory;
+ const effectiveAttachmentsBeforeHistory = didHistoryChange
+ ? []
+ : attachmentsBeforeHistory;
+ promptHistoryScopeRef.current = attachmentScopeKey;
promptHistoryLengthRef.current = promptHistory.length;
+ if (didHistoryChange) {
+ resetHistoryNavigation();
+ }
+
+ // Once history browsing has started, arrows always move between recalled
+ // prompts. The line-boundary guard only protects multiline drafts before
+ // entering history; otherwise a recalled multiline prompt appears stuck.
+ const textarea = event.currentTarget;
+ if (
+ effectiveCursor == null &&
+ direction === "previous" &&
+ !isCaretOnFirstLine(textarea)
+ ) {
+ return false;
+ }
+ if (
+ effectiveCursor == null &&
+ direction === "next" &&
+ !isCaretOnLastLine(textarea)
+ ) {
+ return false;
+ }
const result = getPromptHistoryNavigationResult({
direction,
@@ -291,7 +318,7 @@ export function PromptInputCard({
if (result.cursor == null) {
// Exited history — restore the live draft and its attachments.
setPromptDraft(result.draft);
- replaceAttachments(attachmentsBeforeHistory);
+ replaceAttachments(effectiveAttachmentsBeforeHistory);
setAttachmentsBeforeHistory([]);
} else {
const { body, paths } = parseAttachmentBlock(result.draft);
diff --git a/gui/src/hooks/useSession.ts b/gui/src/hooks/useSession.ts
index 16c2d4cd..5187aab4 100644
--- a/gui/src/hooks/useSession.ts
+++ b/gui/src/hooks/useSession.ts
@@ -284,21 +284,30 @@ export function useAttachments(binding?: ChatBinding | null) {
},
[promptDraftKey],
);
- // Swap the whole tray in one shot (used by prompt-history navigation to
- // rehydrate a restored prompt's attachments).
+ // Swap the whole tray in one store transaction so a recalled prompt cannot
+ // merge with the attachment set from the previously displayed history entry.
const replaceAttachments = useCallback(
(items: Attachment[]) => {
- sessionStore.getState().clearAttachments(promptDraftKey);
- if (items.length > 0) {
- sessionStore.getState().addAttachments(promptDraftKey, items);
- }
+ sessionStore.getState().replaceAttachments(promptDraftKey, items);
},
[promptDraftKey],
);
return useMemo(
- () => ({ attachments, addAttachments, removeAttachment, replaceAttachments }),
- [attachments, addAttachments, removeAttachment, replaceAttachments],
+ () => ({
+ attachmentScopeKey: promptDraftKey,
+ attachments,
+ addAttachments,
+ removeAttachment,
+ replaceAttachments,
+ }),
+ [
+ promptDraftKey,
+ attachments,
+ addAttachments,
+ removeAttachment,
+ replaceAttachments,
+ ],
);
}