Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

19.5 KB
Raw Blame
import type { RecentModel } from "../lib/recent-models";
import type { RemoteProjectTarget } from "../lib/remote-project-session";
import type {
  AgentEventEnvelope,
  BrowserState,
  AgentQueueChangedEvent,
  AgentStatus,
  AppNotification,
  AppSettings,
  AppVersionInfo,
  AskToolResolution,
  ContextCompactionMark,
  Mode,
  ModelInfo,
  OnboardingState,
  PermissionMode,
  PlanProposal,
  PlanResolveRequest,
  PlanResolutionResult,
  PlanningState,
  PlanningStateEvent,
  PluginSummary,
  PluginTheme,
  PluginViewMeta,
  ProjectWorkspace,
  ProviderPublic,
  ReviewRollbackResult,
  SessionSummary,
  SessionThinkingLevel,
  SessionTodoSnapshot,
  UiMessage,
} from "@pi-desktop/shared";
import type { SettingsTabId } from "../lib/settings-search";
import type { TranscriptSearchTarget, TranscriptView } from "../lib/transcript-reading";
import type { TranscriptReadingPosition } from "../lib/transcript-reading-position";
import type {
  ProjectMeta,
  ProjectSort,
  SessionMeta,
  SessionSort,
} from "../lib/sidebar-preferences";
import type { PermissionQueues } from "../lib/pending-permissions";
import type { AskDraft, AskDrafts, AskQueues } from "../lib/pending-asks";
import type {
  QueuedPromptDirection,
  QueuedPrompts,
} from "../lib/queued-prompts";
import type {
  ComposerDraftSnapshot,
  ComposerPrefill,
} from "../lib/composer-smart-stop";
import type { SidebarSessionOutcome } from "../lib/sidebar-session-status";
import type { WorkPanelContext, WorkPanelTab } from "../lib/work-panel-tabs";

export type { WorkPanelTab } from "../lib/work-panel-tabs";

export type ToastVariant = "info" | "success" | "warning" | "error";

export type ToastItem = {
  id: number;
  message: string;
  variant: ToastVariant;
  /** Auto-dismiss delay in ms; 0 keeps the toast until dismissed. */
  duration: number;
  /** Notification chime is enabled by default. */
  sound: boolean;
  /** Optional conversation opened when the user activates the toast. */
  sessionId?: string;
};

export type ToastOptions = {
  variant?: ToastVariant;
  /** Override the variant default (4s, error 8s); 0 disables auto-dismiss. */
  duration?: number;
  /** Suppress the default soft chime when another notification surface already played it. */
  sound?: boolean;
  /** Make the toast message an explicit conversation-navigation action. */
  sessionId?: string;
};

export type AgentTurnResult = {
  status: "completed" | "failed";
  turnId: string;
  finishedAt: number;
  errorCode?: string;
};

export type PendingPlanRefreshResult = "pending" | "terminal" | "unavailable";

export type SessionHistoryWindow = {
  messageStart: number;
  hasMoreBefore: boolean;
  /** A display-capped tail is not canonical action input, even in a short chat. */
  contentLimited?: boolean;
};

export type NavigationOptions = {
  /** Reuse an owning navigation's generation across nested async operations. */
  navigationIntent?: number;
};

export type RefreshSessionsOptions = {
  /** Restore archived project presentation state for newly imported sessions. */
  revealImportedProjects?: boolean;
};

/**
 * Toolbar selections retained on the unpersisted new-task draft. An absent
 * field keeps the default the new session would otherwise start with.
 */
export type DraftSessionConfiguration = {
  mode?: Mode;
  thinkingLevel?: SessionThinkingLevel;
  providerId?: string;
  modelId?: string;
  permissionMode?: PermissionMode;
  /** Session `/fast` switch carried into the created session (ADR 0334). */
  fastMode?: boolean;
};


