Skip to content

feat(sidebar): the host that owns a workspace stamps its Recent and Smart keys (dark) - #30235

Merged
Jinwoo-H merged 6 commits into
mainfrom
jinwoo/sidebar-sort-stamps
Oct 18, 2026
Merged

Jinwoo-H merged 6 commits into
mainfrom
jinwoo/sidebar-sort-stamps

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​892 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​891
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​593 $\color{#cf222e}{\Huge{\mathbf{−}}}$​43 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​550

ELI5

The sidebar's Recent and Smart orders should move only when something actually happens in a workspace: you send a prompt, an agent finishes or asks for input, a terminal rings its bell, a script starts a terminal, or the workspace is created. Today the window decides most of that itself, so the phone and the desktop's background process can't see it. This PR makes the computer that owns each workspace write those moments onto the workspace's own record, so every screen can later sort from the same facts.

This is the first step, and it is switched off: in every build people use, nothing here runs.

What Changed

Behind the build switch ORCA_SIDEBAR_INPUTS=main only:

  • The owning host writes three sort stamps on each worktree or folder workspace record: recentAt (stored in the existing lastActivityAt, so older clients still sort right), and new optional smartTier (needs-you, done or working; absent means Rest) and smartAt.
  • One pure classifier in src/shared/sidebar-list/sort-stamps.ts turns (a pane's previous phase, the new observation, now) into a stamp update. No clock reads. Rules from the approved note: prompt, finish/error and requests for input stamp Recent; a resumed approval moves to Working and keeps the time it asked; Done stays until the next prompt or the agent exits (Q1, kept in nextAgentPaneState so it can change before the flip); a stopped turn rests; Recent stamps closer than 10 s apart are dropped (first wins); tier changes apply at once.
  • SortStampsProducer (src/main/runtime/sidebar-inputs/sort-stamps-producer.ts) feeds it from the sources below and writes the records. A status that is already there when the producer attaches (restored after a restart, or replayed) only reconciles the tier, never Recent, and a tier the record already holds keeps its time, so a restart rewrites nothing.
  • The stamps are published on the existing workspaces feed rows (sidebarInputs.workspaceRows, from feat(sidebar): main produces this host's workspace rows, checked against the window (dark) #30184) as optional recentAt / smartTier / smartAt. The window's shadow check ignores them: the window does not read stamps until the next PR.
  • Folder workspace creation now stamps lastActivityAt (it was 0). Worktree creation already did, on every path.
  • The window's own stamps (including terminal exit and comment edits, which Q3 drops) are untouched here; PR 3 deletes them.

With the switch off: the producer class, the terminal-create stamp and the folder creation stamp are compiled out (checked in the switch-off out/main bundle). What remains is reading the two new optional fields where records are loaded and listed, which nothing writes.

Every event source, and where it is read

Event Where it comes from Read at Test
Agent prompt / finish / error / needs input (Claude, Codex, every hooked agent, SSH via relay) the hook server's status store, row mutations sort-stamps-producer.ts:105 (subscribeStatusRowMutations) sort-stamps-producer.test.ts "stamps prompt, finish and needs-input..." ; e2e sidebar-sort-stamps.spec.ts
Structured chat sessions ingested into the same store, server-ingest-structured.ts:75 same subscription "stamps a structured chat session through the same store"
Status present at attach (restored, replayed, restoredUnconfirmed) getStatusSnapshot() sort-stamps-producer.ts:102 "seeds a status present at attach..."
Agent exits (row removed) row mutation with no row left same subscription "drops to Rest without a Recent stamp..."
Hookless agents (title heuristic) title side-effect facts, terminal-title-tracker.ts:107; phase via detectAgentStatusFromTitle, the heuristic Smart's dots use sort-stamps-producer.ts:164 "turns a hookless agent's titles...", "treats a new PTY in the pane as a new agent", "leaves a pane with hook rows to its hooks"
Hookless agent's terminal exits subscribeToPtyExit sort-stamps-producer.ts:189 same title test
Bell, foreground tab terminal-title-tracker.ts:173 sort-stamps-producer.ts:162 "stamps a bell"; orca-runtime-sort-stamps.test.ts (real runtime bytes)
Bell, parked terminal (daemon holds scan authority) terminal-transient-facts.ts:32 same orca-runtime-sort-stamps.test.ts "stamps a bell the daemon reports for a parked terminal"
Terminal started by the CLI (local, SSH, WSL) terminal.create with caller local-cli terminal-lifecycle-methods.ts:94 terminal-create-sort-stamp.test.ts (window, phone and reattach do not stamp)
Worktree created from window, phone or CLI already stamped: worktree-remote.ts:1522, runtime-local-worktree-materialization.ts:82, runtime-folder-worktree-create.ts:84, folder-workspace-creation.ts:34 unchanged existing creation tests
Folder workspace created folder-workspace-operations.ts:115 new, behind the switch folder-workspace-sort-stamps.test.ts
Paired-server hosts the server runs the same runtime layer and attaches its hook store (orcad-entry.ts:300, main-process-runtime-service.ts:149); a headless server with no client still scans its own bytes because the producer is a side-effect consumer same orca-runtime-sort-stamps.test.ts (headless runtime, no window)
SSH records host taken from the hook row's or batch's connectionId, written host-qualified sort-stamps-producer.ts readStamps/writeStamps "stamps an SSH workspace's record on its own host"
WSL move in progress dropped quietly, like other background bookkeeping isWriteFenced "drops stamps while a WSL move freezes the project"

Why

The design note (owner-approved 2026-10-18, Q1 to Q4 as recommended) moves every sort decision to the host that owns the workspace, so the window, the phone and main sort from identical facts with no timers. This PR only produces the facts; PR 2 makes the shared sort read them.

Choices:

  • Stamps on the record, not a side table: older clients keep sorting by lastActivityAt, and the row feed already publishes records.
  • Hookless agents read title facts inside the producer, not as synthetic hook-store rows: writing title guesses into the hook store would change what every reader of that store shows (sidebar dots, worktree ps, mobile). The producer applies the rule Smart applies today: a pane with hook rows ignores its title. An agent idle at its first title has finished no turn, so it rests rather than reading as Done.
  • No blanket sweep of stored tiers at startup: an SSH host that is not connected yet has no rows at startup, and clearing its tiers would treat lost contact as a dead agent. Local hook rows are persisted and reconciled by the store, which clears them through the normal path.

Known, intended: on a switch-on build the window's Recent order picks up main's stamps when it next re-lists (it reads lastActivityAt), so a prompt or finish in the open workspace can move it there. Shipped builds are unaffected.

Deferred (not in this PR):

  • Must land before PR 2 reads tiers: a tier set from a hookless agent's title can go stale if that terminal died across a restart (no hook row reconciles it). Fix planned: at attach, seed title panes from live terminals' current titles, then clear tiers on this machine's records with no hook row and no live terminal, leaving SSH records alone.
  • Terminals started by automations or orchestration inside an existing workspace (agents launched there stamp through their hooks; plain shells do not).
  • Command Code's output-only working/done facts; re-resolving an agent row's workspace after a late tab sync; measuring headless CPU now that a switch-on server scans every chunk for bells and titles (before the flip).

Linked Issue

Part of the sidebar sort-stamps plan (PR 1 of 4).

Visual Proof

N/A: dark behind a build switch; nothing reads the stamps for ordering yet.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Unit (fixed now): src/shared/sidebar-list/sort-stamps.test.ts (transition table, throttle, tiers, resume, Done held, stopped turn, error), sort-stamps-producer.test.ts, orca-runtime-sort-stamps.test.ts, terminal-create-sort-stamp.test.ts, folder-workspace-sort-stamps.test.ts, workspace-rows.test.ts.

  • e2e on a switch-on build (hidden window, ORCA_BACKGROUND_LAUNCH=1): tests/e2e/sidebar-sort-stamps.spec.ts drives an agent through prompt, finish and needs input over the hook endpoint and reads the stamps over sidebarInputs.workspaceRows; passes twice in a row, along with sidebar-workspace-rows.spec.ts (shadow mismatches 0). Positive control: with the producer not attached, the spec fails (Expected "working", Received undefined).

  • pnpm tc, relevant suites (155 files), check:code-quality:changed, focus-read ratchet, oxlint: pass. macOS only.

Review

Opus elegance and bug review of the diff and of the fix delta; findings applied are listed in the commits.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Mixed versions (Q4): every new row field is optional; an older host writes no tier and its rows sort in Rest by lastActivityAt.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to 0d784

A live workspace can temporarily lose its Smart tier, and an eligible CLI terminal creation can be reported as failed even though the terminal exists. These bounded issues warrant fixes or explicit acceptance before merging.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Description check Warning The description is detailed and covers the change, rationale, testing, visual proof, compatibility, and checklist. The Linked Issue section is incomplete because "Fixes #" is empty and no actual issue… Add the actual linked issue number or URL in the Linked Issue section. If the maintainer exception applies, reference the existing sidebar sort-stamps issue instead of leaving "Fixes #" empty.
Docstring Coverage Warning Docstring coverage is 28.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 20 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: the owning host writes Recent and Smart sort stamps for workspaces. The parenthetical build-switch context does not prevent understanding.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, visual proof, compatibility, and checklist. The Linked Issue section is incomplete because "Fixes #" is empty and no actual issue link or number is provided.

Resolution

Add the actual linked issue number or URL in the Linked Issue section. If the maintainer exception applies, reference the existing sidebar sort-stamps issue instead of leaving "Fixes #" empty.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2c70b503-f68d-4cbd-8763-a3be3fa9947b
📥 Commits

Reviewing files that changed from the base of the PR and between f0a6962 and 0d784ec.

📒 Files selected for processing: 20
  • src/main/ipc/worktree-metadata-merge.ts
  • src/main/persistence/restoring-sessions/folder-workspace-operations.ts
  • src/main/persistence/restoring-sessions/folder-workspace-sort-stamps.test.ts
  • src/main/runtime/rpc/methods/terminal/terminal-create-sort-stamp.test.ts
  • src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts
  • src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts
  • src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts
  • src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts
  • src/main/runtime/sidebar-inputs/sort-stamps-producer.ts
  • src/renderer/src/lib/sidebar-shadow/workspace-rows-shadow.ts
  • src/shared/folder-workspace-types.ts
  • src/shared/folder-workspace-worktree.ts
  • src/shared/folder-workspaces.ts
  • src/shared/sidebar-list/sort-stamps.test.ts
  • src/shared/sidebar-list/sort-stamps.ts
  • src/shared/sidebar-list/workspace-rows.test.ts
  • src/shared/sidebar-list/workspace-rows.ts
  • src/shared/worktree/meta-types.ts
  • src/shared/worktree/types.ts
  • tests/e2e/sidebar-sort-stamps.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +53 to +99
const terminal = await runtime.dedupeTerminalCreate(
pairedDeviceId ?? clientId ?? 'local',
params.worktree,
params.clientMutationId,
params.reconcileExisting === true,
(canonicalWorktreeSelector, preAllocatedHandle) =>
runtime.createTerminal(canonicalWorktreeSelector, {
command: params.command,
terminalImageViewerSupported: terminalImageViewerSupported(context),
...(params.shell ? { shellOverride: params.shell } : {}),
startupCommandDelivery: params.startupCommandDelivery,
env: params.env,
envToDelete: params.envToDelete,
...(params.launchConfig ? { launchConfig: params.launchConfig } : {}),
...(params.resumeProviderSession
? { resumeProviderSession: params.resumeProviderSession }
: {}),
...(params.launchToken ? { launchToken: params.launchToken } : {}),
...(params.launchAgent ? { launchAgent: params.launchAgent } : {}),
...(params.terminalKittyKeyboardProtocol === true
? { terminalKittyKeyboardProtocol: true }
: {}),
...(params.terminalColorQueryReplies
? { terminalColorQueryReplies: params.terminalColorQueryReplies }
: {}),
title: params.title,
focus,
activate,
presentation,
tabId: params.tabId,
leafId: params.leafId,
...(params.spawnIntent ? { spawnIntent: params.spawnIntent } : {}),
...(preAllocatedHandle ? { preAllocatedHandle } : {})
})
)
// Switch point. A CLI start is work in the workspace; a window or phone tab is a person opening one.
if (
ORCA_SIDEBAR_INPUTS_IS_MAIN &&
context.caller?.kind === 'local-cli' &&
!terminal.isReattach
) {
runtime.sidebarFacts?.sortStamps.noteTerminalStarted(
terminal.worktreeId,
terminal.executionHostId
)
}
return { terminal }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '40,110p' src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts
sed -n '280,340p' src/main/runtime/sidebar-inputs/sort-stamps-producer.ts

Repository: stablyai/orca

Length of output: 5336


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- producer definition and direct tests ---'
rg -n -F --glob '*.ts' -e 'noteTerminalStarted' -e 'private writeStamps' -e 'class SortStampsProducer' -e 'SortStampsProducer' src/main src/shared
printf '%s\n' '--- store method declarations and implementations ---'
rg -n -F --glob '*.ts' -e 'updateFolderWorkspace' -e 'setWorktreeMetaForHost' -e 'setWorktreeMeta(' src/main src/shared
printf '%s\n' '--- terminal.create RPC consumers and retry/error boundaries ---'
rg -n -F --glob '*.ts' -e 'terminal.create' -e "'terminal.create'" -e '"terminal.create"' -e 'createTerminal' src/main src/shared
printf '%s\n' '--- relevant source blocks ---'
sed -n '1,360p' src/main/runtime/sidebar-inputs/sort-stamps-producer.ts

Repository: stablyai/orca

Length of output: 41765


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- producer entry and test setup ---'
sed -n '105,132p' src/main/runtime/sidebar-inputs/sort-stamps-producer.ts
sed -n '1,90p' src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts
sed -n '260,300p' src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts
printf '%s\n' '--- concrete store type and methods ---'
rg -n -F --glob '*.ts' -e 'class PersistentStore' -e 'class Persistence' -e 'setWorktreeMetaForHost(' -e 'updateFolderWorkspace(' -e 'setWorktreeMeta(' src/main/persistence src/main | head -240
printf '%s\n' '--- terminal.create call sites and transport retry logic ---'
rg -n -F --glob '*.{ts,tsx}' -e 'call(.*terminal.create' -e 'request(.*terminal.create' -e 'invoke(.*terminal.create' -e 'terminal.create' src | head -260
printf '%s\n' '--- idempotency and unknown-outcome contract ---'
sed -n '65,100p' src/shared/runtime-capability-constants.ts
rg -n -F --glob '*.{ts,tsx}' -e 'terminal.create-idempotency.v2' -e 'unknown outcome' -e 'unknownOutcome' -e 'retry.*terminal' -e 'terminal.*retry' src | head -240

Repository: stablyai/orca

Length of output: 41835


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- metadata persistence methods ---'
sed -n '1,150p' src/main/persistence/loading-store/metadata-lineage-operations.ts
sed -n '180,245p' src/main/persistence/loading-store/worktree-identity-metadata.ts
printf '%s\n' '--- folder persistence methods ---'
sed -n '90,175p' src/main/persistence/restoring-sessions/folder-workspace-operations.ts
sed -n '120,165p' src/main/persistence/loading-store/project-collection-operations.ts
printf '%s\n' '--- terminal create transport call and outcome handling ---'
sed -n '1235,1305p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
sed -n '3075,3185p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
printf '%s\n' '--- create outcome recovery tests ---'
sed -n '1,340p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-outcome-recovery.test.ts
printf '%s\n' '--- idempotency tests ---'
sed -n '1,180p' src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts

Repository: stablyai/orca

Length of output: 39512


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- complete host-qualified write and save scheduling ---'
sed -n '205,285p' src/main/persistence/loading-store/worktree-identity-metadata.ts
rg -n -F --glob '*.ts' -e 'function scheduleSave' -e 'export function scheduleSave' -e 'scheduleSave(' src/main/persistence/loading-store/write-scheduling.ts
sed -n '1,180p' src/main/persistence/loading-store/write-scheduling.ts
printf '%s\n' '--- local-cli caller contract ---'
rg -n -F --glob '*.ts' -e "kind: 'local-cli'" -e 'local-cli' -e 'caller?.kind' -e 'caller:' src/main src/shared | head -240
printf '%s\n' '--- recovery error classification and call boundary ---'
rg -n -F --glob 'remote-runtime-pty-transport.ts' -e 'terminalCreateUnknownOutcomeError' -e 'runtime_timeout' -e 'createWithUnknownOutcomeRecovery' -e 'catch (' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
sed -n '1290,1435p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts

Repository: stablyai/orca

Length of output: 36090


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- ambiguous host metadata test and exact setWorktreeMeta path ---'
sed -n '120,150p' src/main/persistence-worktree-identity-persistence.test.ts
nl -ba src/main/persistence/loading-store/metadata-lineage-operations.ts | sed -n '88,125p'
nl -ba src/main/persistence/loading-store/worktree-identity-metadata.ts | sed -n '213,260p'
printf '%s\n' '--- recoverable connection error classifier ---'
rg -n -F --glob '*.ts' -e 'function isRecoverableRemoteRuntimeConnectionError' -e 'isRecoverableRemoteRuntimeConnectionError' src/renderer/src
sed -n '1,180p' src/renderer/src/components/terminal-pane/remote-runtime-pty-errors.ts 2>/dev/null || true

Repository: stablyai/orca

Length of output: 6641


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- repository ambiguous-identity test ---'
sed -n '125,150p' src/main/worktree-identity-persistence.test.ts
printf '%s\n' '--- connection-error classifier ---'
rg -n -F --glob '*.ts' -e 'export function isRecoverableRemoteRuntimeConnectionError' -e 'function isRecoverableRemoteRuntimeConnectionError' src/shared src/renderer/src
classifier=$(rg -l -F --glob '*.ts' 'isRecoverableRemoteRuntimeConnectionError' src/shared src/renderer/src | grep -v '\.test\.ts$' | head -1)
if [ -n "$classifier" ]; then
  sed -n '1,180p' "$classifier"
fi

Repository: stablyai/orca

Length of output: 4708


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- exact ambiguous-state setup ---'
nl -ba src/main/worktree-identity-persistence.test.ts | sed -n '95,145p'
printf '%s\n' '--- shared recoverable-error classifier ---'
nl -ba src/shared/remote-runtime-client-error-classification.ts | sed -n '1,130p'

Repository: stablyai/orca

Length of output: 5800


Keep stamp persistence from failing terminal.create.

For a local CLI create with an existing host-owned worktree record, an ambiguous host alias makes setWorktreeMeta call setWorktreeMetaForHost, which throws. This call runs after the terminal is created and before the RPC returns { terminal }, so the live terminal can be reported as a failed creation. Treat this stamp as best-effort at the RPC boundary.

Suggested fix
-        runtime.sidebarFacts?.sortStamps.noteTerminalStarted(
-          terminal.worktreeId,
-          terminal.executionHostId
-        )
+        try {
+          runtime.sidebarFacts?.sortStamps.noteTerminalStarted(
+            terminal.worktreeId,
+            terminal.executionHostId
+          )
+        } catch {
+          // Sort stamps are best-effort and must not change terminal.create success.
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const terminal = await runtime.dedupeTerminalCreate(
pairedDeviceId ?? clientId ?? 'local',
params.worktree,
params.clientMutationId,
params.reconcileExisting === true,
(canonicalWorktreeSelector, preAllocatedHandle) =>
runtime.createTerminal(canonicalWorktreeSelector, {
command: params.command,
terminalImageViewerSupported: terminalImageViewerSupported(context),
...(params.shell ? { shellOverride: params.shell } : {}),
startupCommandDelivery: params.startupCommandDelivery,
env: params.env,
envToDelete: params.envToDelete,
...(params.launchConfig ? { launchConfig: params.launchConfig } : {}),
...(params.resumeProviderSession
? { resumeProviderSession: params.resumeProviderSession }
: {}),
...(params.launchToken ? { launchToken: params.launchToken } : {}),
...(params.launchAgent ? { launchAgent: params.launchAgent } : {}),
...(params.terminalKittyKeyboardProtocol === true
? { terminalKittyKeyboardProtocol: true }
: {}),
...(params.terminalColorQueryReplies
? { terminalColorQueryReplies: params.terminalColorQueryReplies }
: {}),
title: params.title,
focus,
activate,
presentation,
tabId: params.tabId,
leafId: params.leafId,
...(params.spawnIntent ? { spawnIntent: params.spawnIntent } : {}),
...(preAllocatedHandle ? { preAllocatedHandle } : {})
})
)
// Switch point. A CLI start is work in the workspace; a window or phone tab is a person opening one.
if (
ORCA_SIDEBAR_INPUTS_IS_MAIN &&
context.caller?.kind === 'local-cli' &&
!terminal.isReattach
) {
runtime.sidebarFacts?.sortStamps.noteTerminalStarted(
terminal.worktreeId,
terminal.executionHostId
)
}
return { terminal }
const terminal = await runtime.dedupeTerminalCreate(
pairedDeviceId ?? clientId ?? 'local',
params.worktree,
params.clientMutationId,
params.reconcileExisting === true,
(canonicalWorktreeSelector, preAllocatedHandle) =>
runtime.createTerminal(canonicalWorktreeSelector, {
command: params.command,
terminalImageViewerSupported: terminalImageViewerSupported(context),
...(params.shell ? { shellOverride: params.shell } : {}),
startupCommandDelivery: params.startupCommandDelivery,
env: params.env,
envToDelete: params.envToDelete,
...(params.launchConfig ? { launchConfig: params.launchConfig } : {}),
...(params.resumeProviderSession
? { resumeProviderSession: params.resumeProviderSession }
: {}),
...(params.launchToken ? { launchToken: params.launchToken } : {}),
...(params.launchAgent ? { launchAgent: params.launchAgent } : {}),
...(params.terminalKittyKeyboardProtocol === true
? { terminalKittyKeyboardProtocol: true }
: {}),
...(params.terminalColorQueryReplies
? { terminalColorQueryReplies: params.terminalColorQueryReplies }
: {}),
title: params.title,
focus,
activate,
presentation,
tabId: params.tabId,
leafId: params.leafId,
...(params.spawnIntent ? { spawnIntent: params.spawnIntent } : {}),
...(preAllocatedHandle ? { preAllocatedHandle } : {})
})
)
// Switch point. A CLI start is work in the workspace; a window or phone tab is a person opening one.
if (
ORCA_SIDEBAR_INPUTS_IS_MAIN &&
context.caller?.kind === 'local-cli' &&
!terminal.isReattach
) {
try {
runtime.sidebarFacts?.sortStamps.noteTerminalStarted(
terminal.worktreeId,
terminal.executionHostId
)
} catch {
// Sort stamps are best-effort and must not change terminal.create success.
}
}
return { terminal }

Comment on lines +126 to +155
private observeHookPane(paneKey: string, seed: boolean): void {
const latest = this.latestHookRow(paneKey)
if (!latest) {
this.move(paneKey, null, 'rest', this.sources.now())
return
}
const worktreeId = resolveAgentStatusWorktreeId(latest, {
get: this.sources.resolveTabWorktreeId
})
const workspace = worktreeId
? { worktreeId, sshHostId: sshHostOfConnection(latest.connectionId) }
: null
const phase = hookRowAgentPhase(latest)
if (seed || latest.restoredUnconfirmed || latest.isReplay) {
this.seed(paneKey, workspace, phase, latest.stateStartedAt)
} else {
this.move(paneKey, workspace, phase, this.sources.now())
}
}

// The window applies a pane's rows in arrival order, so the newest is the one it holds.
private latestHookRow(paneKey: string): AgentStatusIpcPayload | null {
let latest: AgentStatusIpcPayload | null = null
for (const row of this.agentStore?.getStatusSnapshotForPane(paneKey) ?? []) {
if (!row.providerSessionOnly && (!latest || row.receivedAt > latest.receivedAt)) {
latest = row
}
}
return latest
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '95,275p' src/main/runtime/sidebar-inputs/sort-stamps-producer.ts
sed -n '32,80p' src/main/agent-hooks/server/server-cleanup.ts
sed -n '85,125p' src/main/agent-hooks/server/server-tab-cleanup.ts

Repository: stablyai/orca

Length of output: 9767


🏁 Script executed:

rg -n -F --glob '*.ts' -e 'class SortStampsProducer' -e 'subscribeToPtyExit' -e 'clearPaneState' -e 'emitPaneStatusCleared' -e 'observeHookPane' -e 'noteTerminalSideEffects' src/main/runtime/sidebar-inputs src/main/runtime src/main/agent-hooks | sed -n '1,220p'
printf '\n--- producer start ---\n'
sed -n '1,115p' src/main/runtime/sidebar-inputs/sort-stamps-producer.ts
printf '\n--- producer remainder ---\n'
sed -n '240,430p' src/main/runtime/sidebar-inputs/sort-stamps-producer.ts
printf '\n--- title/teardown tests ---\n'
rg -n -F --glob '*sort-stamps-producer*' -e 'exit' -e 'clearPaneState' -e 'dropStatusEntry' -e 'title' -e 'pane' src/main/runtime/sidebar-inputs | sed -n '1,240p'

Repository: stablyai/orca

Length of output: 30138


🏁 Script executed:

printf '%s\n' '--- cleanup mutation paths ---'
sed -n '30,75p' src/main/agent-hooks/server/server-cleanup.ts
sed -n '114,180p' src/main/agent-hooks/server/server-tab-cleanup.ts
sed -n '220,265p' src/main/agent-hooks/server/server-cleanup.ts
printf '%s\n' '--- status mutation types and producer wiring ---'
rg -n -F --glob '*.ts' -e 'subscribeStatusRowMutations' -e 'AgentStatusRowMutation' -e 'StatusRowMutation' -e 'emitPaneStatusCleared' src/main/runtime src/main/agent-hooks src/shared | sed -n '1,220p'
sed -n '1,75p' src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts
printf '%s\n' '--- focused tests ---'
sed -n '1,215p' src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts
sed -n '270,370p' src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts

Repository: stablyai/orca

Length of output: 28962


Limit title replay to a live pane after retained-row removal.

The missing fallback applies when dropStatusEntry retains a providerSessionOnly row. It does not apply to clearPaneState, which uses the same mutation callback for PTY teardown and passes undefined. A cache keyed only by paneKey can replay a stale tier during teardown or after the PTY exits.

Keep the observation tied to the current PTY. Update it for title facts while hook authority is active, clear it on PTY exit and teardown, and replay it only when the mutation retains a provider-session row.

Suggested fix
-type TitlePane = { ptyId: string; releaseExit: () => void }
+type TitlePane = {
+  ptyId: string
+  workspace: WorkspaceRef
+  phase: AgentPhase
+  releaseExit: () => void
+}
 
@@
-    const unsubscribe = store.subscribeStatusRowMutations(({ before, after }) => {
+    const unsubscribe = store.subscribeStatusRowMutations(({ before, after }) => {
       for (const paneKey of new Set([before?.paneKey, after?.paneKey])) {
         if (paneKey) {
-          this.observeHookPane(paneKey, false)
+          const retainedForLiveness =
+            after?.paneKey === paneKey && after.providerSessionOnly === true
+          if (after === undefined && before?.paneKey === paneKey) {
+            this.endTitlePane(paneKey)
+          }
+          this.observeHookPane(paneKey, false, retainedForLiveness)
         }
       }
     })
@@
-  private observeHookPane(paneKey: string, seed: boolean): void {
+  private observeHookPane(
+    paneKey: string,
+    seed: boolean,
+    allowLiveTitleFallback = false
+  ): void {
     const latest = this.latestHookRow(paneKey)
     if (!latest) {
+      const title = allowLiveTitleFallback ? this.titlePanes.get(paneKey) : undefined
+      if (title) {
+        this.observeTitlePane(title.ptyId, paneKey, title.workspace, title.phase)
+        return
+      }
       this.move(paneKey, null, 'rest', this.sources.now())
       return
     }
@@
-      } else if (fact.kind === 'title' && paneKey && !this.latestHookRow(paneKey)) {
+      } else if (fact.kind === 'title' && paneKey) {
         const phase = fact.staleWorkingTitleClear ? 'rest' : titleAgentPhase(fact.rawTitle)
-        this.observeTitlePane(batch.ptyId, paneKey, workspace, phase)
+        this.rememberTitlePane(batch.ptyId, paneKey, workspace, phase)
+        if (!this.latestHookRow(paneKey)) {
+          this.observeTitlePane(batch.ptyId, paneKey, workspace, phase)
+        }
       }
@@
     if (known?.ptyId === ptyId) {
+      known.workspace = workspace
+      known.phase = phase
       this.move(paneKey, workspace, phase, this.sources.now())
       return
@@
-    this.titlePanes.set(paneKey, { ptyId, releaseExit })
+    this.titlePanes.set(paneKey, { ptyId, workspace, phase, releaseExit })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant