Skip to content

refactor(terminal): project main's terminal layout after each save (no reader yet) - #25682

Merged
Jinwoo-H merged 9 commits into
mainfrom
terminal-topology-b2-1-publisher
Oct 7, 2026
Merged

Jinwoo-H merged 9 commits into
mainfrom
terminal-topology-b2-1-publisher

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​530 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​530
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​238 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​238

ELI5

Later in this refactor, the app window will stop keeping its own copy of the terminal layout and will follow main's copy instead. To do that, main first needs a way to notice every time the saved layout changes and to describe one workspace's layout as a single snapshot. This PR adds those two pieces only. Nothing is connected to them yet, so nothing changes for users and no extra work runs.

What Changed

  • A hook on saves. The two places every saved-session change already passes through (scheduleSave and the durable-mutation runner, including its rollback path) now tell any registered observers that the workspace sessions changed. Observers register with onWorkspaceSessionWritten. No observer is registered in the app today, so the hook loops over an empty set.
  • A layout snapshot. src/shared/terminal-topology-slice.ts and src/main/runtime/terminal-topology-projection.ts turn one worktree's saved session into a snapshot: its tabs, split layouts, which terminal sits in each pane, pane titles, sleeping agent records for that worktree, and a revision number. Display-only fields are left out.
  • A publisher that is not plugged in. src/main/runtime/terminal-topology-publisher.ts takes the snapshot source and a send function in its constructor. When told something changed, it batches the burst, compares each worktree's snapshot by value with what it last sent, and sends only the changed ones (plus an empty snapshot for a worktree that lost all its rows), each with an increasing sequence number. If building or sending a snapshot throws, it logs once and carries on; the error never reaches the save.
  • Not in this PR: no IPC channels, no new reply fields, no window code, nothing sent to SSH or remote hosts. The PR that makes the window follow main's layout will connect the publisher to a real send function.

Before/after for users: none.

Why

The alternative was to first route every place in main that changes the terminal layout through one new module, so that module could announce changes. Checking each of those writers showed they all already go through one of the two save paths, so hooking those two paths sees every change without that rerouting. Keeping the publisher unconnected lets it be reviewed and tested on its own, and the change that actually turns it on stays small.

Linked Issue

Maintainer PR. Part of the terminal layout refactor (Linear STA-9417, STA-9259).

Visual Proof

N/A: no behavior or UI change; nothing in the app uses the new code yet.

Testing

  • pnpm tc and oxlint on the changed files pass after merging current main.

  • Save-hook test on a real Store: the same sequence of writes (bind a pane, split, write to an SSH host's rows, a failed write that rolls back, remove the worktree) is run with no observer, with a publisher attached, and with an observer that throws. The saved state is identical in all three, and the throwing observer is logged once. The attached publisher sees each committed change, including the rollback and the removal, in increasing sequence order.

  • Publisher and snapshot unit tests: first flush, one push per burst, catching in-place edits while ignoring equal or display-only rewrites, the empty snapshot on removal, sequence ordering, and a throwing send function.

  • npx vitest run --config config/vitest.config.ts on the three new test files: 12 tests pass.

  • I manually tested these changes locally

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

Not manually tested in the app: no code path in the app reaches the publisher yet.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Cost with no observer registered: one empty-set loop per save.
  • Known limits for the PR that connects it: a folder workspace whose connection is ambiguous can make the snapshot source throw, which the publisher logs and skips; a worktree with rows in both the local and an SSH host's partition publishes only the owning partition.
  • Changes outside both save paths are harmless here: the load-time sweep (runs before anything could be sent), offline profile documents, and the background scrollback swap (scrollback is not part of the snapshot).

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)

…on write

Adds a by-value projection of each worktree's persisted terminal topology and a
publisher hooked on the two persistence funnels (scheduleSave and durable
mutations). Changed slices are pushed to the local window on
session:terminal-topology-changed with a monotonic publishSeq; a startup pull
(session:get-terminal-topology-slices) and publishSeq on pty:spawn and
session:close-terminal-surface replies are in place. No renderer consumer yet,
so behavior and saved state are unchanged. Observer failures are counted and
logged once and never reach the save.
…r pulls

Writes now cost nothing extra until the first session:get-terminal-topology-slices
pull (or subscribe()) takes the baseline; markDirty before that is a no-op.
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8e4087e6-e9d6-48a3-902c-a16e79568e8f
📥 Commits