export type AppState = {
  ready: boolean;
  version?: AppVersionInfo;
  healthOk: boolean;
  settings?: AppSettings;
  sessions: SessionSummary[];
  /** Renderer-owned conversation presentation metadata. */
  sessionMeta: Record<string, SessionMeta>;
  sessionView: SessionView;
  /** Open project tabs and the host's currently active workspace. */
  openProjects: ProjectWorkspace[];
  openProjectPaths: string[];
  createProjectDialogOpen: boolean;
  createProjectDialogRemoteHostKey?: string;
  activeProjectPath?: string;
  projectMeta: Record<string, ProjectMeta>;
  /** Kept as a flat map for lightweight consumers (Sidebar). */
  projectCollapsed: Record<string, boolean>;
  projectSort: ProjectSort;
  activeSessionId?: string;
  /** Composer toolbar choices retained on the draft while it has no session. */
  draftConfiguration: DraftSessionConfiguration | null;
  /** Latest user-selected session while its transcript/workspace is resolving. */
  selectingSessionId?: string;
  messages: UiMessage[];
  /** Renderer-only visibility overrides; never persisted with transcript messages. */
  dismissedAssistantErrorMessages: Record<string, true>;
  /** Session ids whose panes stay mounted, most recently visible first. */
  retainedSessionIds: string[];
  /** Last transcript each retained pane painted. */
  retainedTranscripts: Record<string, UiMessage[]>;
  /** Renderer-owned range metadata for the lazily loaded active transcript. */
  sessionHistory: Record<string, SessionHistoryWindow>;
  /** Reading ranges are separate from the live/runtime transcript projection. */
  transcriptViews: Record<string, TranscriptView>;
  isRunning: boolean;
  /** Run state per session id — sessions run independent agents. */
  runningSessions: Record<string, boolean>;
  /** Runtime-owned phase for explaining quiet intervals in active turns. */
  agentStatuses: Record<string, AgentStatus>;
  /** Latest in-memory result for each session, used by the active transcript. */
  latestTurnResults: Record<string, AgentTurnResult>;
  /** Latest terminal outcome per session for compact sidebar feedback. */
  sessionOutcomes: Record<string, SidebarSessionOutcome>;
  /** Every checkpoint a session has installed, oldest first. */
  sessionCompactions: Record<string, (ContextCompactionMark & { summary?: string })[]>;
  providers: ProviderPublic[];
  recentModels: RecentModel[];
  rememberModel: (model: { providerId?: string; modelId?: string }) => void;
  /** Discovered model lists per provider id (composer model menu). */
  providerModels: Record<string, ModelInfo[]>;
  workspace?: ProjectWorkspace | null;
  onboarding?: OnboardingState;
  plugins: PluginSummary[];
  /** Themes contributed by loaded plugins, with their sanitized CSS. */
  pluginThemes: PluginTheme[];
  /** Work panel views contributed by loaded plugins, in menu order. */
  pluginViews: PluginViewMeta[];
  /** Per-session permission queue, oldest first. */
  pendingPermissions: PermissionQueues;
  /** Inline asktool requests, queued per session without an expiry. */
  pendingAsks: AskQueues;
  /** In-progress AskTool answers keyed by requestId, so a remount keeps them. */
  askDrafts: AskDrafts;
  /** Renderer-owned, in-memory prompt queue, isolated by session. */
  queuedPrompts: QueuedPrompts;
  /** Planning state is durable per session, including sessions outside view. */
  planningStates: Record<string, PlanningState>;
  /** Live host approval rows keyed by session; only pending rows form the gate. */
  pendingPlans: Record<string, PlanProposal>;
  /** Latest immutable Plan checkpoint/execution snapshot per session. */
  planCheckpoints: Record<string, PlanProposal>;
  /** Host-authoritative Todo snapshots keyed by session. */
  sessionTodos: Record<string, SessionTodoSnapshot>;
  applyTodosChanged: (snapshot: SessionTodoSnapshot) => void;
  toasts: ToastItem[];
  notifications: AppNotification[];
  unreadNotificationCount: number;
  page: "chat" | "scheduled" | "plugins";
  /**
   * Settings is a modal dialog over the current page, not a route. The dialog
   * may still wait behind higher-priority startup overlays (guide, notice).
   */
  settingsOpen: boolean;
  /** Tab ids come from the shared settings index. */
  settingsTab: SettingsTabId;
  /** Pending row anchor (i18n key) to flash after landing on a settings tab. */
  settingsAnchor: string | null;
  /** Bumped by every setSettingsTab so a same-tab navigation is observable. */
  settingsTabNonce: number;
  navStack: Array<{ page: AppState["page"]; sessionId?: string }>;
  navIndex: number;
  error?: string | null;
  errorCode?: string | null;
  /** Whether the current error is worth a one-click retry. */
  errorRetriable?: boolean | null;
  bootstrap: () => Promise<void>;
  refreshSessions: (options?: RefreshSessionsOptions) => Promise<void>;
  prefetchSession: (id: string) => Promise<void>;
  navigateTranscript: (target: Omit<TranscriptSearchTarget, "requestId">) => Promise<void>;
  restoreTranscriptReading: (sessionId: string, position: TranscriptReadingPosition, signal: AbortSignal) => Promise<boolean>;
  loadTranscriptPage: (sessionId: string, direction: "before" | "after") => Promise<void>;
  returnToLatestTranscript: (sessionId: string) => void;
  prepareReturnToLatestTranscript: (sessionId: string) => () => void;
  selectSession: (
    id: string,
    opts?: { record?: boolean } & NavigationOptions,
  ) => Promise<void>;
  newSession: (options?: {
    projectPath?: string | null;
    remoteProject?: RemoteProjectTarget;
    /** Create an isolated session in its own git worktree (ADR 0329). */
    isolated?: boolean;
  }) => Promise<void>;
  forkSession: (id: string) => Promise<void>;
  forkAssistantMessage: (messageId: string) => Promise<void>;
  configureActiveSession: (config: {
    mode: Mode;
    providerId?: string;
    modelId?: string;
    thinkingLevel: SessionThinkingLevel;
    permissionMode?: PermissionMode;
    fastMode?: boolean;
  }) => Promise<void>;
  /** Returns true once accepted unless concurrent smart Stop restores it. */
  sendPrompt: (
    content: string,
    draft?: ComposerDraftSnapshot,
    targetSessionId?: string,
    onAccepted?: (sessionId: string) => void,
  ) => Promise<boolean>;
  sendPlanRevision: (proposal: PlanProposal, content: string, draft?: ComposerDraftSnapshot) => Promise<boolean>;
  steerPrompt: (content: string, draft?: ComposerDraftSnapshot) => Promise<boolean>;
  enqueuePrompt: (
    content: string,
    draft?: ComposerDraftSnapshot,
    sessionId?: string,
  ) => Promise<boolean>;
  removeQueuedPrompt: (promptId: string) => void;
  /** Move one waiting row past its neighbour; promoted rows stay locked. */
  moveQueuedPrompt: (
    promptId: string,
    direction: QueuedPromptDirection,
  ) => Promise<void>;
  /** Return one waiting row to the composer as an editable draft. */
  editQueuedPrompt: (promptId: string) => void;
  sendQueuedNow: (promptId: string) => Promise<void>;
  refreshQueuedPrompts: (sessionId: string) => Promise<void>;
  applyQueueChanged: (event: AgentQueueChangedEvent) => void;
  compactContext: () => Promise<void>;
  retryAssistantMessage: (messageId: string) => Promise<void>;
  /** Read canonical text before opening a user-message editor. */
  prepareUserMessageEdit: (messageId: string, signal?: AbortSignal) => Promise<UiMessage | null>;
  /** Replace a user prompt and regenerate from it. */
  editUserMessage: (
    messageId: string,
    content: string,
    attachments?: UiMessage["attachments"],
  ) => Promise<boolean>;
  retryLastPrompt: () => Promise<void>;
  clearError: () => void;
  dismissAssistantErrorMessage: (messageId: string) => void;
  activateMessageRevision: (rootUserId: string, revisionIndex: number) => Promise<void>;
  deleteMessage: (messageId: string) => Promise<void>;
  rollbackWorkspaceChange: (
    messageId: string,
    snapshotId: string,
  ) => Promise<ReviewRollbackResult | null>;
  abort: () => Promise<void>;
  openProject: (options?: { remoteHostKey?: string }) => Promise<void>;
  closeProjectDialog: () => void;
  createProjectFromRemote: (input: {
    name: string;
    hostKey: string;
    path: string;
  }) => Promise<void>;
  createProjectFromFolders: (input: {
    name: string;
    folders: string[];
    primaryPath: string;
  }) => Promise<void>;
  /** Clone a public git remote into a chosen folder, then create its project. */
  createProjectFromGit: (input: {
    name: string;
    url: string;
    parentPath: string;
  }) => Promise<void>;
  cloneProject: (url: string) => Promise<ProjectWorkspace | null>;
  /** Re-read the active workspace metadata without changing the visible project. */
  refreshProject: (path: string) => Promise<ProjectWorkspace | null>;
  activateProject: (
    path: string,
    opts?: NavigationOptions,
  ) => Promise<ProjectWorkspace | null>;
  openProjectPath: (path: string) => Promise<ProjectWorkspace | null>;
  switchProjectPath: (path: string) => Promise<ProjectWorkspace | null>;
  closeProjectPath: (path: string) => Promise<void>;
  clearProject: (opts?: NavigationOptions) => Promise<void>;
  /**
   * Delete a project and its stored sessions on the host, then drop every
   * renderer-local record of it. A path the host has no durable row for is
   * still removed locally instead of being reported as missing. Host errors
   * (such as a path that belongs to a multi-folder project group) propagate to
   * the caller.
   */
  deleteProject: (path: string) => Promise<void>;
  toggleSessionPinned: (id: string) => void;
  toggleSessionArchived: (id: string) => void;
  archiveSession: (id: string) => void;
  restoreSession: (id: string) => void;
  renameSession: (id: string, title: string) => Promise<void>;
  /** Move an idle session into an already-known project, preserving history. */
  /** `projectPath: null` moves the session into the temporary group. */
  moveSessionProject: (id: string, projectPath: string | null) => Promise<boolean>;
  deleteSession: (id: string) => Promise<void>;
  setSessionSort: (sort: SessionSort) => void;
  setSessionArchiveVisibility: (show: boolean) => void;
  setSessionView: (view: Partial<SessionView> | boolean) => void;
  setShowArchived: (show: boolean) => void;
  renameProject: (path: string, name: string) => void;
  toggleProjectPinned: (path: string, pinned?: boolean) => void;
  toggleProjectArchived: (path: string) => void;
  restoreProject: (path: string) => void;
  restoreProjects: (paths: string[]) => void;
  archiveProject: (path: string) => void;
  setProjectCollapsed: (path: string, collapsed?: boolean) => void;
  toggleProjectCollapsed: (path: string) => void;
  closeProject: (path: string) => Promise<void>;
  setProjectSort: (sort: ProjectSort) => void;
  reorderProjects: (paths: string[]) => void;
  getVisibleSessions: (options?: {
    projectPath?: string | null;
    includeArchived?: boolean;
  }) => SessionSummary[];
  getSortedProjects: () => ProjectWorkspace[];
  refreshProviders: () => Promise<void>;
  /** Load a provider's model list into the cache (no-op when cached). */
  loadProviderModels: (providerId: string) => Promise<void>;
  refreshPlugins: () => Promise<void>;
  /** Reload contributed themes. */
  refreshPluginThemes: () => Promise<void>;
  /** Reload contributed work panel views. */
  refreshPluginViews: () => Promise<void>;
  refreshNotifications: () => Promise<void>;
  /** Returns true only when this event was accepted as a new durable row. */
  receiveNotification: (notification: AppNotification) => boolean;
  markNotificationRead: (id: string) => Promise<void>;
  markAllNotificationsRead: () => Promise<void>;
  clearNotifications: () => Promise<void>;
  openNotification: (id: string) => Promise<void>;
  /** Drop a session's sidebar outcome badge and read its task notifications. */
  acknowledgeSessionOutcome: (sessionId: string) => Promise<void>;
  restorePendingPlan: (sessionId: string) => Promise<PendingPlanRefreshResult>;
  /** Re-read a session's open ask / permission cards from Main (reload recovery). */
  restorePendingInteractive: (sessionId: string) => Promise<void>;
  refreshPlanCheckpoints: () => Promise<void>;
  handleAgentEvent: (envelope: AgentEventEnvelope) => void;
  handlePlansChanged: (event: PlanningStateEvent) => void;
  setPage: (page: AppState["page"], opts?: { record?: boolean }) => void;
  /** Open the Settings dialog on its current (or the given) destination. */
  openSettings: (tab?: AppState["settingsTab"]) => void;
  closeSettings: () => void;
  /** Open the Settings dialog on `tab`, even when that tab is already shown. */
  setSettingsTab: (tab: AppState["settingsTab"]) => void;
  setSettingsAnchor: (key: string | null) => void;
  navBack: () => void;
  navForward: () => void;
  canNavBack: () => boolean;
  canNavForward: () => boolean;
  resolvePermission: (
    sessionId: string,
    requestId: string,
    decision: "allow-once" | "allow-session" | "deny",
  ) => Promise<void>;
  resolveAsk: (
    sessionId: string,
    resolution: AskToolResolution,
  ) => Promise<void>;
  /** Persist one question card's in-progress answers by requestId. */
  setAskDraft: (requestId: string, draft: AskDraft) => void;
  /** Forget a request's draft once it is resolved or dismissed. */
  dropAskDraft: (requestId: string) => void;
  resolvePlan: (resolution: PlanResolveRequest) => Promise<PlanResolutionResult>;
  showToast: (message: string, options?: ToastOptions) => void;
  dismissToast: (id: number) => void;
  composerPrefill: ComposerPrefill | null;
  clearComposerPrefill: () => void;
  workPanelOpen: boolean;
  workPanelTabs: WorkPanelTab[];
  activeWorkPanelTabId: string | null;
  /** Runtime-only work panel state owned by each conversation. */
  workPanelContexts: Record<string, WorkPanelContext>;
  /** Runtime-only opt-in, and the last project whose entry each session received. */
  fileManagerProjects: ReadonlySet<string>;
  fileManagerTabReceipts: Record<string, string>;
  /** The user's preferred panel width; persisted, never below the regular minimum. */
  workPanelWidth: number;
  /**
   * Runtime-only width a manual sidebar reopen lends to the sidebar. It ends
   * when the sidebar collapses or the user resizes the panel.
   */
  workPanelYieldedWidth: number | null;
  /** Chat-initiated "preview this file" request consumed by the files viewer. */
  workPanelFileRequest: {
    path: string;
    seq: number;
    mimeType?: string;
    line?: number;
    column?: number;
  } | null;
  /** Open (or activate) the transcript tab of one delegated subagent. */
  openSubagentTab: (delegationId: string, agentName?: string) => void;
  /** Abort one session's running turn, visible or not. */
  abortSession: (sessionId: string) => Promise<void>;
  openWorkPanel: () => void;
  toggleWorkPanel: () => void;
  openWorkPanelTab: (tab: WorkPanelTab) => void;
  /** Create and activate a new blank tool launcher page. */
  openNewWorkPanelTab: () => void;
  /** Open a tool from a blank launcher page, reusing an existing tool tab. */
  replaceWorkPanelTab: (sourceTabId: string, tab: WorkPanelTab) => void;
  openWorkPanelTabForSession: (sessionId: string, tab: WorkPanelTab) => void;
  activateWorkPanelTab: (tabId: string) => void;
  reorderWorkPanelTabs: (
    sourceTabId: string,
    targetTabId: string,
    insertAfter: boolean,
  ) => void;
  closeWorkPanelTab: (tabId: string) => void;
  closeOtherWorkPanelTabs: (tabId: string) => void;
  closeAllWorkPanelTabs: () => void;
  collapseWorkPanel: () => void;
  /** Hide the visible panel while retaining its session-owned context. */
  resetWorkPanelContext: () => void;
  setWorkPanelWidth: (width: number) => void;
  setWorkPanelYieldedWidth: (width: number | null) => void;
  openFileInWorkPanel: (
    path: string,
    mimeType?: string,
    position?: { line?: number; column?: number },
  ) => void;
  openUrlInWorkPanel: (url: string) => void;
  updateBrowserWorkPanelTab: (state: BrowserState) => void;
  restoreBrowserWorkPanelTabs: (sessionId: string, pages: BrowserState[]) => void;
};

export type AppStateData = {
  [Key in keyof AppState as AppState[Key] extends (
    ...args: never[]
  ) => unknown
    ? never
    : Key]: AppState[Key];
};

export type SessionView = {
  sort: SessionSort;
  /** Alias retained for sidebar consumers that use the explicit name. */
  sortBy?: SessionSort;
  /** Whether archived sessions are included in sidebar queries. */
  archived: boolean;
  showArchived?: boolean;
};