Skip to content

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

Python

refactor(gui): split oversized state and client modules

Rach Pradhanbd853cc7a229
diff --git a/gui/src/app/sessionStore.ts b/gui/src/app/sessionStore.ts
index bfb7dff2..10f7bf6d 100644
--- a/gui/src/app/sessionStore.ts
+++ b/gui/src/app/sessionStore.ts
@@ -1,652 +1,29 @@
import { createStore } from "zustand/vanilla";
-import * as desktopClient from "../services/desktop/client";
import type { Attachment } from "@/components/attachments/attachmentTypes";
+import * as desktopClient from "../services/desktop/client";
import type {
ChatBinding,
- ConversationSessionSummary,
ConversationViewSnapshot,
PromptSettings,
RuntimeStatus,
- SessionSnapshot,
- WorkspaceSession,
} from "../services/desktop/types/contracts";
-import type { WorkspaceBoardSelection } from "./types/sessionContext";
-import type {
- PromptDraftEntry,
- SessionStoreSetter,
- SessionStoreState,
- WorkspaceMetaState,
-} from "./types/sessionStore";
-
-const GLOBAL_WORKSPACE_META_KEY = "__global__";
-
-export function getConversationStoreKey(
- workspacePath: string,
- conversationId: string,
-): string {
- return `${workspacePath}::${conversationId}`;
-}
-
-export function getConversationStoreKeyForBinding(binding: ChatBinding): string {
- return getConversationStoreKey(binding.workspacePath, binding.conversationId);
-}
-
-export function getWorkspaceMetaStoreKey(workspacePath: string | null): string {
- return workspacePath ?? GLOBAL_WORKSPACE_META_KEY;
-}
-
-export function areChatBindingsEqual(
- left: ChatBinding | null,
- right: ChatBinding | null,
-): boolean {
- if (left === right) {
- return true;
- }
-
- if (left == null || right == null) {
- return false;
- }
-
- return (
- left.workspacePath === right.workspacePath &&
- left.conversationId === right.conversationId
- );
-}
-
-function getConversationDraftEntry(
- drafts: Record<string, PromptDraftEntry>,
- key: string,
-): PromptDraftEntry | null {
- return drafts[key] ?? null;
-}
-
-function writePromptDraftEntry(
- drafts: Record<string, PromptDraftEntry>,
- key: string,
- entry: PromptDraftEntry | null,
-): Record<string, PromptDraftEntry> {
- const current = drafts[key] ?? null;
- const nextEntry =
- entry == null ||
- (entry.value === "" &&
- !entry.isPending &&
- !entry.isPlanningMode &&
- !entry.isUltraMode)
- ? null
- : entry;
-
- if (nextEntry == null) {
- if (current == null) {
- return drafts;
- }
-
- const nextDrafts = { ...drafts };
- delete nextDrafts[key];
- return nextDrafts;
- }
-
- if (
- current?.value === nextEntry.value &&
- current?.isPending === nextEntry.isPending &&
- current?.isPlanningMode === nextEntry.isPlanningMode &&
- current?.isUltraMode === nextEntry.isUltraMode
- ) {
- return drafts;
- }
-
- return {
- ...drafts,
- [key]: nextEntry,
- };
-}
-
-function setPromptDraftEntryValue(
- drafts: Record<string, PromptDraftEntry>,
- key: string,
- value: string,
-): Record<string, PromptDraftEntry> {
- const current = getConversationDraftEntry(drafts, key) ?? {
- isPending: false,
- isPlanningMode: false,
- isUltraMode: false,
- value: "",
- };
-
- return writePromptDraftEntry(drafts, key, { ...current, value });
-}
-
-function setPromptDraftEntryPending(
- drafts: Record<string, PromptDraftEntry>,
- key: string,
- isPending: boolean,
-): Record<string, PromptDraftEntry> {
- const current = getConversationDraftEntry(drafts, key) ?? {
- isPending: false,
- isPlanningMode: false,
- isUltraMode: false,
- value: "",
- };
-
- return writePromptDraftEntry(drafts, key, { ...current, isPending });
-}
-
-function setPromptDraftEntryPlanningMode(
- drafts: Record<string, PromptDraftEntry>,
- key: string,
- isPlanningMode: boolean,
-): Record<string, PromptDraftEntry> {
- const current = getConversationDraftEntry(drafts, key) ?? {
- isPending: false,
- isPlanningMode: false,
- isUltraMode: false,
- value: "",
- };
-
- return writePromptDraftEntry(drafts, key, { ...current, isPlanningMode });
-}
-
-function setPromptDraftEntryUltraMode(
- drafts: Record<string, PromptDraftEntry>,
- key: string,
- isUltraMode: boolean,
-): Record<string, PromptDraftEntry> {
- const current = getConversationDraftEntry(drafts, key) ?? {
- isPending: false,
- isPlanningMode: false,
- isUltraMode: false,
- value: "",
- };
-
- return writePromptDraftEntry(drafts, key, { ...current, isUltraMode });
-}
-
-function movePromptDraftEntry(
- drafts: Record<string, PromptDraftEntry>,
- fromKey: string | null,
- toKey: string | null,
-): Record<string, PromptDraftEntry> {
- if (fromKey == null || toKey == null || fromKey === toKey) {
- return drafts;
- }
-
- const draft = getConversationDraftEntry(drafts, fromKey);
- if (draft == null) {
- return drafts;
- }
-
- const nextDrafts = {
- ...writePromptDraftEntry(drafts, toKey, draft),
- };
- delete nextDrafts[fromKey];
- return nextDrafts;
-}
-
-export function getSelectionFromSnapshot(
- snapshot: SessionSnapshot,
-): WorkspaceBoardSelection {
- if (
- snapshot.activeWorkspacePath != null &&
- snapshot.activeConversationId != null
- ) {
- return {
- kind: "single-chat",
- chat: {
- workspacePath: snapshot.activeWorkspacePath,
- conversationId: snapshot.activeConversationId,
- },
- };
- }
-
- if (snapshot.activeWorkspacePath != null) {
- return {
- kind: "workspace-draft",
- workspacePath: snapshot.activeWorkspacePath,
- };
- }
-
- return { kind: "empty" };
-}
-
-function deriveConversationViews(snapshot: SessionSnapshot) {
- if (snapshot.conversationViews.length > 0) {
- return snapshot.conversationViews;
- }
-
- if (
- snapshot.activeWorkspacePath != null &&
- snapshot.activeConversationId != null
- ) {
- return [
- {
- activeRequestIds: snapshot.visibleActiveRequestIds,
- conversationId: snapshot.activeConversationId,
- followup: snapshot.visibleFollowup,
- messages: snapshot.visibleMessages,
- requestAgentIds: snapshot.visibleRequestAgentIds,
- todos: snapshot.visibleTodos,
- workspacePath: snapshot.activeWorkspacePath,
- } satisfies ConversationViewSnapshot,
- ];
- }
-
- return [];
-}
-
-function buildWorkspacesByPath(workspaces: WorkspaceSession[]) {
- const byPath: Record<string, WorkspaceSession> = {};
- for (const workspace of workspaces) {
- byPath[workspace.workspacePath] = workspace;
- }
- return byPath;
-}
-
-function buildConversationSummariesByKey(workspaces: WorkspaceSession[]) {
- const byKey: Record<string, ConversationSessionSummary> = {};
-
- for (const workspace of workspaces) {
- for (const conversation of workspace.conversations) {
- byKey[
- getConversationStoreKey(
- workspace.workspacePath,
- conversation.conversationId,
- )
- ] = conversation;
- }
- }
-
- return byKey;
-}
-
-export function areSelectionsEqual(
- left: WorkspaceBoardSelection,
- right: WorkspaceBoardSelection,
-): boolean {
- if (left === right) {
- return true;
- }
-
- if (left.kind !== right.kind) {
- return false;
- }
-
- switch (left.kind) {
- case "empty":
- return true;
- case "single-chat": {
- const rightSelection = right as Extract<
- WorkspaceBoardSelection,
- { kind: "single-chat" }
- >;
- return areChatBindingsEqual(left.chat, rightSelection.chat);
- }
- case "workspace-draft": {
- const rightSelection = right as Extract<
- WorkspaceBoardSelection,
- { kind: "workspace-draft" }
- >;
- return left.workspacePath === rightSelection.workspacePath;
- }
- case "saved-workspace": {
- const rightSelection = right as Extract<
- WorkspaceBoardSelection,
- { kind: "saved-workspace" }
- >;
- return (
- left.workspace.id === rightSelection.workspace.id &&
- left.workspace.layoutJson === rightSelection.workspace.layoutJson &&
- left.workspace.name === rightSelection.workspace.name &&
- left.workspace.updatedAt === rightSelection.workspace.updatedAt &&
- areChatBindingsEqual(left.activeChat, rightSelection.activeChat)
- );
- }
- }
-}
-
-function setWorkspaceMetaState(
- currentState: SessionStoreState,
- workspacePath: string | null,
- updater: (currentMeta: WorkspaceMetaState) => WorkspaceMetaState,
-) {
- const workspaceMetaKey = getWorkspaceMetaStoreKey(workspacePath);
- const currentMeta =
- currentState.workspaceMetaByKey[workspaceMetaKey] ?? defaultWorkspaceMetaState;
- const nextMeta = updater(currentMeta);
-
- if (
- nextMeta.promptSettings === currentMeta.promptSettings &&
- nextMeta.promptSettingsLoaded === currentMeta.promptSettingsLoaded &&
- nextMeta.runtimeStatus === currentMeta.runtimeStatus &&
- nextMeta.runtimeStatusLoaded === currentMeta.runtimeStatusLoaded
- ) {
- return currentState.workspaceMetaByKey;
- }
-
- return {
- ...currentState.workspaceMetaByKey,
- [workspaceMetaKey]: nextMeta,
- };
-}
-
-const defaultWorkspaceMetaState: WorkspaceMetaState = {
- promptSettings: null,
- promptSettingsLoaded: false,
- runtimeStatus: null,
- runtimeStatusLoaded: false,
-};
-
-function createSessionStoreState(set: SessionStoreSetter): SessionStoreState {
- return {
- activeConversationId: null,
- activeWorkspacePath: null,
- attachmentsByKey: {},
- conversationSummariesByKey: {},
- conversationViewsByKey: {},
- isBootstrapped: false,
- isOpeningProject: false,
- promptDraftsByKey: {},
- requestTimingsByConversationId: {},
- savedWorkspaces: [],
- selection: { kind: "empty" },
- uiError: null,
- workspaceMetaByKey: {},
- workspaces: [],
- workspacesByPath: {},
- applySessionSnapshot: (snapshot) => {
- const nextViews = deriveConversationViews(snapshot);
- set((current) => {
- const now = Date.now();
- let nextRequestTimingsByConversationId =
- current.requestTimingsByConversationId;
-
- if (nextViews.length > 0) {
- let didChangeTimings = false;
- const nextTimingsState = {
- ...current.requestTimingsByConversationId,
- };
-
- for (const view of nextViews) {
- const currentConversationTimings =
- current.requestTimingsByConversationId[view.conversationId] ?? {};
- const nextConversationTimings = { ...currentConversationTimings };
- const activeRequestIdSet = new Set(view.activeRequestIds ?? []);
-
- for (const requestId of view.activeRequestIds ?? []) {
- if (nextConversationTimings[requestId] == null) {
- nextConversationTimings[requestId] = {
- completedAtMs: null,
- startedAtMs: now,
- };
- didChangeTimings = true;
- }
- }
-
- for (const [requestId, timing] of Object.entries(
- nextConversationTimings,
- )) {
- if (
- timing.completedAtMs == null &&
- !activeRequestIdSet.has(requestId)
- ) {
- nextConversationTimings[requestId] = {
- ...timing,
- completedAtMs: now,
- };
- didChangeTimings = true;
- }
- }
-
- nextTimingsState[view.conversationId] = nextConversationTimings;
- }
-
- if (didChangeTimings) {
- nextRequestTimingsByConversationId = nextTimingsState;
- }
- }
-
- const nextConversationViewsByKey = { ...current.conversationViewsByKey };
- for (const view of nextViews) {
- nextConversationViewsByKey[
- getConversationStoreKey(view.workspacePath, view.conversationId)
- ] = view;
- }
-
- return {
- activeConversationId: snapshot.activeConversationId,
- activeWorkspacePath: snapshot.activeWorkspacePath,
- conversationSummariesByKey: buildConversationSummariesByKey(
- snapshot.workspaces,
- ),
- conversationViewsByKey: nextConversationViewsByKey,
- requestTimingsByConversationId: nextRequestTimingsByConversationId,
- savedWorkspaces: snapshot.savedWorkspaces,
- selection: (() => {
- if (current.selection.kind === "saved-workspace") {
- const savedWorkspaceSelection = current.selection;
- const matchingSavedWorkspace = snapshot.savedWorkspaces.find(
- (workspace) => workspace.id === savedWorkspaceSelection.workspace.id,
- );
- return matchingSavedWorkspace == null
- ? getSelectionFromSnapshot(snapshot)
- : {
- ...savedWorkspaceSelection,
- workspace: {
- ...savedWorkspaceSelection.workspace,
- name: matchingSavedWorkspace.name,
- updatedAt: matchingSavedWorkspace.updatedAt,
- },
- };
- }
-
- return getSelectionFromSnapshot(snapshot);
- })(),
- uiError: snapshot.uiError,
- workspaces: snapshot.workspaces,
- workspacesByPath: buildWorkspacesByPath(snapshot.workspaces),
- };
- });
- },
- addAttachments: (key, items) => {
- if (key == null || items.length === 0) {
- return;
- }
-
- set((current) => {
- const existing = current.attachmentsByKey[key] ?? [];
- const existingPaths = new Set(existing.map((item) => item.path));
- const additions = items.filter((item) => !existingPaths.has(item.path));
- if (additions.length === 0) {
- return current;
- }
-
- return {
- attachmentsByKey: {
- ...current.attachmentsByKey,
- [key]: [...existing, ...additions],
- },
- };
- });
- },
- removeAttachment: (key, id) => {
- if (key == null) {
- return;
- }
-
- set((current) => {
- const existing = current.attachmentsByKey[key];
- if (existing == null) {
- return current;
- }
-
- const next = existing.filter((item) => item.id !== id);
- const nextByKey = { ...current.attachmentsByKey };
- if (next.length === 0) {
- delete nextByKey[key];
- } else {
- nextByKey[key] = next;
- }
-
- return { attachmentsByKey: nextByKey };
- });
- },
- clearAttachments: (key) => {
- if (key == null) {
- return;
- }
-
- set((current) => {
- if (current.attachmentsByKey[key] == null) {
- return current;
- }
-
- const nextByKey = { ...current.attachmentsByKey };
- delete nextByKey[key];
- return { attachmentsByKey: nextByKey };
- });
- },
- clearPromptDraft: (key) => {
- if (key == null) {
- return;
- }
-
- set((current) => ({
- promptDraftsByKey: setPromptDraftEntryValue(
- current.promptDraftsByKey,
- key,
- "",
- ),
- }));
- },
- movePromptDraft: (fromKey, toKey) => {
- set((current) => ({
- promptDraftsByKey: movePromptDraftEntry(
- current.promptDraftsByKey,
- fromKey,
- toKey,
- ),
- }));
- },
- moveAttachments: (fromKey, toKey) => {
- if (fromKey == null || toKey == null || fromKey === toKey) {
- return;
- }
-
- set((current) => {
- const moving = current.attachmentsByKey[fromKey];
- if (moving == null) {
- return current;
- }
-
- const nextByKey = { ...current.attachmentsByKey };
- delete nextByKey[fromKey];
-
- const existing = nextByKey[toKey] ?? [];
- const existingPaths = new Set(existing.map((item) => item.path));
- nextByKey[toKey] = [
- ...existing,
- ...moving.filter((item) => !existingPaths.has(item.path)),
- ];
-
- return { attachmentsByKey: nextByKey };
- });
- },
- setBoardSelection: (selection) => {
- set((current) =>
- areSelectionsEqual(current.selection, selection) ? current : { selection },
- );
- },
- setIsBootstrapped: (value) => {
- set((current) =>
- current.isBootstrapped === value ? current : { isBootstrapped: value },
- );
- },
- setIsOpeningProject: (value) => {
- set((current) =>
- current.isOpeningProject === value
- ? current
- : { isOpeningProject: value },
- );
- },
- setPromptDraftPending: (key, isPending) => {
- if (key == null) {
- return;
- }
-
- set((current) => ({
- promptDraftsByKey: setPromptDraftEntryPending(
- current.promptDraftsByKey,
- key,
- isPending,
- ),
- }));
- },
- setPromptDraftPlanningMode: (key, isPlanningMode) => {
- if (key == null) {
- return;
- }
-
- set((current) => ({
- promptDraftsByKey: setPromptDraftEntryPlanningMode(
- current.promptDraftsByKey,
- key,
- isPlanningMode,
- ),
- }));
- },
- setPromptDraftUltraMode: (key, isUltraMode) => {
- if (key == null) {
- return;
- }
-
- set((current) => ({
- promptDraftsByKey: setPromptDraftEntryUltraMode(
- current.promptDraftsByKey,
- key,
- isUltraMode,
- ),
- }));
- },
- setPromptDraftValue: (key, value) => {
- if (key == null) {
- return;
- }
-
- set((current) => ({
- promptDraftsByKey: setPromptDraftEntryValue(
- current.promptDraftsByKey,
- key,
- value,
- ),
- }));
- },
- setWorkspacePromptSettings: (workspacePath, promptSettings) => {
- set((current) => ({
- workspaceMetaByKey: setWorkspaceMetaState(
- current,
- workspacePath,
- (currentMeta) => ({
- ...currentMeta,
- promptSettings,
- promptSettingsLoaded: true,
- }),
- ),
- }));
- },
- setWorkspaceRuntimeStatus: (workspacePath, runtimeStatus) => {
- set((current) => ({
- workspaceMetaByKey: setWorkspaceMetaState(
- current,
- workspacePath,
- (currentMeta) => ({
- ...currentMeta,
- runtimeStatus,
- runtimeStatusLoaded: true,
- }),
- ),
- }));
- },
- };
-}
+import {
+ defaultWorkspaceMetaState,
+ getConversationStoreKeyForBinding,
+ getWorkspaceMetaStoreKey,
+} from "./sessionStoreHelpers";
+import { createSessionStoreState } from "./sessionStoreState";
+import type { SessionStoreState } from "./types/sessionStore";
+
+export {
+ areChatBindingsEqual,
+ areSelectionsEqual,
+ getConversationStoreKey,
+ getConversationStoreKeyForBinding,
+ getSelectionFromSnapshot,
+ getWorkspaceMetaStoreKey,
+} from "./sessionStoreHelpers";
export const sessionStore = createStore<SessionStoreState>((set) =>
createSessionStoreState(set),
@@ -772,7 +149,9 @@ export function getUiActiveWorkspacePath(
): string | null {
switch (state.selection.kind) {
case "saved-workspace":
- return state.selection.activeChat?.workspacePath ?? state.activeWorkspacePath;
+ return (
+ state.selection.activeChat?.workspacePath ?? state.activeWorkspacePath
+ );
case "single-chat":
return state.selection.chat.workspacePath;
case "workspace-draft":
@@ -897,12 +276,14 @@ export async function ensureWorkspacePromptSettingsLoaded(
const request = (async () => {
try {
- const promptSettings = await desktopClient.getPromptSettings(workspacePath);
+ const promptSettings =
+ await desktopClient.getPromptSettings(workspacePath);
sessionStore
.getState()
.setWorkspacePromptSettings(workspacePath, promptSettings);
try {
- const runtimeStatus = await desktopClient.getRuntimeStatus(workspacePath);
+ const runtimeStatus =
+ await desktopClient.getRuntimeStatus(workspacePath);
sessionStore
.getState()
.setWorkspaceRuntimeStatus(workspacePath, runtimeStatus);
diff --git a/gui/src/app/sessionStoreHelpers.ts b/gui/src/app/sessionStoreHelpers.ts
new file mode 100644
index 00000000..670946b8
--- /dev/null
+++ b/gui/src/app/sessionStoreHelpers.ts
@@ -0,0 +1,332 @@
+import type {
+ ChatBinding,
+ ConversationSessionSummary,
+ ConversationViewSnapshot,
+ SessionSnapshot,
+ WorkspaceSession,
+} from "../services/desktop/types/contracts";
+import type { WorkspaceBoardSelection } from "./types/sessionContext";
+import type {
+ PromptDraftEntry,
+ SessionStoreState,
+ WorkspaceMetaState,
+} from "./types/sessionStore";
+
+const GLOBAL_WORKSPACE_META_KEY = "__global__";
+
+export function getConversationStoreKey(
+ workspacePath: string,
+ conversationId: string,
+): string {
+ return `${workspacePath}::${conversationId}`;
+}
+
+export function getConversationStoreKeyForBinding(binding: ChatBinding): string {
+ return getConversationStoreKey(binding.workspacePath, binding.conversationId);
+}
+
+export function getWorkspaceMetaStoreKey(workspacePath: string | null): string {
+ return workspacePath ?? GLOBAL_WORKSPACE_META_KEY;
+}
+
+export function areChatBindingsEqual(
+ left: ChatBinding | null,
+ right: ChatBinding | null,
+): boolean {
+ if (left === right) {
+ return true;
+ }
+
+ if (left == null || right == null) {
+ return false;
+ }
+
+ return (
+ left.workspacePath === right.workspacePath &&
+ left.conversationId === right.conversationId
+ );
+}
+
+function getConversationDraftEntry(
+ drafts: Record<string, PromptDraftEntry>,
+ key: string,
+): PromptDraftEntry | null {
+ return drafts[key] ?? null;
+}
+
+function writePromptDraftEntry(
+ drafts: Record<string, PromptDraftEntry>,
+ key: string,
+ entry: PromptDraftEntry | null,
+): Record<string, PromptDraftEntry> {
+ const current = drafts[key] ?? null;
+ const nextEntry =
+ entry == null ||
+ (entry.value === "" &&
+ !entry.isPending &&
+ !entry.isPlanningMode &&
+ !entry.isUltraMode)
+ ? null
+ : entry;
+
+ if (nextEntry == null) {
+ if (current == null) {
+ return drafts;
+ }
+
+ const nextDrafts = { ...drafts };
+ delete nextDrafts[key];
+ return nextDrafts;
+ }
+
+ if (
+ current?.value === nextEntry.value &&
+ current?.isPending === nextEntry.isPending &&
+ current?.isPlanningMode === nextEntry.isPlanningMode &&
+ current?.isUltraMode === nextEntry.isUltraMode
+ ) {
+ return drafts;
+ }
+
+ return {
+ ...drafts,
+ [key]: nextEntry,
+ };
+}
+
+export function setPromptDraftEntryValue(
+ drafts: Record<string, PromptDraftEntry>,
+ key: string,
+ value: string,
+): Record<string, PromptDraftEntry> {
+ const current = getConversationDraftEntry(drafts, key) ?? {
+ isPending: false,
+ isPlanningMode: false,
+ isUltraMode: false,
+ value: "",
+ };
+
+ return writePromptDraftEntry(drafts, key, { ...current, value });
+}
+
+export function setPromptDraftEntryPending(
+ drafts: Record<string, PromptDraftEntry>,
+ key: string,
+ isPending: boolean,
+): Record<string, PromptDraftEntry> {
+ const current = getConversationDraftEntry(drafts, key) ?? {
+ isPending: false,
+ isPlanningMode: false,
+ isUltraMode: false,
+ value: "",
+ };
+
+ return writePromptDraftEntry(drafts, key, { ...current, isPending });
+}
+
+export function setPromptDraftEntryPlanningMode(
+ drafts: Record<string, PromptDraftEntry>,
+ key: string,
+ isPlanningMode: boolean,
+): Record<string, PromptDraftEntry> {
+ const current = getConversationDraftEntry(drafts, key) ?? {
+ isPending: false,
+ isPlanningMode: false,
+ isUltraMode: false,
+ value: "",
+ };
+
+ return writePromptDraftEntry(drafts, key, { ...current, isPlanningMode });
+}
+
+export function setPromptDraftEntryUltraMode(
+ drafts: Record<string, PromptDraftEntry>,
+ key: string,
+ isUltraMode: boolean,
+): Record<string, PromptDraftEntry> {
+ const current = getConversationDraftEntry(drafts, key) ?? {
+ isPending: false,
+ isPlanningMode: false,
+ isUltraMode: false,
+ value: "",
+ };
+
+ return writePromptDraftEntry(drafts, key, { ...current, isUltraMode });
+}
+
+export function movePromptDraftEntry(
+ drafts: Record<string, PromptDraftEntry>,
+ fromKey: string | null,
+ toKey: string | null,
+): Record<string, PromptDraftEntry> {
+ if (fromKey == null || toKey == null || fromKey === toKey) {
+ return drafts;
+ }
+
+ const draft = getConversationDraftEntry(drafts, fromKey);
+ if (draft == null) {
+ return drafts;
+ }
+
+ const nextDrafts = {
+ ...writePromptDraftEntry(drafts, toKey, draft),
+ };
+ delete nextDrafts[fromKey];
+ return nextDrafts;
+}
+
+export function getSelectionFromSnapshot(
+ snapshot: SessionSnapshot,
+): WorkspaceBoardSelection {
+ if (
+ snapshot.activeWorkspacePath != null &&
+ snapshot.activeConversationId != null
+ ) {
+ return {
+ kind: "single-chat",
+ chat: {
+ workspacePath: snapshot.activeWorkspacePath,
+ conversationId: snapshot.activeConversationId,
+ },
+ };
+ }
+
+ if (snapshot.activeWorkspacePath != null) {
+ return {
+ kind: "workspace-draft",
+ workspacePath: snapshot.activeWorkspacePath,
+ };
+ }
+
+ return { kind: "empty" };
+}
+
+export function deriveConversationViews(snapshot: SessionSnapshot) {
+ if (snapshot.conversationViews.length > 0) {
+ return snapshot.conversationViews;
+ }
+
+ if (
+ snapshot.activeWorkspacePath != null &&
+ snapshot.activeConversationId != null
+ ) {
+ return [
+ {
+ activeRequestIds: snapshot.visibleActiveRequestIds,
+ conversationId: snapshot.activeConversationId,
+ followup: snapshot.visibleFollowup,
+ messages: snapshot.visibleMessages,
+ requestAgentIds: snapshot.visibleRequestAgentIds,
+ todos: snapshot.visibleTodos,
+ workspacePath: snapshot.activeWorkspacePath,
+ } satisfies ConversationViewSnapshot,
+ ];
+ }
+
+ return [];
+}
+
+export function buildWorkspacesByPath(workspaces: WorkspaceSession[]) {
+ const byPath: Record<string, WorkspaceSession> = {};
+ for (const workspace of workspaces) {
+ byPath[workspace.workspacePath] = workspace;
+ }
+ return byPath;
+}
+
+export function buildConversationSummariesByKey(
+ workspaces: WorkspaceSession[],
+) {
+ const byKey: Record<string, ConversationSessionSummary> = {};
+
+ for (const workspace of workspaces) {
+ for (const conversation of workspace.conversations) {
+ byKey[
+ getConversationStoreKey(
+ workspace.workspacePath,
+ conversation.conversationId,
+ )
+ ] = conversation;
+ }
+ }
+
+ return byKey;
+}
+
+export function areSelectionsEqual(
+ left: WorkspaceBoardSelection,
+ right: WorkspaceBoardSelection,
+): boolean {
+ if (left === right) {
+ return true;
+ }
+
+ if (left.kind !== right.kind) {
+ return false;
+ }
+
+ switch (left.kind) {
+ case "empty":
+ return true;
+ case "single-chat": {
+ const rightSelection = right as Extract<
+ WorkspaceBoardSelection,
+ { kind: "single-chat" }
+ >;
+ return areChatBindingsEqual(left.chat, rightSelection.chat);
+ }
+ case "workspace-draft": {
+ const rightSelection = right as Extract<
+ WorkspaceBoardSelection,
+ { kind: "workspace-draft" }
+ >;
+ return left.workspacePath === rightSelection.workspacePath;
+ }
+ case "saved-workspace": {
+ const rightSelection = right as Extract<
+ WorkspaceBoardSelection,
+ { kind: "saved-workspace" }
+ >;
+ return (
+ left.workspace.id === rightSelection.workspace.id &&
+ left.workspace.layoutJson === rightSelection.workspace.layoutJson &&
+ left.workspace.name === rightSelection.workspace.name &&
+ left.workspace.updatedAt === rightSelection.workspace.updatedAt &&
+ areChatBindingsEqual(left.activeChat, rightSelection.activeChat)
+ );
+ }
+ }
+}
+
+export const defaultWorkspaceMetaState: WorkspaceMetaState = {
+ promptSettings: null,
+ promptSettingsLoaded: false,
+ runtimeStatus: null,
+ runtimeStatusLoaded: false,
+};
+
+export function setWorkspaceMetaState(
+ currentState: SessionStoreState,
+ workspacePath: string | null,
+ updater: (currentMeta: WorkspaceMetaState) => WorkspaceMetaState,
+) {
+ const workspaceMetaKey = getWorkspaceMetaStoreKey(workspacePath);
+ const currentMeta =
+ currentState.workspaceMetaByKey[workspaceMetaKey] ??
+ defaultWorkspaceMetaState;
+ const nextMeta = updater(currentMeta);
+
+ if (
+ nextMeta.promptSettings === currentMeta.promptSettings &&
+ nextMeta.promptSettingsLoaded === currentMeta.promptSettingsLoaded &&
+ nextMeta.runtimeStatus === currentMeta.runtimeStatus &&
+ nextMeta.runtimeStatusLoaded === currentMeta.runtimeStatusLoaded
+ ) {
+ return currentState.workspaceMetaByKey;
+ }
+
+ return {
+ ...currentState.workspaceMetaByKey,
+ [workspaceMetaKey]: nextMeta,
+ };
+}
diff --git a/gui/src/app/sessionStoreState.ts b/gui/src/app/sessionStoreState.ts
new file mode 100644
index 00000000..f49179cf
--- /dev/null
+++ b/gui/src/app/sessionStoreState.ts
@@ -0,0 +1,336 @@
+import type {
+ SessionStoreSetter,
+ SessionStoreState,
+} from "./types/sessionStore";
+import {
+ areSelectionsEqual,
+ buildConversationSummariesByKey,
+ buildWorkspacesByPath,
+ deriveConversationViews,
+ getConversationStoreKey,
+ getSelectionFromSnapshot,
+ movePromptDraftEntry,
+ setPromptDraftEntryPending,
+ setPromptDraftEntryPlanningMode,
+ setPromptDraftEntryUltraMode,
+ setPromptDraftEntryValue,
+ setWorkspaceMetaState,
+} from "./sessionStoreHelpers";
+
+export function createSessionStoreState(
+ set: SessionStoreSetter,
+): SessionStoreState {
+ return {
+ activeConversationId: null,
+ activeWorkspacePath: null,
+ attachmentsByKey: {},
+ conversationSummariesByKey: {},
+ conversationViewsByKey: {},
+ isBootstrapped: false,
+ isOpeningProject: false,
+ promptDraftsByKey: {},
+ requestTimingsByConversationId: {},
+ savedWorkspaces: [],
+ selection: { kind: "empty" },
+ uiError: null,
+ workspaceMetaByKey: {},
+ workspaces: [],
+ workspacesByPath: {},
+ applySessionSnapshot: (snapshot) => {
+ const nextViews = deriveConversationViews(snapshot);
+ set((current) => {
+ const now = Date.now();
+ let nextRequestTimingsByConversationId =
+ current.requestTimingsByConversationId;
+
+ if (nextViews.length > 0) {
+ let didChangeTimings = false;
+ const nextTimingsState = {
+ ...current.requestTimingsByConversationId,
+ };
+
+ for (const view of nextViews) {
+ const currentConversationTimings =
+ current.requestTimingsByConversationId[view.conversationId] ?? {};
+ const nextConversationTimings = { ...currentConversationTimings };
+ const activeRequestIdSet = new Set(view.activeRequestIds ?? []);
+
+ for (const requestId of view.activeRequestIds ?? []) {
+ if (nextConversationTimings[requestId] == null) {
+ nextConversationTimings[requestId] = {
+ completedAtMs: null,
+ startedAtMs: now,
+ };
+ didChangeTimings = true;
+ }
+ }
+
+ for (const [requestId, timing] of Object.entries(
+ nextConversationTimings,
+ )) {
+ if (
+ timing.completedAtMs == null &&
+ !activeRequestIdSet.has(requestId)
+ ) {
+ nextConversationTimings[requestId] = {
+ ...timing,
+ completedAtMs: now,
+ };
+ didChangeTimings = true;
+ }
+ }
+
+ nextTimingsState[view.conversationId] = nextConversationTimings;
+ }
+
+ if (didChangeTimings) {
+ nextRequestTimingsByConversationId = nextTimingsState;
+ }
+ }
+
+ const nextConversationViewsByKey = { ...current.conversationViewsByKey };
+ for (const view of nextViews) {
+ nextConversationViewsByKey[
+ getConversationStoreKey(view.workspacePath, view.conversationId)
+ ] = view;
+ }
+
+ return {
+ activeConversationId: snapshot.activeConversationId,
+ activeWorkspacePath: snapshot.activeWorkspacePath,
+ conversationSummariesByKey: buildConversationSummariesByKey(
+ snapshot.workspaces,
+ ),
+ conversationViewsByKey: nextConversationViewsByKey,
+ requestTimingsByConversationId: nextRequestTimingsByConversationId,
+ savedWorkspaces: snapshot.savedWorkspaces,
+ selection: (() => {
+ if (current.selection.kind === "saved-workspace") {
+ const savedWorkspaceSelection = current.selection;
+ const matchingSavedWorkspace = snapshot.savedWorkspaces.find(
+ (workspace) =>
+ workspace.id === savedWorkspaceSelection.workspace.id,
+ );
+ return matchingSavedWorkspace == null
+ ? getSelectionFromSnapshot(snapshot)
+ : {
+ ...savedWorkspaceSelection,
+ workspace: {
+ ...savedWorkspaceSelection.workspace,
+ name: matchingSavedWorkspace.name,
+ updatedAt: matchingSavedWorkspace.updatedAt,
+ },
+ };
+ }
+
+ return getSelectionFromSnapshot(snapshot);
+ })(),
+ uiError: snapshot.uiError,
+ workspaces: snapshot.workspaces,
+ workspacesByPath: buildWorkspacesByPath(snapshot.workspaces),
+ };
+ });
+ },
+ addAttachments: (key, items) => {
+ if (key == null || items.length === 0) {
+ return;
+ }
+
+ set((current) => {
+ const existing = current.attachmentsByKey[key] ?? [];
+ const existingPaths = new Set(existing.map((item) => item.path));
+ const additions = items.filter((item) => !existingPaths.has(item.path));
+ if (additions.length === 0) {
+ return current;
+ }
+
+ return {
+ attachmentsByKey: {
+ ...current.attachmentsByKey,
+ [key]: [...existing, ...additions],
+ },
+ };
+ });
+ },
+ removeAttachment: (key, id) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => {
+ const existing = current.attachmentsByKey[key];
+ if (existing == null) {
+ return current;
+ }
+
+ const next = existing.filter((item) => item.id !== id);
+ const nextByKey = { ...current.attachmentsByKey };
+ if (next.length === 0) {
+ delete nextByKey[key];
+ } else {
+ nextByKey[key] = next;
+ }
+
+ return { attachmentsByKey: nextByKey };
+ });
+ },
+ clearAttachments: (key) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => {
+ if (current.attachmentsByKey[key] == null) {
+ return current;
+ }
+
+ const nextByKey = { ...current.attachmentsByKey };
+ delete nextByKey[key];
+ return { attachmentsByKey: nextByKey };
+ });
+ },
+ clearPromptDraft: (key) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => ({
+ promptDraftsByKey: setPromptDraftEntryValue(
+ current.promptDraftsByKey,
+ key,
+ "",
+ ),
+ }));
+ },
+ movePromptDraft: (fromKey, toKey) => {
+ set((current) => ({
+ promptDraftsByKey: movePromptDraftEntry(
+ current.promptDraftsByKey,
+ fromKey,
+ toKey,
+ ),
+ }));
+ },
+ moveAttachments: (fromKey, toKey) => {
+ if (fromKey == null || toKey == null || fromKey === toKey) {
+ return;
+ }
+
+ set((current) => {
+ const moving = current.attachmentsByKey[fromKey];
+ if (moving == null) {
+ return current;
+ }
+
+ const nextByKey = { ...current.attachmentsByKey };
+ delete nextByKey[fromKey];
+
+ const existing = nextByKey[toKey] ?? [];
+ const existingPaths = new Set(existing.map((item) => item.path));
+ nextByKey[toKey] = [
+ ...existing,
+ ...moving.filter((item) => !existingPaths.has(item.path)),
+ ];
+
+ return { attachmentsByKey: nextByKey };
+ });
+ },
+ setBoardSelection: (selection) => {
+ set((current) =>
+ areSelectionsEqual(current.selection, selection)
+ ? current
+ : { selection },
+ );
+ },
+ setIsBootstrapped: (value) => {
+ set((current) =>
+ current.isBootstrapped === value ? current : { isBootstrapped: value },
+ );
+ },
+ setIsOpeningProject: (value) => {
+ set((current) =>
+ current.isOpeningProject === value
+ ? current
+ : { isOpeningProject: value },
+ );
+ },
+ setPromptDraftPending: (key, isPending) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => ({
+ promptDraftsByKey: setPromptDraftEntryPending(
+ current.promptDraftsByKey,
+ key,
+ isPending,
+ ),
+ }));
+ },
+ setPromptDraftPlanningMode: (key, isPlanningMode) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => ({
+ promptDraftsByKey: setPromptDraftEntryPlanningMode(
+ current.promptDraftsByKey,
+ key,
+ isPlanningMode,
+ ),
+ }));
+ },
+ setPromptDraftUltraMode: (key, isUltraMode) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => ({
+ promptDraftsByKey: setPromptDraftEntryUltraMode(
+ current.promptDraftsByKey,
+ key,
+ isUltraMode,
+ ),
+ }));
+ },
+ setPromptDraftValue: (key, value) => {
+ if (key == null) {
+ return;
+ }
+
+ set((current) => ({
+ promptDraftsByKey: setPromptDraftEntryValue(
+ current.promptDraftsByKey,
+ key,
+ value,
+ ),
+ }));
+ },
+ setWorkspacePromptSettings: (workspacePath, promptSettings) => {
+ set((current) => ({
+ workspaceMetaByKey: setWorkspaceMetaState(
+ current,
+ workspacePath,
+ (currentMeta) => ({
+ ...currentMeta,
+ promptSettings,
+ promptSettingsLoaded: true,
+ }),
+ ),
+ }));
+ },
+ setWorkspaceRuntimeStatus: (workspacePath, runtimeStatus) => {
+ set((current) => ({
+ workspaceMetaByKey: setWorkspaceMetaState(
+ current,
+ workspacePath,
+ (currentMeta) => ({
+ ...currentMeta,
+ runtimeStatus,
+ runtimeStatusLoaded: true,
+ }),
+ ),
+ }));
+ },
+ };
+}
diff --git a/gui/src/components/chat/utils/chatThread.ts b/gui/src/components/chat/utils/chatThread.ts
index b9dd9e42..206d63a9 100644
--- a/gui/src/components/chat/utils/chatThread.ts
+++ b/gui/src/components/chat/utils/chatThread.ts
@@ -2,7 +2,6 @@ import type {
TranscriptMessage,
} from "@/services/desktop/types/contracts";
-import { TOOL_DEBUG_TITLES } from "../constants/chatThread";
import type {
ActivityGroupBuilder,
ActivityItem,
@@ -10,6 +9,18 @@ import type {
ChatThreadItem,
FlushActivityGroupOptions,
} from "../types/chatThread";
+import {
+ createFallbackOperation,
+ finalizeRequestActivities,
+ findMatchingOperation,
+ findOperationForStatusOutput,
+ findRequestWorkInsertionKey,
+ hasPendingReasoningGroup,
+ isDecorativeToolStatus,
+ mergeOutputText,
+ splitActivityOperationGroups,
+ summarizeActivityGroup,
+} from "./chatThreadActivity";
function shouldDisplayOperationInActivity(operation: ActivityOperation): boolean {
return (
@@ -393,213 +404,3 @@ export function buildChatThreadItems(
finalItems.push(...trailingWorkItems);
return finalItems;
}
-
-function isDecorativeToolStatus(
- message: Extract<TranscriptMessage, { kind: "status" }>,
-): boolean {
- return (
- message.category === "debug" &&
- (TOOL_DEBUG_TITLES.has(message.title) ||
- message.title.startsWith("Execute [") ||
- message.title.startsWith("Search for '"))
- );
-}
-
-function findOperationForOutput(
- operations: ActivityOperation[],
-): ActivityOperation | undefined {
- return [...operations]
- .reverse()
- .find((operation) => !operation.completed || operation.outputText == null);
-}
-
-function findOperationForStatusOutput(
- group: ActivityGroupBuilder | null,
- message: Extract<TranscriptMessage, { kind: "status_output" }>,
-): ActivityOperation | undefined {
- if (group == null || group.requestId !== message.requestId) {
- return undefined;
- }
-
- return findOperationForOutput(group.operations);
-}
-
-function findMatchingOperation(
- operations: ActivityOperation[],
- callId: string | null | undefined,
- name: string,
-): ActivityOperation | undefined {
- if (callId != null) {
- return operations.find((operation) => operation.callId === callId);
- }
-
- return [...operations]
- .reverse()
- .find((operation) => !operation.completed && operation.name === name);
-}
-
-function createFallbackOperation(
- message: Extract<TranscriptMessage, { kind: "tool_end" }>,
-): ActivityOperation {
- return {
- id: message.id,
- requestId: message.requestId,
- name: message.name,
- callId: message.callId,
- detail: { kind: "unknown", name: message.name },
- completed: false,
- isError: false,
- };
-}
-
-function hasPendingReasoningGroup(
- group: ActivityGroupBuilder | null,
- scopeId: string,
-): boolean {
- return (
- group != null &&
- group.scopeId === scopeId &&
- group.operations.length === 0 &&
- group.reasoningText.trim().length > 0
- );
-}
-
-function mergeOutputText(current: string | undefined, next: string): string {
- const trimmed = next.trim();
- if (trimmed.length === 0) {
- return current ?? "";
- }
-
- if (current == null || current.trim().length === 0) {
- return trimmed;
- }
-
- return `${current}\n\n${trimmed}`;
-}
-
-function finalizeRequestActivities(
- activities: ActivityItem[],
- isRunning: boolean,
-): ActivityItem[] {
- if (activities.length === 0) {
- return activities;
- }
-
- const lastRunningIndex = isRunning ? activities.length - 1 : -1;
- return activities.map((activity, index) => ({
- ...activity,
- key: `${activity.key}:${index}`,
- isRunning: index === lastRunningIndex,
- }));
-}
-
-function findRequestWorkInsertionKey(
- scopeId: string,
- scopeAnchorMessageKeyByScopeId: Map<string, string>,
-): string | null {
- return scopeAnchorMessageKeyByScopeId.get(scopeId) ?? null;
-}
-
-function splitActivityOperationGroups(
- operations: ActivityOperation[],
-): ActivityOperation[][] {
- const groups: ActivityOperation[][] = [];
-
- for (const operation of operations) {
- const previousGroup = groups.at(-1);
- if (
- previousGroup == null ||
- getOperationGroupKey(previousGroup[0]) !== getOperationGroupKey(operation)
- ) {
- groups.push([operation]);
- continue;
- }
-
- previousGroup.push(operation);
- }
-
- return groups;
-}
-
-function getOperationGroupKey(operation: ActivityOperation): string {
- switch (operation.detail.kind) {
- case "file_read":
- return "file_read";
- case "file_update":
- return "file_update";
- case "shell":
- return "shell";
- case "search":
- case "codebase_search":
- return "search";
- case "fetch":
- return "fetch";
- case "todo_read":
- return "todo_read";
- case "todo_write":
- return "todo_write";
- default:
- return operation.detail.kind;
- }
-}
-
-function summarizeActivityGroup(operations: ActivityOperation[]): string {
- let fileReads = 0;
- let fileUpdates = 0;
- let commands = 0;
- let searches = 0;
- let fetches = 0;
- let subagents = 0;
- let others = 0;
-
- for (const operation of operations) {
- switch (operation.detail.kind) {
- case "file_read":
- fileReads += 1;
- break;
- case "file_update":
- fileUpdates += 1;
- break;
- case "shell":
- commands += 1;
- break;
- case "search":
- case "codebase_search":
- searches += 1;
- break;
- case "fetch":
- fetches += 1;
- break;
- case "task":
- subagents += 1;
- break;
- default:
- others += 1;
- break;
- }
- }
-
- if (subagents > 0) {
- return `${subagents} subagent${subagents === 1 ? "" : "s"}`;
- }
- if (fileReads > 0) {
- return `Explored ${fileReads} file${fileReads === 1 ? "" : "s"}`;
- }
- if (commands > 0) {
- return `Ran ${commands} command${commands === 1 ? "" : "s"}`;
- }
- if (fileUpdates > 0) {
- return `Updated ${fileUpdates} file${fileUpdates === 1 ? "" : "s"}`;
- }
- if (searches > 0) {
- return `Ran ${searches} search${searches === 1 ? "" : "es"}`;
- }
- if (fetches > 0) {
- return `Fetched ${fetches} URL${fetches === 1 ? "" : "s"}`;
- }
- if (others > 0) {
- return `Used ${others} tool${others === 1 ? "" : "s"}`;
- }
-
- return "Activity";
-}
diff --git a/gui/src/components/chat/utils/chatThreadActivity.ts b/gui/src/components/chat/utils/chatThreadActivity.ts
new file mode 100644
index 00000000..5a3d5db3
--- /dev/null
+++ b/gui/src/components/chat/utils/chatThreadActivity.ts
@@ -0,0 +1,223 @@
+import type { TranscriptMessage } from "@/services/desktop/types/contracts";
+
+import { TOOL_DEBUG_TITLES } from "../constants/chatThread";
+import type {
+ ActivityGroupBuilder,
+ ActivityItem,
+ ActivityOperation,
+} from "../types/chatThread";
+
+export function isDecorativeToolStatus(
+ message: Extract<TranscriptMessage, { kind: "status" }>,
+): boolean {
+ return (
+ message.category === "debug" &&
+ (TOOL_DEBUG_TITLES.has(message.title) ||
+ message.title.startsWith("Execute [") ||
+ message.title.startsWith("Search for '"))
+ );
+}
+
+function findOperationForOutput(
+ operations: ActivityOperation[],
+): ActivityOperation | undefined {
+ return [...operations]
+ .reverse()
+ .find((operation) => !operation.completed || operation.outputText == null);
+}
+
+export function findOperationForStatusOutput(
+ group: ActivityGroupBuilder | null,
+ message: Extract<TranscriptMessage, { kind: "status_output" }>,
+): ActivityOperation | undefined {
+ if (group == null || group.requestId !== message.requestId) {
+ return undefined;
+ }
+
+ return findOperationForOutput(group.operations);
+}
+
+export function findMatchingOperation(
+ operations: ActivityOperation[],
+ callId: string | null | undefined,
+ name: string,
+): ActivityOperation | undefined {
+ if (callId != null) {
+ return operations.find((operation) => operation.callId === callId);
+ }
+
+ return [...operations]
+ .reverse()
+ .find((operation) => !operation.completed && operation.name === name);
+}
+
+export function createFallbackOperation(
+ message: Extract<TranscriptMessage, { kind: "tool_end" }>,
+): ActivityOperation {
+ return {
+ id: message.id,
+ requestId: message.requestId,
+ name: message.name,
+ callId: message.callId,
+ detail: { kind: "unknown", name: message.name },
+ completed: false,
+ isError: false,
+ };
+}
+
+export function hasPendingReasoningGroup(
+ group: ActivityGroupBuilder | null,
+ scopeId: string,
+): boolean {
+ return (
+ group != null &&
+ group.scopeId === scopeId &&
+ group.operations.length === 0 &&
+ group.reasoningText.trim().length > 0
+ );
+}
+
+export function mergeOutputText(
+ current: string | undefined,
+ next: string,
+): string {
+ const trimmed = next.trim();
+ if (trimmed.length === 0) {
+ return current ?? "";
+ }
+
+ if (current == null || current.trim().length === 0) {
+ return trimmed;
+ }
+
+ return `${current}\n\n${trimmed}`;
+}
+
+export function finalizeRequestActivities(
+ activities: ActivityItem[],
+ isRunning: boolean,
+): ActivityItem[] {
+ if (activities.length === 0) {
+ return activities;
+ }
+
+ const lastRunningIndex = isRunning ? activities.length - 1 : -1;
+ return activities.map((activity, index) => ({
+ ...activity,
+ key: `${activity.key}:${index}`,
+ isRunning: index === lastRunningIndex,
+ }));
+}
+
+export function findRequestWorkInsertionKey(
+ scopeId: string,
+ scopeAnchorMessageKeyByScopeId: Map<string, string>,
+): string | null {
+ return scopeAnchorMessageKeyByScopeId.get(scopeId) ?? null;
+}
+
+export function splitActivityOperationGroups(
+ operations: ActivityOperation[],
+): ActivityOperation[][] {
+ const groups: ActivityOperation[][] = [];
+
+ for (const operation of operations) {
+ const previousGroup = groups.at(-1);
+ if (
+ previousGroup == null ||
+ getOperationGroupKey(previousGroup[0]) !== getOperationGroupKey(operation)
+ ) {
+ groups.push([operation]);
+ continue;
+ }
+
+ previousGroup.push(operation);
+ }
+
+ return groups;
+}
+
+function getOperationGroupKey(operation: ActivityOperation): string {
+ switch (operation.detail.kind) {
+ case "file_read":
+ return "file_read";
+ case "file_update":
+ return "file_update";
+ case "shell":
+ return "shell";
+ case "search":
+ case "codebase_search":
+ return "search";
+ case "fetch":
+ return "fetch";
+ case "todo_read":
+ return "todo_read";
+ case "todo_write":
+ return "todo_write";
+ default:
+ return operation.detail.kind;
+ }
+}
+
+export function summarizeActivityGroup(
+ operations: ActivityOperation[],
+): string {
+ let fileReads = 0;
+ let fileUpdates = 0;
+ let commands = 0;
+ let searches = 0;
+ let fetches = 0;
+ let subagents = 0;
+ let others = 0;
+
+ for (const operation of operations) {
+ switch (operation.detail.kind) {
+ case "file_read":
+ fileReads += 1;
+ break;
+ case "file_update":
+ fileUpdates += 1;
+ break;
+ case "shell":
+ commands += 1;
+ break;
+ case "search":
+ case "codebase_search":
+ searches += 1;
+ break;
+ case "fetch":
+ fetches += 1;
+ break;
+ case "task":
+ subagents += 1;
+ break;
+ default:
+ others += 1;
+ break;
+ }
+ }
+
+ if (subagents > 0) {
+ return `${subagents} subagent${subagents === 1 ? "" : "s"}`;
+ }
+ if (fileReads > 0) {
+ return `Explored ${fileReads} file${fileReads === 1 ? "" : "s"}`;
+ }
+ if (commands > 0) {
+ return `Ran ${commands} command${commands === 1 ? "" : "s"}`;
+ }
+ if (fileUpdates > 0) {
+ return `Updated ${fileUpdates} file${fileUpdates === 1 ? "" : "s"}`;
+ }
+ if (searches > 0) {
+ return `Ran ${searches} search${searches === 1 ? "" : "es"}`;
+ }
+ if (fetches > 0) {
+ return `Fetched ${fetches} URL${fetches === 1 ? "" : "s"}`;
+ }
+ if (others > 0) {
+ return `Used ${others} tool${others === 1 ? "" : "s"}`;
+ }
+
+ return "Activity";
+}
diff --git a/gui/src/services/desktop/client.ts b/gui/src/services/desktop/client.ts
index 7ef05482..91ad0456 100644
--- a/gui/src/services/desktop/client.ts
+++ b/gui/src/services/desktop/client.ts
@@ -8,6 +8,7 @@ import {
TERMINAL_OUTPUT_EVENT_NAME,
PROVIDER_OAUTH_CALLBACK_EVENT_NAME,
} from "./constants/events";
+import { isQaMockMode, mockInvokeCommand } from "./clientQaMock";
import type {
AgentsPayload,
HandoffChatInput,
@@ -53,261 +54,6 @@ import type {
WorkspaceSyncPayload,
} from "./types/contracts";
-const QA_WORKSPACE_PATH = "/Users/pranavp/projects/harness/codegraff/gui";
-const QA_CONVERSATION_ID = "qa-existing-chat";
-// Browser-based visual QA cannot call Tauri commands, so this flag swaps the
-// desktop boundary for deterministic fixtures while leaving production calls untouched.
-const isQaMockMode = import.meta.env.VITE_CODEGRAFF_QA_MOCK === "1";
-
-let qaActiveAgentId = "forge";
-let qaReasoningEffort: string | null = "medium";
-
-const qaCommandRows: Array<[
- string,
- string,
- string | null,
- CommandDescriptor["resultKind"],
-]> = [
- ["help", "Show available slash commands.", null, "text"],
- ["agent", "Show active agent and available agents.", null, "agents"],
- ["bash", "Run a shell command in the workspace.", "<command>", "text"],
- ["sage", "Switch to Sage.", null, "agents"],
- ["reasoning-effort", "Update reasoning effort.", "<low|medium|high>", "text"],
- ["goal", "Set/show the current objective.", "<objective|clear>", "text"],
- ["loop", "Run an autonomous plan→act→verify pass.", "<prompt>", "snapshot"],
- ["workspace-info", "Show indexed workspace metadata.", null, "workspaceInfo"],
- ["workspace-status", "Show workspace file status.", null, "workspaceStatus"],
- ["workspace-query", "Search the workspace semantically.", "<query>", "workspaceSearch"],
- ["mcp", "Show MCP server status.", "list", "mcp"],
- ["workflow", "Draft a reviewable workflow.", "<goal>", "workflowDraft"],
-];
-
-const qaCommands: CommandDescriptor[] = qaCommandRows.map(
- ([name, usage, argumentHint, resultKind]) =>
- ({
- aliases:
- name === "workspace-query"
- ? ["workspace-search"]
- : name === "sage"
- ? ["plan"]
- : [],
- argumentHint,
- executionKind: resultKind === "workflowDraft" ? "modal" : "runnable",
- isAgentSwitch: name === "sage",
- kind:
- resultKind === "workflowDraft"
- ? "workflow"
- : name === "sage"
- ? "agent"
- : "builtin",
- name,
- requiresConversation: false,
- requiresWorkspace: name === "bash" || name.startsWith("workspace-"),
- resultKind,
- usage,
- value: name === "sage" ? "sage" : null,
- }) as CommandDescriptor,
-);
-
-function createQaSnapshot(
- activeConversationId: string | null = null,
- messages: SessionSnapshot["visibleMessages"] = [],
-): SessionSnapshot {
- const existingMessages: SessionSnapshot["visibleMessages"] = [
- {
- id: "qa-user-1",
- kind: "user",
- requestId: "qa-request-1",
- text: "Can you explain how slash command routing works?",
- },
- {
- id: "qa-assistant-1",
- kind: "assistant",
- requestId: "qa-request-1",
- text: "Slash commands are detected in the composer and rendered inline when they return informational output.",
- },
- ];
-
- return {
- activeConversationId,
- activeWorkspacePath: QA_WORKSPACE_PATH,
- conversationViews: [
- {
- activeRequestIds: [],
- conversationId: activeConversationId ?? QA_CONVERSATION_ID,
- followup: null,
- messages: activeConversationId == null ? existingMessages : messages,
- requestAgentIds: {},
- todos: [],
- workspacePath: QA_WORKSPACE_PATH,
- },
- ],
- savedWorkspaces: [],
- uiError: null,
- visibleActiveRequestIds: [],
- visibleFollowup: null,
- visibleMessages: messages,
- visibleRequestAgentIds: {},
- visibleTodos: [],
- workspaces: [
- {
- configurationError: null,
- configured: true,
- conversations: [
- {
- conversationId: QA_CONVERSATION_ID,
- hasPendingFollowup: false,
- isDraft: false,
- isRunning: false,
- title: "Existing QA chat",
- updatedAt: "2026-06-03T00:00:00Z",
- },
- ],
- kind: "project",
- selectedConversationId: activeConversationId,
- workspaceName: "Codegraff GUI",
- workspacePath: QA_WORKSPACE_PATH,
- },
- ],
- };
-}
-
-function qaPromptSettings(): PromptSettings {
- return {
- availableModels: [
- {
- contextLength: 200000n,
- modelId: "claude-sonnet-4",
- modelName: "Claude Sonnet 4",
- providerId: "anthropic",
- providerName: "Anthropic",
- reasoningEfforts: ["low", "medium", "high"],
- supportsReasoning: true,
- },
- ],
- selectedModelId: "claude-sonnet-4",
- selectedProviderId: "anthropic",
- selectedReasoningEffort: qaReasoningEffort,
- fastEnabled: false,
- fastApplies: false,
- };
-}
-
-function qaRuntimeStatus(): RuntimeStatus {
- return {
- availableOpenTargets: ["vscode", "terminal"],
- configurationError: null,
- configured: true,
- gitBranchName: "qa/mock-browser",
- gitBranches: ["main", "qa/mock-browser"],
- gitMainWorkspacePath: QA_WORKSPACE_PATH,
- gitRepoName: "codegraff",
- gitWorkspaceKind: "local",
- workspaceName: "Codegraff GUI",
- workspacePath: QA_WORKSPACE_PATH,
- };
-}
-
-function qaAgentsPayload(): AgentsPayload {
- return {
- activeAgentId: qaActiveAgentId,
- agents: [
- { description: "Implementation assistant for focused coding tasks.", id: "forge", isActive: qaActiveAgentId === "forge", modelId: "claude-sonnet-4", title: "Forge" },
- { description: "Research assistant for deeper analysis.", id: "sage", isActive: qaActiveAgentId === "sage", modelId: "claude-sonnet-4", title: "Sage" },
- ],
- selectedModelId: "claude-sonnet-4",
- selectedProviderId: "anthropic",
- selectedReasoningEffort: qaReasoningEffort,
- };
-}
-
-function qaCommandResult(input: {
- name: string;
- args: string[];
- workspacePath?: string | null;
- conversationId?: string | null;
-}): CommandRunResult {
- const title = `/${input.name}${input.args.length > 0 ? ` ${input.args.join(" ")}` : ""}`;
-
- switch (input.name) {
- case "help":
- return { body: "| Command | What it does | UI expectation |\n|---|---|---|\n| `/help` | Lists commands | Inline table |\n| `/agent` | Shows current agent | Inline cards |\n| `/bash <command>` | Runs a workspace shell command | Inline text |\n| `/workspace-info` | Shows metadata | Inline markdown/table |\n| `/workflow <goal>` | Builds a workflow draft | Review modal |", payload: null, resultKind: "text", savedPath: null, snapshot: null, title: "/help" };
- case "agent":
- return { body: "Current agent status.", payload: { kind: "agents", ...qaAgentsPayload() }, resultKind: "agents", savedPath: null, snapshot: null, title };
- case "bash": {
- const command = input.args.join(" ").trim();
- return { body: command.length > 0 ? `QA mock did not execute shell command:\n\n$ ${command}` : "usage: /bash <command>", payload: null, resultKind: "text", savedPath: null, snapshot: null, title: command.length > 0 ? `/bash ${command}` : "/bash" };
- }
- case "sage":
- qaActiveAgentId = "sage";
- return { body: "Switched active agent to Sage.", payload: { kind: "agents", ...qaAgentsPayload() }, resultKind: "agents", savedPath: null, snapshot: null, title };
- case "reasoning-effort":
- qaReasoningEffort = input.args[0] ?? qaReasoningEffort;
- return { body: `Reasoning effort is now **${qaReasoningEffort ?? "default"}**.`, payload: null, resultKind: "text", savedPath: null, snapshot: null, title };
- case "goal":
- return { body: input.args.length > 0 ? `Goal set: **${input.args.join(" ")}**.` : "No active goal. Set one with `/goal <objective>`.", payload: null, resultKind: "text", savedPath: null, snapshot: null, title };
- case "loop":
- return { body: "Started an autonomous plan→act→verify pass.", payload: null, resultKind: "snapshot", savedPath: null, snapshot: createQaSnapshot(input.conversationId ?? QA_CONVERSATION_ID, [{ id: "qa-loop-user", kind: "user", requestId: "qa-loop-request", text: `/loop ${input.args.join(" ")}` }, { id: "qa-loop-assistant", kind: "assistant", requestId: "qa-loop-request", text: "Loop pass complete: planned, acted, and verified the requested change." }]), title };
- case "workspace-info":
- return { body: "| Field | Value |\n|---|---|\n| Workspace | Codegraff GUI |\n| Branch | qa/mock-browser |\n| Indexed nodes | 1,284 |", payload: { createdAt: "2026-06-03T00:00:00Z", kind: "workspaceInfo", lastUpdated: "2026-06-03T12:00:00Z", nodeCount: 1284n, relationCount: 642n, workingDir: QA_WORKSPACE_PATH, workspaceId: "qa-codegraff-gui", workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceInfo", savedPath: null, snapshot: null, title };
- case "workspace-status":
- return { body: "Workspace has 2 modified files and no conflicts.", payload: { files: [{ path: "src/hooks/useCommandRouter.ts", status: "modified" }, { path: "src/components/chat/ChatCommandResultRow.tsx", status: "modified" }, { path: "src/components/PromptInputCard.tsx", status: "clean" }], kind: "workspaceStatus", workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceStatus", savedPath: null, snapshot: null, title };
- case "workspace-query":
- return { body: `Found 2 results for **${input.args.join(" ") || "command routing"}**.`, payload: { kind: "workspaceSearch", query: input.args.join(" "), results: [{ distance: 0.12, endLine: 99, kind: "function", nodeId: "router", path: "src/hooks/useCommandRouter.ts", preview: "publishCommandResult sends command output into the chat thread.", relevance: 0.91, startLine: 70 }, { distance: 0.18, endLine: 35, kind: "component", nodeId: "result-row", path: "src/components/chat/ChatCommandResultRow.tsx", preview: "ChatCommandResultRow renders markdown and structured payload cards.", relevance: 0.84, startLine: 16 }], workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceSearch", savedPath: null, snapshot: null, title };
- case "mcp":
- return { body: "No MCP servers are configured in this QA workspace.", payload: { kind: "mcp", servers: [] }, resultKind: "mcp", savedPath: null, snapshot: null, title };
- case "workflow":
- return { body: "Review the generated workflow before approving.", payload: { approvedPrompt: `Execute workflow: ${input.args.join(" ")}`, exportText: "goal: test a small change\nnodes:\n - inspect\n - verify", goal: input.args.join(" ") || "test a small change", kind: "workflowDraft", nodes: [{ access: [], artifact: "findings", dependencies: [], name: "inspect", stopCondition: "UI issues identified", task: "Inspect the slash command UI.", worker: "sage" }, { access: ["inspect"], artifact: "fixes", dependencies: ["inspect"], name: "verify", stopCondition: "QA pass complete", task: "Verify fixes in the browser.", worker: "forge" }], summary: "Two-step QA workflow for slash command behavior.", trace: ["Created QA workflow draft"] }, resultKind: "workflowDraft", savedPath: null, snapshot: null, title };
- default:
- return { body: `Unknown command: /${input.name}`, payload: null, resultKind: "text", savedPath: null, snapshot: null, title: "Command failed" };
- }
-}
-
-function mockInvokeCommand<T>(
- command: string,
- args?: Record<string, unknown>,
-): Promise<T> {
- // Keep the mock at the invoke boundary so the rest of the app exercises the
- // same service functions, stores, and component flows used by the desktop app.
- switch (command) {
- case "get_session_snapshot":
- case "create_managed_chat":
- case "start_new_chat":
- return Promise.resolve(createQaSnapshot() as T);
- case "select_conversation":
- case "ensure_conversation_view":
- return Promise.resolve(createQaSnapshot(QA_CONVERSATION_ID, createQaSnapshot().conversationViews[0]?.messages ?? []) as T);
- case "get_runtime_status":
- return Promise.resolve(qaRuntimeStatus() as T);
- case "get_prompt_settings":
- return Promise.resolve(qaPromptSettings() as T);
- case "update_prompt_settings":
- qaReasoningEffort = (args?.input as UpdatePromptSettingsInput | undefined)?.reasoningEffort ?? qaReasoningEffort;
- return Promise.resolve(qaPromptSettings() as T);
- case "list_commands":
- return Promise.resolve(qaCommands as T);
- case "run_slash_command":
- return Promise.resolve(qaCommandResult(args as Parameters<typeof qaCommandResult>[0]) as T);
- case "send_prompt": {
- const input = args?.input as SendPromptInput;
- const conversationId = input.conversationId ?? "qa-new-chat";
- return Promise.resolve(createQaSnapshot(conversationId, [
- { id: `${conversationId}-user`, kind: "user", requestId: `${conversationId}-request`, text: input.prompt },
- { id: `${conversationId}-assistant`, kind: "assistant", requestId: `${conversationId}-request`, text: "QA mock response with a bullet list:\n\n- Markdown bullets align correctly.\n- `inline code` stays readable.\n\n```ts\nconst theme = 'clean-modern';\n```\n\n[Codegraff](https://github.com/justrach/codegraff)" },
- ]) as T);
- }
- case "read_workspace_file":
- return Promise.resolve("// QA mock file contents\nexport const value = 1;\n" as T);
- case "list_mcp_servers":
- return Promise.resolve({ servers: [] } as T);
- case "pick_workspace":
- case "pick_directory":
- return Promise.resolve(QA_WORKSPACE_PATH as T);
- default:
- return Promise.resolve(undefined as T);
- }
-}
-
function invokeCommand<T>(
command: string,
args?: Record<string, unknown>,
diff --git a/gui/src/services/desktop/clientQaMock.ts b/gui/src/services/desktop/clientQaMock.ts
new file mode 100644
index 00000000..04049542
--- /dev/null
+++ b/gui/src/services/desktop/clientQaMock.ts
@@ -0,0 +1,263 @@
+import type {
+ AgentsPayload,
+ CommandDescriptor,
+ CommandRunResult,
+ PromptSettings,
+ RuntimeStatus,
+ SendPromptInput,
+ SessionSnapshot,
+ UpdatePromptSettingsInput,
+} from "./types/contracts";
+
+const QA_WORKSPACE_PATH = "/Users/pranavp/projects/harness/codegraff/gui";
+const QA_CONVERSATION_ID = "qa-existing-chat";
+
+export const isQaMockMode =
+ import.meta.env.VITE_CODEGRAFF_QA_MOCK === "1";
+
+let qaActiveAgentId = "forge";
+let qaReasoningEffort: string | null = "medium";
+
+const qaCommandRows: Array<[
+ string,
+ string,
+ string | null,
+ CommandDescriptor["resultKind"],
+]> = [
+ ["help", "Show available slash commands.", null, "text"],
+ ["agent", "Show active agent and available agents.", null, "agents"],
+ ["bash", "Run a shell command in the workspace.", "<command>", "text"],
+ ["sage", "Switch to Sage.", null, "agents"],
+ ["reasoning-effort", "Update reasoning effort.", "<low|medium|high>", "text"],
+ ["goal", "Set/show the current objective.", "<objective|clear>", "text"],
+ ["loop", "Run an autonomous plan→act→verify pass.", "<prompt>", "snapshot"],
+ ["workspace-info", "Show indexed workspace metadata.", null, "workspaceInfo"],
+ ["workspace-status", "Show workspace file status.", null, "workspaceStatus"],
+ ["workspace-query", "Search the workspace semantically.", "<query>", "workspaceSearch"],
+ ["mcp", "Show MCP server status.", "list", "mcp"],
+ ["workflow", "Draft a reviewable workflow.", "<goal>", "workflowDraft"],
+];
+
+const qaCommands: CommandDescriptor[] = qaCommandRows.map(
+ ([name, usage, argumentHint, resultKind]) =>
+ ({
+ aliases:
+ name === "workspace-query"
+ ? ["workspace-search"]
+ : name === "sage"
+ ? ["plan"]
+ : [],
+ argumentHint,
+ executionKind: resultKind === "workflowDraft" ? "modal" : "runnable",
+ isAgentSwitch: name === "sage",
+ kind:
+ resultKind === "workflowDraft"
+ ? "workflow"
+ : name === "sage"
+ ? "agent"
+ : "builtin",
+ name,
+ requiresConversation: false,
+ requiresWorkspace: name === "bash" || name.startsWith("workspace-"),
+ resultKind,
+ usage,
+ value: name === "sage" ? "sage" : null,
+ }) as CommandDescriptor,
+);
+
+function createQaSnapshot(
+ activeConversationId: string | null = null,
+ messages: SessionSnapshot["visibleMessages"] = [],
+): SessionSnapshot {
+ const existingMessages: SessionSnapshot["visibleMessages"] = [
+ {
+ id: "qa-user-1",
+ kind: "user",
+ requestId: "qa-request-1",
+ text: "Can you explain how slash command routing works?",
+ },
+ {
+ id: "qa-assistant-1",
+ kind: "assistant",
+ requestId: "qa-request-1",
+ text: "Slash commands are detected in the composer and rendered inline when they return informational output.",
+ },
+ ];
+
+ return {
+ activeConversationId,
+ activeWorkspacePath: QA_WORKSPACE_PATH,
+ conversationViews: [
+ {
+ activeRequestIds: [],
+ conversationId: activeConversationId ?? QA_CONVERSATION_ID,
+ followup: null,
+ messages: activeConversationId == null ? existingMessages : messages,
+ requestAgentIds: {},
+ todos: [],
+ workspacePath: QA_WORKSPACE_PATH,
+ },
+ ],
+ savedWorkspaces: [],
+ uiError: null,
+ visibleActiveRequestIds: [],
+ visibleFollowup: null,
+ visibleMessages: messages,
+ visibleRequestAgentIds: {},
+ visibleTodos: [],
+ workspaces: [
+ {
+ configurationError: null,
+ configured: true,
+ conversations: [
+ {
+ conversationId: QA_CONVERSATION_ID,
+ hasPendingFollowup: false,
+ isDraft: false,
+ isRunning: false,
+ title: "Existing QA chat",
+ updatedAt: "2026-06-03T00:00:00Z",
+ },
+ ],
+ kind: "project",
+ selectedConversationId: activeConversationId,
+ workspaceName: "Codegraff GUI",
+ workspacePath: QA_WORKSPACE_PATH,
+ },
+ ],
+ };
+}
+
+function qaPromptSettings(): PromptSettings {
+ return {
+ availableModels: [
+ {
+ contextLength: 200000n,
+ modelId: "claude-sonnet-4",
+ modelName: "Claude Sonnet 4",
+ providerId: "anthropic",
+ providerName: "Anthropic",
+ reasoningEfforts: ["low", "medium", "high"],
+ supportsReasoning: true,
+ },
+ ],
+ selectedModelId: "claude-sonnet-4",
+ selectedProviderId: "anthropic",
+ selectedReasoningEffort: qaReasoningEffort,
+ fastEnabled: false,
+ fastApplies: false,
+ };
+}
+
+function qaRuntimeStatus(): RuntimeStatus {
+ return {
+ availableOpenTargets: ["vscode", "terminal"],
+ configurationError: null,
+ configured: true,
+ gitBranchName: "qa/mock-browser",
+ gitBranches: ["main", "qa/mock-browser"],
+ gitMainWorkspacePath: QA_WORKSPACE_PATH,
+ gitRepoName: "codegraff",
+ gitWorkspaceKind: "local",
+ workspaceName: "Codegraff GUI",
+ workspacePath: QA_WORKSPACE_PATH,
+ };
+}
+
+function qaAgentsPayload(): AgentsPayload {
+ return {
+ activeAgentId: qaActiveAgentId,
+ agents: [
+ { description: "Implementation assistant for focused coding tasks.", id: "forge", isActive: qaActiveAgentId === "forge", modelId: "claude-sonnet-4", title: "Forge" },
+ { description: "Research assistant for deeper analysis.", id: "sage", isActive: qaActiveAgentId === "sage", modelId: "claude-sonnet-4", title: "Sage" },
+ ],
+ selectedModelId: "claude-sonnet-4",
+ selectedProviderId: "anthropic",
+ selectedReasoningEffort: qaReasoningEffort,
+ };
+}
+
+function qaCommandResult(input: {
+ name: string;
+ args: string[];
+ workspacePath?: string | null;
+ conversationId?: string | null;
+}): CommandRunResult {
+ const title = `/${input.name}${input.args.length > 0 ? ` ${input.args.join(" ")}` : ""}`;
+
+ switch (input.name) {
+ case "help":
+ return { body: "| Command | What it does | UI expectation |\n|---|---|---|\n| `/help` | Lists commands | Inline table |\n| `/agent` | Shows current agent | Inline cards |\n| `/bash <command>` | Runs a workspace shell command | Inline text |\n| `/workspace-info` | Shows metadata | Inline markdown/table |\n| `/workflow <goal>` | Builds a workflow draft | Review modal |", payload: null, resultKind: "text", savedPath: null, snapshot: null, title: "/help" };
+ case "agent":
+ return { body: "Current agent status.", payload: { kind: "agents", ...qaAgentsPayload() }, resultKind: "agents", savedPath: null, snapshot: null, title };
+ case "bash": {
+ const command = input.args.join(" ").trim();
+ return { body: command.length > 0 ? `QA mock did not execute shell command:\n\n$ ${command}` : "usage: /bash <command>", payload: null, resultKind: "text", savedPath: null, snapshot: null, title: command.length > 0 ? `/bash ${command}` : "/bash" };
+ }
+ case "sage":
+ qaActiveAgentId = "sage";
+ return { body: "Switched active agent to Sage.", payload: { kind: "agents", ...qaAgentsPayload() }, resultKind: "agents", savedPath: null, snapshot: null, title };
+ case "reasoning-effort":
+ qaReasoningEffort = input.args[0] ?? qaReasoningEffort;
+ return { body: `Reasoning effort is now **${qaReasoningEffort ?? "default"}**.`, payload: null, resultKind: "text", savedPath: null, snapshot: null, title };
+ case "goal":
+ return { body: input.args.length > 0 ? `Goal set: **${input.args.join(" ")}**.` : "No active goal. Set one with `/goal <objective>`.", payload: null, resultKind: "text", savedPath: null, snapshot: null, title };
+ case "loop":
+ return { body: "Started an autonomous plan→act→verify pass.", payload: null, resultKind: "snapshot", savedPath: null, snapshot: createQaSnapshot(input.conversationId ?? QA_CONVERSATION_ID, [{ id: "qa-loop-user", kind: "user", requestId: "qa-loop-request", text: `/loop ${input.args.join(" ")}` }, { id: "qa-loop-assistant", kind: "assistant", requestId: "qa-loop-request", text: "Loop pass complete: planned, acted, and verified the requested change." }]), title };
+ case "workspace-info":
+ return { body: "| Field | Value |\n|---|---|\n| Workspace | Codegraff GUI |\n| Branch | qa/mock-browser |\n| Indexed nodes | 1,284 |", payload: { createdAt: "2026-06-03T00:00:00Z", kind: "workspaceInfo", lastUpdated: "2026-06-03T12:00:00Z", nodeCount: 1284n, relationCount: 642n, workingDir: QA_WORKSPACE_PATH, workspaceId: "qa-codegraff-gui", workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceInfo", savedPath: null, snapshot: null, title };
+ case "workspace-status":
+ return { body: "Workspace has 2 modified files and no conflicts.", payload: { files: [{ path: "src/hooks/useCommandRouter.ts", status: "modified" }, { path: "src/components/chat/ChatCommandResultRow.tsx", status: "modified" }, { path: "src/components/PromptInputCard.tsx", status: "clean" }], kind: "workspaceStatus", workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceStatus", savedPath: null, snapshot: null, title };
+ case "workspace-query":
+ return { body: `Found 2 results for **${input.args.join(" ") || "command routing"}**.`, payload: { kind: "workspaceSearch", query: input.args.join(" "), results: [{ distance: 0.12, endLine: 99, kind: "function", nodeId: "router", path: "src/hooks/useCommandRouter.ts", preview: "publishCommandResult sends command output into the chat thread.", relevance: 0.91, startLine: 70 }, { distance: 0.18, endLine: 35, kind: "component", nodeId: "result-row", path: "src/components/chat/ChatCommandResultRow.tsx", preview: "ChatCommandResultRow renders markdown and structured payload cards.", relevance: 0.84, startLine: 16 }], workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceSearch", savedPath: null, snapshot: null, title };
+ case "mcp":
+ return { body: "No MCP servers are configured in this QA workspace.", payload: { kind: "mcp", servers: [] }, resultKind: "mcp", savedPath: null, snapshot: null, title };
+ case "workflow":
+ return { body: "Review the generated workflow before approving.", payload: { approvedPrompt: `Execute workflow: ${input.args.join(" ")}`, exportText: "goal: test a small change\nnodes:\n - inspect\n - verify", goal: input.args.join(" ") || "test a small change", kind: "workflowDraft", nodes: [{ access: [], artifact: "findings", dependencies: [], name: "inspect", stopCondition: "UI issues identified", task: "Inspect the slash command UI.", worker: "sage" }, { access: ["inspect"], artifact: "fixes", dependencies: ["inspect"], name: "verify", stopCondition: "QA pass complete", task: "Verify fixes in the browser.", worker: "forge" }], summary: "Two-step QA workflow for slash command behavior.", trace: ["Created QA workflow draft"] }, resultKind: "workflowDraft", savedPath: null, snapshot: null, title };
+ default:
+ return { body: `Unknown command: /${input.name}`, payload: null, resultKind: "text", savedPath: null, snapshot: null, title: "Command failed" };
+ }
+}
+
+export function mockInvokeCommand<T>(
+ command: string,
+ args?: Record<string, unknown>,
+): Promise<T> {
+ switch (command) {
+ case "get_session_snapshot":
+ case "create_managed_chat":
+ case "start_new_chat":
+ return Promise.resolve(createQaSnapshot() as T);
+ case "select_conversation":
+ case "ensure_conversation_view":
+ return Promise.resolve(createQaSnapshot(QA_CONVERSATION_ID, createQaSnapshot().conversationViews[0]?.messages ?? []) as T);
+ case "get_runtime_status":
+ return Promise.resolve(qaRuntimeStatus() as T);
+ case "get_prompt_settings":
+ return Promise.resolve(qaPromptSettings() as T);
+ case "update_prompt_settings":
+ qaReasoningEffort = (args?.input as UpdatePromptSettingsInput | undefined)?.reasoningEffort ?? qaReasoningEffort;
+ return Promise.resolve(qaPromptSettings() as T);
+ case "list_commands":
+ return Promise.resolve(qaCommands as T);
+ case "run_slash_command":
+ return Promise.resolve(qaCommandResult(args as Parameters<typeof qaCommandResult>[0]) as T);
+ case "send_prompt": {
+ const input = args?.input as SendPromptInput;
+ const conversationId = input.conversationId ?? "qa-new-chat";
+ return Promise.resolve(createQaSnapshot(conversationId, [
+ { id: `${conversationId}-user`, kind: "user", requestId: `${conversationId}-request`, text: input.prompt },
+ { id: `${conversationId}-assistant`, kind: "assistant", requestId: `${conversationId}-request`, text: "QA mock response with a bullet list:\n\n- Markdown bullets align correctly.\n- `inline code` stays readable.\n\n```ts\nconst theme = 'clean-modern';\n```\n\n[Codegraff](https://github.com/justrach/codegraff)" },
+ ]) as T);
+ }
+ case "read_workspace_file":
+ return Promise.resolve("// QA mock file contents\nexport const value = 1;\n" as T);
+ case "list_mcp_servers":
+ return Promise.resolve({ servers: [] } as T);
+ case "pick_workspace":
+ case "pick_directory":
+ return Promise.resolve(QA_WORKSPACE_PATH as T);
+ default:
+ return Promise.resolve(undefined as T);
+ }
+}