Reviewing files that changed from the base of the PR and between ec15853 and b7b7966.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d0a37354-ae66-4809-9873-d835acf23e09
📥 Commits

Reviewing files that changed from the base of the PR and between d3a94dd and ec15853.

📒 Files selected for processing (5)
  • src/main/persistence/loading-store/workspace-session-write-listeners.test.ts
  • src/main/persistence/loading-store/workspace-session-write-listeners.ts
  • src/main/runtime/terminal-topology-projection.ts
  • src/main/runtime/terminal-topology-publisher.test.ts
  • src/main/runtime/terminal-topology-publisher.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.


📝 Walkthrough

Walkthrough

The change adds shared types and projection helpers for worktree terminal-topology slices. It adds workspace-session write listeners and notifies them during write scheduling and admitted mutation callbacks. A publisher reconciles projected slices, assigns publication sequence numbers, and sends changed or removed worktree slices to a sink. Tests cover projection, listener behavior, publication sequencing, and failure handling.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to ec158

A temporary topology-publication failure can leave a snapshot stale until another write. The write path remains protected, but the publication gap warrants owner awareness before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to ec158

The change has a limited recovery risk when delivery fails. It is not connected to a live reader in this revision, and no new attacker-accessible path was established.

Retained concerns

  • Low · reliability · inferred: Reconciliation caches changed snapshots and deletes removed entries before invoking the sink. If the sink throws, a later identical reconciliation will not retry that update or removal, and settle can return a sequence that was not delivered. A failed rollback or removal publication can therefore leave a consumer's binding or ownership view stale. This newly introduced recovery weakness has only test callers at the reviewed head; no live security impact was established.
Security review details

Security Blast Radius

  • inferred — If connected, the sink can receive slices for every worktree and host partition returned by the injected owner reader, not merely one requesting worktree. No production sink or attacker-controlled route to this publication capability was identified at the reviewed head.

Trust Boundaries and Controls

  • observed — Projection carries the caller-supplied host identity and reads the caller-supplied session. Worktree filtering is a data-selection control, not recipient authorization or proof that the supplied host owns that session. Production owner resolution and recipient authorization are not supplied by this component.

Resilience and Maintainability Implications

  • observed — Publisher projection and sink exceptions are caught outside the persistence callback and warned once. The observer mechanism itself invokes callbacks synchronously without exception isolation and explicitly requires them not to throw or block. The inspected throwing-mode integration scenario throws from the sink, not directly from an observer; it does not establish notifier-wide failure containment.

Hardening Proposals

  • proposed — Before enabling production delivery, define recipient authorization for the host/worktree scope and decide whether readers need complete sleeping-agent records or a narrower projection. This addresses the proposed data boundary; it is not an observed disclosure finding.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 18 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the terminal-layout projection and states that no reader is included yet. It matches the main scope of the changes.
Description check ✅ Passed The description covers the required sections, explains the changes and rationale, reports testing, and marks visual proof as not applicable because there is no user-visible change. The linked-issue se…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · 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.

🧹 Nitpick comments (1)
src/main/runtime/terminal-topology-publisher.ts (1)

72-78: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Do not return lastSeq on the sinkless read path.

With no sink, readSlices projects live state and stamps every slice with this.lastSeq. setSink(null) clears published but keeps lastSeq. A worktree that changed after the last push can therefore come back with a publishSeq that equals an earlier push for different content. A reader keeps the highest publishSeq per worktree, so a later push could carry a value it treats as already seen. This path is reachable only during the no-window gap, and that gap has no IPC reader today. Increment the sequence for each slice on this path, or document that this path is unsequenced.

Proposed fix
       return [...this.readOwners()].map(([worktreeId, owner]) => ({
         ...projectTerminalTopologySlice(owner.session, owner.hostId, worktreeId),
-        publishSeq: this.lastSeq
+        publishSeq: ++this.lastSeq
       }))

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8c1b2e24-898e-4feb-a6ca-af9fc9a9070f
📥 Commits

Reviewing files that changed from the base of the PR and between e9ed75a and 4f780d5.

📒 Files selected for processing (18)
  • src/main/ipc/pty/ipc/spawn.ts
  • src/main/ipc/session.ts
  • src/main/persistence/loading-store/primary-state-write-runtime.ts
  • src/main/persistence/loading-store/primary-state-writes.ts
  • src/main/persistence/loading-store/store-runtime-state.ts
  • src/main/persistence/loading-store/workspace-session-write-listeners.test.ts
  • src/main/persistence/loading-store/workspace-session-write-listeners.ts
  • src/main/persistence/loading-store/write-scheduling.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/runtime-notifier-contract.ts
  • src/main/runtime/runtime-store-contract.ts
  • src/main/runtime/runtime-workspace-session-controller.ts
  • src/main/runtime/terminal-topology-projection.test.ts
  • src/main/runtime/terminal-topology-projection.ts
  • src/main/runtime/terminal-topology-publisher.test.ts
  • src/main/runtime/terminal-topology-publisher.ts
  • src/main/window/runtime-window-lifecycle.ts
  • src/shared/terminal-topology-slice.ts

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

@pullfrog pullfrog 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.

ℹ️ No blocking issues — the change is correctly dormant and the save-funnel census checks out. Two latent contract gaps in the publisher are worth tightening before the reader lands; both are inline.

Reviewed changes

  • New snapshot type and projection — src/shared/terminal-topology-slice.ts and src/main/runtime/terminal-topology-projection.ts: a per-worktree view of main's topology (tabs with topology/creation fields only, layout root/ptyIdsByLeafId/titlesByLeafId, sleeping records, per-repo revision), read only from the partition that owns the worktree.
  • Dormant publisher — src/main/runtime/terminal-topology-publisher.ts: coalesces session writes via queueMicrotask, diffs by value (isDeepStrictEqual against structuredCloned snapshots), pushes changed and removed slices with a monotonic publishSeq, and stays off until the first pull/subscribe.
  • Runtime wiring — src/main/runtime/orca-runtime.ts: constructs the publisher, registers store.onWorkspaceSessionWritten(() => markDirty()), binds the sink from setNotifier to the local window, and exposes settleTerminalTopology / getTerminalTopologySlices.
  • Save-funnel observer — workspace-session-write-listeners.ts plus hooks in write-scheduling.ts (domain-filtered) and primary-state-writes.ts (runDurableMutation finally, covering rollback); listener throws are caught and logged once so a save is never affected.
  • Local IPC — session:get-terminal-topology-slices pull, session:terminal-topology-changed push, and an optional publishSeq on the pty:spawn and session:close-terminal-surface replies.
  • Tests — projection and publisher unit tests (batching, in-place change detection, removal, seq ordering, dormant mode) and an inertness test asserting saved state and write order are identical with/without the observer, including a throwing observer.

I also verified independently and via a census of main-process writers that no path mutates in-snapshot topology without passing through scheduleSave or runDurableMutation: the two documented bypasses (async scrollback swap, offline profile documents) touch fields the projection never reads, and the load-time sweep reaches scheduleSave before the listener is registered, so it is an inert no-op.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

if (!this.dirty) {
return
}
this.dirty = false

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.

flush() clears dirty before the guarded reconcile runs. If readOwners() or a projection throws — the PR body documents ambiguous-folder owner resolution as exactly this trigger — the whole reconcile aborts after dirty is already false, and no retry is armed. That burst's topology changes are never pushed (and reconcile is all-or-nothing, so healthy worktrees in the same pass are dropped too); publishing only resumes on the next write, which may never come once the layout has settled.

Technical details
# A projection/owner-read throw consumes `dirty` and loses the burst

## Affected sites
- `src/main/runtime/terminal-topology-publisher.ts:58-64` — `flush()` sets `dirty = false` before `guard(() => this.reconcile(true))`.
- `src/main/runtime/terminal-topology-publisher.ts:84-109` — `reconcile` iterates all owners in one pass and aborts on the first throw.
- `src/main/runtime/terminal-topology-publisher.ts:116-126` — `guard` swallows the throw.

## Required outcome
- A transient projection/owner-read failure should not silently lose the changes it prevented from being published; publishing should not require an unrelated later write to resume.

## Suggested approach
- Keep `dirty` set until `reconcile` succeeds, or re-arm a bounded retry on failure. A naive unconditional re-queue could spin while the ambiguity persists, so gate it.

Jinwoo-H and others added 5 commits October 5, 2026 18:45
…r and save hook

Drop the window sink, pull handler and publishSeq replies; no listener attaches
in production. Filter sleeping records by worktree id only, and guard observer
failures once inside the publisher.

Co-Authored-By: Claude <[email protected]>
@Jinwoo-H Jinwoo-H changed the title refactor(terminal): publish main's terminal layout after each save (dormant until read) refactor(terminal): project main's terminal layout after each save (no reader yet) Oct 6, 2026

@pullfrog pullfrog 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.

ℹ️ No critical issues — this delta narrows the PR to an unwired publisher plus the dormant save hook. One failure-ordering gap is inline; the earlier flush() concern remains open.

Reviewed changes

  • Runtime wiring removed — OrcaRuntimeService no longer constructs the publisher, binds a sink from setNotifier, or exposes settleTerminalTopology/getTerminalTopologySlices; the IPC pull/push channels, notifier/store contracts, and window-lifecycle send are gone. The publisher is now an unwired class whose sink arrives via the constructor.
  • Publisher API reworked — dropped setSink, subscribe, readSlices, and failureCount; WorkspaceSessionOwner moved here from RuntimeWorkspaceSessionController, and the "dormant until a reader subscribes" state is gone.
  • Save hook simplified — notifyWorkspaceSessionWritten no longer short-circuits on an empty listener set and no longer catches listener throws; the publisher's own flush guard logs the first failure instead.
  • Sleeping-record projection narrowed — only records whose worktreeId matches the worktree are included; the paneKey tab-prefix fallback was removed.
  • Tests reworked to the new API: first-flush publishing, per-burst coalescing, in-place edits, removal, monotonic publishSeq, and a throwing sink/projection.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +79 to +87
for (const snapshot of removed) {
this.published.delete(snapshot.worktreeId)
this.send({ publishSeq: ++this.lastSeq, snapshot })
}
for (const snapshot of changed) {
const entry = { publishSeq: ++this.lastSeq, snapshot }
this.published.set(snapshot.worktreeId, entry)
this.send(entry)
}

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.

reconcile commits the published entry (or deletes it for a removal) before send runs, and send is no longer individually guarded. A throwing sink therefore aborts the rest of the pass and, worse, records the failed slice as already published — a removal is deleted from published outright — so it is never re-sent unless that worktree changes again. The logs a throwing sink or projection once test drives this exact path but only asserts the warning count, so it passes with the slice silently lost.

Technical details
# A throwing sink marks the undelivered slice as published

## Affected sites
- `src/main/runtime/terminal-topology-publisher.ts:79-87` — `published.delete` / `published.set` run before `this.send(...)`, and `send` throws straight into `flush`'s guard.

## Required outcome
- A slice whose `send` throws must not be recorded as delivered, so a later flush can retry it, and one failing send must not drop the other worktrees in the same pass.

@Jinwoo-H
Jinwoo-H merged commit 66c775f into main Oct 7, 2026
39 checks passed
Jinwoo-H added a commit that referenced this pull request Oct 9, 2026
…heck (#26964)

* feat(layout): read-only layout.subscribe stream and the round-trip self-check (inert)

- layout.subscribe streams each workspace's layout as an explicit published projection
  (tabs, groups, panes and their terminals), never the model itself: no runtime records,
  closed-tab records, spawn inputs or legacy persistence values. It is re-projected from the
  Store's sessions after each write, only while someone subscribes, and only from the
  partition that owns each workspace. Not advertised as a capability and not on the mobile
  allowlist, so nothing calls it yet.
- Replaces the unused terminal-topology publisher (#25682) it generalizes.
- The round-trip self-check: a partition must load and save to a fixed point, changing only
  the kinds of value the Loader's rules change. It runs on Store writes in dev and e2e (logged,
  never thrown) and as the oracle's new roundTrip check.

* fix(layout): know the spawn handoff main's minimal row mint stores

* fix(layout): name-based invented ids, no partition on the wire, isolated listeners

- Every id the Loader invents is derived from what it stands in for (a workspace's group from
  its key, a pane from its row or tab and position, a repeated tab id from its terminal), so
  removing an earlier workspace or tab no longer re-ids later ones.
- The published layout no longer names its partition: the workspace key is the address and
  routing stays with the host; each tab still names the host that runs it.
- One throwing stream listener no longer costs the others the event.
- The self-check says plainly it is an idempotence check, and logs each new kind of first-load
  change with its count.
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