Mobile improvements: scrollback hydration, keyboard layout, and worktree-creation polish (#1423)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -0,0 +1,651 @@
|
||||
# Mobile scrollback parity: hydrate headless emulator from renderer on first PTY data
|
||||
|
||||
## Problem
|
||||
|
||||
When a mobile companion client subscribes to a terminal, it sees substantially less scrollback than the desktop renderer for the same PTY. In the worst case observed (a `claude`-then-shell session in the `edit-issues` worktree), the desktop shows ~30 lines of post-exit agent summary while mobile shows a single bare prompt.
|
||||
|
||||
The mismatch is reproducible and not a transient race: it persists across resubscribes, app return-from-background, and PTY-clean shell prompts.
|
||||
|
||||
## Where data lives today
|
||||
|
||||
Two separate xterm.js instances exist for every connected PTY:
|
||||
|
||||
1. **Renderer xterm** — owned by `TerminalPane` in the renderer process. Created when the user mounts the pane. Listens to `pty:data` IPC for the lifetime of the pane. 50,000-row scrollback. Source of truth for the visible desktop terminal.
|
||||
|
||||
2. **Runtime headless emulator** — `HeadlessEmulator` in `src/main/runtime/orca-runtime.ts`. Created lazily on first `runtime.onPtyData(ptyId, …)` call. 5,000-row scrollback. Used to serve `terminal.read`, `terminal.subscribe`, `lastAgentStatus`, and TUI-idle detection. This is what mobile, the CLI, and any non-renderer consumer get.
|
||||
|
||||
| Consumer | Reads from | Lifetime |
|
||||
|---|---|---|
|
||||
| Desktop pane | Renderer xterm | Pane mount → unmount |
|
||||
| Mobile (`terminal.subscribe`) | Headless emulator (primary), renderer (fallback) | Runtime startup → PTY exit |
|
||||
| `terminal.read` (CLI / agent) | Headless emulator | Runtime startup → PTY exit |
|
||||
| `lastAgentStatus` | Headless emulator (via OSC detection on `onPtyData`) | Runtime startup → PTY exit |
|
||||
|
||||
The two xterms are fed by the same provider stream but are "born" at different moments:
|
||||
|
||||
- The renderer xterm gets hydrated on attach via cold-restore data (`result.coldRestore.scrollback`) or warm reattach (`result.snapshot`) in `pty-connection.ts`, plus all live bytes since.
|
||||
- The headless emulator only sees bytes that flow through `runtime.onPtyData` since *runtime* startup. After an Orca relaunch, the headless emulator starts empty and only catches up on new live data; it never replays the cold-restore payload.
|
||||
- Commit `8a5ea4b7` added `seedHeadlessTerminal(ptyId, data, size?)` which runs from `ipc/pty.ts` on `provider.spawn` and seeds the emulator from `result.snapshot` / `result.coldRestore.scrollback`. That helps daemon-restored sessions but **does not help when the daemon's persisted state is itself near-empty** — the `edit-issues` reproduction has `checkpoint.json` with `scrollbackAnsi: ""` because the daemon checkpoint only stores the visible screen, not real scrollback.
|
||||
|
||||
So the dominant residual case is: daemon checkpoint is near-empty, the user opens a desktop pane (which hydrates from the live PTY post-spawn and accumulates a rich 50k-row buffer), then the user opens mobile — and mobile reads from the headless emulator, which has only seen bytes since runtime startup with nothing to replay.
|
||||
|
||||
## Goal
|
||||
|
||||
Mobile, CLI, and `lastAgentStatus` should display the same scrollback as the desktop renderer for any PTY whenever the user has a desktop pane mounted for it. The fix must:
|
||||
|
||||
- Be a small, targeted change to the runtime (no daemon, IPC schema, or persistence-format changes).
|
||||
- Not regress the "no desktop pane mounted" cases (background terminals, headless agent runs, CLI on a freshly-restored daemon).
|
||||
- Not introduce reflow / SGR drift between desktop and mobile.
|
||||
- Not introduce a per-keystroke or per-subscribe renderer round-trip on the hot path.
|
||||
- Reinforce — not violate — the existing invariant that the main process is authoritative for terminal state served to mobile/CLI/`terminal.read`.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **Mobile-only-after-relaunch (Scenario A).** A user who relaunches Orca and opens mobile *without* ever opening the desktop pane will still see only what the daemon checkpoint stored (often the visible screen and nothing more). Solving this requires daemon-side persisted scrollback, which is a separate, larger effort with its own privacy, format-stability, retention, and IO-cost considerations. This design explicitly does not solve Scenario A.
|
||||
- Persisting full scrollback to disk (the "option 2" architecture).
|
||||
- Unifying the renderer and headless emulators into a single main-process service.
|
||||
- Changing mobile's xterm-side replay logic. Today it correctly handles either source.
|
||||
- Changing the read-priority order in `serializeTerminalBufferFromAvailableState`. Headless stays primary; renderer stays the no-headless fallback.
|
||||
|
||||
## Proposed change
|
||||
|
||||
When the runtime first sees `pty:data` for a `ptyId` that already has a renderer pane registered (detected via a new `ptyController.hasRendererSerializer(ptyId)` predicate, backed by the `serializersByPtyId` registry in `pty-buffer-serializer.ts`), perform a one-time IPC round-trip to the renderer, get its serialized buffer, and seed the headless emulator with it **before** writing the live byte that just arrived. Subsequent `pty:data` calls for the same `ptyId` skip hydration via a per-PTY guard. If no renderer serializer is registered yet on the first byte, the guard is left absent so a later byte can retry once the pane mounts.
|
||||
|
||||
This is structurally the same operation `seedHeadlessTerminal` already does on `provider.spawn` from daemon-restored state. The new path covers the gap the existing seeding doesn't: the renderer has a richer buffer than the daemon does, and we want that richer buffer mirrored into the headless emulator on first runtime touch.
|
||||
|
||||
After hydration, all consumers (`terminal.read`, `terminal.subscribe`, `lastAgentStatus`, mobile, CLI) get the same fuller scrollback through the existing read paths. No priority flip is required. No per-consumer fallback. No per-subscribe IPC.
|
||||
|
||||
### System context — before
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Renderer process │
|
||||
│ │
|
||||
│ TerminalPane → xterm.js (50k rows) │
|
||||
│ ▲ │
|
||||
│ │ replayIntoTerminal(coldRestore. │
|
||||
│ │ scrollback) on pane mount │
|
||||
│ │ + live pty:data writes │
|
||||
└─────┼───────────────────────────────────────┘
|
||||
│
|
||||
pty:data│IPC
|
||||
│
|
||||
┌─────┴───────────────────────────────────────┐
|
||||
│ Main process │
|
||||
│ │
|
||||
│ ipc/pty.ts (provider.spawn) │
|
||||
│ ├─→ seedHeadlessTerminal(snapshot) │
|
||||
│ │ ↓ │
|
||||
│ │ HeadlessEmulator (5k rows) ───┐ │
|
||||
│ │ ▲ │ │
|
||||
│ │ │ trackHeadlessTerminalData│ │
|
||||
│ │ │ on every onPtyData │ │
|
||||
│ └─→ runtime.onPtyData(...)────────┘ │
|
||||
│ ▼ │
|
||||
│ serializeHeadless │
|
||||
│ (primary read source) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ mobile / CLI / lastStatus │
|
||||
└─────────────────────────────────────────────┘
|
||||
▲
|
||||
pty:data│from daemon
|
||||
│
|
||||
┌─────┴───────────────────────────────────────┐
|
||||
│ Daemon │
|
||||
│ checkpoint.json (visible screen only) │
|
||||
└─────────────────────────────────────────────┘
|
||||
|
||||
Bug: when daemon checkpoint is near-empty but the renderer xterm has
|
||||
accumulated a rich live buffer, mobile reads from the headless emulator
|
||||
which only saw bytes since runtime startup — and so sees less than desktop.
|
||||
```
|
||||
|
||||
### System context — after
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Renderer process │
|
||||
│ │
|
||||
│ TerminalPane → xterm.js (50k rows) │
|
||||
│ │ ▲ │
|
||||
│ │ │ unchanged hydration path │
|
||||
│ │ └─── live pty:data writes │
|
||||
│ │ │
|
||||
│ │ ptyController.serializeBuffer(ptyId) │
|
||||
│ │ called ONCE per (ptyId, runtime) │
|
||||
│ │ on first onPtyData │
|
||||
│ ▼ │
|
||||
└─────┼───────────────────────────────────────┘
|
||||
│
|
||||
pty:data│IPC + one-time serialize round-trip
|
||||
│
|
||||
┌─────┴───────────────────────────────────────┐
|
||||
│ Main process │
|
||||
│ │
|
||||
│ onPtyData(ptyId, data) (first time) │
|
||||
│ ├─→ if ptyController.serializeBuffer │
|
||||
│ │ returns non-empty: │
|
||||
│ │ hydrateHeadlessFromRenderer → │
|
||||
│ │ seedHeadlessTerminal(rendered) │
|
||||
│ │ mark hydrated │
|
||||
│ ├─→ trackHeadlessTerminalData(data) │
|
||||
│ │ (chained via writeChain after seed) │
|
||||
│ │ │
|
||||
│ HeadlessEmulator (5k rows, now seeded │
|
||||
│ with renderer's view) │
|
||||
│ ↓ │
|
||||
│ serializeHeadless (UNCHANGED PRIMARY) │
|
||||
│ ↓ │
|
||||
│ mobile / CLI / lastAgentStatus / read │
|
||||
└─────────────────────────────────────────────┘
|
||||
|
||||
Read priorities are unchanged. Headless emulator is still the primary
|
||||
source of truth; renderer is consulted exactly once, at hydration time,
|
||||
not per consumer or per subscribe.
|
||||
```
|
||||
|
||||
### Ordering invariant (DO NOT REORDER)
|
||||
|
||||
In `onPtyData(ptyId, data, at)`, the call sequence is:
|
||||
|
||||
```ts
|
||||
this.agentDetector?.onData(ptyId, data, at)
|
||||
this.maybeHydrateHeadlessFromRenderer(ptyId) // ← MUST come BEFORE
|
||||
this.trackHeadlessTerminalData(ptyId, data) // ← this line
|
||||
```
|
||||
|
||||
**`maybeHydrateHeadlessFromRenderer` MUST be invoked before `trackHeadlessTerminalData`.** If reordered, `trackHeadlessTerminalData`'s lazy-create branch will populate `headlessTerminals` with a fresh empty emulator first, and `maybeHydrateHeadlessFromRenderer`'s `!headlessTerminals.has(ptyId)` precondition (the "live bytes already arrived" guard) will short-circuit — silently disabling hydration for the lifetime of the PTY. There is no test that catches this regression cheaply (the failure mode is "less scrollback than expected", which is the original bug); the guarantee lives in the call-site comment in `orca-runtime.ts`.
|
||||
|
||||
A `// DO NOT REORDER — see "Ordering invariant" in mobile-prefer-renderer-scrollback.md` comment is mandatory at this call site.
|
||||
|
||||
### Pseudocode
|
||||
|
||||
```ts
|
||||
// Per-PTY hydration tracker. Key absent = idle (next byte may attempt).
|
||||
// 'pending' = round-trip in flight; 'done' = succeeded or unrecoverably
|
||||
// finished; 'skipped' is no longer used — instead we leave the key absent
|
||||
// when the precondition fails so a later byte can retry.
|
||||
private headlessHydrationState = new Map<string, 'pending' | 'done'>()
|
||||
|
||||
onPtyData(ptyId: string, data: string, at: number): void {
|
||||
this.agentDetector?.onData(ptyId, data, at)
|
||||
this.maybeHydrateHeadlessFromRenderer(ptyId)
|
||||
this.trackHeadlessTerminalData(ptyId, data)
|
||||
// …existing OSC / tail / leaf bookkeeping unchanged
|
||||
}
|
||||
|
||||
private async maybeHydrateHeadlessFromRenderer(ptyId: string): Promise<void> {
|
||||
if (this.headlessHydrationState.has(ptyId)) return
|
||||
if (this.headlessTerminals.has(ptyId)) {
|
||||
// Live bytes already arrived for this ptyId — re-seeding now would
|
||||
// duplicate them. Mark done; never retry. (Daemon-snapshot seeding
|
||||
// is handled separately: see "Cooperation with seedHeadlessTerminal"
|
||||
// — that path is gated on `!hasRendererSerializer(ptyId)` so it does
|
||||
// not pre-empt this hydration when a renderer pane is mounted.)
|
||||
this.headlessHydrationState.set(ptyId, 'done')
|
||||
return
|
||||
}
|
||||
// Why: leave the state absent (not 'done') when there's no renderer
|
||||
// serializer or controller. The pane may mount one byte later; the
|
||||
// next onPtyData call gets another chance. This is the contract change
|
||||
// motivated by Open Question P2-2.
|
||||
if (!this.ptyController?.serializeBuffer) return
|
||||
if (!this.ptyController.hasRendererSerializer?.(ptyId)) return // not yet registered
|
||||
|
||||
this.headlessHydrationState.set(ptyId, 'pending')
|
||||
|
||||
// Why: eagerly create the headless state at PTY dims so concurrent live
|
||||
// writes from trackHeadlessTerminalData chain onto the same writeChain.
|
||||
// This matches seedHeadlessTerminal's pattern (orca-runtime.ts:780-803);
|
||||
// without it, a live byte arriving during the serializeBuffer await would
|
||||
// lazy-create a separate state that we'd later overwrite, dropping the
|
||||
// live byte.
|
||||
const dims = this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 }
|
||||
const state: RuntimeHeadlessTerminal = {
|
||||
emulator: new HeadlessEmulator({ cols: dims.cols, rows: dims.rows }),
|
||||
writeChain: Promise.resolve()
|
||||
}
|
||||
this.headlessTerminals.set(ptyId, state)
|
||||
|
||||
// Why: append the renderer-fetch + seed-write to the chain. Live writes
|
||||
// that arrive before the chain head resolves are queued behind it via
|
||||
// trackHeadlessTerminalData's existing `state.writeChain.then(...)` pattern.
|
||||
state.writeChain = state.writeChain.then(async () => {
|
||||
try {
|
||||
const rendered = await this.ptyController!.serializeBuffer!(ptyId, {
|
||||
scrollbackRows: MOBILE_SUBSCRIBE_SCROLLBACK_ROWS,
|
||||
altScreenForcesZeroRows: true
|
||||
})
|
||||
if (!rendered || rendered.data.length === 0) {
|
||||
this.headlessHydrationState.set(ptyId, 'done')
|
||||
return
|
||||
}
|
||||
// Why: resize to the renderer's reported dims before writing the seed
|
||||
// so the serialized layout reflows correctly. Then resize back to the
|
||||
// PTY's current dims after the seed lands so subsequent live writes
|
||||
// use the right cell grid.
|
||||
state.emulator.resize(rendered.cols, rendered.rows)
|
||||
await state.emulator.write(rendered.data)
|
||||
const ptyDims = this.getTerminalSize(ptyId)
|
||||
if (ptyDims && (ptyDims.cols !== rendered.cols || ptyDims.rows !== rendered.rows)) {
|
||||
state.emulator.resize(ptyDims.cols, ptyDims.rows)
|
||||
}
|
||||
// Why: status parity. SerializeAddon does NOT round-trip OSC 0/1/2
|
||||
// title bytes, so extracting from rendered.data would always be null.
|
||||
// applySeededAgentStatus runs detectAgentStatusFromTitle and writes
|
||||
// leaf.lastAgentStatus only when the result is non-null; it MUST NOT
|
||||
// call resolveTuiIdleWaiters or deliverPendingMessages because seed-
|
||||
// derived status reflects historical state.
|
||||
if (rendered.lastTitle) {
|
||||
this.applySeededAgentStatus(ptyId, rendered.lastTitle)
|
||||
}
|
||||
} catch {
|
||||
// Hydration is best-effort. Live writes continue via the same
|
||||
// writeChain that this catch-arm leaves intact.
|
||||
} finally {
|
||||
this.headlessHydrationState.set(ptyId, 'done')
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Eager-state ordering invariant.** Even though the chain head blocks live writes until the seed completes, the LIVE BYTE ITSELF (the one that triggered `onPtyData`) is enqueued onto `state.writeChain` BY `trackHeadlessTerminalData` AFTER `maybeHydrateHeadlessFromRenderer` returns synchronously and registers its seed-write link. The live byte's chain link executes after the seed-write resolves. That is the ordering invariant the eager-state pattern preserves.
|
||||
|
||||
**Resize-during-hydration note.** `resizeHeadlessTerminal` (orca-runtime.ts:828) deliberately bypasses `writeChain` and calls `state.emulator.resize(...)` directly — that's existing behavior we preserve. If a `pty:resize` IPC arrives during the hydration window (between `headlessTerminals.set` and `seedPromise` resolution), the resize lands on the emulator while the seed-write is mid-flight; this can produce a one-frame visual artifact in the seed but cannot corrupt subsequent live writes (which the seed-then-resize-back invariant restores). The narrow window — typically <200ms — is bounded by the renderer-IPC round-trip duration.
|
||||
|
||||
The cap and alt-screen rule on the renderer side mirror `serializeHeadlessTerminalBuffer`: 1000-row limit on rehydration payload, force `scrollbackRows = 0` when the renderer xterm reports `buffer.active.type === 'alternate'`. This unifies semantics between hydration source and live-serialize source — the user sees the same depth regardless of which path served them, and an alt-screen TUI never bleeds normal-buffer scrollback into the seed.
|
||||
|
||||
### IPC contract changes
|
||||
|
||||
Hydration relies on the renderer-side serializer accepting an option bag. Today the chain is single-arg end to end, so changes must land in lockstep:
|
||||
|
||||
- `src/preload/index.ts` — the `pty:serializeBuffer:request` payload extends to `{ requestId, ptyId, opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean } }`. Renderer-side type for the listener callback widens accordingly.
|
||||
- `src/main/ipc/pty.ts` — `requestSerializedBuffer(ptyId, opts?)` accepts the opts object and forwards it on the IPC `webContents.send` payload. Snapshot-shape validation widens to accept an optional `lastTitle: string`. Existing 750 ms timeout unchanged.
|
||||
- `src/main/runtime/orca-runtime.ts` — the `RuntimePtyController.serializeBuffer?` signature widens to `(ptyId, opts?) => Promise<{ data: string, cols: number, rows: number, lastTitle?: string } | null>`. A new optional `hasRendererSerializer?(ptyId): boolean` lets the runtime check pane mount status before paying the IPC cost (implementation: a getter against `serializersByPtyId` in `pty-buffer-serializer.ts`).
|
||||
- `src/renderer/src/components/terminal-pane/pty-buffer-serializer.ts` — the registered `SerializeFn` widens to `(opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }) => Promise<{ data, cols, rows, lastTitle?: string } | null> | …`. The pane's serializer reads the opts: if `altScreenForcesZeroRows && pane.terminal.buffer.active.type === 'alternate'`, call `pane.serializeAddon.serialize({ scrollback: 0 })`; otherwise `pane.serializeAddon.serialize({ scrollback: opts?.scrollbackRows })`. The response payload includes `lastTitle: lastTitleByPtyId.get(ptyId)?.title` (omitted when no title has been observed for this PTY). Default behavior (no opts) preserves today's full-buffer serialize for any caller that hasn't migrated.
|
||||
- `serializeTerminalBufferFromAvailableState` (the renderer-fallback read path in `orca-runtime.ts:843`) forwards `scrollbackRows` so the fallback's depth matches the primary path. **It does NOT pass `altScreenForcesZeroRows: true`** — see "alt-screen flag scoping" below.
|
||||
|
||||
**alt-screen flag scoping (only on hydration path).** `altScreenForcesZeroRows: true` is passed ONLY by `maybeHydrateHeadlessFromRenderer` (the hydration path). The read-fallback path (`serializeTerminalBufferFromAvailableState`) passes `altScreenForcesZeroRows: false` (or omits the flag, default false). Reasoning:
|
||||
|
||||
- **Hydration:** wants the *normal* buffer's scrollback. xterm discards alt-screen content when alt-screen exits anyway, so suppressing scrollback during alt-screen prevents transient TUI bytes from bleeding into the seed that the headless emulator will hold for the rest of the session.
|
||||
- **Read fallback:** is invoked by `terminal.read` / `terminal.subscribe` for an actively-running TUI when the headless emulator returned null. The caller wants whatever is currently visible — including alt-screen content — so suppressing it would produce a worse result than today.
|
||||
|
||||
Both call sites pass explicit opts in the pseudocode (no implicit defaults relied on). The read-fallback shape:
|
||||
|
||||
```ts
|
||||
// In serializeTerminalBufferFromAvailableState (read-fallback):
|
||||
rendererSnapshot = await (this.ptyController?.serializeBuffer?.(ptyId, {
|
||||
scrollbackRows: opts.scrollbackRows,
|
||||
altScreenForcesZeroRows: false // read-fallback wants visible alt-screen content
|
||||
}) ?? Promise.resolve(null))
|
||||
```
|
||||
|
||||
### Renderer-side prerequisite
|
||||
|
||||
Today, `registerPtySerializer(ptyId, …)` is only called inside `handleReattachResult` (`pty-connection.ts:571`). Fresh spawns — the dominant case — never register, so `hasRendererSerializer(ptyId)` would always return false and hydration would no-op. The renderer change required:
|
||||
|
||||
- Move (or duplicate) the `registerPtySerializer` call so it fires for **both** reattach and fresh spawn paths. Cleanest shape: extract the body (closure capturing `pane`, `deps.pendingWritesRef`, `deps.replayingPanesRef`) into a `registerPaneSerializerFor(ptyId)` helper and call it from `handleReattachResult` AND from `startFreshSpawn`'s `.then(spawnedPtyId => …)` once a `ptyId` is known.
|
||||
- The helper accepts the new `opts` arg and threads it into `pane.serializeAddon.serialize({ scrollback: … })` per the IPC contract above.
|
||||
|
||||
**Cleanup contract & StrictMode safety.** Two requirements, both motivated by React 18 StrictMode double-mount and async pane disposal:
|
||||
|
||||
1. **`if (disposed) return` guard at the top of every post-spawn registration call** (both reattach and fresh-spawn paths). Rationale: StrictMode mounts the pane twice; the first mount is disposed before the second runs, but its `pty:spawn` IPC may have already resolved by the time `disposed` flips to true. Without the guard, the disposed first mount would call `registerPaneSerializerFor` after teardown — replacing the live registration from the second mount or registering a closure over a torn-down `pane.terminal`.
|
||||
|
||||
2. **Unregister via ownership token, not unconditional delete.** `serializersByPtyId` becomes `Map<ptyId, { fn: SerializeFn, owner: symbol }>`. Each call to `registerPtySerializer` mints a fresh `owner` symbol and returns an unregister closure that **only deletes the entry when the current entry's `owner === thisOwner`**. If a later registration has overwritten the entry (StrictMode second mount, fast pane swap), the unregister is a no-op so the live registration is preserved. The body of the unregister closure also clears any module-level state keyed off the same owner (lastTitle bookkeeping introduced below) AND disposes the xterm `onTitleChange` IDisposable that was installed at register time.
|
||||
|
||||
```ts
|
||||
export function registerPtySerializer(ptyId, fn): () => void {
|
||||
const owner = Symbol(ptyId)
|
||||
serializersByPtyId.set(ptyId, { fn, owner })
|
||||
ensureSerializerListener()
|
||||
return () => {
|
||||
const current = serializersByPtyId.get(ptyId)
|
||||
if (current?.owner === owner) {
|
||||
serializersByPtyId.delete(ptyId)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Spawn-rejection cleanup is mandatory.** The renderer MUST call `pty:clearPendingPaneSerializer(paneKey, gen)` from the catch-arm of `pty:spawn` AND from pane unmount AFTER pre-signal but BEFORE settle. Without this, a failed-spawn paneKey leaks a pending intent that suppresses the next legitimate daemon-snapshot seed for that paneKey.
|
||||
|
||||
4. **Pre-signal applies to BOTH fresh-spawn AND reattach paths.** `declarePendingPaneSerializer(paneKey)` is mandatory on both — mirroring the `registerPaneSerializerFor(ptyId)` requirement. Reattach paths today already register the serializer in `handleReattachResult`, but the pre-signal must also fire on the reattach path so the cooperation gate in `pty:spawn` behaves consistently regardless of whether the renderer is taking over a pre-existing PTY or a fresh one.
|
||||
|
||||
The `unregisterSerializer()` call is wired into `onDataDisposable.dispose` so the registration is torn down on pane unmount, regardless of which path registered it.
|
||||
|
||||
### Renderer pre-signal handshake
|
||||
|
||||
The cooperation gate (`ipc/pty.ts` skipping `seedHeadlessTerminal` when a renderer serializer is registered) has a fundamental timing problem on **fresh spawns**: the renderer cannot have registered the serializer for the new ptyId yet, because it doesn't know the ptyId until `pty:spawn` resolves. So at the moment the cooperation gate runs (immediately after `provider.spawn` returns inside `pty:spawn`'s handler), `runtime.hasRendererSerializerFor(ptyId) === false` for every fresh spawn — and the daemon-snapshot seed always wins, defeating the gate for the dominant case.
|
||||
|
||||
The renderer does, however, know its **paneKey** before spawn: every pane has a stable `ORCA_PANE_KEY` env var that is part of `args.env` on `pty:spawn`. We use the paneKey as a pre-signal, on a channel that doesn't depend on knowing the ptyId yet:
|
||||
|
||||
1. **Pre-signal IPC with generation token.** Renderer calls `pty:declarePendingPaneSerializer(paneKey)` BEFORE invoking `pty:spawn`. Main process maintains `pendingByPaneKey: Map<paneKey, generation: number>` keyed by paneKey. On each pre-signal, main mints a fresh monotonic `gen` value (incrementing a module-level `genSeq` counter) and overwrites the entry, then returns `gen` to the renderer. The renderer awaits this IPC (capturing `gen`), then awaits the spawn IPC — guaranteeing the main process has the pending intent recorded by the time `pty:spawn` runs.
|
||||
|
||||
```ts
|
||||
let genSeq = 0
|
||||
const pendingByPaneKey = new Map<string, number>() // paneKey -> generation
|
||||
|
||||
function declarePending(paneKey: string): number {
|
||||
const gen = ++genSeq
|
||||
pendingByPaneKey.set(paneKey, gen)
|
||||
return gen // returned to renderer, echoed back on settle/clear
|
||||
}
|
||||
|
||||
function settlePending(paneKey: string, gen: number): void {
|
||||
if (pendingByPaneKey.get(paneKey) === gen) pendingByPaneKey.delete(paneKey)
|
||||
}
|
||||
|
||||
paneKeyTeardownListeners.add((paneKey, gen) => settlePending(paneKey, gen))
|
||||
```
|
||||
|
||||
Why a generation counter: today's design hooks `pendingByPaneKey.delete(paneKey)` into `clearProviderPtyState` via `paneKeyTeardownListeners`. If the OLD PTY's `clearProviderPtyState` fires AFTER mount-2's pre-signal but BEFORE mount-2's spawn, an unconditional teardown deletes mount-2's pending entry — defeating the gate. The generation counter solves this: the `paneKeyTeardownListeners` wiring captures the generation at the time the old PTY was REGISTERED (via the existing `registerPty` call site) and the teardown only fires `settlePending` with that generation. If mount-2 has already replaced the entry with a new gen, `pendingByPaneKey.get(K) !== oldGen` and the teardown is a no-op.
|
||||
|
||||
2. **Cooperation gate consults the pre-signal.** Inside `pty:spawn`, after `provider.spawn` returns, the gate becomes:
|
||||
```ts
|
||||
const paneKey = args.env?.ORCA_PANE_KEY
|
||||
const rendererPreSignaled =
|
||||
typeof paneKey === 'string' && paneKey.length > 0 && paneKey.length <= 256
|
||||
&& pendingByPaneKey.has(paneKey)
|
||||
const rendererAlreadyRegistered =
|
||||
runtime?.hasRendererSerializerFor?.(result.id) ?? false
|
||||
if (!rendererPreSignaled && !rendererAlreadyRegistered) {
|
||||
// No renderer is or will be authoritative for this PTY — daemon-snapshot
|
||||
// seed runs as today.
|
||||
runtime?.seedHeadlessTerminal(result.id, /* …snapshot/coldRestore… */)
|
||||
}
|
||||
```
|
||||
The `rendererAlreadyRegistered` branch covers reattach, where the pane mounted before spawn returned and registration completed in the meantime. The `rendererPreSignaled` branch covers fresh spawn, where registration has not happened yet but is imminent. Note: the gate matches when `pendingByPaneKey.has(paneKey)` is true *regardless of generation*; the generation is only used by cleanup paths (teardown listeners, settle, clear) to prevent cross-generation deletion. **Invariant:** fresh-spawn always relies on the pre-signal branch (`hasRendererSerializerFor(ptyId)` is necessarily false at gate-time since the renderer hasn't received `ptyId` yet); the registered branch only fires for reattach where the pane mounted before spawn returned.
|
||||
|
||||
3. **Settle / clear (echo gen back).** After the spawn IPC resolves and the renderer calls `registerPtySerializer(ptyId, …)`, it calls `pty:settlePaneSerializer(paneKey, gen)` to remove the pending intent (echoing the `gen` value it captured from declarePending). The handler runs `settlePending(paneKey, gen)` which only deletes if the stored gen still matches. (The simpler "clear on first onPtyData" or "clear on receipt of `pty:registerPaneSerializer`" alternatives work too — the design picks the explicit `settle` IPC because it makes the contract auditable from the renderer side and avoids coupling main-process state to onPtyData flow.) On pane unmount or registration failure, the renderer also calls `pty:clearPendingPaneSerializer(paneKey, gen)` (sibling handler with the same `settlePending` semantics) to drop the pending intent.
|
||||
|
||||
**Sequence diagram (fresh spawn, happy path):**
|
||||
|
||||
```
|
||||
Renderer Main / ipc-pty.ts Runtime
|
||||
│ │ │
|
||||
│ pty:declarePendingPaneSerializer │ │
|
||||
│ (paneKey) ───────────────────────────▶│ pendingByPaneKey.set(K, gen) │
|
||||
│ ◀──────────────────────── ack(gen) ──│ │
|
||||
│ │ │
|
||||
│ pty:spawn(args incl. ORCA_PANE_KEY) ─▶│ │
|
||||
│ │ provider.spawn(...) → result │
|
||||
│ │ pendingByPaneKey.has(paneKey)│
|
||||
│ │ === true → SKIP │
|
||||
│ │ seedHeadlessTerminal │
|
||||
│ │ │
|
||||
│ ◀──────────────────────────── ptyId ──│ │
|
||||
│ │ │
|
||||
│ registerPtySerializer(ptyId, fn) │ │
|
||||
│ pty:settlePaneSerializer(paneKey, │ │
|
||||
│ gen) ──────────────────────────────▶│ settlePending(paneKey, gen) │
|
||||
│ │ if gen matches → delete │
|
||||
│ │ │
|
||||
│ │ first onPtyData(ptyId,data)──▶│
|
||||
│ │ │ maybeHydrateFromRenderer
|
||||
│ │ │ (headlessTerminals empty,
|
||||
│ │ │ hasRendererSerializer true
|
||||
│ │ │ → IPC round-trip → seed)
|
||||
```
|
||||
|
||||
**Renderer-side call shape.** The renderer threads `gen` through every call site so cleanup (settle/clear) can be matched against the generation it captured at declare time:
|
||||
|
||||
```ts
|
||||
// In pty-connection.ts startFreshSpawn / handleReattachResult:
|
||||
const gen = await window.api.pty.declarePendingPaneSerializer(paneKey)
|
||||
try {
|
||||
const ptyId = await window.api.pty.spawn(args)
|
||||
registerPaneSerializerFor(ptyId)
|
||||
await window.api.pty.settlePaneSerializer(paneKey, gen)
|
||||
} catch (err) {
|
||||
await window.api.pty.clearPendingPaneSerializer(paneKey, gen)
|
||||
throw err
|
||||
}
|
||||
```
|
||||
|
||||
**Correctness properties:**
|
||||
|
||||
1. **Pre-signal arrives before `pty:spawn`.** The renderer awaits the pre-signal IPC, then awaits the spawn IPC. Electron `ipcRenderer.invoke`/`send` ordering on a single renderer is preserved on the main side, so the main process processes the pre-signal before `pty:spawn`'s handler runs.
|
||||
2. **Missing paneKey degrades to today's behavior.** If `args.env?.ORCA_PANE_KEY` is absent (e.g., a pane that isn't yet wired to set it, an old renderer build, or a non-pane spawn path), the pre-signal lookup returns false, `rendererAlreadyRegistered` is also false on a fresh spawn, and the daemon-snapshot seed runs as today. No regression for callers that don't participate in the handshake.
|
||||
3. **Pre-signal without settle (renderer crashes between spawn and registerPtySerializer).** The pending intent stays in the map, but it has no observable effect: the cooperation gate already ran, so the daemon snapshot was suppressed; the headless emulator stays empty; the first `onPtyData` falls through `hasRendererSerializer(ptyId) === false` and hydration's precondition leaves the state map absent. `trackHeadlessTerminalData` then lazy-creates the emulator and live writes populate it. We lose the daemon snapshot for this PTY in that narrow window — accepted limitation, since the renderer was clearly going to be authoritative but didn't make it. (To bound staleness, the entry in `pendingByPaneKey` is cleared whenever a paneKey teardown event fires via the existing `paneKeyTeardownListeners` registry, gated by the generation token.)
|
||||
|
||||
**Files-touched implications:** see "IPC contract changes" and "Files touched" — both `pty:declarePendingPaneSerializer` and `pty:settlePaneSerializer` need preload bindings AND main handlers.
|
||||
|
||||
### Status parity
|
||||
|
||||
Seeding the emulator bypasses `onPtyData`'s OSC-extraction path, so without intervention `leaf.lastAgentStatus` stays whatever it was (typically `null` for daemon-restored leaves) until the next live byte happens to carry an OSC title. Mobile would then see a stale or missing agent badge despite a rich seed.
|
||||
|
||||
A previous draft of this design called `extractLastOscTitle(rendered.data)` on the seed payload to recover the title. **That doesn't work**: xterm's `SerializeAddon.serialize()` writes out the visible buffer as a stream of cursor moves, SGR resets, and printable characters — it does NOT round-trip OSC 0/1/2 (window/icon title) escape sequences. The renderer xterm consumes the OSC and sets `terminal.options.title`, but the bytes never appear in `serialize()`'s output. So `extractLastOscTitle` on a seed payload is dead code — it always returns null even when the renderer's pane currently shows a perfectly good title. We need the title via a different channel.
|
||||
|
||||
**Approach: ship now via IPC widening, document as best-effort.** The renderer pane already wires `pane.terminal.onTitleChange` (in `pty-connection.ts`) to keep the tab title in sync. We capture the latest observed title in module state alongside the serializer registration, and widen the serialize-buffer IPC payload to carry it back to main:
|
||||
|
||||
1. **Renderer side** (`pty-buffer-serializer.ts`):
|
||||
- Module-level `lastTitleByPtyId: Map<ptyId, { title: string, owner: symbol, disposable: IDisposable }>` keyed by the same ownership-token symbol as `serializersByPtyId` (see "Renderer-side prerequisite"). Populated by a wrapper around `pane.terminal.onTitleChange` installed at the same time as `registerPtySerializer`. The entry stores BOTH the IDisposable returned from `pane.terminal.onTitleChange(...)` AND the owner symbol alongside the latest title.
|
||||
- When the pane unregisters, the `unregisterSerializer` closure disposes the IDisposable AND deletes the map entry, both gated by the owner-token match — same ownership semantics as the serializer map, so a StrictMode disposed first-mount cannot wipe the live second-mount's title or leak a dangling listener.
|
||||
- The IPC response payload widens from `{ data, cols, rows }` to `{ data, cols, rows, lastTitle?: string }`. Default omitted when no title was observed for this PTY (e.g., fresh shell pre-prompt).
|
||||
|
||||
2. **Main side** (`ipc/pty.ts`, `orca-runtime.ts`):
|
||||
- `requestSerializedBuffer` snapshot-shape validation accepts `lastTitle?: string`.
|
||||
- `RuntimePtyController.serializeBuffer(ptyId, opts?)` returns `Promise<{ data, cols, rows, lastTitle?: string } | null>`.
|
||||
- `maybeHydrateHeadlessFromRenderer` calls `applySeededAgentStatus(ptyId, rendered.lastTitle)` only when `rendered.lastTitle` is a non-empty string (the helper itself also short-circuits on null/empty for safety). The helper internally runs `detectAgentStatusFromTitle` and only writes `leaf.lastAgentStatus` when the result is one of `'idle' | 'working' | 'permission'`.
|
||||
|
||||
3. **`applySeededAgentStatus(ptyId, title)`** (new helper in `orca-runtime.ts`). Behavior:
|
||||
- If `title == null` or empty, no-op.
|
||||
- Look up the leaf for `ptyId` via the existing pty→leaf mapping. Run `detectAgentStatusFromTitle(rendered.lastTitle)` (the helper from `src/shared/agent-detection.ts`). If the result is non-null, set `leaf.lastAgentStatus = result`. If null (title is not a recognizable agent title), leave `lastAgentStatus` untouched — the next live OSC byte will populate it through the normal onPtyData path.
|
||||
- **MUST NOT** call `resolveTuiIdleWaiters(leaf)` or `deliverPendingMessages(leaf)`. The seeded status reflects the renderer's last-observed historical title, not a live transition; resolving idle waiters or delivering pending messages on stale data could mistakenly unblock orchestration callers that should only react to a fresh prompt-return.
|
||||
- **Why** (mandatory comment in the helper definition): `// seed-derived status reflects historical state; orchestration waiters must only react to live transitions to avoid resolving on stale data.`
|
||||
- **Rationale for routing through `detectAgentStatusFromTitle`:** we mirror the live path (`onPtyData` already uses `detectAgentStatusFromTitle`) so seeded and live paths produce the same union value, and downstream `leaf.lastAgentStatus === 'idle'` consumers (orchestration `tui-idle` waiters, pending-message gating) keep working. `leaf.lastAgentStatus` is typed `AgentStatus | null` where `AgentStatus = 'working' | 'idle' | 'permission'`; assigning the raw title string would be type-incorrect.
|
||||
|
||||
This delivers status parity for the dominant case via the `lastTitle` field (any pane that has rendered a prompt or had a TUI emit OSC titles will have populated `lastTitleByPtyId` long before mobile subscribes). Edge cases where the renderer never observed a title — fresh shell pre-prompt, pane that mounted but never received bytes — leave `lastAgentStatus` as `null`; that's acceptable since `lastAgentStatus` is documented best-effort and the next live OSC title will populate it through the normal `onPtyData` path.
|
||||
|
||||
**Status parity / accepted limitations.** Side effect of seeding `lastAgentStatus`: if the seed sets status to `'idle'`, the next live OSC byte that re-emits the same `'idle'` title will see `prevStatus === 'idle'` and the existing transition gate (`agentStatus === 'idle' && prevStatus !== 'idle'`) skips. Orchestration `tui-idle` waiters registered between seeding and the next idle transition will hang until either (a) a non-idle status arrives followed by another idle transition, or (b) the waiter times out. This is an accepted limitation. If it becomes a real problem, future work could split into `lastSeededAgentStatus` (informational, not gating) vs `lastAgentStatus` (gates transitions).
|
||||
|
||||
### Files touched
|
||||
|
||||
- `src/main/runtime/orca-runtime.ts` — add `headlessHydrationState`, `maybeHydrateHeadlessFromRenderer`, wire into `onPtyData` (with mandatory `// DO NOT REORDER` comment per "Ordering invariant"). Widen `RuntimePtyController.serializeBuffer?` to `(ptyId, opts?) => Promise<{ data, cols, rows, lastTitle?: string } | null>` and add `hasRendererSerializer?(ptyId)`. Add `applySeededAgentStatus(ptyId, title)` helper that writes `leaf.lastAgentStatus` only — must NOT call `resolveTuiIdleWaiters` or `deliverPendingMessages` (mandatory "Why" comment in the helper definition). Add `hasRendererSerializerFor(ptyId)` runtime-service-level method that delegates to `ptyController.hasRendererSerializer` (consumed by `ipc/pty.ts`'s cooperation gate). Forward `scrollbackRows` from `serializeTerminalBufferFromAvailableState` into the renderer-fallback call (do NOT pass `altScreenForcesZeroRows: true` on this path — see "alt-screen flag scoping").
|
||||
- `src/main/ipc/pty.ts` — `requestSerializedBuffer(ptyId, opts?)` accepts opts and forwards them on the `pty:serializeBuffer:request` IPC payload. Wire `hasRendererSerializer` through a renderer-registry getter. **Cooperate with hydration:** when a renderer serializer is registered for the spawning PTY *or* the renderer pre-signaled intent for `args.env.ORCA_PANE_KEY`, skip seeding from `result.snapshot` / `result.coldRestore.scrollback` so the daemon's bare-prompt state cannot pre-empt the richer renderer hydration that follows on first byte. **Add three new IPC handlers** with consistent paneKey validation (`typeof paneKey === 'string' && paneKey.length > 0 && paneKey.length <= 256` — invalid input is rejected before mutating state): `pty:declarePendingPaneSerializer(paneKey): Promise<number>` (renderer → main, before `pty:spawn`) mints a fresh generation `gen`, stores `pendingByPaneKey.set(paneKey, gen)` in a module-level `pendingByPaneKey: Map<string, number>`, and returns `gen` to the renderer; `pty:settlePaneSerializer(paneKey, gen)` (renderer → main, after `registerPtySerializer`) runs `settlePending(paneKey, gen)` which deletes only if the stored gen still matches; `pty:clearPendingPaneSerializer(paneKey, gen)` (renderer → main, on spawn-rejection / unmount-before-settle) has the same `settlePending` semantics. Hook `paneKeyTeardownListeners.add((paneKey, gen) => settlePending(paneKey, gen))` so a torn-down PTY's listener captures the generation it was registered under and only clears the map when that generation still matches — ensuring a teardown for the OLD PTY cannot delete a NEW PTY's pending intent if mount-2's pre-signal landed in between. (See "Renderer pre-signal handshake" and "Cooperation with seedHeadlessTerminal" in Open questions.)
|
||||
- `src/preload/index.ts` — extend the `pty:serializeBuffer:request` listener payload type to include `opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }`. Add three new bindings under `pty`: `declarePendingPaneSerializer(paneKey: string): Promise<number>` (returns the `gen` token), `settlePaneSerializer(paneKey: string, gen: number): Promise<void>`, and `clearPendingPaneSerializer(paneKey: string, gen: number): Promise<void>`, all forwarded as `ipcRenderer.invoke('pty:declarePendingPaneSerializer', …)` / `'pty:settlePaneSerializer'` / `'pty:clearPendingPaneSerializer'` so the renderer can `await` them and rely on main-side ordering before issuing `pty:spawn` / after `registerPtySerializer`. The renderer captures `gen` from declare and threads it through every settle/clear call.
|
||||
- `src/renderer/src/components/terminal-pane/pty-buffer-serializer.ts` — widen `SerializeFn` to `(opts?) => Promise<{ data, cols, rows, lastTitle?: string } | null> | …`; default to today's full-buffer behavior when opts is absent. Convert `serializersByPtyId: Map<ptyId, SerializeFn>` to `Map<ptyId, { fn: SerializeFn, owner: symbol }>` and have `registerPtySerializer` mint a fresh owner symbol per call, returning an unregister closure that deletes only when `current?.owner === thisOwner` (StrictMode safety — see "Renderer-side prerequisite"). Add a parallel `lastTitleByPtyId: Map<ptyId, { title: string, owner: symbol, disposable: IDisposable }>` populated by a wrapper around `pane.terminal.onTitleChange`, with the unregister closure both disposing the IDisposable AND deleting the entry under the same owner-token check. The serialize listener reads from `lastTitleByPtyId` to populate `lastTitle` in the IPC response.
|
||||
- `src/renderer/src/components/terminal-pane/pty-connection.ts` — register the serializer for **fresh spawns** as well as reattach. Extract the registration body into a shared `registerPaneSerializerFor(ptyId)` helper called from both `handleReattachResult` AND the post-spawn callback in `startFreshSpawn`. Thread opts (scrollback cap, alt-screen flag) into `pane.serializeAddon.serialize`. Add `if (disposed) return` guard at the top of every post-spawn registration call (StrictMode safety — see "Renderer-side prerequisite"). Track the latest `pane.terminal.onTitleChange` value in module state alongside the serializer registration so the serializer's IPC response can include `lastTitle` (see "Status parity"). Call `const gen = await window.api.pty.declarePendingPaneSerializer(paneKey)` BEFORE `pty:spawn` on every fresh-spawn path (capturing the returned generation token), and `settlePaneSerializer(paneKey, gen)` AFTER `registerPaneSerializerFor(ptyId)` succeeds. On spawn-rejection (catch-arm) AND on pane unmount AFTER pre-signal but BEFORE settle, call `clearPendingPaneSerializer(paneKey, gen)` — this is mandatory (see "Renderer-side prerequisite" item 3). Unregister on pane unmount via the existing `onDataDisposable.dispose` hook (now using the ownership-token contract from "Renderer-side prerequisite").
|
||||
- `src/main/runtime/scrollback-limits.ts` (new) — main-process module exporting `MOBILE_SUBSCRIBE_SCROLLBACK_ROWS = 1000`. Imported by both `src/main/runtime/rpc/methods/terminal.ts` and `src/main/runtime/orca-runtime.ts`. (The constant is main-process-only; promoting it to `src/shared/` would expose a runtime cap to the renderer for no benefit.)
|
||||
- `src/main/runtime/orca-runtime.test.ts` — add hydration unit tests (see "Test plan").
|
||||
- `src/main/runtime/mobile-subscribe-integration.test.ts` — extend with cross-process hydration scenario.
|
||||
|
||||
No changes to:
|
||||
- `pty:data` batching, daemon adapter.
|
||||
- `serializeTerminalBufferFromAvailableState` priority order (headless still primary; renderer still no-headless fallback).
|
||||
- Mobile RPC method signatures (`terminal.subscribe`, `terminal.resizeForClient`).
|
||||
- Mobile WebView / `TerminalWebView.tsx`.
|
||||
- Persistence (`HistoryManager`, `checkpoint.json` shape).
|
||||
|
||||
## Why this is structurally sound
|
||||
|
||||
The renderer xterm is, in practice, the fuller and more authoritative state for any mounted pane:
|
||||
|
||||
1. **It hydrates on attach.** `pty-connection.ts` calls `replayIntoTerminal(pane, …, coldRestore.scrollback)` and writes `snapshot` immediately after pane mount. The headless emulator never replays either. So even on a session that started before the current Orca run, the renderer xterm contains the full history; the headless emulator does not.
|
||||
|
||||
2. **It has a bigger buffer.** 50,000 rows vs 5,000.
|
||||
|
||||
3. **It is updated on the same IPC tick as the visible UI.** No staleness vs what the user sees.
|
||||
|
||||
Hydrating the headless emulator from the renderer on first runtime touch is the same shape of operation as the existing `seedHeadlessTerminal(provider.spawn snapshot)` path. We are not introducing a new architectural pattern; we are extending an existing one to the case where the daemon snapshot is empty but the renderer is rich. The runtime remains authoritative for everything mobile, CLI, `terminal.read`, and `lastAgentStatus` see — the renderer is consulted exactly once per `(ptyId, runtime)` pair.
|
||||
|
||||
This is a structural-adjacent improvement that fixes the dominant case (user has both desktop and mobile open) while consciously deferring Scenario A (mobile-only after relaunch) to a separate daemon-persistence design. It is honest about what it does and does not solve.
|
||||
|
||||
## Data flow paths
|
||||
|
||||
### Happy path — renderer mounted, hydration succeeds
|
||||
|
||||
```
|
||||
T0 user opens desktop pane.
|
||||
- Fresh spawn: pty-connection.ts calls
|
||||
const gen = await pty:declarePendingPaneSerializer(paneKey)
|
||||
BEFORE pty:spawn, then awaits both. Main mints a fresh gen and
|
||||
records the pending intent under it. After spawn resolves with
|
||||
ptyId, registerPaneSerializerFor(ptyId) +
|
||||
pty:settlePaneSerializer(paneKey, gen) clear the intent (only if
|
||||
the stored gen still matches). On spawn-rejection or unmount-
|
||||
before-settle, pty:clearPendingPaneSerializer(paneKey, gen) runs
|
||||
instead (mandatory — see "Renderer-side prerequisite" item 3).
|
||||
- Reattach: registerPaneSerializerFor(ptyId) runs in
|
||||
handleReattachResult once the ptyId is known.
|
||||
Either way, ipc/pty.ts's cooperation gate sees that the renderer
|
||||
is or will be authoritative for this PTY (via either
|
||||
hasRendererSerializerFor(ptyId) === true OR a pre-signaled paneKey)
|
||||
and SKIPS the daemon-snapshot seedHeadlessTerminal call.
|
||||
T1 PTY emits live byte → ipc/pty.ts forwards to renderer (xterm grows)
|
||||
→ ipc/pty.ts forwards to runtime.onPtyData
|
||||
T2 onPtyData: maybeHydrateHeadlessFromRenderer
|
||||
- hasRendererSerializer(ptyId) === true → state: absent → pending
|
||||
- serialize round-trip with opts {scrollbackRows, altScreenForcesZeroRows}
|
||||
- on resolve: HeadlessEmulator built at rendered.cols/rows,
|
||||
applySeededAgentStatus(ptyId, rendered.lastTitle), write(rendered.data)
|
||||
- resize emulator to PTY dims if they diverge from rendered dims
|
||||
T3 trackHeadlessTerminalData(data) chains AFTER the seed via writeChain,
|
||||
so the live byte is appended on top of the seeded buffer — order
|
||||
preserved.
|
||||
T4 hydration state → done. Subsequent onPtyData calls skip the guard.
|
||||
T5 user opens mobile → terminal.subscribe → serializeHeadless returns
|
||||
seeded buffer + everything since. Mobile == desktop, and
|
||||
leaf.lastAgentStatus is populated from rendered.lastTitle
|
||||
(sourced from pane.terminal.onTitleChange, NOT from the seed payload —
|
||||
SerializeAddon does not round-trip OSC titles).
|
||||
```
|
||||
|
||||
### Nil path — Scenario A: no renderer ever mounts
|
||||
|
||||
```
|
||||
T0 user relaunches Orca, opens mobile only.
|
||||
T1 ipc/pty.ts: provider.spawn returns coldRestore.scrollback = ""
|
||||
(daemon checkpoint had scrollbackAnsi: "" — visible screen only)
|
||||
or a thin visible-screen snapshot. hasRendererSerializerFor(ptyId)
|
||||
is false (no pane mounted), so the cooperation gate does NOT skip:
|
||||
seedHeadlessTerminal runs as today.
|
||||
T2 PTY emits live byte → onPtyData → maybeHydrateHeadlessFromRenderer
|
||||
- hasRendererSerializer(ptyId) is false → state map left absent.
|
||||
(Pane could still mount later in this runtime; we'd retry then.)
|
||||
T3 trackHeadlessTerminalData populates from live bytes; emulator
|
||||
already contains the daemon-snapshot seed.
|
||||
T4 Mobile sees daemon's visible-screen snapshot + live bytes since.
|
||||
KNOWN LIMITATION; out of scope for this design.
|
||||
```
|
||||
|
||||
### Error path — renderer throws or unmounts mid-hydration
|
||||
|
||||
```
|
||||
T0–T1 same as happy path through `pending` state.
|
||||
T2 ptyController.serializeBuffer rejects (renderer disposed,
|
||||
channel closed, IPC timeout, etc.).
|
||||
- catch swallows the error.
|
||||
- hydration state → done (we do not loop on every byte).
|
||||
T3 Live bytes continue to populate the emulator via
|
||||
trackHeadlessTerminalData (which lazily creates the headless
|
||||
state at PTY dims). We lose the seed for this runtime but do
|
||||
not block live data flow.
|
||||
```
|
||||
|
||||
The "advance to done on serialize failure" rule is intentional. Re-trying on every subsequent byte would create a renderer round-trip on every byte until success — too costly for a best-effort path. The "leave state absent when the renderer isn't ready yet" rule (the precondition checks before `pending`) is the inverse trade-off: those checks are cheap (Map lookups), so retrying them is fine.
|
||||
|
||||
### SSH note
|
||||
|
||||
SSH-backed PTYs flow through the same `runtime.onPtyData` entry point as local and daemon-backed PTYs (see `ipc/pty.ts` provider listener — all providers call `runtime.onPtyData(id, data, at)` uniformly). Hydration applies to SSH PTYs without special-casing: when a desktop pane is mounted on an SSH-backed terminal, its `registerPtySerializer` registration is identical to the local case, and the runtime sees `hasRendererSerializer(ptyId) === true` regardless of provider. The mobile + SSH + relaunch case (rare in practice) inherits Scenario A's known-limitation behavior.
|
||||
|
||||
### Concurrent path — live data arrives during hydration
|
||||
|
||||
The renderer round-trip is asynchronous; live `pty:data` will continue to arrive before `serializeBuffer` resolves. The pattern from `seedHeadlessTerminal` already handles this: every emulator write is appended to `state.writeChain`, so:
|
||||
|
||||
```
|
||||
writeChain: Promise.resolve()
|
||||
→ seed write ← scheduled by maybeHydrateHeadlessFromRenderer
|
||||
→ live byte 1 ← scheduled by trackHeadlessTerminalData
|
||||
→ live byte 2
|
||||
→ live byte N
|
||||
```
|
||||
|
||||
`emulator.write` is invoked in chain order, preserving the byte sequence exactly as the wire delivered it. The seed always lands before the live bytes that triggered hydration, because the trigger logic schedules the seed write *before* it returns control to `onPtyData`, which then schedules the live write.
|
||||
|
||||
## Performance
|
||||
|
||||
`ptyController.serializeBuffer(ptyId)` does an IPC round-trip to the renderer where xterm's SerializeAddon runs synchronously over the buffer. Cost is roughly proportional to scrollback size: empirically ~50–200 ms for a full 50k-row buffer.
|
||||
|
||||
The cost profile is materially different from the rejected priority-flip approach:
|
||||
|
||||
| Approach | Renderer round-trip frequency |
|
||||
|---|---|
|
||||
| Priority flip (rejected) | Once per `terminal.subscribe` AND `terminal.resizeForClient` |
|
||||
| Hydrate-on-first-touch (this) | Once per `(ptyId, runtime)` pair, ever |
|
||||
|
||||
For a typical session — Orca starts, user opens desktop pane, agent runs for hours, user opens mobile periodically — this approach pays the IPC cost exactly once *for hydration* per `(ptyId, runtime)` pair. The existing renderer-fallback inside `serializeTerminalBufferFromAvailableState` is preserved — it can still hit the renderer on `terminal.read` / `terminal.subscribe` when the headless emulator returns null — but that path is the read-time fallback, not the hydration path. The priority-flip approach paid the IPC cost on every mobile re-subscribe (foreground/background, navigation between worktrees, phone-fit toggle). The "first byte after pane mount" trigger ties the hydration cost to a moment that is already doing IO work, so the latency is hidden inside the existing flow.
|
||||
|
||||
There is no per-keystroke cost; `trackHeadlessTerminalData` is unchanged.
|
||||
|
||||
## Reflow asymmetry
|
||||
|
||||
Hydration happens at whatever cols the renderer is currently at — typically the desktop's natural size (e.g., 105 cols). When mobile later subscribes and triggers a 49-col phone-fit resize, the headless emulator (now seeded with 105-col data) reflows to 49 cols just like the renderer would. Both buffers reflow from the same starting content, so they stay in sync.
|
||||
|
||||
This is a real improvement over the priority-flip proposal, which was sensitive to the order in which renderer and headless reflow completed across the IPC tick boundary. With hydrate-on-mount the seed has already landed before any phone-fit resize is even requested, so the reflow asymmetry concerns largely go away: at subscribe time both buffers contain the same content and respond to the same resize event in the same `handleMobileSubscribe` synchronous block.
|
||||
|
||||
## Risks
|
||||
|
||||
1. **Live data arrives during pending hydration.** Mitigated by chaining through `state.writeChain`, exactly as `seedHeadlessTerminal` already does. Order is preserved.
|
||||
|
||||
2. **Renderer pane unmount mid-round-trip.** Caught by `try/catch`; the guard advances to `done` so we don't loop on every subsequent byte, and live writes continue via lazy emulator creation in `trackHeadlessTerminalData`. We lose the seed for that PTY, which is acceptable given how rare unmount-during-IPC is.
|
||||
|
||||
3. **Wire-payload size on hydration.** Capped at 1000 rows from day one via the shared `MOBILE_SUBSCRIBE_SCROLLBACK_ROWS` constant. Alt-screen forces 0 rows. This matches the existing serialize path's behavior, so users see identical depth from both sources. The headless emulator's own 5,000-row `DEFAULT_SCROLLBACK` (in `HeadlessEmulator`) is comfortably above the 1k hydration cap; if a future change raises the hydration cap, `HeadlessEmulator`'s default must be bumped in lockstep or the seed will be silently truncated as it lands in the emulator.
|
||||
|
||||
4. **Renderer xterm is *behind* the runtime.** Theoretically possible if `pty:data` is delivered to the runtime before the renderer (depends on dispatch order in `ipc/pty.ts`). The renderer's xterm uses an asynchronous `write(callback)`, so even when bytes are delivered the buffer may not yet contain them. In practice this is sub-millisecond and the seed will be at most one frame behind the live byte that triggered it — better than today's headless-only path which has none of those bytes.
|
||||
|
||||
5. **Hydration races registerPty.** If `onPtyData` fires before `runtime.registerPty` has been called for this PTY, `getTerminalSize` may return null and we default to 80×24 for the post-seed PTY dims. The seed itself is constructed at the renderer's reported dims (see Pseudocode), so xterm reflow only happens on the post-seed `resize` call — at most one reflow, and only when PTY and renderer dims actually diverge.
|
||||
|
||||
6. **PTY-size vs renderer-dim divergence (resize-after-seed reflow).** Under mobile-fit overrides, or in the brief window before a `pty:resize` lands on the main process, the renderer's xterm dims and the runtime's `ptySizes` entry can disagree. Constructing the headless emulator at PTY-size and then writing a seed captured at renderer-dim would force xterm to wrap/reflow the seed in the wrong column count — visible as broken line breaks or doubled prompts. Mitigation: build the emulator at `rendered.cols / rendered.rows`, then resize to PTY-size after the seed lands. See Pseudocode. **At extreme size deltas (e.g., 105→32), the seed-then-reflow path can produce minor visible divergence vs the renderer's own reflow** (xterm reflow is not strictly invertible across very different widths, and the headless emulator runs the reflow on already-laid-out cells rather than the original byte stream). This is an accepted limitation, not a correctness issue: the reflow result is still valid xterm output, just potentially line-broken slightly differently than what the desktop pane shows for the same scrollback. Mobile users have always seen a phone-fit reflow distinct from desktop's; this design does not change that.
|
||||
|
||||
7. **Note: writes are flushed before serialize.** The renderer-side serializer (`pty-buffer-serializer.ts:registerPtySerializer`) flushes `pendingWritesRef` via `replayIntoTerminalAsync` before calling `pane.serializeAddon.serialize()`, so the seed faithfully includes hidden-pane buffered writes. No additional sequencing logic is needed in the runtime.
|
||||
|
||||
8. **`pendingWritesRef` double-write window (severity-adjusted P2).** When a pane is hidden at the moment bytes arrive, the renderer-side `pendingWritesRef` buffers them while `runtime.onPtyData` simultaneously routes the same bytes into the headless emulator via `trackHeadlessTerminalData`. The renderer's serializer flushes `pendingWritesRef` before serializing, so the seed payload includes those bytes. If hydration runs after `trackHeadlessTerminalData` has already written the same bytes, the headless emulator ends up with a duplicated stretch.
|
||||
|
||||
**Mitigation: the P0-A2 pre-signal handshake makes this rare in practice.** With pre-signal, hydration is the FIRST writer for a fresh-spawn-with-pre-signal — `trackHeadlessTerminalData`'s lazy-create check sees the emulator already exists (created at hydration time) and just appends, so live bytes between seed-fetch and seed-resolve are queued behind the seed via `state.writeChain`. The double-write only manifests in the narrow combo of: (a) reattach path, (b) hidden pane buffering live bytes into `pendingWritesRef`, AND (c) hydration runs after `trackHeadlessTerminalData` has already populated the headless emulator. The impact is bounded: at most one ~8 ms PTY-batch's worth of bytes can be duplicated, the duplicate is visible only in mobile/CLI scrollback (desktop renders from its own xterm which never duplicates), and a future shell prompt overwrites the area anyway. Document as a known limitation; not a correctness-blocking issue. If it becomes user-visible, the fix is to track a per-pty "live bytes seen since last serialize request" cursor on the renderer and trim the seed payload to bytes the renderer observed before hydration started — out of scope for this design.
|
||||
|
||||
## Test plan
|
||||
|
||||
### Unit (`orca-runtime.test.ts`)
|
||||
|
||||
- Hydration runs on the *first* `onPtyData` for a `ptyId` when `hasRendererSerializer` is true and `serializeBuffer` returns non-empty data. Assert the emulator's serialized output contains both the seeded prefix and the live byte.
|
||||
- Subsequent `onPtyData` calls do **not** re-trigger hydration after a successful run. Mock `serializeBuffer` and assert it was called exactly once across N `onPtyData` invocations for the same ptyId.
|
||||
- "Exactly once" claim is qualified: the renderer round-trip happens once per `(ptyId, runtime)` for hydration. The existing `serializeTerminalBufferFromAvailableState` renderer-fallback (consulted only when the headless emulator returns null) is preserved and may still hit the renderer on `terminal.read` / `terminal.subscribe` paths.
|
||||
- When `ptyController` is null (CLI / headless test runs), hydration leaves the state map untouched, headless emulator is created lazily as today, no IPC attempt.
|
||||
- When `hasRendererSerializer(ptyId)` returns false on the first byte but true on a later byte, hydration **does** run on the later byte (state is left absent on idle, not consumed). Confirms the contract change for Open Question P2-2.
|
||||
- When `ptyController.serializeBuffer` rejects, the guard advances to `done` (no infinite retry), the emulator is created lazily by `trackHeadlessTerminalData`, live bytes still write through.
|
||||
- Live data arriving during pending hydration is queued behind the seed write. Schedule the seed-write as a long pending promise, fire several `onPtyData` calls, await `writeChain`, assert the final emulator content has the seed prefix followed by the live bytes in correct order.
|
||||
- The 1000-row cap is applied to the renderer-sourced hydration: mock `serializeBuffer` to return a payload representing >1000 rows, assert the requested option bag includes `scrollbackRows: MOBILE_SUBSCRIBE_SCROLLBACK_ROWS`.
|
||||
- Alt-screen flag is forwarded: assert the request includes `altScreenForcesZeroRows: true`. (The alt-screen branch is exercised in renderer-side serializer tests where it has access to a real xterm `buffer.active.type`.)
|
||||
- **Status parity (lastTitle field):** mock `serializeBuffer` to return `{ data, cols, rows, lastTitle }` where `lastTitle` is a recognizable agent title. Fire `onPtyData`. Assert `leaf.lastAgentStatus` is one of `'idle' | 'working' | 'permission'` (whatever `detectAgentStatusFromTitle` returns for that title) after hydration and before any live OSC title bytes are observed. Conversely, when `lastTitle` is absent / undefined OR `detectAgentStatusFromTitle(lastTitle)` returns `null` (unrecognizable title), assert `leaf.lastAgentStatus` is left unchanged from its prior value (no overwrite).
|
||||
- **Multi-PTY concurrent hydration:** fire `onPtyData` for ptyA and ptyB before either `serializeBuffer` resolves. Assert each PTY's hydration completes with its own payload (no cross-talk through the IPC response listener pool — each request has a unique `requestId`).
|
||||
- **Re-entrant `onPtyData`:** when `agentDetector.onData` synchronously triggers another `onPtyData` for the same ptyId (or a different ptyId), confirm the hydration state machine still holds — no double-pending, no skipped seed, no out-of-order emulator writes.
|
||||
- **Cooperation with `seedHeadlessTerminal`:** when a renderer serializer is registered for `ptyId`, the spawn-time call from `ipc/pty.ts` skips seeding (no daemon-snapshot bytes written to the emulator). When no serializer is registered, the daemon-snapshot path runs as today.
|
||||
- **Fresh-spawn timing race (P0-A2 pre-signal handshake):** simulate the renderer pre-signaling intent for paneKey via `const gen = await pty:declarePendingPaneSerializer(paneKey)`, then call the `pty:spawn` handler with `args.env.ORCA_PANE_KEY === paneKey`. Assert `seedHeadlessTerminal` is **NOT** invoked even though `hasRendererSerializerFor(result.id)` is false at that moment (the renderer hasn't received the ptyId yet). The renderer mock then `registerPtySerializer(ptyId, …)` and `pty:settlePaneSerializer(paneKey, gen)`. Fire `onPtyData(ptyId, liveByte)`. Assert `maybeHydrateHeadlessFromRenderer` runs and the headless emulator is populated from the renderer's serialize payload, with the live byte appended after the seed via `writeChain`.
|
||||
- **Pre-signal without settle (renderer crash):** simulate `pty:declarePendingPaneSerializer(paneKey)` followed by `pty:spawn` (gate skips daemon seed) but the renderer never calls `registerPtySerializer` or `settlePaneSerializer`. Fire `onPtyData`. Assert hydration's preconditions leave the state map absent, `trackHeadlessTerminalData` lazy-creates the emulator, and live bytes populate it. The pending-paneKey entry is dropped on the next paneKey teardown event.
|
||||
- **Pre-signal preserved across paneKey reuse during teardown:** simulate (a) old PTY for paneKey K is exiting, its `paneKeyTeardownListener` is queued (captured at registration time with `gen1`). (b) Mount-2 calls `pty:declarePendingPaneSerializer(K)` and stores generation `gen2` (`gen2 > gen1`). (c) The queued teardown for the old PTY runs; the listener invokes `settlePending(K, gen1)` and SKIPS the delete because `pendingByPaneKey.get(K) === gen2`. (d) Mount-2 calls `pty:spawn`; the cooperation gate matches (`pendingByPaneKey.has(K) === true`) and seed is suppressed. Assert daemon-snapshot seed did NOT run.
|
||||
- **Test imports for `scrollback-limits.ts`:** tests in `orca-runtime.test.ts` and `mobile-subscribe-integration.test.ts` import `MOBILE_SUBSCRIBE_SCROLLBACK_ROWS` from `../scrollback-limits` so cap-assertion lines match the production constant (no hardcoded `1000`).
|
||||
- **Status parity (real `SerializeAddon` round-trip):** in a renderer-side unit test (using a real `xterm` `Terminal` + `SerializeAddon`), write OSC 0/1/2 title bytes (e.g., `\x1b]0;some-title\x07`) into the terminal, await the `onTitleChange` listener, then call `serializeAddon.serialize()`. **Assert the serialize output does NOT contain the OSC title bytes** — this codifies the limitation that motivated the `lastTitle` field. Then, in a runtime-side unit test, mock the renderer-IPC response to include `{ data, cols, rows, lastTitle }` where `lastTitle` is a known agent title, fire `onPtyData`, and assert `applySeededAgentStatus` was called with that title and `leaf.lastAgentStatus` is the corresponding `'idle' | 'working' | 'permission'` value returned by `detectAgentStatusFromTitle` afterward.
|
||||
- **`applySeededAgentStatus` does not resolve waiters:** with a leaf that has pending TUI-idle waiters and pending orchestration messages registered, call `applySeededAgentStatus(ptyId, title)` where `title` is a recognizable agent title. Assert `leaf.lastAgentStatus` matches `detectAgentStatusFromTitle(title)` (one of `'idle' | 'working' | 'permission'`), AND assert `resolveTuiIdleWaiters` and `deliverPendingMessages` were **NOT** invoked. (Spy on the methods or assert the waiter / pending-message queues are unchanged.) This guards against future drift where a refactor lifts shared logic between the live and seeded paths.
|
||||
|
||||
### Integration (`mobile-subscribe-integration.test.ts`)
|
||||
|
||||
- Cross-process scenario with a mocked renderer that registers a richer scrollback than the headless adapter would produce. After the runtime sees its first live byte, mobile subscribes; assert the `scrollback` frame's `serialized` field includes the seeded prefix.
|
||||
- Scenario A regression guard: no renderer registered, mobile subscribes, assert mobile receives only what the daemon snapshot + live bytes provide, hydration was never invoked. (Documents the known limitation.)
|
||||
|
||||
### Manual
|
||||
|
||||
On a real device, reproduce the original `edit-issues` post-claude-exit scenario, confirm the mobile WebView now shows the same agent summary the desktop shows.
|
||||
|
||||
## Open questions
|
||||
|
||||
- **Hydration trigger point.** Three plausible options: (a) first `onPtyData`, (b) `runtime.registerPty`, (c) an explicit renderer-pane-mount notification from the renderer. (a) is the chosen approach: cheap, ties cost to a moment already paying IO, and **retryable within a runtime**. The state map is left absent (not `done` or `skipped`) when the renderer serializer isn't yet registered, so a later byte can attempt hydration once the pane mounts. The only consume-on-idle case is `headlessTerminals.has(ptyId)` (live bytes already arrived), where re-seeding would duplicate. (b) fires before the renderer has any data to serialize. (c) needs a new wire from `pty-connection.ts → ipc/pty.ts → runtime`.
|
||||
|
||||
- **Cooperation with `seedHeadlessTerminal`.** Today `seedHeadlessTerminal` writes to the headless emulator on `provider.spawn` from `result.snapshot` / `result.coldRestore.scrollback`. The daemon's `result.snapshot` is the visible-screen-only ANSI from `checkpoint.json` — almost always non-empty (it includes the bare prompt) but typically much thinner than what the renderer pane has. If both fire for the same PTY, the daemon path lands first and `headlessTerminals.has(ptyId)` becomes true; the hydration guard would then mark itself `done` and the richer renderer payload is lost. **Decision: gate `seedHeadlessTerminal` on (a) an already-registered renderer serializer OR (b) a renderer pre-signal for the spawning PTY's paneKey.** In `ipc/pty.ts`, before calling `runtime.seedHeadlessTerminal(...)`, check both `runtime.hasRendererSerializerFor(result.id)` AND `pendingByPaneKey.has(args.env?.ORCA_PANE_KEY)` (after validating the paneKey shape — see P1-B2 in the cooperation gate snippet). If either is true, skip the daemon-snapshot seed entirely and let renderer hydration be canonical. (a) covers reattach, where the pane mounted before spawn returned. (b) covers fresh spawn, where the renderer pre-signaled intent before `pty:spawn` but cannot have registered yet because it doesn't know the ptyId. If neither is true (Scenario A — mobile-only, no desktop pane), the daemon-snapshot path runs unchanged. See "Renderer pre-signal handshake" for the full sequence and correctness properties. This is cleaner than a length-comparison "richness heuristic" and lets the renderer be authoritative whenever it's mounted *or* about to mount.
|
||||
|
||||
## Rollout
|
||||
|
||||
Single change touching the runtime and the renderer-side serialize controller. No feature flag — the hydration is best-effort and degrades to today's behavior when the renderer cannot answer or has nothing useful to share.
|
||||
|
||||
Ready for implementation review. Scenario A remains a known limitation tracked for a future daemon-persistence design.
|
||||
@@ -0,0 +1,690 @@
|
||||
# Mobile Presence Lock for Desktop Terminal
|
||||
|
||||
Design doc for repurposing the existing "phone-fit" banner into a general
|
||||
presence-based interaction lock between the desktop renderer and mobile
|
||||
clients sharing a single PTY.
|
||||
|
||||
## Problem
|
||||
|
||||
The desktop and mobile clients share full read/write access to the same
|
||||
underlying PTY. There is no synchronization between desktop's xterm `onData`
|
||||
(which calls `provider.write(ptyId, bytes)` via the `pty:write` IPC) and
|
||||
mobile's `terminal.send` RPC (which also calls `provider.write` through the
|
||||
runtime). When both parties type at the same time, bytes interleave at the
|
||||
TTY level — `ls<enter>` and `pwd<enter>` typed concurrently can produce
|
||||
`lpws<enter>d<enter>` and execute unintended commands.
|
||||
|
||||
The same is true for resize: desktop `pty:resize` and mobile
|
||||
`terminal.resizeForClient` both reach `provider.resize(ptyId, ...)` without
|
||||
coordination. The renderer-side `safeFit` has a partial guard, but the
|
||||
`pty:resize` IPC handler does not check the override server-side.
|
||||
|
||||
A teammate using the original mobile build reported "odd behavior using
|
||||
laptop + mobile at the same time." The most visible symptom is the desktop
|
||||
terminal jumping to phone dimensions; the more dangerous symptom is silent
|
||||
input interleaving.
|
||||
|
||||
## Today's banner
|
||||
|
||||
The existing banner in `TerminalPane.tsx` is keyed on
|
||||
`getFitOverrideForPty(ptyId)`:
|
||||
|
||||
- It only appears when mobile is in `auto`/`phone` display mode AND a phone
|
||||
resize actually happened.
|
||||
- It says "Terminal resized for phone (W×H)" with a "Restore" button that
|
||||
calls `runtime:restoreTerminalFit(ptyId)`.
|
||||
- That IPC handler sets the display mode to `desktop` and applies the
|
||||
display mode, which resizes the PTY back to desktop dims and clears the
|
||||
override. The banner unmounts.
|
||||
|
||||
In `desktop` display mode (mobile is subscribed but viewing at desktop dims)
|
||||
there is no override and no banner — the desktop user has no idea mobile is
|
||||
watching.
|
||||
|
||||
## Goal
|
||||
|
||||
Repurpose the banner into a general presence-based lock with this single
|
||||
rule:
|
||||
|
||||
> At any moment, each PTY has exactly one *driver* — desktop, a specific
|
||||
> mobile client, or nobody. While mobile drives, desktop input and resize
|
||||
> are dropped; the desktop banner explains why and offers **Take back** to
|
||||
> hand the floor over. While desktop drives, mobile keystrokes silently
|
||||
> reclaim the floor (no mobile-side banner — see "Asymmetric UX" below).
|
||||
|
||||
The lock exists at two layers:
|
||||
|
||||
- **Renderer guard** (primary UX): `pty-connection.ts` drops xterm `onData`
|
||||
and `onResize` while a mobile client is the driver. Banner explains why.
|
||||
- **Server-side defense** (defense-in-depth): the `pty:write` and
|
||||
`pty:resize` IPC handlers consult the runtime's driver state and drop
|
||||
desktop-side calls while a mobile client is the driver.
|
||||
|
||||
## Behavioral model
|
||||
|
||||
### Driver state machine
|
||||
|
||||
Instead of a binary lock, each PTY carries a tagged driver state. There is
|
||||
exactly one driver per PTY at any moment, and transitions are atomic
|
||||
(updated and emitted together from the runtime).
|
||||
|
||||
```ts
|
||||
type DriverState =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'desktop' }
|
||||
| { kind: 'mobile'; clientId: string }
|
||||
```
|
||||
|
||||
- `idle` — no mobile subscribers; desktop input and resize flow through
|
||||
normally. (We don't bother distinguishing "no one is here" from "only
|
||||
desktop is here" since they behave identically; `idle` is the catch-all
|
||||
for "nothing is currently locking the desktop out.")
|
||||
- `desktop` — at least one mobile client is subscribed but the desktop has
|
||||
reclaimed the floor; desktop input and resize flow through.
|
||||
- `mobile{clientId}` — `clientId` is the mobile actor that most recently
|
||||
drove this PTY. The banner is mounted on desktop; desktop input and
|
||||
resize are dropped.
|
||||
|
||||
Invariants:
|
||||
|
||||
- `currentDriver(ptyId)` is always exactly one of the three kinds.
|
||||
- On the main process, a transition mutates `currentDriver(ptyId)` and
|
||||
emits `terminalDriverChanged(ptyId, driver)` in the same critical
|
||||
section. The renderer's mirror in `mobile-driver-state.ts` is updated
|
||||
only when the IPC arrives — there is a brief IPC-hop window during
|
||||
which the renderer's `getDriverForPty(ptyId)` returns a stale value.
|
||||
This is why the server-side `pty:write` / `pty:resize` defenses are
|
||||
**load-bearing, not redundant**: a desktop keystroke fired during
|
||||
that window passes the renderer guard and is dropped by the server
|
||||
guard.
|
||||
- Only one driver per PTY at any moment. Multiple mobile clients can
|
||||
*subscribe* simultaneously (see "Multi-mobile subscriber model"), but
|
||||
only the most recent mobile actor is the driver.
|
||||
|
||||
### Transitions
|
||||
|
||||
| Current driver | Trigger | Next driver | Side effect |
|
||||
|---|---|---|---|
|
||||
| `idle` | mobile subscribes with `displayMode='auto'\|'phone'` (first client for this ptyId) | `mobile{clientId}` | banner mounts on desktop; PTY resizes to phone dims |
|
||||
| `idle` | mobile subscribes with `displayMode='desktop'` (first client for this ptyId) | `desktop` | inner subscriber map populated; **no** banner; PTY stays at desktop dims |
|
||||
| `idle` | desktop input or first PTY data after no subscribers | `idle` (no transition) | — |
|
||||
| `mobile{A}` | desktop clicks **Take back** | `desktop` | banner unmounts; PTY snaps to desktop dims if at phone dims |
|
||||
| `mobile{A}` | mobile A sends input/resize/setDisplayMode | `mobile{A}` (no transition) | — |
|
||||
| `mobile{A}` | mobile B sends input | `mobile{B}` | (no banner change; both are "mobile") |
|
||||
| `mobile{A}` | last mobile client unsubscribes | `idle` | banner unmounts |
|
||||
| `desktop` | any mobile client sends input/resize | `mobile{thatClient}` | banner mounts; PTY snaps to phone dims if that client's mode is auto/phone |
|
||||
| `desktop` | mobile sets `displayMode` to `auto` or `phone` | `mobile{thatClient}` | banner mounts; PTY snaps to phone dims (deliberate "I want to drive" gesture) |
|
||||
| `desktop` | mobile sets `displayMode` to `desktop` | `desktop` (no transition) | — (already desktop-mode watching) |
|
||||
| `desktop` | mobile subscribes-fresh with `auto`/`phone` | `mobile{thatClient}` | banner mounts; PTY snaps to phone dims |
|
||||
| `desktop` | mobile subscribes-fresh with `desktop` | `desktop` (no transition) | inner map updated; no banner |
|
||||
| `desktop` | last mobile client unsubscribes | `idle` | (banner already unmounted) |
|
||||
|
||||
**Subscribe-in-desktop-mode rule.** A mobile client subscribing in
|
||||
`displayMode='desktop'` is treated as a passive watch, not a take-floor
|
||||
gesture. The driver stays at `idle`/`desktop`, so the desktop user is not
|
||||
interrupted. The instant that client (or any peer) sends input, sets the
|
||||
display mode to `auto`/`phone`, or sends a resize, the runtime transitions
|
||||
to `mobile{thatClient}` and the banner appears. This matches the rest of
|
||||
the design: the lock engages on *interaction*, not on *presence*.
|
||||
|
||||
The protocol is "first-mover wins until the other party acts." Desktop
|
||||
clicks Take back, mobile types, desktop types again — banner ping-pongs as
|
||||
each side acts. The `clientId` carried in `mobile{clientId}` is updated
|
||||
each time a mobile actor takes the floor; this is the wire channel by
|
||||
which the runtime knows *which* phone last drove (useful for the
|
||||
forward-path coordinator described at the bottom of this doc, and for the
|
||||
multi-mobile semantics described below).
|
||||
|
||||
### Take back and PTY dimensions
|
||||
|
||||
Take back has two sub-cases:
|
||||
|
||||
1. **Mobile was in `phone`/`auto` mode (PTY at phone dims)**. Take back
|
||||
resizes PTY back to desktop dims (existing behavior of
|
||||
`applyMobileDisplayMode('desktop')` when `wasResizedToPhone` is true).
|
||||
2. **Mobile was in `desktop` mode (PTY already at desktop dims)**. Take
|
||||
back is a pure lock-flag flip; no resize. Today's
|
||||
`applyMobileDisplayMode('desktop')` already short-circuits the resize in
|
||||
this case.
|
||||
|
||||
In the symmetric direction, mobile reclaim:
|
||||
|
||||
1. **Mobile is in `phone`/`auto` mode but PTY is at desktop dims** (because
|
||||
desktop just clicked Take back): mobile reclaim re-applies the phone
|
||||
resize via `applyMobileDisplayMode(currentMode)`.
|
||||
2. **Mobile is in `desktop` mode**: pure lock-flag flip; no resize.
|
||||
|
||||
## End-user UX
|
||||
|
||||
| Driver | Banner (desktop) | Desktop input | Desktop resize |
|
||||
|---|---|---|---|
|
||||
| `idle` | hidden | allowed | allowed |
|
||||
| `mobile{*}` | "🔒 Mobile is driving this terminal — your input is paused. Click **Take back** to resume." | blocked at xterm.onData (silent drop) | blocked in renderer + dropped in `pty:resize` IPC server-side |
|
||||
| `desktop` | hidden | allowed | allowed |
|
||||
|
||||
Walkthroughs:
|
||||
|
||||
**Phone connects while you're typing.** Banner pops in. PTY may resize to
|
||||
phone dims (existing). Your next keystroke is dropped. Click Take back to
|
||||
unlock and (if needed) restore desktop dims.
|
||||
|
||||
**You click Take back.** Banner gone. You type freely. Mobile stays
|
||||
connected; mobile sees the desktop-sized terminal because PTY snapped back
|
||||
(or stayed at desktop dims if mobile was in desktop mode).
|
||||
|
||||
**Mobile types something while you're reclaimed.** Banner reappears. Your
|
||||
next keystroke is blocked. PTY may snap back to phone dims (if mobile is in
|
||||
auto/phone mode).
|
||||
|
||||
**Mobile disconnects.** Banner gone permanently. Driver returns to `idle`.
|
||||
|
||||
**Multiple panes.** Driver state is per-pane. Phone on pane A doesn't
|
||||
affect pane B.
|
||||
|
||||
**Text selection / scrollback / copy.** Always allowed. The lock is
|
||||
keystroke and resize only.
|
||||
|
||||
**Output continues to render.** While the banner is mounted, terminal
|
||||
output streams to xterm normally — it is the mobile actor's bytes you
|
||||
are seeing. Only desktop-side keystrokes and resize are dropped. This
|
||||
matters because "your input is paused" can read ambiguously; output
|
||||
flow is unaffected.
|
||||
|
||||
## Asymmetric UX (accepted tradeoff)
|
||||
|
||||
Mobile sees no banner in this PR. The mobile UI is visually unchanged: no
|
||||
"Desktop is driving" indicator, no analog to the Take back affordance.
|
||||
This is asymmetric and we are accepting it deliberately:
|
||||
|
||||
- **Smaller mobile UI surface.** Mobile already has limited screen real
|
||||
estate and a constrained component set; introducing a presence banner
|
||||
there is a non-trivial design + i18n + dismissibility task that we want
|
||||
to defer until the lock model has settled in production.
|
||||
- **Faster ship.** Driver state machine + multi-mobile subscriber fix +
|
||||
desktop banner is the smallest change that fixes the dangerous collision
|
||||
(silent input interleaving). Adding a mobile-side banner doubles the UI
|
||||
scope.
|
||||
- **Mobile reclaim is naturally signaled.** When a mobile user types
|
||||
while desktop drives, the runtime flips the driver to
|
||||
`mobile{thatClient}`, the desktop banner remounts, and (if mobile is in
|
||||
auto/phone mode) the PTY snaps back to phone dims. The mobile user sees
|
||||
the pane reflow and their keystrokes appear in the output stream. There
|
||||
is no silent black-hole condition on mobile that a banner would
|
||||
resolve.
|
||||
- **Mobile keystrokes always reclaim implicitly.** The protocol on mobile
|
||||
is "just type to take the floor." There is no mobile-side button to
|
||||
surface; a banner with no actionable control is closer to noise than
|
||||
signal.
|
||||
|
||||
The flip side: a mobile user typing into a stale view *won't* be told
|
||||
"hold on, desktop is driving" before their keystroke lands. They just take
|
||||
the floor. We consider that acceptable because (a) they're explicitly
|
||||
acting, and (b) the desktop user gets the warning side of the tradeoff
|
||||
where the risk of unintended action is much higher.
|
||||
|
||||
If usage data later shows mobile users frequently being surprised by
|
||||
desktop activity, a mobile banner can be added without changing the wire
|
||||
format — `terminalDriverChanged(ptyId, driver)` already carries everything
|
||||
needed.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Where the truth lives
|
||||
|
||||
The `mobileSubscribers` map (re-keyed; see "Multi-mobile subscriber model"
|
||||
below) plus a new `currentDriver: Map<ptyId, DriverState>` on the runtime
|
||||
are the source of truth. The renderer learns the driver state via a new
|
||||
IPC event `terminal-driver-changed(ptyId, driver: DriverState)` emitted
|
||||
from the runtime through the existing notifier path. The structured
|
||||
payload is intentional: a binary `locked: boolean` would lose the
|
||||
`clientId` we need for multi-mobile semantics today and for the unified
|
||||
write coordinator on the forward path.
|
||||
|
||||
The runtime exposes `getDriver(ptyId): DriverState`, replacing the old
|
||||
`isLocked(ptyId): boolean`. Server-side `pty:write` / `pty:resize`
|
||||
defenses check `runtime.getDriver(ptyId).kind === 'mobile'` to drop
|
||||
desktop-side calls.
|
||||
|
||||
A new renderer module `mobile-driver-state.ts` mirrors
|
||||
`mobile-fit-overrides.ts`: keyed by ptyId, supports
|
||||
`getDriverForPty(ptyId): DriverState` and a subscribe-style change
|
||||
listener. The `TerminalPane` banner mounts when
|
||||
`getDriverForPty(ptyId).kind === 'mobile'`, and `pty-connection`'s
|
||||
`onData`/`onResize` guards drop input/resize under the same predicate.
|
||||
|
||||
### Why not reuse `getFitOverrideForPty`?
|
||||
|
||||
The fit override only fires when the PTY was actually resized
|
||||
(`mode='auto'|'phone'` and `wasResizedToPhone=true`). It misses the
|
||||
desktop-mode case where mobile is subscribed but no resize happened. The
|
||||
driver state is broader than the fit override.
|
||||
|
||||
### Why a new IPC event vs extending `terminal-fit-override-changed`?
|
||||
|
||||
Cleaner separation. The fit override is about dimensions; the driver
|
||||
state is about ownership. They happen to overlap in the auto/phone
|
||||
subcase, but conflating them long-term ties future work on either to the
|
||||
other.
|
||||
|
||||
### Why a structured payload vs `locked: boolean`?
|
||||
|
||||
The runtime needs to know *which* mobile client most recently drove (for
|
||||
multi-mobile semantics today and for the future write coordinator). A
|
||||
structured `DriverState` payload makes that information first-class on
|
||||
the wire instead of smuggling it through a side channel. The cost is ~70
|
||||
LoC over a binary lock; the payoff is a symmetric UX foundation and a
|
||||
future-proof wire format.
|
||||
|
||||
## Multi-mobile subscriber model
|
||||
|
||||
The `mobileSubscribers` map is today shaped `Map<ptyId, Subscriber>` and
|
||||
each `terminal.subscribe` call overwrites the previous subscriber for that
|
||||
ptyId. That overwrite is fine for a binary `has(ptyId)` presence check but
|
||||
breaks the moment we treat presence as a real set: phone B subscribing
|
||||
silently evicts phone A, so phone A unsubscribing or its WS dropping looks
|
||||
like "no mobile clients" even while phone B is still on the line. The
|
||||
driver state machine sits directly on top of presence, so soundness here
|
||||
is a prerequisite, not a polish.
|
||||
|
||||
We rekey to `Map<ptyId, Map<clientId, Subscriber>>` and update each
|
||||
callsite:
|
||||
|
||||
- **`handleMobileSubscribe(ptyId, clientId, subscriber)`** — get-or-create
|
||||
the inner map, then `inner.set(clientId, subscriber)`. Do not overwrite
|
||||
peer clients. If the inner map was empty before insert, this is the
|
||||
first subscriber for the PTY; emit the `idle → mobile{clientId}` driver
|
||||
transition.
|
||||
- **`handleMobileUnsubscribe(ptyId, clientId)`** — `inner.delete(clientId)`,
|
||||
then if the inner map is now empty, delete the outer entry, run the
|
||||
existing restore-resize logic, and emit the `* → idle` driver
|
||||
transition. If the inner map is non-empty, do **not** fire restore /
|
||||
driver-change; peers still have the floor.
|
||||
- **`applyMobileDisplayMode(ptyId)`** — iterate the inner map. The
|
||||
restore-resize semantics need a single representative subscriber (the
|
||||
desktop dims to restore *to* are stored on the subscriber record). Pick
|
||||
the earliest by subscribe time so the restore target is stable as
|
||||
later phones come and go. The display mode itself is per-PTY runtime
|
||||
state, not per-client.
|
||||
|
||||
**Active phone-fit dim selection (multi-mobile).** When two or more
|
||||
mobile clients subscribe with different viewports (e.g., iPhone +
|
||||
iPad), the PTY can only be at one phone-fit size at a time. Rule:
|
||||
**the most recent mobile actor's viewport wins**. This matches the
|
||||
driver state machine — whoever last took the floor (`mobile{X}`)
|
||||
also dictates the active phone-fit dims. When that client
|
||||
unsubscribes, the next-most-recent surviving subscriber's viewport
|
||||
wins; on the last client leaving, the inner map empties and we run
|
||||
the existing restore back to the earliest-recorded desktop dims. We
|
||||
do not use `min(cols, rows)` across subscribers because that
|
||||
produces no clear principal — multiple TUIs are forced to render
|
||||
for an aggregate viewport that nobody actually has, which is worse
|
||||
than picking a single owner. Most-recent-actor is consistent with
|
||||
the rest of the protocol (whoever acted last has the floor) and is
|
||||
cheap to reason about.
|
||||
|
||||
**Subscriber record extension.** "Most-recent actor" and
|
||||
"earliest-by-subscribe-time" both require timestamps that today's
|
||||
Subscriber record does not carry. Extend it with two fields:
|
||||
|
||||
```ts
|
||||
interface Subscriber {
|
||||
clientId: string
|
||||
viewport: { cols: number; rows: number }
|
||||
wasResizedToPhone: boolean
|
||||
previousCols: number | null
|
||||
previousRows: number | null
|
||||
subscribedAt: number // ms since epoch, set on insert
|
||||
lastActedAt: number // ms since epoch, init = subscribedAt;
|
||||
// updated on every mobileTookFloor for this client
|
||||
}
|
||||
```
|
||||
|
||||
- `applyMobileDisplayMode(ptyId)` for active phone-fit dims:
|
||||
iterate the inner map, pick `argmax(lastActedAt)`, use that
|
||||
subscriber's `viewport`.
|
||||
- For restore-to-desktop semantics on last-client-leaves: pick
|
||||
`argmin(subscribedAt)` **among subscribers with non-null
|
||||
`previousCols`/`previousRows`** and use that subscriber's
|
||||
`previousCols/Rows` as the restore target. Desktop-mode
|
||||
subscribers carry `previousCols/Rows = null` by design (the
|
||||
existing `handleMobileSubscribe` short-circuits dim capture for
|
||||
desktop-mode joins to avoid capturing a stale full-width size),
|
||||
so they are not viable restore targets. If no surviving
|
||||
subscriber has captured dims, fall back to
|
||||
`lastRendererSizes.get(ptyId)` (the desktop renderer's most
|
||||
recent reported size) — same fallback the existing first-insert
|
||||
capture path uses.
|
||||
|
||||
Both operations are O(n) over the inner map, which is bounded by
|
||||
the number of concurrently subscribed mobile clients (typically 1,
|
||||
rarely 2-3). No indexing needed.
|
||||
- **`isMobileSubscriberActive(ptyId)`** — returns `true` iff the inner map
|
||||
is non-empty.
|
||||
- **Driver state for the mobile side** stores the `clientId` of the most
|
||||
recent mobile actor. Whenever any mobile client sends
|
||||
input/resize/setDisplayMode/subscribes-fresh, that client becomes the
|
||||
`currentDriver` (`mobile{thatClient}`). Phone B taking over from phone A
|
||||
is an internal mobile→mobile transition: no banner change, but the
|
||||
recorded `clientId` updates so the runtime always knows who is the
|
||||
authoritative mobile actor.
|
||||
|
||||
The semantic upshot is that the desktop banner is governed by "is the
|
||||
inner map non-empty AND has the desktop not reclaimed?" rather than the
|
||||
old single-slot heuristic, and Take back / mobile-reclaim correctly
|
||||
ping-pong even when two phones are on the same PTY.
|
||||
|
||||
## Implementation
|
||||
|
||||
Files touched:
|
||||
|
||||
1. `src/main/runtime/orca-runtime.ts` — rekey `mobileSubscribers` to
|
||||
`Map<ptyId, Map<clientId, Subscriber>>`, add `currentDriver` map,
|
||||
`getDriver(ptyId)` getter, transition methods, notifier hook. Update
|
||||
`handleMobileSubscribe` / `handleMobileUnsubscribe` /
|
||||
`applyMobileDisplayMode` / `isMobileSubscriberActive` per the
|
||||
multi-mobile model above. **Extend `onPtyExit` cleanup** to
|
||||
`currentDriver.delete(ptyId)` and emit `terminalDriverChanged(ptyId,
|
||||
{ kind: 'idle' })` so any banner mounted on the dead pane unmounts.
|
||||
Without this, a dead PTY's last driver state lingers and the
|
||||
renderer banner could persist on a dead pane until tab teardown.
|
||||
2. `src/main/runtime/orca-runtime.ts` interface `RuntimeNotifier` — add
|
||||
`terminalDriverChanged(ptyId, driver: DriverState)`.
|
||||
3. `src/main/window-manager.ts` (or wherever `RuntimeNotifier` is wired) —
|
||||
forward to renderer via `webContents.send('terminal-driver-changed', …)`.
|
||||
4. `src/preload/index.ts` + `src/preload/api-types.ts` — expose the new
|
||||
event with the structured `DriverState` payload.
|
||||
5. `src/main/ipc/runtime.ts` — add `runtime:reclaimTerminal` IPC (or
|
||||
extend `runtime:restoreTerminalFit`) which drives the
|
||||
`mobile{*} → desktop` transition.
|
||||
6. `src/main/runtime/rpc/methods/terminal.ts` — drive the
|
||||
`* → mobile{clientId}` transition in `terminal.send`,
|
||||
`terminal.resizeForClient`, `terminal.setDisplayMode`, and the
|
||||
subscribe handler (with the subscribe-in-desktop-mode exception
|
||||
above).
|
||||
|
||||
**Wire-format changes required.** The driver state machine tags
|
||||
the active mobile actor with `clientId`, so every mobile RPC method
|
||||
that can take the floor must carry the caller's identity. Today
|
||||
only `terminal.subscribe` and `terminal.resizeForClient` do; we
|
||||
extend the others.
|
||||
|
||||
**Canonical identity shape.** Use the existing
|
||||
`terminal.subscribe` shape: `client: { id: string; type: 'mobile'
|
||||
\| 'desktop' }` (with `type` optional). `TerminalResizeForClient`
|
||||
keeps its grandfathered top-level `clientId: string` field for
|
||||
backward compatibility — implementers may add an aliased nested
|
||||
`client.id` setter for consistency at the call site, but the wire
|
||||
shape is preserved.
|
||||
|
||||
New fields on existing schemas:
|
||||
|
||||
- `TerminalSend` gains `client: { id: string; type?: 'mobile' \|
|
||||
'desktop' }` (optional for backward compatibility — falls back
|
||||
to "the most recent mobile actor" when absent).
|
||||
- `TerminalSetDisplayMode` gains the same `client` field.
|
||||
- `TerminalUnsubscribe` gains `client: { id: string }` so the
|
||||
server can derive the composite cleanup key (see below); the
|
||||
existing `subscriptionId` field is kept and remains the primary
|
||||
lookup, with `client.id` used only when the caller passed a
|
||||
bare-handle `subscriptionId`.
|
||||
|
||||
**Subscribe-side composite key.** Change `subscriptionId` from
|
||||
`params.terminal` to `${params.terminal}:${params.client.id}` so
|
||||
two phones subscribing to the same terminal handle do not evict
|
||||
each other via `registerSubscriptionCleanup`. Without this fix,
|
||||
the multi-mobile rekey to `Map<ptyId, Map<clientId, Subscriber>>`
|
||||
would be silently defeated at the RPC subscription layer (phone
|
||||
B's subscribe runs phone A's cleanup → A's data listener tears
|
||||
down → A's `handleMobileUnsubscribe` fires).
|
||||
|
||||
**Unsubscribe-side composite key.** The mobile RPC client today
|
||||
emits `terminal.unsubscribe` with `params: { subscriptionId:
|
||||
stream.params.terminal }` — the bare handle. With the subscribe
|
||||
side now keying by composite, a bare-handle unsubscribe will miss
|
||||
in `subscriptionCleanups.get(bareHandle)` and silently no-op,
|
||||
leaking the data listener and leaving `mobileSubscribers`
|
||||
populated forever (banner stuck, driver never returns to `idle`).
|
||||
Fix: the mobile RPC client emits `{ subscriptionId:
|
||||
${terminal}:${clientId}, client: { id: clientId } }`, and the
|
||||
server's `cleanupSubscription` uses whichever the caller sent —
|
||||
if both `subscriptionId` and `client.id` are present and the
|
||||
caller passed only `terminal` in `subscriptionId`, the server
|
||||
reconstructs the composite key from `client.id`. Belt-and-braces
|
||||
so a stale older mobile build still cleans up correctly.
|
||||
|
||||
This is a coordinated client/server wire-format change. The
|
||||
mobile app must ship in lockstep; if a stale mobile client emits
|
||||
bare-handle unsubscribe to a new server, the server's
|
||||
reconstruction path catches it. If a new mobile client emits
|
||||
composite-handle unsubscribe to a stale server, the stale server
|
||||
ignores `client.id` and the composite key fails to match — but
|
||||
that direction is moot because the stale server has not adopted
|
||||
composite keys on subscribe either. No client newer than server,
|
||||
so this is safe.
|
||||
7. `src/main/ipc/pty.ts` — defense in depth: drop `pty:write` and
|
||||
`pty:resize` calls when
|
||||
`runtime.getDriver(id).kind === 'mobile'`. **Preserve the existing
|
||||
`runtime.isResizeSuppressed()` short-circuit at the top of the
|
||||
`pty:resize` handler** — the new driver-state guard is *in
|
||||
addition to*, not in place of, the suppression window. The two
|
||||
guards have different purposes: `isResizeSuppressed()` blocks the
|
||||
safeFit cascade after a take-back transition (preventing
|
||||
collateral resize corruption of background panes), while the
|
||||
driver-state check blocks desktop-side resizes whenever mobile is
|
||||
driving. Both must apply.
|
||||
8. `src/renderer/src/lib/pane-manager/mobile-driver-state.ts` — new
|
||||
renderer store mirroring `mobile-fit-overrides.ts`. Exposes
|
||||
`getDriverForPty(ptyId): DriverState` and a change listener.
|
||||
9. `src/renderer/src/components/terminal-pane/pty-connection.ts` — guard
|
||||
`onData` and `onResize` on
|
||||
`getDriverForPty(ptyId).kind === 'mobile'`.
|
||||
10. `src/renderer/src/components/terminal-pane/TerminalPane.tsx` — switch
|
||||
banner to consume driver state, update copy, rename Restore → Take
|
||||
back.
|
||||
|
||||
### Server-side detail
|
||||
|
||||
```ts
|
||||
// orca-runtime.ts
|
||||
private currentDriver = new Map<string, DriverState>()
|
||||
|
||||
getDriver(ptyId: string): DriverState {
|
||||
return this.currentDriver.get(ptyId) ?? { kind: 'idle' }
|
||||
}
|
||||
|
||||
private setDriver(ptyId: string, next: DriverState): void {
|
||||
this.currentDriver.set(ptyId, next)
|
||||
this.notifier?.terminalDriverChanged(ptyId, next)
|
||||
}
|
||||
|
||||
reclaimTerminalForDesktop(ptyId: string): void {
|
||||
if (!this.isMobileSubscriberActive(ptyId)) return
|
||||
// Snap PTY back to desktop dims if currently at phone dims.
|
||||
// applyMobileDisplayMode is a no-op resize when already at desktop dims.
|
||||
this.setMobileDisplayMode(ptyId, 'desktop')
|
||||
this.applyMobileDisplayMode(ptyId)
|
||||
this.setDriver(ptyId, { kind: 'desktop' })
|
||||
}
|
||||
|
||||
private mobileTookFloor(ptyId: string, clientId: string): void {
|
||||
// If mobile is in phone/auto mode, re-apply phone resize on the first
|
||||
// hand-off back from desktop. Mobile-to-mobile hand-offs are no-ops
|
||||
// for resize.
|
||||
const prev = this.getDriver(ptyId)
|
||||
if (prev.kind === 'desktop') this.applyMobileDisplayMode(ptyId)
|
||||
this.setDriver(ptyId, { kind: 'mobile', clientId })
|
||||
}
|
||||
|
||||
handleMobileUnsubscribe(ptyId: string, clientId: string) {
|
||||
const inner = this.mobileSubscribers.get(ptyId)
|
||||
if (!inner) return
|
||||
inner.delete(clientId)
|
||||
if (inner.size > 0) return // peer mobile clients still drive
|
||||
this.mobileSubscribers.delete(ptyId)
|
||||
// Drive transition fires synchronously so the desktop banner
|
||||
// unmounts immediately. The PTY restore runs inside the existing
|
||||
// 300ms pendingRestoreTimers debounce — see "Restore-debounce
|
||||
// window" under Edge cases.
|
||||
this.setDriver(ptyId, { kind: 'idle' })
|
||||
// Existing restore-resize logic (300ms debounced timer) runs here.
|
||||
}
|
||||
```
|
||||
|
||||
The mobile-took-floor path is invoked from the RPC method handlers (not
|
||||
from `sendTerminal` directly) so that the driver flip is bound to
|
||||
deliberate mobile actions, not to internal runtime calls.
|
||||
|
||||
### Renderer guards
|
||||
|
||||
```ts
|
||||
// pty-connection.ts onData
|
||||
if (currentPtyId && getDriverForPty(currentPtyId).kind === 'mobile') {
|
||||
return // Mobile is driving this PTY; banner explains.
|
||||
}
|
||||
// existing transport.sendInput(data)
|
||||
|
||||
// pty-connection.ts onResize
|
||||
// Why: keep both predicates. getFitOverrideForPty fires synchronously
|
||||
// in the renderer the moment safeFit runs; getDriverForPty arrives via
|
||||
// IPC and lags by one round-trip. Removing the fit-override predicate
|
||||
// would re-introduce the resize-over-mobile-fit bug mobile-fit-overrides
|
||||
// was added to prevent.
|
||||
if (
|
||||
currentPtyId &&
|
||||
(getFitOverrideForPty(currentPtyId) ||
|
||||
getDriverForPty(currentPtyId).kind === 'mobile')
|
||||
) {
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
### Banner copy
|
||||
|
||||
```
|
||||
🔒 Mobile is driving this terminal — your input is paused. [ Take back ]
|
||||
```
|
||||
|
||||
When PTY is at phone dims, append the dim suffix:
|
||||
```
|
||||
🔒 Mobile is driving this terminal (80×24) — your input is paused. [ Take back ]
|
||||
```
|
||||
|
||||
The phrasing makes Take back the discoverable resolution. There is no
|
||||
auto-unlock-on-WS-silence and no liveness probing; the banner stays up
|
||||
until the desktop user takes back, until mobile actor sends input (which
|
||||
keeps mobile as driver), or until the last mobile subscriber disconnects.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- **Mobile drops network**. WS doesn't immediately know. The inner
|
||||
subscriber map retains the entry for ~30s until ping timeout. Banner
|
||||
stays. Take back still works during this window — it transitions to
|
||||
`desktop` immediately. When mobile eventually reconnects with
|
||||
`terminal.subscribe`, that client takes the floor again
|
||||
(`desktop → mobile{thatClient}`).
|
||||
- **Two phones on same PTY**. The inner map carries both subscribers.
|
||||
Driver state is `mobile{whicheverActedLast}`. Phone A unsubscribing
|
||||
while phone B is still on does *not* drop the banner; only the last
|
||||
client leaving the inner map transitions to `idle`.
|
||||
- **Pre-locked input in flight**. `transport.sendInput` is
|
||||
fire-and-forget; there is no in-flight queue to drain. The first
|
||||
dropped keystroke is on the renderer side, which is good enough.
|
||||
- **Take back while phone is offline**. Works (transitions to `desktop`).
|
||||
When phone reconnects with a fresh subscribe, driver flips to
|
||||
`mobile{thatClient}`.
|
||||
- **Display mode toggle from mobile**. `terminal.setDisplayMode` is
|
||||
treated as mobile interaction → that client takes the floor. Aligns
|
||||
with "any deliberate mobile action takes the floor."
|
||||
- **Subscribe from a fresh client (reconnect with new clientId)**. The
|
||||
subscribe path runs the `desktop → mobile{thatClient}` (or
|
||||
`idle → mobile{thatClient}`) transition. A mobile reconnect takes back
|
||||
the floor from desktop — correct semantic since the user actively
|
||||
reopened the mobile view.
|
||||
- **Restore-debounce window on last-subscriber-leaves**. When the
|
||||
last mobile subscriber unsubscribes, the driver transitions to
|
||||
`idle` synchronously (banner unmounts immediately on desktop), but
|
||||
the PTY-dim restore runs inside the existing 300ms
|
||||
`pendingRestoreTimers` debounce. For up to 300ms after the banner
|
||||
unmounts, the PTY remains at phone dims while desktop input flows
|
||||
through. Desktop typing into a still-squished terminal is a brief
|
||||
visual mismatch, not a correctness bug — the existing debounce is
|
||||
there to absorb rapid tab switches without thrashing PTY size, and
|
||||
emitting `idle` synchronously preserves that behavior. Do not
|
||||
reorder these (driver-emit-first, then debounced restore) without
|
||||
re-introducing thrash.
|
||||
|
||||
## Tests
|
||||
|
||||
- `orca-runtime.test.ts` (driver state machine):
|
||||
- Every transition row in the table above has a unit test asserting
|
||||
`(prev, trigger) → (next, side effect, emitted event payload)`.
|
||||
- `getDriver` defaults to `{ kind: 'idle' }` for unknown ptyIds.
|
||||
- `terminalDriverChanged` is emitted exactly once per state change and
|
||||
carries the structured `DriverState` payload (not a boolean).
|
||||
- `orca-runtime.test.ts` (multi-mobile subscriber sequencing):
|
||||
- Phone A subscribes (`auto`) → driver is `mobile{A}`, banner emit
|
||||
fires.
|
||||
- Phone A subscribes (`desktop`) from `idle` → driver stays `desktop`
|
||||
(subscribe-in-desktop-mode does not take the floor); inner map
|
||||
has A.
|
||||
- Phone B subscribes (`auto`) while A is still on (`auto`) → driver
|
||||
flips to `mobile{B}` (subscribe-fresh-with-auto/phone counts as
|
||||
take-floor); inner map has both subscribers; active phone-fit
|
||||
dims switch to B's viewport.
|
||||
- Phone B unsubscribes while A is still on → driver remains mobile;
|
||||
active phone-fit dims revert to A's viewport (next-most-recent
|
||||
actor); banner stays up; no `idle` transition.
|
||||
- Phone A unsubscribes (last client leaves) → driver transitions to
|
||||
`idle`, banner unmounts, PTY restores to earliest-recorded
|
||||
desktop dims.
|
||||
- `applyMobileDisplayMode` picks the **most-recent-actor's**
|
||||
viewport for active phone-fit dims and the
|
||||
**earliest-by-subscribe-time** desktop dims for restore.
|
||||
- Mobile sets `displayMode` to `desktop` from `mobile{*}` does *not*
|
||||
transition to `desktop` automatically (existing setDisplayMode
|
||||
semantics stand) — but the runtime's *driver* transition rule for
|
||||
`desktop → desktop` (mode change to desktop while already in
|
||||
desktop driver) is a no-op.
|
||||
- `terminal.test.ts` (subscriptionId per-client keying):
|
||||
- Phone A subscribes to terminal handle `T`, phone B subscribes to
|
||||
the same handle `T` → A's data listener still receives bytes
|
||||
after B's subscribe (subscriptionId is `${T}:${clientId}` so
|
||||
`registerSubscriptionCleanup` does not collide).
|
||||
- Regression: prior to the fix, the second subscribe ran the first
|
||||
subscribe's cleanup and tore down phone A's stream.
|
||||
- `pty-connection.test.ts`:
|
||||
- `onData` is dropped while `getDriverForPty(id).kind === 'mobile'`.
|
||||
- `onData` is delivered when driver flips to `desktop` or `idle`.
|
||||
- `onResize` is dropped while driver is `mobile`.
|
||||
- `pty.test.ts` (or new `pty-driver-state.test.ts`):
|
||||
- `pty:write` IPC is dropped when `runtime.getDriver(id).kind ===
|
||||
'mobile'`.
|
||||
- `pty:resize` IPC is dropped under the same predicate.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Mobile yanking desktop tab focus via `terminal.focus`.
|
||||
- Cold-restore ack from mobile-only attach.
|
||||
- Mobile-side "Desktop is driving" banner (see "Asymmetric UX" above).
|
||||
|
||||
These are independent collisions tracked separately.
|
||||
|
||||
## Forward path
|
||||
|
||||
The natural next step (not in this PR) is unifying both writers — the
|
||||
desktop renderer's `pty:write` IPC and the mobile RPC's `terminal.send`
|
||||
— into a single coordinator that queues bytes through a runtime-owned
|
||||
write path. The driver state machine cleanly supports this: the
|
||||
coordinator can use `currentDriver(ptyId)` as the admission predicate
|
||||
(only the current driver's bytes are dequeued), and the
|
||||
`mobile{clientId}` payload tells it which queue head to drain when a
|
||||
specific phone is the active actor. Today's PR keeps two independent
|
||||
write paths and uses driver state purely as a drop-filter; the same
|
||||
state machine becomes the scheduling input on the forward path without
|
||||
a wire-format change.
|
||||
|
||||
## Rollout
|
||||
|
||||
Single PR. No feature flag needed; behavior is strictly additive (locks
|
||||
an existing collision surface) and the existing banner UX continues to
|
||||
work under the new driver-state model with sharper copy.
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
ActivityIndicator,
|
||||
TextInput
|
||||
} from 'react-native'
|
||||
import { SafeAreaView } from 'react-native-safe-area-context'
|
||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router'
|
||||
import {
|
||||
Search,
|
||||
@@ -51,6 +51,11 @@ type Worktree = {
|
||||
repo: string
|
||||
branch: string
|
||||
displayName: string
|
||||
// Why: on-disk worktree directory path. Needed by NewWorktreeModal so the
|
||||
// marine-creature fallback dedupes against the actual filesystem basenames
|
||||
// (matching the desktop's collision check), not against displayName which
|
||||
// the user may have renamed.
|
||||
path: string
|
||||
liveTerminalCount: number
|
||||
hasAttachedPty: boolean
|
||||
preview: string
|
||||
@@ -235,6 +240,7 @@ function buildSections(
|
||||
export default function HostScreen() {
|
||||
const { hostId, action } = useLocalSearchParams<{ hostId: string; action?: string }>()
|
||||
const router = useRouter()
|
||||
const insets = useSafeAreaInsets()
|
||||
const [initialCache] = useState(() =>
|
||||
hostId ? (getCachedWorktrees(hostId) as Worktree[] | null) : null
|
||||
)
|
||||
@@ -764,7 +770,10 @@ export default function HostScreen() {
|
||||
sections={sections}
|
||||
keyExtractor={(w) => w.worktreeId}
|
||||
stickySectionHeadersEnabled={false}
|
||||
contentContainerStyle={styles.list}
|
||||
// Why: edge-to-edge — the list scrolls under the system nav bar
|
||||
// while reserving insets.bottom keeps the last worktree row reachable
|
||||
// above the Samsung 3-button nav / iOS home indicator.
|
||||
contentContainerStyle={[styles.list, { paddingBottom: spacing.lg + insets.bottom }]}
|
||||
renderSectionHeader={({ section }) => {
|
||||
if (!section.title) return null
|
||||
const isCollapsed = collapsedGroups.has(section.title)
|
||||
@@ -1016,6 +1025,7 @@ export default function HostScreen() {
|
||||
<NewWorktreeModal
|
||||
visible={showNewWorktree}
|
||||
client={client}
|
||||
existingWorktreePaths={worktrees.map((w) => w.path)}
|
||||
onCreated={(worktreeId, worktreeName) => {
|
||||
void fetchWorktrees()
|
||||
const params = new URLSearchParams({ name: worktreeName, created: '1' })
|
||||
|
||||
@@ -6,11 +6,12 @@ import {
|
||||
ScrollView,
|
||||
TextInput,
|
||||
Pressable,
|
||||
KeyboardAvoidingView,
|
||||
Keyboard,
|
||||
Platform,
|
||||
ActivityIndicator
|
||||
ActivityIndicator,
|
||||
type KeyboardEvent
|
||||
} from 'react-native'
|
||||
import { SafeAreaView } from 'react-native-safe-area-context'
|
||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import { ArrowUp, ChevronLeft, Monitor, Plus, Smartphone } from 'lucide-react-native'
|
||||
@@ -121,6 +122,7 @@ export default function SessionScreen() {
|
||||
created?: string
|
||||
}>()
|
||||
const router = useRouter()
|
||||
const insets = useSafeAreaInsets()
|
||||
const [client, setClient] = useState<RpcClient | null>(null)
|
||||
const [connState, setConnState] = useState<ConnectionState>('disconnected')
|
||||
const [terminals, setTerminals] = useState<Terminal[]>([])
|
||||
@@ -134,6 +136,11 @@ export default function SessionScreen() {
|
||||
const [customKeys, setCustomKeys] = useState<CustomKey[]>([])
|
||||
const [showCustomKeyModal, setShowCustomKeyModal] = useState(false)
|
||||
const [deleteKeyTarget, setDeleteKeyTarget] = useState<CustomKey | null>(null)
|
||||
// Why: in Expo SDK 55 edge-to-edge mode the OS does NOT resize the window when
|
||||
// the IME opens — the keyboard draws on top of the app. We track the keyboard
|
||||
// height ourselves and apply it as paddingBottom on the input/accessory area
|
||||
// so the input lifts above the IME and the terminal flex container shrinks.
|
||||
const [keyboardHeight, setKeyboardHeight] = useState(0)
|
||||
// Why: server-authoritative display mode per terminal. The runtime is the
|
||||
// single source of truth — this state is populated from subscribe responses.
|
||||
const [terminalModes, setTerminalModes] = useState<Map<string, MobileDisplayMode>>(new Map())
|
||||
@@ -253,6 +260,14 @@ export default function SessionScreen() {
|
||||
new Map(prev).set(handle, data.displayMode as MobileDisplayMode)
|
||||
)
|
||||
}
|
||||
// Why: cold-start fit-to-screen guard. The first init() runs
|
||||
// before xterm's DOM/canvas has fully laid out, so the
|
||||
// applyFitScale that init queues internally can land while
|
||||
// term.element.scrollWidth is still stale or zero — leaving
|
||||
// the terminal un-zoomed until the user toggles the resize
|
||||
// button. Re-fire resetZoom after a short delay so it runs
|
||||
// against a settled DOM. Mirrors the 'resized' handler below.
|
||||
setTimeout(() => getTerminalRef(handle)?.resetZoom(), 200)
|
||||
// Why: viewport measurement needs xterm to be initialized (cell
|
||||
// dimensions come from the renderer). On the first subscribe the
|
||||
// WebView hasn't loaded yet, so viewportRef is null and the server
|
||||
@@ -320,7 +335,15 @@ export default function SessionScreen() {
|
||||
const next: MobileDisplayMode = current === 'auto' || current === 'phone' ? 'desktop' : 'auto'
|
||||
toggleInFlightRef.current.add(handle)
|
||||
try {
|
||||
await client.sendRequest('terminal.setDisplayMode', { terminal: handle, mode: next })
|
||||
await client.sendRequest('terminal.setDisplayMode', {
|
||||
terminal: handle,
|
||||
mode: next,
|
||||
// Why: presence-lock take-floor signal. Sending mode=auto/phone
|
||||
// is a deliberate "I want to drive at phone dims" gesture.
|
||||
...(deviceTokenRef.current
|
||||
? { client: { id: deviceTokenRef.current, type: 'mobile' as const } }
|
||||
: {})
|
||||
})
|
||||
} catch {
|
||||
// Mode change failed — server state unchanged, UI stays in sync.
|
||||
} finally {
|
||||
@@ -429,6 +452,76 @@ export default function SessionScreen() {
|
||||
void loadCustomKeys().then(setCustomKeys)
|
||||
}, [])
|
||||
|
||||
// Why: drive the bottom padding from the keyboard height (edge-to-edge mode
|
||||
// doesn't resize the window) and refit xterm once the layout settles so the
|
||||
// terminal grid matches the new visible area. iOS exposes 'will' events that
|
||||
// animate in sync with the IME; Android only fires 'did' events reliably.
|
||||
useEffect(() => {
|
||||
let refitTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const scheduleRefit = () => {
|
||||
if (refitTimer) clearTimeout(refitTimer)
|
||||
refitTimer = setTimeout(() => {
|
||||
const handle = activeHandleRef.current
|
||||
if (!handle) return
|
||||
const ref = terminalRefs.current.get(handle)
|
||||
if (!ref) return
|
||||
void (async () => {
|
||||
const dims = await ref.measureFitDimensions(terminalFrameHeightRef.current || undefined)
|
||||
if (!dims) return
|
||||
const prev = viewportRef.current
|
||||
if (prev && prev.cols === dims.cols && prev.rows === dims.rows) return
|
||||
viewportRef.current = dims
|
||||
viewportMeasuredRef.current = true
|
||||
// Why: prefer the in-place viewport update RPC over the legacy
|
||||
// unsubscribe → subscribe cycle. This keeps the server-side
|
||||
// mobile subscriber record alive (no driver=idle blip on the
|
||||
// desktop banner; no false phone-fit baseline capture on the
|
||||
// re-subscribe). The 'resized' event from the server reinits
|
||||
// the xterm at the new dims via the existing subscription
|
||||
// stream. Falls back to the unsubscribe/subscribe path if the
|
||||
// RPC isn't available (older host build) or no client is
|
||||
// connected. See docs/mobile-presence-lock.md.
|
||||
const rpc = clientRef.current
|
||||
const deviceToken = deviceTokenRef.current
|
||||
if (rpc && deviceToken) {
|
||||
try {
|
||||
const response = await rpc.sendRequest('terminal.updateViewport', {
|
||||
terminal: handle,
|
||||
client: { id: deviceToken, type: 'mobile' as const },
|
||||
viewport: dims
|
||||
})
|
||||
if (response.ok) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through to legacy resubscribe.
|
||||
}
|
||||
}
|
||||
unsubscribeTerminal(handle)
|
||||
initializedHandlesRef.current.delete(handle)
|
||||
subscribeToTerminal(handle)
|
||||
})()
|
||||
}, 150)
|
||||
}
|
||||
const onShow = (e: KeyboardEvent) => {
|
||||
setKeyboardHeight(e.endCoordinates?.height ?? 0)
|
||||
scheduleRefit()
|
||||
}
|
||||
const onHide = () => {
|
||||
setKeyboardHeight(0)
|
||||
scheduleRefit()
|
||||
}
|
||||
const showEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow'
|
||||
const hideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide'
|
||||
const showSub = Keyboard.addListener(showEvent, onShow)
|
||||
const hideSub = Keyboard.addListener(hideEvent, onHide)
|
||||
return () => {
|
||||
if (refitTimer) clearTimeout(refitTimer)
|
||||
showSub.remove()
|
||||
hideSub.remove()
|
||||
}
|
||||
}, [subscribeToTerminal, unsubscribeTerminal])
|
||||
|
||||
useEffect(() => {
|
||||
if (hostId && worktreeId) {
|
||||
void AsyncStorage.setItem(
|
||||
@@ -599,7 +692,13 @@ export default function SessionScreen() {
|
||||
await client.sendRequest('terminal.send', {
|
||||
terminal: activeHandle,
|
||||
text,
|
||||
enter: true
|
||||
enter: true,
|
||||
// Why: presence-lock take-floor signal. Identifies this phone as
|
||||
// the active mobile actor so the runtime can resolve multi-mobile
|
||||
// contention (most-recent-actor's viewport wins).
|
||||
...(deviceTokenRef.current
|
||||
? { client: { id: deviceTokenRef.current, type: 'mobile' as const } }
|
||||
: {})
|
||||
})
|
||||
} catch {
|
||||
setInput(text)
|
||||
@@ -615,7 +714,10 @@ export default function SessionScreen() {
|
||||
await client.sendRequest('terminal.send', {
|
||||
terminal: activeHandle,
|
||||
text: bytes,
|
||||
enter: false
|
||||
enter: false,
|
||||
...(deviceTokenRef.current
|
||||
? { client: { id: deviceTokenRef.current, type: 'mobile' as const } }
|
||||
: {})
|
||||
})
|
||||
} catch {
|
||||
// Transient failure
|
||||
@@ -733,13 +835,21 @@ export default function SessionScreen() {
|
||||
: `${terminals.length} terminals`
|
||||
: STATUS_LABELS[connState]
|
||||
|
||||
// Why: on Android (Samsung 3-button) the keyboard event reports only the IME
|
||||
// height; the system nav bar sits below the keyboard and adds its own height
|
||||
// on top, so we must add insets.bottom too or the input stays clipped behind
|
||||
// the nav bar. On iOS the keyboard coordinates already include the home
|
||||
// indicator region, so adding insets.bottom would double-count.
|
||||
const bottomPadding =
|
||||
keyboardHeight > 0
|
||||
? Platform.OS === 'ios'
|
||||
? keyboardHeight
|
||||
: keyboardHeight + insets.bottom
|
||||
: insets.bottom
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<KeyboardAvoidingView
|
||||
style={styles.kavInner}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
keyboardVerticalOffset={0}
|
||||
>
|
||||
<View style={styles.kavInner}>
|
||||
<SafeAreaView style={styles.sessionChrome} edges={['top']}>
|
||||
<View style={styles.sessionTopBar}>
|
||||
<Pressable
|
||||
@@ -845,113 +955,120 @@ export default function SessionScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Accessory keys */}
|
||||
<View style={styles.accessoryBar}>
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={styles.accessoryContent}
|
||||
>
|
||||
<Pressable
|
||||
style={({ pressed }) => [
|
||||
styles.accessoryKey,
|
||||
pressed && styles.accessoryKeyPressed,
|
||||
!canSend && styles.accessoryKeyDisabled
|
||||
]}
|
||||
disabled={!canSend}
|
||||
onPress={() => {
|
||||
if (activeHandle) {
|
||||
void toggleDisplayMode(activeHandle)
|
||||
}
|
||||
}}
|
||||
accessibilityLabel={
|
||||
isPhoneMode(activeHandle) ? 'Switch to desktop mode' : 'Switch to phone mode'
|
||||
}
|
||||
{/* Why: bottomPadding lifts the entire input region above the keyboard
|
||||
(when shown) or above the system nav bar / home indicator (when hidden). */}
|
||||
<View style={{ paddingBottom: bottomPadding }}>
|
||||
{/* Accessory keys */}
|
||||
<View style={styles.accessoryBar}>
|
||||
<ScrollView
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={styles.accessoryContent}
|
||||
>
|
||||
{isPhoneMode(activeHandle) ? (
|
||||
<Monitor size={14} color={canSend ? colors.textSecondary : colors.textMuted} />
|
||||
) : (
|
||||
<Smartphone size={14} color={canSend ? colors.textSecondary : colors.textMuted} />
|
||||
)}
|
||||
</Pressable>
|
||||
{ACCESSORY_KEYS.map((key) => (
|
||||
<Pressable
|
||||
key={key.label}
|
||||
style={({ pressed }) => [
|
||||
styles.accessoryKey,
|
||||
pressed && styles.accessoryKeyPressed,
|
||||
!canSend && styles.accessoryKeyDisabled
|
||||
]}
|
||||
disabled={!canSend}
|
||||
onPress={() => void handleAccessoryKey(key.bytes)}
|
||||
accessibilityLabel={key.accessibilityLabel ?? `Send ${key.label}`}
|
||||
>
|
||||
<Text
|
||||
style={[styles.accessoryKeyText, !canSend && styles.accessoryKeyTextDisabled]}
|
||||
>
|
||||
{key.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
{customKeys.map((key) => (
|
||||
<Pressable
|
||||
key={key.id}
|
||||
style={({ pressed }) => [
|
||||
styles.accessoryKey,
|
||||
styles.customAccessoryKey,
|
||||
pressed && styles.accessoryKeyPressed,
|
||||
!canSend && styles.accessoryKeyDisabled
|
||||
]}
|
||||
disabled={!canSend}
|
||||
onPress={() => void handleAccessoryKey(key.bytes)}
|
||||
onLongPress={() => {
|
||||
triggerMediumImpact()
|
||||
setDeleteKeyTarget(key)
|
||||
onPress={() => {
|
||||
if (activeHandle) {
|
||||
void toggleDisplayMode(activeHandle)
|
||||
}
|
||||
}}
|
||||
delayLongPress={400}
|
||||
accessibilityLabel={`Send ${key.label}`}
|
||||
accessibilityLabel={
|
||||
isPhoneMode(activeHandle) ? 'Switch to desktop mode' : 'Switch to phone mode'
|
||||
}
|
||||
>
|
||||
<Text
|
||||
style={[styles.accessoryKeyText, !canSend && styles.accessoryKeyTextDisabled]}
|
||||
>
|
||||
{key.label}
|
||||
</Text>
|
||||
{isPhoneMode(activeHandle) ? (
|
||||
<Monitor size={14} color={canSend ? colors.textSecondary : colors.textMuted} />
|
||||
) : (
|
||||
<Smartphone size={14} color={canSend ? colors.textSecondary : colors.textMuted} />
|
||||
)}
|
||||
</Pressable>
|
||||
))}
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.accessoryKey, pressed && styles.accessoryKeyPressed]}
|
||||
onPress={() => setShowCustomKeyModal(true)}
|
||||
accessibilityLabel="Add custom shortcut"
|
||||
>
|
||||
<Plus size={14} color={colors.textSecondary} strokeWidth={2.2} />
|
||||
</Pressable>
|
||||
</ScrollView>
|
||||
</View>
|
||||
{ACCESSORY_KEYS.map((key) => (
|
||||
<Pressable
|
||||
key={key.label}
|
||||
style={({ pressed }) => [
|
||||
styles.accessoryKey,
|
||||
pressed && styles.accessoryKeyPressed,
|
||||
!canSend && styles.accessoryKeyDisabled
|
||||
]}
|
||||
disabled={!canSend}
|
||||
onPress={() => void handleAccessoryKey(key.bytes)}
|
||||
accessibilityLabel={key.accessibilityLabel ?? `Send ${key.label}`}
|
||||
>
|
||||
<Text
|
||||
style={[styles.accessoryKeyText, !canSend && styles.accessoryKeyTextDisabled]}
|
||||
>
|
||||
{key.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
{customKeys.map((key) => (
|
||||
<Pressable
|
||||
key={key.id}
|
||||
style={({ pressed }) => [
|
||||
styles.accessoryKey,
|
||||
styles.customAccessoryKey,
|
||||
pressed && styles.accessoryKeyPressed,
|
||||
!canSend && styles.accessoryKeyDisabled
|
||||
]}
|
||||
disabled={!canSend}
|
||||
onPress={() => void handleAccessoryKey(key.bytes)}
|
||||
onLongPress={() => {
|
||||
triggerMediumImpact()
|
||||
setDeleteKeyTarget(key)
|
||||
}}
|
||||
delayLongPress={400}
|
||||
accessibilityLabel={`Send ${key.label}`}
|
||||
>
|
||||
<Text
|
||||
style={[styles.accessoryKeyText, !canSend && styles.accessoryKeyTextDisabled]}
|
||||
>
|
||||
{key.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
<Pressable
|
||||
style={({ pressed }) => [
|
||||
styles.accessoryKey,
|
||||
pressed && styles.accessoryKeyPressed
|
||||
]}
|
||||
onPress={() => setShowCustomKeyModal(true)}
|
||||
accessibilityLabel="Add custom shortcut"
|
||||
>
|
||||
<Plus size={14} color={colors.textSecondary} strokeWidth={2.2} />
|
||||
</Pressable>
|
||||
</ScrollView>
|
||||
</View>
|
||||
|
||||
{/* Input bar */}
|
||||
<View style={styles.inputBar}>
|
||||
<TextInput
|
||||
style={styles.textInput}
|
||||
value={input}
|
||||
onChangeText={setInput}
|
||||
placeholder="Type a command…"
|
||||
placeholderTextColor={colors.textMuted}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="send"
|
||||
editable={canSend}
|
||||
onSubmitEditing={() => void handleSend()}
|
||||
/>
|
||||
<Pressable
|
||||
style={[styles.sendButton, !canSend && styles.sendButtonDisabled]}
|
||||
disabled={!canSend}
|
||||
onPress={() => void handleSend()}
|
||||
accessibilityLabel="Send command"
|
||||
>
|
||||
<ArrowUp size={18} color={colors.textSecondary} strokeWidth={2.5} />
|
||||
</Pressable>
|
||||
{/* Input bar */}
|
||||
<View style={styles.inputBar}>
|
||||
<TextInput
|
||||
style={styles.textInput}
|
||||
value={input}
|
||||
onChangeText={setInput}
|
||||
placeholder="Type a command…"
|
||||
placeholderTextColor={colors.textMuted}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="send"
|
||||
editable={canSend}
|
||||
onSubmitEditing={() => void handleSend()}
|
||||
/>
|
||||
<Pressable
|
||||
style={[styles.sendButton, !canSend && styles.sendButtonDisabled]}
|
||||
disabled={!canSend}
|
||||
onPress={() => void handleSend()}
|
||||
accessibilityLabel="Send command"
|
||||
>
|
||||
<ArrowUp size={18} color={colors.textSecondary} strokeWidth={2.5} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
</View>
|
||||
|
||||
<ActionSheetModal
|
||||
visible={actionTarget != null}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useCallback, useEffect, useMemo, useRef } from 'react'
|
||||
import { View, Text, StyleSheet, Pressable, FlatList } from 'react-native'
|
||||
import { SafeAreaView } from 'react-native-safe-area-context'
|
||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'
|
||||
import { useRouter, useFocusEffect } from 'expo-router'
|
||||
import {
|
||||
Monitor,
|
||||
@@ -156,6 +156,7 @@ function repoColor(name: string): string {
|
||||
|
||||
export default function HomeScreen() {
|
||||
const router = useRouter()
|
||||
const insets = useSafeAreaInsets()
|
||||
const [hosts, setHosts] = useState<HostProfile[]>([])
|
||||
const [actionTarget, setActionTarget] = useState<HostProfile | null>(null)
|
||||
const [renameTarget, setRenameTarget] = useState<HostProfile | null>(null)
|
||||
@@ -330,7 +331,7 @@ export default function HomeScreen() {
|
||||
|
||||
{hosts.length === 0 ? (
|
||||
/* ─── Empty state: onboarding ─── */
|
||||
<View style={styles.emptyContainer}>
|
||||
<View style={[styles.emptyContainer, { paddingBottom: insets.bottom }]}>
|
||||
<View style={styles.emptyHero}>
|
||||
<Text style={styles.emptyTitle}>Connect your desktop</Text>
|
||||
<Text style={styles.emptyBody}>
|
||||
@@ -363,7 +364,10 @@ export default function HomeScreen() {
|
||||
<FlatList
|
||||
data={sortedHosts}
|
||||
keyExtractor={(h) => h.id}
|
||||
contentContainerStyle={styles.list}
|
||||
// Why: edge-to-edge — let the list scroll under the system nav bar
|
||||
// but reserve insets.bottom so the last row stays reachable above
|
||||
// the Samsung 3-button nav / iOS home indicator.
|
||||
contentContainerStyle={[styles.list, { paddingBottom: spacing.xl + insets.bottom }]}
|
||||
ListHeaderComponent={
|
||||
<View>
|
||||
<View style={styles.hero}>
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { RpcClient } from '../transport/rpc-client'
|
||||
import type { RpcSuccess } from '../transport/types'
|
||||
import { colors, spacing, radii, typography } from '../theme/mobile-theme'
|
||||
import { BottomDrawer } from './BottomDrawer'
|
||||
import { getSuggestedCreatureName } from './worktree-name-suggestion'
|
||||
|
||||
type Repo = {
|
||||
id: string
|
||||
@@ -248,11 +249,23 @@ function PickerListModal<T extends { id: string; label: string }>({
|
||||
type Props = {
|
||||
visible: boolean
|
||||
client: RpcClient | null
|
||||
// Why: existing worktree paths from the host so we can pick a unique
|
||||
// marine-creature default when the user leaves the name blank, matching
|
||||
// the desktop UI's behavior. The "already exists locally" collision is
|
||||
// on the on-disk directory basename, so paths (not displayNames) are
|
||||
// what the suggestion logic must dedupe against.
|
||||
existingWorktreePaths?: readonly string[]
|
||||
onCreated: (worktreeId: string, name: string) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function NewWorktreeModal({ visible, client, onCreated, onClose }: Props) {
|
||||
export function NewWorktreeModal({
|
||||
visible,
|
||||
client,
|
||||
existingWorktreePaths,
|
||||
onCreated,
|
||||
onClose
|
||||
}: Props) {
|
||||
const [repos, setRepos] = useState<Repo[]>([])
|
||||
const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null)
|
||||
const [showRepoPicker, setShowRepoPicker] = useState(false)
|
||||
@@ -268,6 +281,12 @@ export function NewWorktreeModal({ visible, client, onCreated, onClose }: Props)
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
// Why: matches the desktop UI — the input shows a generic "Workspace name"
|
||||
// placeholder, not the suggested creature. The creature name is only used
|
||||
// as a server-bound fallback when the user submits with a blank field, so
|
||||
// it's recomputed lazily inside handleCreate() to stay fresh against
|
||||
// existingWorktreePaths at submission time.
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) {
|
||||
setShowRepoPicker(false)
|
||||
@@ -358,25 +377,57 @@ export function NewWorktreeModal({ visible, client, onCreated, onClose }: Props)
|
||||
const command =
|
||||
selectedAgent.id !== '__blank__' ? AGENT_COMMANDS[selectedAgent.id] : undefined
|
||||
|
||||
const params: Record<string, unknown> = {
|
||||
repo: `id:${selectedRepo.id}`,
|
||||
startupCommand: command,
|
||||
setupDecision: runSetup ? 'inherit' : 'skip'
|
||||
}
|
||||
if (name.trim()) params.name = name.trim()
|
||||
if (note.trim()) params.comment = note.trim()
|
||||
|
||||
const response = await client.sendRequest('worktree.create', params)
|
||||
|
||||
if (response.ok) {
|
||||
const result = (response as RpcSuccess).result as { worktree: { id: string } }
|
||||
const worktreeId = result.worktree.id
|
||||
|
||||
onClose()
|
||||
onCreated(worktreeId, name.trim() || 'New workspace')
|
||||
} else {
|
||||
setError(response.error.message)
|
||||
// Why: blank name field — match desktop behavior by computing the
|
||||
// next available marine-creature name at submit time and passing it
|
||||
// to the server. The server's worktree.create rejects empty/invalid
|
||||
// names, so we must generate one client-side rather than letting the
|
||||
// server invent one. The pre-flight basename dedupe is only a hint;
|
||||
// the authoritative collision is checked server-side against git
|
||||
// branches/remotes/PRs, so we also retry-with-suffix on conflict.
|
||||
const trimmedName = name.trim()
|
||||
const baseName = trimmedName || getSuggestedCreatureName(existingWorktreePaths ?? [])
|
||||
|
||||
// Why: mirrors src/renderer/src/store/slices/worktrees.ts
|
||||
// (createWorktree retry loop). Server-side checks (Branch X already
|
||||
// exists locally / on a remote / already has PR #N) can fire even
|
||||
// after the pre-flight basename dedupe — branches outlive worktrees
|
||||
// in git, and remote branches/PRs aren't visible from worktree.ps.
|
||||
// Retry up to 25 times by appending -2, -3, ... before surfacing
|
||||
// the error. The desktop applies this to user-typed names too, so
|
||||
// mobile follows suit for parity.
|
||||
const retryablePatterns = [
|
||||
/already exists locally/i,
|
||||
/already exists on a remote/i,
|
||||
/already has pr #\d+/i
|
||||
]
|
||||
const candidateFor = (attempt: number): string =>
|
||||
attempt === 0 ? baseName : `${baseName}-${attempt + 1}`
|
||||
|
||||
let lastError: string | null = null
|
||||
for (let attempt = 0; attempt < 25; attempt += 1) {
|
||||
const candidateName = candidateFor(attempt)
|
||||
const params: Record<string, unknown> = {
|
||||
repo: `id:${selectedRepo.id}`,
|
||||
startupCommand: command,
|
||||
setupDecision: runSetup ? 'inherit' : 'skip',
|
||||
name: candidateName
|
||||
}
|
||||
if (note.trim()) params.comment = note.trim()
|
||||
|
||||
const response = await client.sendRequest('worktree.create', params)
|
||||
if (response.ok) {
|
||||
const result = (response as RpcSuccess).result as { worktree: { id: string } }
|
||||
onClose()
|
||||
onCreated(result.worktree.id, candidateName)
|
||||
return
|
||||
}
|
||||
|
||||
lastError = response.error.message
|
||||
if (!retryablePatterns.some((p) => p.test(lastError ?? ''))) {
|
||||
break
|
||||
}
|
||||
}
|
||||
setError(lastError ?? 'Failed to create workspace')
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to create workspace')
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { MARINE_CREATURES } from '../constants/marine-creatures'
|
||||
|
||||
// Why: matches the desktop fallback in
|
||||
// src/renderer/src/components/sidebar/worktree-name-suggestions.ts. The
|
||||
// "already exists locally" collision is on the on-disk worktree directory
|
||||
// name (the path basename), not the user-facing displayName — so we derive
|
||||
// the used set from path basenames just like the desktop does.
|
||||
|
||||
function stripTrailingSeparators(p: string): string {
|
||||
return p.replace(/[\\/]+$/, '')
|
||||
}
|
||||
|
||||
// Why: cross-platform path basename — handles both POSIX ("/") and Windows
|
||||
// ("\\") separators, mirroring src/renderer/src/lib/path.ts so the mobile
|
||||
// suggestion logic agrees with the desktop's collision check.
|
||||
export function pathBasename(p: string): string {
|
||||
const normalized = stripTrailingSeparators(p)
|
||||
const idx = Math.max(normalized.lastIndexOf('/'), normalized.lastIndexOf('\\'))
|
||||
return idx === -1 ? normalized : normalized.slice(idx + 1)
|
||||
}
|
||||
|
||||
function normalize(name: string): string {
|
||||
return name.trim().toLowerCase()
|
||||
}
|
||||
|
||||
export function getSuggestedCreatureName(existingPaths: readonly string[]): string {
|
||||
const used = new Set<string>()
|
||||
for (const p of existingPaths) {
|
||||
used.add(normalize(pathBasename(p)))
|
||||
}
|
||||
for (const candidate of MARINE_CREATURES) {
|
||||
if (!used.has(normalize(candidate))) return candidate
|
||||
}
|
||||
let suffix = 2
|
||||
while (true) {
|
||||
for (const candidate of MARINE_CREATURES) {
|
||||
const numbered = `${candidate}-${suffix}`
|
||||
if (!used.has(normalize(numbered))) return numbered
|
||||
}
|
||||
suffix += 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
export const MARINE_CREATURES = [
|
||||
'Nautilus',
|
||||
'Seahorse',
|
||||
'Starfish',
|
||||
'Coral',
|
||||
'Narwhal',
|
||||
'Jellyfish',
|
||||
'Octopus',
|
||||
'Manta',
|
||||
'Dolphin',
|
||||
'Manatee',
|
||||
'Cuttlefish',
|
||||
'Anemone',
|
||||
'Urchin',
|
||||
'Triton',
|
||||
'Nudibranch',
|
||||
'Coelacanth',
|
||||
'Oarfish',
|
||||
'Beluga',
|
||||
'Dugong',
|
||||
'Porpoise',
|
||||
'Stingray',
|
||||
'Hammerhead',
|
||||
'Wobbegong',
|
||||
'Sawfish',
|
||||
'Chimaera',
|
||||
'Anglerfish',
|
||||
'Viperfish',
|
||||
'Dragonfish',
|
||||
'Axolotl',
|
||||
'Otter',
|
||||
'Seadragon',
|
||||
'Seahare',
|
||||
'Squid',
|
||||
'Argonaut',
|
||||
'Sponge',
|
||||
'Barnacle',
|
||||
'Cowrie',
|
||||
'Guitarfish',
|
||||
'Lamprey',
|
||||
'Isopod',
|
||||
'Lionfish',
|
||||
'Clownfish',
|
||||
'Angelfish',
|
||||
'Butterflyfish',
|
||||
'Parrotfish',
|
||||
'Pufferfish',
|
||||
'Moonfish',
|
||||
'Firefish',
|
||||
'Unicornfish',
|
||||
'Rainbowfish',
|
||||
'Betta',
|
||||
'Discus',
|
||||
'Arowana',
|
||||
'Koi',
|
||||
'Piranha',
|
||||
'Barracuda',
|
||||
'Moray',
|
||||
'Sunfish',
|
||||
'Lanternfish',
|
||||
'Archerfish',
|
||||
'Mudskipper',
|
||||
'Hatchetfish',
|
||||
'Knifefish',
|
||||
'Leaffish',
|
||||
'Glassfish',
|
||||
'Ropefish',
|
||||
'Bichir',
|
||||
'Tigerfish',
|
||||
'Cardinalfish',
|
||||
'Lungfish',
|
||||
'Opah',
|
||||
'Frogfish',
|
||||
'Stonefish',
|
||||
'Cutlassfish',
|
||||
'Paddlefish',
|
||||
'Arapaima',
|
||||
'Mandarin',
|
||||
'Blobfish',
|
||||
'Thresher',
|
||||
'Vaquita',
|
||||
'Pipefish',
|
||||
'Guppy',
|
||||
'Tetra',
|
||||
'Danio',
|
||||
'Cichlid',
|
||||
'Oscar',
|
||||
'Gourami',
|
||||
'Killifish',
|
||||
'Rasbora',
|
||||
'Pleco',
|
||||
'Goldfish',
|
||||
'Molly',
|
||||
'Platy',
|
||||
'Barb',
|
||||
'Loach',
|
||||
'Medaka',
|
||||
'Pacu',
|
||||
'Filefish',
|
||||
'Boxfish',
|
||||
'Cowfish',
|
||||
'Surgeonfish',
|
||||
'Damselfish',
|
||||
'Wrasse',
|
||||
'Goby',
|
||||
'Blenny',
|
||||
'Conger',
|
||||
'Sculpin',
|
||||
'Darter',
|
||||
'Remora',
|
||||
'Pilotfish',
|
||||
'Trumpetfish',
|
||||
'Cornetfish',
|
||||
'Jawfish',
|
||||
'Toadfish',
|
||||
'Pearlfish',
|
||||
'Driftfish',
|
||||
'Lumpfish',
|
||||
'Snailfish',
|
||||
'Stickleback',
|
||||
'Halfbeak',
|
||||
'Snipefish',
|
||||
'Pencilfish',
|
||||
'Snakehead',
|
||||
'Tripletail',
|
||||
'Lookdown',
|
||||
'Sweetlips',
|
||||
'Squirrelfish',
|
||||
'Soldierfish',
|
||||
'Rabbitfish',
|
||||
'Hawkfish',
|
||||
'Bannerfish',
|
||||
'Batfish',
|
||||
'Chromis',
|
||||
'Anthias',
|
||||
'Fusilier',
|
||||
'Sweeper',
|
||||
'Emperor',
|
||||
'Ponyfish',
|
||||
'Kelpfish',
|
||||
'Weever',
|
||||
'Pearlside',
|
||||
'Opaleye',
|
||||
'Ballyhoo',
|
||||
'Needlefish',
|
||||
'Triggerfish',
|
||||
'Gar',
|
||||
'Tarpon',
|
||||
'Sailfish',
|
||||
'Conch',
|
||||
'Walrus',
|
||||
'Seal',
|
||||
'Penguin',
|
||||
'Hagfish',
|
||||
'Gulper',
|
||||
'Hydra',
|
||||
'Krill',
|
||||
'Salp',
|
||||
'Tunicate',
|
||||
'Crinoid',
|
||||
'Polyp',
|
||||
'Limpet',
|
||||
'Whelk',
|
||||
'Bowfin',
|
||||
'Minnow',
|
||||
'Gudgeon',
|
||||
'Goldeye',
|
||||
'Mooneye',
|
||||
'Soapfish',
|
||||
'Leatherjacket',
|
||||
'Rudderfish',
|
||||
'Sabrefish',
|
||||
'Puffin',
|
||||
'Albatross',
|
||||
'Osprey',
|
||||
'Pelican',
|
||||
'Petrel',
|
||||
'Gannet',
|
||||
'Tern',
|
||||
'Cormorant',
|
||||
'Leatherback',
|
||||
'Hawksbill',
|
||||
'Loggerhead',
|
||||
'Dottyback',
|
||||
'Basslet',
|
||||
'Gramma',
|
||||
'Hamlet',
|
||||
'Hogfish',
|
||||
'Dartfish',
|
||||
'Foxface',
|
||||
'Shrimpfish',
|
||||
'Pyrosome',
|
||||
'Seapen',
|
||||
'Medusa',
|
||||
'Candlefish',
|
||||
'Silverside',
|
||||
'Shiner',
|
||||
'Eelpout',
|
||||
'Madtom',
|
||||
'Shovelnose',
|
||||
'Sandlance',
|
||||
'Tubesnout',
|
||||
'Marlin',
|
||||
'Bonefish',
|
||||
'Dace',
|
||||
'Rudd',
|
||||
'Spirula',
|
||||
'Permit',
|
||||
'Grunt',
|
||||
'Trevally',
|
||||
'Croaker',
|
||||
'Drum',
|
||||
'Ladyfish',
|
||||
'Bullhead',
|
||||
'Torpedo',
|
||||
'Skate',
|
||||
'Hermit',
|
||||
'Fiddler',
|
||||
'Fireworm',
|
||||
'Tubeworm',
|
||||
'Amphipod',
|
||||
'Copepod',
|
||||
'Pteropod',
|
||||
'Seaslug',
|
||||
'Swordtail',
|
||||
'Bluegill',
|
||||
'Pickerel',
|
||||
'Redhorse',
|
||||
'Logperch',
|
||||
'Goblin',
|
||||
'Catshark',
|
||||
'Harlequin',
|
||||
'Murex',
|
||||
'Volute',
|
||||
'Wentletrap',
|
||||
'Nerite',
|
||||
'Stargazer',
|
||||
'Handfish',
|
||||
'Flyingfish',
|
||||
'Waspfish',
|
||||
'Skua',
|
||||
'Shearwater',
|
||||
'Guillemot',
|
||||
'Razorbill',
|
||||
'Auk',
|
||||
'Fulmar',
|
||||
'Murre',
|
||||
'Velvetfish',
|
||||
'Prowfish',
|
||||
'Sandperch',
|
||||
'Bobtail',
|
||||
'Chiton',
|
||||
'Featherstar',
|
||||
'Nereid',
|
||||
'Siren',
|
||||
'Kraken',
|
||||
'Selkie',
|
||||
'Leviathan',
|
||||
'Wolffish',
|
||||
'Wreckfish',
|
||||
'Horseshoe'
|
||||
] as const
|
||||
@@ -159,7 +159,41 @@ const XTERM_HTML = `<!DOCTYPE html>
|
||||
}
|
||||
}
|
||||
|
||||
// Why: on cold start (first WebView load + first scrollback) xterm's DOM
|
||||
// and canvas need several frames to reflow after term.open(). If we
|
||||
// computeFitScale() too eagerly we read scrollWidth=0 or a stale width
|
||||
// from before the new cols took effect, scrollWidth/vpWidth >= 1, and
|
||||
// currentScale snaps to 1 — which is exactly the "didn't zoom to fit"
|
||||
// bug users see on first load. Retry across frames until we get a
|
||||
// positive, stable scrollWidth, then commit. Capped to keep this from
|
||||
// spinning forever if the WebView never lays out (e.g. backgrounded).
|
||||
var FIT_RETRY_MAX_FRAMES = 30;
|
||||
var fitRetryToken = 0;
|
||||
function applyFitScale() {
|
||||
if (!term || !term.element) return;
|
||||
var token = ++fitRetryToken;
|
||||
var attempts = 0;
|
||||
var lastWidth = -1;
|
||||
function attempt() {
|
||||
if (token !== fitRetryToken) return;
|
||||
if (!term || !term.element) return;
|
||||
var w = term.element.scrollWidth;
|
||||
attempts++;
|
||||
if (w > 0 && w === lastWidth) {
|
||||
commitFitScale();
|
||||
return;
|
||||
}
|
||||
lastWidth = w;
|
||||
if (attempts >= FIT_RETRY_MAX_FRAMES) {
|
||||
commitFitScale();
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(attempt);
|
||||
}
|
||||
requestAnimationFrame(attempt);
|
||||
}
|
||||
|
||||
function commitFitScale() {
|
||||
if (!term || !term.element) return;
|
||||
currentScale = computeFitScale();
|
||||
// Why: when the scale is very close to 1 (e.g. 0.97 due to xterm
|
||||
|
||||
@@ -328,13 +328,29 @@ export function connect(
|
||||
typeof stream.params === 'object' &&
|
||||
typeof (stream.params as { terminal?: unknown }).terminal === 'string'
|
||||
) {
|
||||
// Why: the runtime registers cleanup under the composite key
|
||||
// `${terminal}:${clientId}` so two phones subscribing to the same
|
||||
// terminal handle don't evict each other. Echo that composite key
|
||||
// back on unsubscribe; also include `client.id` so the server can
|
||||
// reconstruct it if a stale build emits a bare-handle id. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
const subscribeParams = stream.params as {
|
||||
terminal: string
|
||||
client?: { id?: string }
|
||||
}
|
||||
const clientId =
|
||||
typeof subscribeParams.client?.id === 'string' ? subscribeParams.client.id : undefined
|
||||
const subscriptionId = clientId
|
||||
? `${subscribeParams.terminal}:${clientId}`
|
||||
: subscribeParams.terminal
|
||||
sendEncrypted({
|
||||
id: nextId(),
|
||||
deviceToken,
|
||||
method: 'terminal.unsubscribe',
|
||||
// Why: the runtime keys terminal subscription cleanup by terminal
|
||||
// handle, not by the RPC request id used to open the stream.
|
||||
params: { subscriptionId: (stream.params as { terminal: string }).terminal }
|
||||
params: {
|
||||
subscriptionId,
|
||||
...(clientId ? { client: { id: clientId } } : {})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+202
-7
@@ -70,6 +70,45 @@ export function registerPaneKeyTeardownListener(listener: PaneKeyTeardownListene
|
||||
return () => paneKeyTeardownListeners.delete(listener)
|
||||
}
|
||||
|
||||
// Why: pre-signal handshake — the renderer declares it will own the serializer
|
||||
// for a paneKey BEFORE issuing pty:spawn. The cooperation gate at provider.spawn
|
||||
// return consults this map to suppress the daemon-snapshot seed when a renderer
|
||||
// is taking over. Generation tokens prevent paneKey-reuse races during teardown:
|
||||
// a paneKeyTeardownListener cleanup only fires settle when the captured gen
|
||||
// still matches, so a remount that pre-signals before the old PTY's teardown
|
||||
// runs is preserved. See docs/mobile-prefer-renderer-scrollback.md.
|
||||
let pendingSerializerGenSeq = 0
|
||||
const pendingByPaneKey = new Map<string, number>()
|
||||
// Why: at PTY spawn time we capture the gen that was pending for the spawn's
|
||||
// paneKey, so teardown can settle ONLY that gen. Without this, a paneKey
|
||||
// remount that replaces the pending entry with a new gen would still get
|
||||
// stomped by the old PTY's teardown firing settle on the wrong gen.
|
||||
const ptyPendingGenByPtyId = new Map<string, number>()
|
||||
// Why: the runtime's hasRendererSerializer probe needs a ptyId-keyed signal.
|
||||
// Populated on settlePaneSerializer (renderer has registered for this ptyId)
|
||||
// and cleared on PTY teardown.
|
||||
const rendererSerializerByPtyId = new Set<string>()
|
||||
|
||||
function isValidPaneKey(paneKey: unknown): paneKey is string {
|
||||
return typeof paneKey === 'string' && paneKey.length > 0 && paneKey.length <= 256
|
||||
}
|
||||
|
||||
function declarePendingPaneSerializer(paneKey: string): number {
|
||||
const gen = ++pendingSerializerGenSeq
|
||||
pendingByPaneKey.set(paneKey, gen)
|
||||
return gen
|
||||
}
|
||||
|
||||
function settlePendingPaneSerializer(paneKey: string, gen: number): void {
|
||||
if (pendingByPaneKey.get(paneKey) === gen) {
|
||||
pendingByPaneKey.delete(paneKey)
|
||||
}
|
||||
}
|
||||
|
||||
export function hasPendingRendererSerializerForPaneKey(paneKey: string): boolean {
|
||||
return isValidPaneKey(paneKey) && pendingByPaneKey.has(paneKey)
|
||||
}
|
||||
|
||||
function getProvider(connectionId: string | null | undefined): IPtyProvider {
|
||||
if (!connectionId) {
|
||||
return localProvider
|
||||
@@ -293,6 +332,7 @@ export function clearProviderPtyState(id: string): void {
|
||||
// trying to resolve its (now-dead) pid on every snapshot. Safe no-op for
|
||||
// PTYs that were never registered (SSH-owned).
|
||||
unregisterPty(id)
|
||||
rendererSerializerByPtyId.delete(id)
|
||||
// Why: the hook server's per-paneKey caches (lastPrompt / lastTool) would
|
||||
// otherwise accumulate entries for dead panes over the process lifetime.
|
||||
// Use the spawn-time paneKey mapping since the server has no other way to
|
||||
@@ -302,6 +342,17 @@ export function clearProviderPtyState(id: string): void {
|
||||
agentHookServer.clearPaneState(paneKey)
|
||||
ptyPaneKey.delete(id)
|
||||
paneKeyPtyId.delete(paneKey)
|
||||
// Why: drop the pre-signal pending entry only if it still belongs to THIS
|
||||
// PTY's spawn generation. If a remount for the same paneKey has already
|
||||
// pre-signaled a new gen, this teardown must NOT touch it — otherwise
|
||||
// the second mount's hydration loses to the daemon-snapshot seed. See
|
||||
// the generation-token rationale in
|
||||
// docs/mobile-prefer-renderer-scrollback.md.
|
||||
const ownedGen = ptyPendingGenByPtyId.get(id)
|
||||
if (ownedGen !== undefined) {
|
||||
settlePendingPaneSerializer(paneKey, ownedGen)
|
||||
}
|
||||
ptyPendingGenByPtyId.delete(id)
|
||||
// Why: notify registered consumers AFTER we've dropped the paneKey↔ptyId
|
||||
// entries so a listener that re-reads the map sees the post-teardown
|
||||
// state. Wrap each call so one throwing listener cannot block the rest.
|
||||
@@ -368,6 +419,9 @@ export function registerPtyHandlers(
|
||||
ipcMain.removeHandler('pty:hasChildProcesses')
|
||||
ipcMain.removeHandler('pty:getForegroundProcess')
|
||||
ipcMain.removeHandler('pty:getCwd')
|
||||
ipcMain.removeHandler('pty:declarePendingPaneSerializer')
|
||||
ipcMain.removeHandler('pty:settlePaneSerializer')
|
||||
ipcMain.removeHandler('pty:clearPendingPaneSerializer')
|
||||
ipcMain.removeAllListeners('pty:write')
|
||||
ipcMain.removeAllListeners('pty:ackColdRestore')
|
||||
|
||||
@@ -492,8 +546,9 @@ export function registerPtyHandlers(
|
||||
rebindProviderListeners = bindProviderListeners
|
||||
|
||||
function requestSerializedBuffer(
|
||||
ptyId: string
|
||||
): Promise<{ data: string; cols: number; rows: number } | null> {
|
||||
ptyId: string,
|
||||
opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }
|
||||
): Promise<{ data: string; cols: number; rows: number; lastTitle?: string } | null> {
|
||||
if (mainWindow.isDestroyed()) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
@@ -514,7 +569,12 @@ export function registerPtyHandlers(
|
||||
_event: Electron.IpcMainEvent,
|
||||
args: {
|
||||
requestId?: string
|
||||
snapshot?: { data?: unknown; cols?: unknown; rows?: unknown } | null
|
||||
snapshot?: {
|
||||
data?: unknown
|
||||
cols?: unknown
|
||||
rows?: unknown
|
||||
lastTitle?: unknown
|
||||
} | null
|
||||
}
|
||||
): void => {
|
||||
if (args.requestId !== requestId) {
|
||||
@@ -528,14 +588,30 @@ export function registerPtyHandlers(
|
||||
typeof snapshot.cols === 'number' &&
|
||||
typeof snapshot.rows === 'number'
|
||||
) {
|
||||
resolve({ data: snapshot.data, cols: snapshot.cols, rows: snapshot.rows })
|
||||
const result: { data: string; cols: number; rows: number; lastTitle?: string } = {
|
||||
data: snapshot.data,
|
||||
cols: snapshot.cols,
|
||||
rows: snapshot.rows
|
||||
}
|
||||
if (typeof snapshot.lastTitle === 'string' && snapshot.lastTitle.length > 0) {
|
||||
result.lastTitle = snapshot.lastTitle
|
||||
}
|
||||
resolve(result)
|
||||
} else {
|
||||
resolve(null)
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.on('pty:serializeBuffer:response', onResponse)
|
||||
mainWindow.webContents.send('pty:serializeBuffer:request', { requestId, ptyId })
|
||||
const payload: {
|
||||
requestId: string
|
||||
ptyId: string
|
||||
opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }
|
||||
} = { requestId, ptyId }
|
||||
if (opts) {
|
||||
payload.opts = opts
|
||||
}
|
||||
mainWindow.webContents.send('pty:serializeBuffer:request', payload)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -598,10 +674,18 @@ export function registerPtyHandlers(
|
||||
])
|
||||
return providerSessions.flat()
|
||||
},
|
||||
serializeBuffer: (ptyId) => {
|
||||
serializeBuffer: (ptyId, opts) => {
|
||||
// Why: mobile xterm must start from the desktop xterm's exact screen
|
||||
// state and dimensions before live TUI chunks can render correctly.
|
||||
return requestSerializedBuffer(ptyId)
|
||||
return requestSerializedBuffer(ptyId, opts)
|
||||
},
|
||||
hasRendererSerializer: (ptyId) => {
|
||||
// Why: the runtime needs a synchronous probe so it can decide whether to
|
||||
// skip the daemon-snapshot seed (the renderer will hydrate it) or run the
|
||||
// seed (no renderer authoritative for this PTY). A registry write happens
|
||||
// when the renderer calls registerPtySerializer; we check via the same
|
||||
// pendingByPaneKey + ptyId pairing that the cooperation gate uses.
|
||||
return rendererSerializerByPtyId.has(ptyId)
|
||||
},
|
||||
getSize: (ptyId) => ptySizes.get(ptyId) ?? null,
|
||||
resize: (ptyId, cols, rows) => {
|
||||
@@ -802,6 +886,53 @@ export function registerPtyHandlers(
|
||||
runtime?.registerPreAllocatedHandleForPty(result.id, preAllocatedHandle)
|
||||
}
|
||||
ptySizes.set(result.id, { cols: args.cols, rows: args.rows })
|
||||
// Why: pre-signal cooperation gate — when the renderer has declared it
|
||||
// will own the serializer for this paneKey, suppress the daemon-snapshot
|
||||
// seed so the renderer's hydration path (maybeHydrateHeadlessFromRenderer)
|
||||
// is the sole authority. The pre-signal is keyed on paneKey because at
|
||||
// spawn time the renderer doesn't yet know the new ptyId. See
|
||||
// docs/mobile-prefer-renderer-scrollback.md.
|
||||
const spawnPaneKey = args.env?.ORCA_PANE_KEY
|
||||
const rendererPreSignaled = isValidPaneKey(spawnPaneKey)
|
||||
? pendingByPaneKey.has(spawnPaneKey)
|
||||
: false
|
||||
const rendererAlreadyRegistered = rendererSerializerByPtyId.has(result.id)
|
||||
// Why: capture the pending gen at spawn time so teardown for THIS PTY
|
||||
// only settles its own generation. A remount that replaces the entry
|
||||
// with a new gen must not be stomped by the old PTY's teardown.
|
||||
if (isValidPaneKey(spawnPaneKey) && rendererPreSignaled) {
|
||||
const gen = pendingByPaneKey.get(spawnPaneKey)
|
||||
if (gen !== undefined) {
|
||||
ptyPendingGenByPtyId.set(result.id, gen)
|
||||
}
|
||||
}
|
||||
|
||||
// Why: hydrate the runtime's headless emulator with the adapter's
|
||||
// restore data BEFORE registerPty so any live PTY data that arrives
|
||||
// concurrently lands on top of the seed instead of replacing it. Mobile
|
||||
// subscribers then see the same scrollback the desktop xterm received
|
||||
// via coldRestore/snapshot. Without this, mobile snapshots after a
|
||||
// daemon-restored attach contain only bytes emitted since the relaunch
|
||||
// and the prior agent output silently disappears.
|
||||
//
|
||||
// Skip when the renderer is or will be authoritative for this PTY:
|
||||
// its hydration path will seed the emulator from xterm's live buffer,
|
||||
// which is richer than the daemon snapshot.
|
||||
if (runtime && !rendererPreSignaled && !rendererAlreadyRegistered) {
|
||||
const seedSize =
|
||||
typeof result.snapshotCols === 'number' && typeof result.snapshotRows === 'number'
|
||||
? { cols: result.snapshotCols, rows: result.snapshotRows }
|
||||
: undefined
|
||||
if (typeof result.snapshot === 'string' && result.snapshot.length > 0) {
|
||||
runtime.seedHeadlessTerminal(result.id, result.snapshot, seedSize)
|
||||
} else if (
|
||||
result.coldRestore &&
|
||||
typeof result.coldRestore.scrollback === 'string' &&
|
||||
result.coldRestore.scrollback.length > 0
|
||||
) {
|
||||
runtime.seedHeadlessTerminal(result.id, result.coldRestore.scrollback, seedSize)
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof args.worktreeId === 'string' &&
|
||||
args.worktreeId.length > 0 &&
|
||||
@@ -867,6 +998,15 @@ export function registerPtyHandlers(
|
||||
)
|
||||
|
||||
ipcMain.on('pty:write', (_event, args: { id: string; data: string }) => {
|
||||
// Why: defense-in-depth for the mobile-presence lock. The renderer's
|
||||
// xterm.onData guard already drops desktop keystrokes when mobile is
|
||||
// driving, but a stale view between the main-side state flip and the
|
||||
// IPC arriving in the renderer can let one keystroke slip through.
|
||||
// This server-side check catches it. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
if (runtime?.getDriver(args.id).kind === 'mobile') {
|
||||
return
|
||||
}
|
||||
getProviderForPty(args.id).write(args.id, args.data)
|
||||
})
|
||||
|
||||
@@ -883,6 +1023,16 @@ export function registerPtyHandlers(
|
||||
if (runtime?.isResizeSuppressed()) {
|
||||
return
|
||||
}
|
||||
// Why: presence-lock defense-in-depth. While mobile is driving,
|
||||
// desktop-side resizes (auto-fit on window resize, split drag) must
|
||||
// not reach the PTY. The renderer guard checks the driver state too,
|
||||
// but this is the load-bearing layer because the renderer mirror lags
|
||||
// by one IPC hop. Note: BOTH guards apply — isResizeSuppressed handles
|
||||
// the safeFit cascade after take-back; this driver check handles the
|
||||
// ongoing locked state. See docs/mobile-presence-lock.md.
|
||||
if (runtime?.getDriver(args.id).kind === 'mobile') {
|
||||
return
|
||||
}
|
||||
ptySizes.set(args.id, { cols: args.cols, rows: args.rows })
|
||||
getProviderForPty(args.id).resize(args.id, args.cols, args.rows)
|
||||
runtime?.onExternalPtyResize(args.id, args.cols, args.rows)
|
||||
@@ -980,6 +1130,51 @@ export function registerPtyHandlers(
|
||||
return ''
|
||||
}
|
||||
})
|
||||
|
||||
// Why: pre-signal handshake handlers. See
|
||||
// docs/mobile-prefer-renderer-scrollback.md and the rationale on
|
||||
// `pendingByPaneKey` above. The IPC contract is: renderer awaits declare
|
||||
// (capturing the returned gen), awaits pty:spawn, then registers its
|
||||
// serializer locally and calls settle (echoing the gen). On spawn rejection
|
||||
// or pane unmount before settle, renderer calls clear with the same gen.
|
||||
ipcMain.handle(
|
||||
'pty:declarePendingPaneSerializer',
|
||||
async (_event, args: { paneKey?: unknown }): Promise<number> => {
|
||||
if (!isValidPaneKey(args.paneKey)) {
|
||||
throw new Error('Invalid paneKey')
|
||||
}
|
||||
return declarePendingPaneSerializer(args.paneKey)
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'pty:settlePaneSerializer',
|
||||
async (_event, args: { paneKey?: unknown; gen?: unknown }): Promise<void> => {
|
||||
if (!isValidPaneKey(args.paneKey) || typeof args.gen !== 'number') {
|
||||
return
|
||||
}
|
||||
settlePendingPaneSerializer(args.paneKey, args.gen)
|
||||
// Why: settle means the renderer has registered its serializer locally
|
||||
// for whatever ptyId came back from spawn. The renderer doesn't carry
|
||||
// the ptyId back through this IPC because the cooperation gate ran
|
||||
// pre-spawn; instead we mark the pane as authoritative by paneKey →
|
||||
// ptyId via the existing paneKeyPtyId mapping populated at spawn.
|
||||
const ptyId = paneKeyPtyId.get(args.paneKey)
|
||||
if (ptyId) {
|
||||
rendererSerializerByPtyId.add(ptyId)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'pty:clearPendingPaneSerializer',
|
||||
async (_event, args: { paneKey?: unknown; gen?: unknown }): Promise<void> => {
|
||||
if (!isValidPaneKey(args.paneKey) || typeof args.gen !== 'number') {
|
||||
return
|
||||
}
|
||||
settlePendingPaneSerializer(args.paneKey, args.gen)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -39,14 +39,15 @@ export function registerRuntimeHandlers(runtime: OrcaRuntimeService): void {
|
||||
// code path as the mobile toggle button (terminal.setDisplayMode RPC).
|
||||
ipcMain.removeHandler('runtime:restoreTerminalFit')
|
||||
ipcMain.handle('runtime:restoreTerminalFit', (_event, args: { ptyId: string }) => {
|
||||
const override = runtime.getTerminalFitOverride(args.ptyId)
|
||||
if (!override) {
|
||||
return { restored: false }
|
||||
}
|
||||
// Why: this IPC powers the desktop "Take back" button. Beyond restoring
|
||||
// PTY dims (the original semantic), it now also reclaims the input
|
||||
// floor for the desktop via the driver state machine. The lock banner
|
||||
// unmounts and desktop input/resize are unblocked until the next
|
||||
// mobile interaction takes the floor again. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
try {
|
||||
runtime.setMobileDisplayMode(args.ptyId, 'desktop')
|
||||
runtime.applyMobileDisplayMode(args.ptyId)
|
||||
return { restored: true }
|
||||
const reclaimed = runtime.reclaimTerminalForDesktop(args.ptyId)
|
||||
return { restored: reclaimed }
|
||||
} catch {
|
||||
return { restored: false }
|
||||
}
|
||||
|
||||
@@ -98,7 +98,8 @@ describe('fit override integration', () => {
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: (ptyId, mode, cols, rows) => {
|
||||
notifications.push({ ptyId, mode, cols, rows })
|
||||
}
|
||||
},
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
|
||||
// Simulate a synced leaf (mounted desktop pane)
|
||||
@@ -200,7 +201,8 @@ describe('fit override integration', () => {
|
||||
focusTerminal: vi.fn(),
|
||||
closeTerminal: vi.fn(),
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: vi.fn()
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
|
||||
// Synced leaf = mounted desktop pane
|
||||
@@ -261,7 +263,8 @@ describe('fit override integration', () => {
|
||||
focusTerminal: vi.fn(),
|
||||
closeTerminal: vi.fn(),
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: vi.fn()
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
|
||||
runtime.resizeForClient('pty-1', 'mobile-fit', 'phone-disconnect', 45, 20)
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* Tests for the presence-based mobile driver lock.
|
||||
*
|
||||
* Covers (per docs/mobile-presence-lock.md):
|
||||
* - State machine transitions (idle | desktop | mobile{clientId})
|
||||
* - Most-recent-actor wins for active phone-fit dims
|
||||
* - Earliest-by-subscribe-time wins for desktop-restore target
|
||||
* - Subscribe-in-desktop-mode is a passive watch (does NOT take floor)
|
||||
* - mobileTookFloor → re-applies phone-fit when transitioning from desktop
|
||||
* - reclaimTerminalForDesktop → idempotent, drops banner, restores dims
|
||||
* - Multi-mobile sequencing: A subscribes / B subscribes / B unsubscribes /
|
||||
* A unsubscribes leaves the runtime cleanly idle without dim regressions
|
||||
* - terminalDriverChanged notifications fire at the right transitions
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
|
||||
vi.mock('../git/worktree', () => ({
|
||||
listWorktrees: vi.fn().mockResolvedValue([])
|
||||
}))
|
||||
vi.mock('../hooks', () => ({
|
||||
createSetupRunnerScript: vi.fn(),
|
||||
getEffectiveHooks: vi.fn().mockReturnValue(null),
|
||||
runHook: vi.fn().mockResolvedValue({ success: true, output: '' })
|
||||
}))
|
||||
vi.mock('../ipc/worktree-logic', async (importOriginal) => {
|
||||
const actual = (await importOriginal()) as Record<string, unknown>
|
||||
return { ...actual, computeWorktreePath: vi.fn(), ensurePathWithinWorkspace: vi.fn() }
|
||||
})
|
||||
vi.mock('../ipc/filesystem-auth', () => ({ invalidateAuthorizedRootsCache: vi.fn() }))
|
||||
vi.mock('../git/repo', async (importOriginal) => {
|
||||
const actual = (await importOriginal()) as Record<string, unknown>
|
||||
return {
|
||||
...actual,
|
||||
getDefaultBaseRef: vi.fn().mockReturnValue('origin/main'),
|
||||
getBranchConflictKind: vi.fn().mockResolvedValue(null),
|
||||
getGitUsername: vi.fn().mockReturnValue('')
|
||||
}
|
||||
})
|
||||
|
||||
const store = {
|
||||
getRepo: () => ({
|
||||
id: 'repo-1',
|
||||
path: '/tmp/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: 'blue',
|
||||
addedAt: 1
|
||||
}),
|
||||
getRepos: () => [store.getRepo()],
|
||||
addRepo: () => {},
|
||||
updateRepo: () => undefined as never,
|
||||
getAllWorktreeMeta: () => ({}),
|
||||
getWorktreeMeta: () => undefined,
|
||||
getGitHubCache: () => ({ pr: {}, issue: {} }),
|
||||
setWorktreeMeta: () => undefined as never,
|
||||
removeWorktreeMeta: () => {},
|
||||
getSettings: () => ({
|
||||
workspaceDir: '/tmp/workspaces',
|
||||
nestWorkspaces: false,
|
||||
refreshLocalBaseRefOnWorktreeCreate: false,
|
||||
branchPrefix: 'none',
|
||||
branchPrefixCustom: ''
|
||||
})
|
||||
}
|
||||
|
||||
function createRuntime() {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
const ptySizes = new Map<string, { cols: number; rows: number }>([
|
||||
['pty-1', { cols: 150, rows: 40 }]
|
||||
])
|
||||
const resizes: { ptyId: string; cols: number; rows: number }[] = []
|
||||
const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = []
|
||||
|
||||
runtime.setPtyController({
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null,
|
||||
resize: (ptyId, cols, rows) => {
|
||||
ptySizes.set(ptyId, { cols, rows })
|
||||
resizes.push({ ptyId, cols, rows })
|
||||
return true
|
||||
},
|
||||
getSize: (ptyId) => ptySizes.get(ptyId) ?? null
|
||||
})
|
||||
runtime.setNotifier({
|
||||
worktreesChanged: vi.fn(),
|
||||
reposChanged: vi.fn(),
|
||||
activateWorktree: vi.fn(),
|
||||
createTerminal: vi.fn(),
|
||||
splitTerminal: vi.fn(),
|
||||
renameTerminal: vi.fn(),
|
||||
focusTerminal: vi.fn(),
|
||||
closeTerminal: vi.fn(),
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: (ptyId, driver) => {
|
||||
driverEvents.push({ ptyId, driver: { ...driver } })
|
||||
}
|
||||
})
|
||||
|
||||
return { runtime, ptySizes, resizes, driverEvents }
|
||||
}
|
||||
|
||||
describe('mobile presence lock — driver state machine', () => {
|
||||
beforeEach(() => vi.useFakeTimers())
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('starts idle for unknown PTY', () => {
|
||||
const { runtime } = createRuntime()
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
})
|
||||
|
||||
it('handleMobileSubscribe in auto mode transitions idle → mobile{clientId}', () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
expect(driverEvents.at(-1)?.driver).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
})
|
||||
|
||||
it('handleMobileSubscribe in desktop mode is passive — does NOT take floor', () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
// Pretend a previous take-back put us in desktop mode.
|
||||
runtime.setMobileDisplayMode('pty-1', 'desktop')
|
||||
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
|
||||
// Driver stays idle (the desktop banner was already gone). Phone is
|
||||
// "passively watching" at desktop dims.
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
expect(driverEvents.find((e) => e.driver.kind === 'mobile')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reclaimTerminalForDesktop transitions mobile → desktop and is idempotent', () => {
|
||||
const { runtime } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
expect(runtime.getDriver('pty-1').kind).toBe('mobile')
|
||||
|
||||
expect(runtime.reclaimTerminalForDesktop('pty-1')).toBe(true)
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'desktop' })
|
||||
|
||||
// Idempotent — second call is a no-op (no active mobile subscriber to
|
||||
// reclaim from).
|
||||
expect(runtime.reclaimTerminalForDesktop('pty-1')).toBe(true)
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'desktop' })
|
||||
})
|
||||
|
||||
it('mobileTookFloor after reclaim re-applies phone-fit and flips driver back to mobile', () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
runtime.reclaimTerminalForDesktop('pty-1')
|
||||
expect(runtime.getDriver('pty-1').kind).toBe('desktop')
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
|
||||
runtime.mobileTookFloor('pty-1', 'phone-A')
|
||||
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
// PTY is back at phone dims.
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 })
|
||||
})
|
||||
|
||||
it('handleMobileUnsubscribe last leaver flips driver to idle after soft-leave grace', () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-A')
|
||||
|
||||
// Why: soft-leave grace keeps driver=mobile{phone-A} for ~250ms so a
|
||||
// re-subscribe (e.g. mobile keyboard show/hide on legacy clients)
|
||||
// doesn't cause a desktop banner flash.
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
|
||||
vi.advanceTimersByTime(250)
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
expect(driverEvents.at(-1)?.driver).toEqual({ kind: 'idle' })
|
||||
})
|
||||
|
||||
it('resubscribe within soft-leave grace cancels idle without driver flap', () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-A')
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
|
||||
// Same client re-subscribes inside the grace window — no idle should
|
||||
// ever be observed by the renderer.
|
||||
vi.advanceTimersByTime(100)
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
vi.advanceTimersByTime(500)
|
||||
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
expect(driverEvents.find((e) => e.driver.kind === 'idle')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('onPtyExit clears driver state and emits idle', () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
|
||||
runtime.onPtyExit('pty-1', 0)
|
||||
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
// The last emitted event for pty-1 must be idle.
|
||||
const last = [...driverEvents].reverse().find((e) => e.ptyId === 'pty-1')
|
||||
expect(last?.driver).toEqual({ kind: 'idle' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('mobile presence lock — multi-mobile semantics', () => {
|
||||
beforeEach(() => vi.useFakeTimers())
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('most-recent actor wins active phone-fit dims (B subscribes after A)', () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 45, rows: 20 })
|
||||
|
||||
// Advance fake clock so B's subscribedAt is strictly greater than A's.
|
||||
vi.advanceTimersByTime(10)
|
||||
// B's narrower viewport must win when it subscribes.
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-B', { cols: 38, rows: 18 })
|
||||
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 38, rows: 18 })
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-B' })
|
||||
})
|
||||
|
||||
it('B unsubscribes — A still present, driver re-elects to A', () => {
|
||||
const { runtime, driverEvents } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
vi.advanceTimersByTime(10)
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-B', { cols: 38, rows: 18 })
|
||||
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-B')
|
||||
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
expect(driverEvents.at(-1)?.driver).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
})
|
||||
|
||||
it('A then B unsubscribes — peer survives; final unsubscribe goes idle', () => {
|
||||
const { runtime } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
vi.advanceTimersByTime(10)
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-B', { cols: 38, rows: 18 })
|
||||
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-A')
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-B' })
|
||||
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-B')
|
||||
// Last leaver enters soft-grace; advance past it before asserting idle.
|
||||
vi.advanceTimersByTime(250)
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
})
|
||||
|
||||
it('terminal.send by phone-B updates lastActedAt — applyMobileDisplayMode picks B viewport', () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
// Advance the fake clock so phone-B's subscribe records a strictly
|
||||
// later subscribedAt/lastActedAt — keeps tie-break deterministic.
|
||||
vi.advanceTimersByTime(10)
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-B', { cols: 38, rows: 18 })
|
||||
// Switch to desktop, then phone-B types — its viewport wins on re-fit.
|
||||
runtime.setMobileDisplayMode('pty-1', 'desktop')
|
||||
runtime.applyMobileDisplayMode('pty-1')
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
|
||||
// Simulate B taking the floor by typing (advance again so lastActedAt
|
||||
// is unambiguously the most recent).
|
||||
vi.advanceTimersByTime(10)
|
||||
runtime.mobileTookFloor('pty-1', 'phone-B')
|
||||
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 38, rows: 18 })
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-B' })
|
||||
})
|
||||
|
||||
it('updateMobileViewport re-fits PTY without flipping the driver', () => {
|
||||
const { runtime, ptySizes, driverEvents } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 })
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 38 })
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
const before = driverEvents.length
|
||||
|
||||
// Keyboard opens — viewport shrinks.
|
||||
expect(runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })).toBe(true)
|
||||
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 16 })
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
// Why: a viewport update may re-emit driver to refresh listener
|
||||
// wiring, but it must never go through `idle` (no banner flash).
|
||||
expect(driverEvents.slice(before).every((e) => e.driver.kind === 'mobile')).toBe(true)
|
||||
})
|
||||
|
||||
it('updateMobileViewport then disconnect restores PTY to original baseline', () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 })
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 38 })
|
||||
|
||||
// Keyboard cycles a few times.
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 38 })
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
|
||||
// Phone disconnects (router.back → WS close).
|
||||
runtime.onClientDisconnected('phone-A')
|
||||
|
||||
// PTY must restore to the original 150x40 baseline, not the last
|
||||
// phone-fit dim. This was the stuck-dim bug.
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'idle' })
|
||||
})
|
||||
|
||||
it('legacy unsubscribe → resubscribe within grace preserves baseline (regression)', () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 })
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 38 })
|
||||
|
||||
// Simulate legacy keyboard re-subscribe cycle within grace.
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-A')
|
||||
vi.advanceTimersByTime(100)
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
// Apply mode after re-subscribe so the new viewport drives PTY dims.
|
||||
runtime.applyMobileDisplayMode('pty-1')
|
||||
|
||||
// PTY at new viewport, phone-A still drives.
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
|
||||
// Disconnect — must restore to original 150x40, not 49x16.
|
||||
runtime.onClientDisconnected('phone-A')
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
})
|
||||
|
||||
it('earliest-subscribe restore target is preserved when peers churn', () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
// A captures the original 150x40 baseline.
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 45, rows: 20 })
|
||||
// B subscribes later at 38x18 (advance clock for unambiguous ordering).
|
||||
vi.advanceTimersByTime(10)
|
||||
runtime.handleMobileSubscribe('pty-1', 'phone-B', { cols: 38, rows: 18 })
|
||||
|
||||
// A leaves, B leaves — final restore must use A's earliest baseline (150x40),
|
||||
// NOT B's (which captured 45x20 when it joined a phone-fitted PTY).
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-A')
|
||||
runtime.handleMobileUnsubscribe('pty-1', 'phone-B')
|
||||
vi.advanceTimersByTime(300)
|
||||
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
})
|
||||
})
|
||||
@@ -102,7 +102,8 @@ function createRuntime() {
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: (ptyId, mode, cols, rows) => {
|
||||
notifications.push({ ptyId, mode, cols, rows })
|
||||
}
|
||||
},
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
|
||||
return { runtime, ptySizes, resizes, notifications }
|
||||
|
||||
@@ -945,7 +945,8 @@ describe('OrcaRuntimeService', () => {
|
||||
focusTerminal: vi.fn(),
|
||||
closeTerminal: vi.fn(),
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: vi.fn()
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
runtime.attachWindow(1)
|
||||
|
||||
@@ -1022,7 +1023,8 @@ describe('OrcaRuntimeService', () => {
|
||||
focusTerminal: vi.fn(),
|
||||
closeTerminal: vi.fn(),
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: vi.fn()
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
runtime.attachWindow(1)
|
||||
|
||||
@@ -1115,7 +1117,8 @@ describe('OrcaRuntimeService', () => {
|
||||
focusTerminal: vi.fn(),
|
||||
closeTerminal: vi.fn(),
|
||||
sleepWorktree: vi.fn(),
|
||||
terminalFitOverrideChanged: vi.fn()
|
||||
terminalFitOverrideChanged: vi.fn(),
|
||||
terminalDriverChanged: vi.fn()
|
||||
})
|
||||
|
||||
computeWorktreePathMock.mockReturnValue('/tmp/workspaces/cli-worktree')
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -262,5 +262,31 @@ describe('E2EEChannel', () => {
|
||||
|
||||
expect(received).toEqual([])
|
||||
})
|
||||
|
||||
// Why: streaming RPC handlers (terminal.subscribe) retain the
|
||||
// encryptedReply closure created inside handleRawMessage. If destroy()
|
||||
// runs (mobile disconnect) before a late streaming emit, the closure's
|
||||
// captured this.sharedKey is null. Without a guard, encrypt() would
|
||||
// call nacl.box.after with a null key and throw an unhandled
|
||||
// "unexpected type, use Uint8Array" rejection.
|
||||
it('does not throw when streaming emit fires after destroy', () => {
|
||||
const ctx = setup()
|
||||
const sharedKey = doHandshake(ctx)
|
||||
const sentBefore = ctx.ws.sent.length
|
||||
|
||||
let capturedReply: ((response: string) => void) | null = null
|
||||
ctx.channel.onMessage((_plaintext, encryptedReply) => {
|
||||
capturedReply = encryptedReply
|
||||
})
|
||||
|
||||
ctx.channel.handleRawMessage(encrypt('subscribe-trigger', sharedKey))
|
||||
expect(capturedReply).not.toBeNull()
|
||||
|
||||
ctx.channel.destroy()
|
||||
|
||||
const callLateEmit = () => capturedReply?.('late streaming frame')
|
||||
expect(callLateEmit).not.toThrow()
|
||||
expect(ctx.ws.sent.length).toBe(sentBefore)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -88,10 +88,17 @@ export class E2EEChannel {
|
||||
return
|
||||
}
|
||||
|
||||
// Why: streaming RPC handlers (e.g. terminal.subscribe) retain this
|
||||
// closure and may fire emits long after the inbound message handled
|
||||
// here. If destroy() runs in between (mobile disconnect, handshake
|
||||
// failure) sharedKey becomes null and tweetnacl throws "unexpected
|
||||
// type, use Uint8Array" from inside nacl.box.after. Guard both the
|
||||
// socket state AND the key so late emits become silent no-ops.
|
||||
const encryptedReply = (response: string) => {
|
||||
if (this.ws.readyState === this.ws.OPEN) {
|
||||
this.ws.send(encrypt(response, this.sharedKey!))
|
||||
if (!this.sharedKey || this.ws.readyState !== this.ws.OPEN) {
|
||||
return
|
||||
}
|
||||
this.ws.send(encrypt(response, this.sharedKey))
|
||||
}
|
||||
this.messageHandler?.(plaintext, encryptedReply)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,14 @@ import { z } from 'zod'
|
||||
import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core'
|
||||
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
|
||||
|
||||
// Why: when a mobile client subscribes the server resizes the PTY to phone
|
||||
// dims and serializes the buffer. Sending only the visible screen meant
|
||||
// users coming back to the app or switching terminals could no longer scroll
|
||||
// up to see prior agent output. Include enough scrollback to keep typical
|
||||
// agent runs (Claude Code chats, command output) reachable. The mobile
|
||||
// WebView's xterm has a 5000-row buffer so this fits comfortably.
|
||||
const MOBILE_SUBSCRIBE_SCROLLBACK_ROWS = 1000
|
||||
|
||||
const TerminalHandle = z.object({
|
||||
terminal: requiredString('Missing terminal handle')
|
||||
})
|
||||
@@ -50,7 +58,18 @@ const TerminalRename = TerminalHandle.extend({
|
||||
const TerminalSend = TerminalHandle.extend({
|
||||
text: OptionalString,
|
||||
enter: z.unknown().optional(),
|
||||
interrupt: z.unknown().optional()
|
||||
interrupt: z.unknown().optional(),
|
||||
// Why: identifies the caller for the driver state machine. Optional for
|
||||
// backward compatibility with older mobile clients (server falls back to
|
||||
// the most recent mobile actor when absent). New mobile builds populate
|
||||
// this so multi-mobile semantics resolve correctly. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
client: z
|
||||
.object({
|
||||
id: requiredString('Missing client ID'),
|
||||
type: z.enum(['mobile', 'desktop']).default('desktop').optional()
|
||||
})
|
||||
.optional()
|
||||
})
|
||||
|
||||
const TerminalWait = TerminalHandle.extend({
|
||||
@@ -109,11 +128,47 @@ const TerminalSubscribe = TerminalHandle.extend({
|
||||
})
|
||||
|
||||
const TerminalSetDisplayMode = TerminalHandle.extend({
|
||||
mode: z.enum(['auto', 'phone', 'desktop'])
|
||||
mode: z.enum(['auto', 'phone', 'desktop']),
|
||||
// Why: identifies the caller for the driver state machine. Optional for
|
||||
// backward compatibility with older mobile clients.
|
||||
client: z
|
||||
.object({
|
||||
id: requiredString('Missing client ID'),
|
||||
type: z.enum(['mobile', 'desktop']).default('desktop').optional()
|
||||
})
|
||||
.optional()
|
||||
})
|
||||
|
||||
const TerminalUnsubscribe = z.object({
|
||||
subscriptionId: requiredString('Missing subscription ID')
|
||||
subscriptionId: requiredString('Missing subscription ID'),
|
||||
// Why: required when subscribe registered the cleanup under the composite
|
||||
// key `${terminal}:${clientId}`. If the caller passes a bare-handle
|
||||
// subscriptionId (older clients), the server reconstructs the composite
|
||||
// key from `client.id`. See docs/mobile-presence-lock.md.
|
||||
client: z
|
||||
.object({
|
||||
id: requiredString('Missing client ID')
|
||||
})
|
||||
.optional()
|
||||
})
|
||||
|
||||
// Why: in-place viewport update for an existing mobile subscription. Used
|
||||
// when the keyboard opens/closes on the mobile client and the visible
|
||||
// terminal area changes — without this, the mobile app had to
|
||||
// unsubscribe → resubscribe, which (a) flashed the desktop lock banner
|
||||
// during the brief idle gap and (b) caused the new subscribe to capture
|
||||
// the already-phone-fitted PTY size as its restore baseline, leaving the
|
||||
// PTY stuck at phone dims after the phone disconnected. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
const TerminalUpdateViewport = TerminalHandle.extend({
|
||||
client: z.object({
|
||||
id: requiredString('Missing client ID'),
|
||||
type: z.enum(['mobile', 'desktop']).default('mobile').optional()
|
||||
}),
|
||||
viewport: z.object({
|
||||
cols: z.number().int().min(20).max(240),
|
||||
rows: z.number().int().min(8).max(120)
|
||||
})
|
||||
})
|
||||
|
||||
export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
@@ -153,13 +208,27 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
defineMethod({
|
||||
name: 'terminal.send',
|
||||
params: TerminalSend,
|
||||
handler: async (params, { runtime }) => ({
|
||||
send: await runtime.sendTerminal(params.terminal, {
|
||||
handler: async (params, { runtime }) => {
|
||||
const result = await runtime.sendTerminal(params.terminal, {
|
||||
text: params.text,
|
||||
enter: params.enter === true,
|
||||
interrupt: params.interrupt === true
|
||||
})
|
||||
})
|
||||
// Why: deliberate mobile input is a take-floor action. Drives the
|
||||
// `* → mobile{clientId}` driver transition so the desktop banner
|
||||
// remounts (if previously reclaimed) and active phone-fit dims follow
|
||||
// the most recent actor. Only mobile-typed callers take the floor;
|
||||
// desktop callers (CLI / agents) do not. Older mobile builds without
|
||||
// a `client` field continue to work — the runtime then keeps the
|
||||
// current driver state.
|
||||
if (params.client && params.client.type === 'mobile') {
|
||||
const leaf = runtime.resolveLeafForHandle(params.terminal)
|
||||
if (leaf?.ptyId) {
|
||||
runtime.mobileTookFloor(leaf.ptyId, params.client.id)
|
||||
}
|
||||
}
|
||||
return { send: result }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'terminal.wait',
|
||||
@@ -243,6 +312,13 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
}
|
||||
runtime.setMobileDisplayMode(leaf.ptyId, params.mode)
|
||||
runtime.applyMobileDisplayMode(leaf.ptyId)
|
||||
// Why: a deliberate mobile mode change is a take-floor action when
|
||||
// moving to auto/phone (the user explicitly chose to drive at phone
|
||||
// dims). Setting mode to desktop is intentionally NOT a take-floor
|
||||
// action — that's a "watch from desktop dims" gesture.
|
||||
if (params.client && params.client.type === 'mobile' && params.mode !== 'desktop') {
|
||||
runtime.mobileTookFloor(leaf.ptyId, params.client.id)
|
||||
}
|
||||
return { mode: params.mode }
|
||||
}
|
||||
}),
|
||||
@@ -256,6 +332,18 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
return { mode, isPhoneFitted }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'terminal.updateViewport',
|
||||
params: TerminalUpdateViewport,
|
||||
handler: async (params, { runtime }) => {
|
||||
const leaf = runtime.resolveLeafForHandle(params.terminal)
|
||||
if (!leaf?.ptyId) {
|
||||
throw new Error('no_connected_pty')
|
||||
}
|
||||
const updated = runtime.updateMobileViewport(leaf.ptyId, params.client.id, params.viewport)
|
||||
return { updated }
|
||||
}
|
||||
}),
|
||||
// Why: terminal.subscribe streams live terminal output over WebSocket.
|
||||
// It sends initial scrollback, then live data chunks as they arrive.
|
||||
// Mobile clients pass client+viewport params for server-side auto-fit.
|
||||
@@ -302,7 +390,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
}
|
||||
|
||||
const read = await runtime.readTerminal(params.terminal)
|
||||
const serialized = await runtime.serializeTerminalBuffer(ptyId)
|
||||
const serialized = await runtime.serializeTerminalBuffer(ptyId, {
|
||||
scrollbackRows: isMobile ? MOBILE_SUBSCRIBE_SCROLLBACK_ROWS : 0
|
||||
})
|
||||
const size = runtime.getTerminalSize(ptyId)
|
||||
const displayMode = runtime.getMobileDisplayMode(ptyId)
|
||||
emit({
|
||||
@@ -324,7 +414,12 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
// mobile clients. They include fresh serialized scrollback so the client
|
||||
// can reinitialize xterm without resubscribing.
|
||||
const unsubscribeResize = runtime.subscribeToTerminalResize(ptyId, async (event) => {
|
||||
const fresh = await runtime.serializeTerminalBuffer(ptyId)
|
||||
// Why: mobile subscriptions need the same scrollback on inline
|
||||
// resize as on initial subscribe — without it, toggling phone/desktop
|
||||
// mode or the keyboard-driven refit would silently wipe history.
|
||||
const fresh = await runtime.serializeTerminalBuffer(ptyId, {
|
||||
scrollbackRows: isMobile ? MOBILE_SUBSCRIBE_SCROLLBACK_ROWS : 0
|
||||
})
|
||||
emit({
|
||||
type: 'resized',
|
||||
cols: event.cols,
|
||||
@@ -347,7 +442,11 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
})
|
||||
: () => {}
|
||||
|
||||
const subscriptionId = params.terminal
|
||||
// Why: composite subscriptionId per (terminal, clientId) so two
|
||||
// mobile clients subscribing to the same terminal handle do not
|
||||
// evict each other via registerSubscriptionCleanup's
|
||||
// duplicate-key cleanup. See docs/mobile-presence-lock.md.
|
||||
const subscriptionId = clientId ? `${params.terminal}:${clientId}` : params.terminal
|
||||
runtime.registerSubscriptionCleanup(subscriptionId, () => {
|
||||
unsubscribeData()
|
||||
unsubscribeResize()
|
||||
@@ -365,7 +464,16 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
name: 'terminal.unsubscribe',
|
||||
params: TerminalUnsubscribe,
|
||||
handler: async (params, { runtime }) => {
|
||||
// Why: the subscribe handler now registers cleanup under a composite
|
||||
// key `${terminal}:${clientId}`. New mobile builds emit the composite
|
||||
// key directly. Older builds emit a bare-handle subscriptionId; if
|
||||
// they additionally provide `client.id`, reconstruct the composite
|
||||
// key server-side. We always try the as-sent value first, then fall
|
||||
// back to the reconstructed composite, so both wire formats work.
|
||||
runtime.cleanupSubscription(params.subscriptionId)
|
||||
if (params.client && !params.subscriptionId.includes(':')) {
|
||||
runtime.cleanupSubscription(`${params.subscriptionId}:${params.client.id}`)
|
||||
}
|
||||
return { unsubscribed: true }
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Why: mobile subscribers hydrate the runtime headless emulator from the
|
||||
// desktop renderer's xterm buffer. The renderer holds a 50k-row scrollback;
|
||||
// shipping all of it across IPC + replaying through HeadlessEmulator is
|
||||
// expensive and unnecessary for a phone screen. Cap at 1000 rows so the seed
|
||||
// covers a meaningful amount of agent context while keeping the round-trip
|
||||
// bounded. See docs/mobile-prefer-renderer-scrollback.md.
|
||||
export const MOBILE_SUBSCRIBE_SCROLLBACK_ROWS = 1000
|
||||
@@ -235,7 +235,9 @@ function registerRuntimeWindowLifecycle(
|
||||
closeTerminal: (tabId, paneRuntimeId) => send('ui:closeTerminal', { tabId, paneRuntimeId }),
|
||||
sleepWorktree: (worktreeId) => send('ui:sleepWorktree', { worktreeId }),
|
||||
terminalFitOverrideChanged: (ptyId, mode, cols, rows) =>
|
||||
send('runtime:terminalFitOverrideChanged', { ptyId, mode, cols, rows })
|
||||
send('runtime:terminalFitOverrideChanged', { ptyId, mode, cols, rows }),
|
||||
terminalDriverChanged: (ptyId, driver) =>
|
||||
send('runtime:terminalDriverChanged', { ptyId, driver })
|
||||
})
|
||||
// Why: the runtime must fail closed while the renderer graph is being torn
|
||||
// down or rebuilt, otherwise future CLI calls could act on stale terminal
|
||||
|
||||
@@ -443,12 +443,19 @@ export type PreloadApi = {
|
||||
onReplay: (callback: (data: { id: string; data: string }) => void) => () => void
|
||||
onExit: (callback: (data: { id: string; code: number }) => void) => () => void
|
||||
onSerializeBufferRequest: (
|
||||
callback: (data: { requestId: string; ptyId: string }) => void
|
||||
callback: (data: {
|
||||
requestId: string
|
||||
ptyId: string
|
||||
opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }
|
||||
}) => void
|
||||
) => () => void
|
||||
sendSerializedBuffer: (
|
||||
requestId: string,
|
||||
snapshot: { data: string; cols: number; rows: number } | null
|
||||
snapshot: { data: string; cols: number; rows: number; lastTitle?: string } | null
|
||||
) => void
|
||||
declarePendingPaneSerializer: (paneKey: string) => Promise<number>
|
||||
settlePaneSerializer: (paneKey: string, gen: number) => Promise<void>
|
||||
clearPendingPaneSerializer: (paneKey: string, gen: number) => Promise<void>
|
||||
management: PtyManagementApi
|
||||
}
|
||||
feedback: {
|
||||
@@ -962,6 +969,12 @@ export type PreloadApi = {
|
||||
rows: number
|
||||
}) => void
|
||||
) => () => void
|
||||
onTerminalDriverChanged: (
|
||||
callback: (event: {
|
||||
ptyId: string
|
||||
driver: { kind: 'idle' } | { kind: 'desktop' } | { kind: 'mobile'; clientId: string }
|
||||
}) => void
|
||||
) => () => void
|
||||
}
|
||||
rateLimits: {
|
||||
get: () => Promise<RateLimitState>
|
||||
|
||||
+41
-3
@@ -397,11 +397,19 @@ const api = {
|
||||
},
|
||||
|
||||
onSerializeBufferRequest: (
|
||||
callback: (data: { requestId: string; ptyId: string }) => void
|
||||
callback: (data: {
|
||||
requestId: string
|
||||
ptyId: string
|
||||
opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }
|
||||
}) => void
|
||||
): (() => void) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
data: { requestId: string; ptyId: string }
|
||||
data: {
|
||||
requestId: string
|
||||
ptyId: string
|
||||
opts?: { scrollbackRows?: number; altScreenForcesZeroRows?: boolean }
|
||||
}
|
||||
) => callback(data)
|
||||
ipcRenderer.on('pty:serializeBuffer:request', listener)
|
||||
return () => ipcRenderer.removeListener('pty:serializeBuffer:request', listener)
|
||||
@@ -409,11 +417,25 @@ const api = {
|
||||
|
||||
sendSerializedBuffer: (
|
||||
requestId: string,
|
||||
snapshot: { data: string; cols: number; rows: number } | null
|
||||
snapshot: { data: string; cols: number; rows: number; lastTitle?: string } | null
|
||||
): void => {
|
||||
ipcRenderer.send('pty:serializeBuffer:response', { requestId, snapshot })
|
||||
},
|
||||
|
||||
// Why: pre-signal handshake — renderer declares it will own the serializer
|
||||
// for `paneKey` BEFORE issuing pty:spawn so the cooperation gate in main
|
||||
// can suppress the daemon-snapshot seed. Returns a generation token that
|
||||
// the renderer must echo on settle/clear so paneKey-reuse during teardown
|
||||
// cannot defeat the pre-signal. See docs/mobile-prefer-renderer-scrollback.md.
|
||||
declarePendingPaneSerializer: (paneKey: string): Promise<number> =>
|
||||
ipcRenderer.invoke('pty:declarePendingPaneSerializer', { paneKey }),
|
||||
|
||||
settlePaneSerializer: (paneKey: string, gen: number): Promise<void> =>
|
||||
ipcRenderer.invoke('pty:settlePaneSerializer', { paneKey, gen }),
|
||||
|
||||
clearPendingPaneSerializer: (paneKey: string, gen: number): Promise<void> =>
|
||||
ipcRenderer.invoke('pty:clearPendingPaneSerializer', { paneKey, gen }),
|
||||
|
||||
management: {
|
||||
listSessions: () => ipcRenderer.invoke('pty:management:listSessions'),
|
||||
killAll: () => ipcRenderer.invoke('pty:management:killAll'),
|
||||
@@ -1724,6 +1746,22 @@ const api = {
|
||||
) => callback(data)
|
||||
ipcRenderer.on('runtime:terminalFitOverrideChanged', listener)
|
||||
return () => ipcRenderer.removeListener('runtime:terminalFitOverrideChanged', listener)
|
||||
},
|
||||
onTerminalDriverChanged: (
|
||||
callback: (event: {
|
||||
ptyId: string
|
||||
driver: { kind: 'idle' } | { kind: 'desktop' } | { kind: 'mobile'; clientId: string }
|
||||
}) => void
|
||||
): (() => void) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
data: {
|
||||
ptyId: string
|
||||
driver: { kind: 'idle' } | { kind: 'desktop' } | { kind: 'mobile'; clientId: string }
|
||||
}
|
||||
) => callback(data)
|
||||
ipcRenderer.on('runtime:terminalDriverChanged', listener)
|
||||
return () => ipcRenderer.removeListener('runtime:terminalDriverChanged', listener)
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -29,11 +29,8 @@ import { useTerminalPaneLifecycle } from './use-terminal-pane-lifecycle'
|
||||
import { useTerminalPaneContextMenu } from './use-terminal-pane-context-menu'
|
||||
import { useNotificationDispatch } from './use-notification-dispatch'
|
||||
import { connectPanePty } from './pty-connection'
|
||||
import {
|
||||
getFitOverrideForPty,
|
||||
getPaneIdsForPty,
|
||||
onOverrideChange
|
||||
} from '@/lib/pane-manager/mobile-fit-overrides'
|
||||
import { getPaneIdsForPty, onOverrideChange } from '@/lib/pane-manager/mobile-fit-overrides'
|
||||
import { getDriverForPty, onDriverChange } from '@/lib/pane-manager/mobile-driver-state'
|
||||
import { safeFit } from '@/lib/pane-manager/pane-tree-ops'
|
||||
|
||||
/** Global set of buffer-capture callbacks, one per mounted TerminalPane.
|
||||
@@ -167,6 +164,18 @@ export default function TerminalPane({
|
||||
[]
|
||||
)
|
||||
|
||||
// Why: presence-lock banner re-render. Driver state lives in a plain Map
|
||||
// for perf; this counter forces a re-render when the driver flips so the
|
||||
// lock banner appears/disappears. See docs/mobile-presence-lock.md.
|
||||
const [, setDriverTick] = useState(0)
|
||||
useEffect(
|
||||
() =>
|
||||
onDriverChange(() => {
|
||||
setDriverTick((n) => n + 1)
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
// Pane title state — keyed by ephemeral paneId, persisted via titlesByLeafId
|
||||
// in the layout snapshot. Ref keeps persistLayoutSnapshot closures fresh.
|
||||
const [paneTitles, setPaneTitles] = useState<Record<number, string>>({})
|
||||
@@ -1123,14 +1132,23 @@ export default function TerminalPane({
|
||||
// pane 1). Using the transport's actual ptyId avoids showing banners
|
||||
// on the wrong pane when IDs overlap.
|
||||
const ptyId = paneTransportsRef.current.get(pane.id)?.getPtyId()
|
||||
const override = ptyId ? getFitOverrideForPty(ptyId) : null
|
||||
if (!override) {
|
||||
if (!ptyId) {
|
||||
return null
|
||||
}
|
||||
// Why: presence-lock — banner is gated on driver state, not on
|
||||
// fit-override. The banner now communicates "input is paused"
|
||||
// (the load-bearing fact) instead of dimensional state. The
|
||||
// dimensional override may still be active and is reflected in
|
||||
// the PTY but not in the banner copy. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
const driver = getDriverForPty(ptyId)
|
||||
if (driver.kind !== 'mobile') {
|
||||
return null
|
||||
}
|
||||
return createPortal(
|
||||
<div
|
||||
key={`mobile-fit-${pane.id}`}
|
||||
className="mobile-fit-banner"
|
||||
key={`mobile-driver-${pane.id}`}
|
||||
className="mobile-driver-banner"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
@@ -1147,7 +1165,7 @@ export default function TerminalPane({
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
Terminal resized for phone ({override.cols}×{override.rows})
|
||||
Mobile is driving this terminal — your input is paused. Click Take back to resume.
|
||||
</span>
|
||||
<button
|
||||
style={{
|
||||
@@ -1162,15 +1180,19 @@ export default function TerminalPane({
|
||||
onClick={() => {
|
||||
const ptyId = paneTransportsRef.current.get(pane.id)?.getPtyId()
|
||||
if (ptyId) {
|
||||
// Why: same IPC route — handler now also reclaims the
|
||||
// input floor for the desktop via the driver state
|
||||
// machine, so the banner unmounts and input is unblocked
|
||||
// until the next mobile interaction.
|
||||
void window.api.runtime.restoreTerminalFit(ptyId)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Restore
|
||||
Take back
|
||||
</button>
|
||||
</div>,
|
||||
pane.container,
|
||||
`mobile-fit-banner-${pane.id}`
|
||||
`mobile-driver-banner-${pane.id}`
|
||||
)
|
||||
})}
|
||||
<CloseTerminalDialog
|
||||
|
||||
@@ -3,20 +3,106 @@
|
||||
// serialize functions keyed by ptyId, and handles IPC requests from the
|
||||
// main process to serialize a specific terminal's buffer.
|
||||
|
||||
type SerializedBuffer = { data: string; cols: number; rows: number }
|
||||
type SerializeFn = () => SerializedBuffer | null | Promise<SerializedBuffer | null>
|
||||
import type { IDisposable } from '@xterm/xterm'
|
||||
|
||||
const serializersByPtyId = new Map<string, SerializeFn>()
|
||||
export type SerializeOpts = {
|
||||
scrollbackRows?: number
|
||||
altScreenForcesZeroRows?: boolean
|
||||
}
|
||||
|
||||
export type SerializedBuffer = {
|
||||
data: string
|
||||
cols: number
|
||||
rows: number
|
||||
lastTitle?: string
|
||||
}
|
||||
|
||||
export type SerializeFn = (
|
||||
opts?: SerializeOpts
|
||||
) => SerializedBuffer | null | Promise<SerializedBuffer | null>
|
||||
|
||||
// Why: ownership tokens prevent a disposed StrictMode first-mount from clobbering
|
||||
// the live registration of a remounted pane. Each registration mints a fresh
|
||||
// owner symbol; the unregister closure only deletes when the entry's owner
|
||||
// matches its captured token.
|
||||
type SerializerEntry = {
|
||||
fn: SerializeFn
|
||||
owner: symbol
|
||||
}
|
||||
|
||||
type TitleEntry = {
|
||||
title: string
|
||||
owner: symbol
|
||||
disposable: IDisposable
|
||||
}
|
||||
|
||||
const serializersByPtyId = new Map<string, SerializerEntry>()
|
||||
const lastTitleByPtyId = new Map<string, TitleEntry>()
|
||||
let listenerAttached = false
|
||||
|
||||
export function registerPtySerializer(ptyId: string, serialize: SerializeFn): () => void {
|
||||
serializersByPtyId.set(ptyId, serialize)
|
||||
const owner = Symbol(ptyId)
|
||||
serializersByPtyId.set(ptyId, { fn: serialize, owner })
|
||||
ensureSerializerListener()
|
||||
return () => {
|
||||
serializersByPtyId.delete(ptyId)
|
||||
const current = serializersByPtyId.get(ptyId)
|
||||
if (current?.owner === owner) {
|
||||
serializersByPtyId.delete(ptyId)
|
||||
}
|
||||
const titleEntry = lastTitleByPtyId.get(ptyId)
|
||||
if (titleEntry?.owner === owner) {
|
||||
// Why: dispose the xterm onTitleChange IDisposable alongside the map
|
||||
// cleanup. Without this, the listener stays attached to xterm's emitter
|
||||
// for the lifetime of the xterm instance, firing against a torn-down
|
||||
// pane (or worse, leaking during HMR).
|
||||
titleEntry.disposable.dispose()
|
||||
lastTitleByPtyId.delete(ptyId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Why: the renderer pane installs an onTitleChange wrapper at the same time
|
||||
// it registers the serializer. The wrapper updates lastTitleByPtyId so the
|
||||
// IPC response payload can carry the latest observed title without needing
|
||||
// the renderer to round-trip xterm state on every serializeBuffer request.
|
||||
// xterm's SerializeAddon does NOT round-trip OSC 0/1/2 title sequences, so
|
||||
// this is the only channel that gets the title back to the main process.
|
||||
export function registerPtyTitleSource(
|
||||
ptyId: string,
|
||||
attach: (handler: (title: string) => void) => IDisposable
|
||||
): () => void {
|
||||
const serializerOwner = serializersByPtyId.get(ptyId)?.owner
|
||||
if (!serializerOwner) {
|
||||
// Why: the title source must be registered AFTER the serializer so the
|
||||
// owner token is available. Calling out of order is a programming bug.
|
||||
throw new Error(`registerPtyTitleSource called before serializer for ptyId ${ptyId}`)
|
||||
}
|
||||
const disposable = attach((title) => {
|
||||
const current = lastTitleByPtyId.get(ptyId)
|
||||
if (current && current.owner !== serializerOwner) {
|
||||
return
|
||||
}
|
||||
lastTitleByPtyId.set(ptyId, { title, owner: serializerOwner, disposable })
|
||||
})
|
||||
// Seed an entry with an empty title so the disposable is tracked even
|
||||
// before the first onTitleChange fires. Subsequent updates overwrite it.
|
||||
const existing = lastTitleByPtyId.get(ptyId)
|
||||
if (!existing) {
|
||||
lastTitleByPtyId.set(ptyId, { title: '', owner: serializerOwner, disposable })
|
||||
}
|
||||
return () => {
|
||||
const entry = lastTitleByPtyId.get(ptyId)
|
||||
if (entry?.owner === serializerOwner) {
|
||||
entry.disposable.dispose()
|
||||
lastTitleByPtyId.delete(ptyId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function hasPtySerializer(ptyId: string): boolean {
|
||||
return serializersByPtyId.has(ptyId)
|
||||
}
|
||||
|
||||
function ensureSerializerListener(): void {
|
||||
if (listenerAttached) {
|
||||
return
|
||||
@@ -24,10 +110,26 @@ function ensureSerializerListener(): void {
|
||||
listenerAttached = true
|
||||
|
||||
window.api.pty.onSerializeBufferRequest((request) => {
|
||||
const serializer = serializersByPtyId.get(request.ptyId)
|
||||
void Promise.resolve(serializer?.() ?? null)
|
||||
const entry = serializersByPtyId.get(request.ptyId)
|
||||
void Promise.resolve(entry?.fn(request.opts) ?? null)
|
||||
.then((result) => {
|
||||
window.api.pty.sendSerializedBuffer(request.requestId, result ?? null)
|
||||
if (!result) {
|
||||
window.api.pty.sendSerializedBuffer(request.requestId, null)
|
||||
return
|
||||
}
|
||||
const titleEntry = lastTitleByPtyId.get(request.ptyId)
|
||||
const lastTitle = titleEntry && titleEntry.title.length > 0 ? titleEntry.title : undefined
|
||||
const payload: SerializedBuffer = {
|
||||
data: result.data,
|
||||
cols: result.cols,
|
||||
rows: result.rows
|
||||
}
|
||||
if (lastTitle !== undefined) {
|
||||
payload.lastTitle = lastTitle
|
||||
} else if (result.lastTitle !== undefined) {
|
||||
payload.lastTitle = result.lastTitle
|
||||
}
|
||||
window.api.pty.sendSerializedBuffer(request.requestId, payload)
|
||||
})
|
||||
.catch(() => {
|
||||
window.api.pty.sendSerializedBuffer(request.requestId, null)
|
||||
|
||||
@@ -4,6 +4,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { POST_REPLAY_FOCUS_REPORTING_RESET, POST_REPLAY_MODE_RESET } from './layout-serialization'
|
||||
import type * as UseNotificationDispatchModule from './use-notification-dispatch'
|
||||
|
||||
// Why: the fresh-spawn and reattach paths now chain pre-signal → spawn →
|
||||
// register/settle through multiple microtasks. Tests that previously flushed
|
||||
// once with `await Promise.resolve()` must drain a few extra ticks before
|
||||
// asserting against IPC mocks. See docs/mobile-prefer-renderer-scrollback.md.
|
||||
async function flushAsyncTicks(count = 6): Promise<void> {
|
||||
for (let i = 0; i < count; i++) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
const toastInfo = vi.fn()
|
||||
|
||||
type StoreState = {
|
||||
@@ -139,7 +149,8 @@ function createPane(paneId: number) {
|
||||
rows: 40,
|
||||
write: vi.fn(),
|
||||
onData: vi.fn(() => ({ dispose: vi.fn() })),
|
||||
onResize: vi.fn(() => ({ dispose: vi.fn() }))
|
||||
onResize: vi.fn(() => ({ dispose: vi.fn() })),
|
||||
onTitleChange: vi.fn(() => ({ dispose: vi.fn() }))
|
||||
},
|
||||
container: { dataset: {} },
|
||||
fitAddon: {
|
||||
@@ -238,7 +249,10 @@ describe('connectPanePty', () => {
|
||||
pty: {
|
||||
signal: vi.fn(),
|
||||
ackColdRestore: vi.fn(),
|
||||
onSerializeBufferRequest: vi.fn(() => vi.fn())
|
||||
onSerializeBufferRequest: vi.fn(() => vi.fn()),
|
||||
declarePendingPaneSerializer: vi.fn().mockResolvedValue(1),
|
||||
settlePaneSerializer: vi.fn().mockResolvedValue(undefined),
|
||||
clearPendingPaneSerializer: vi.fn().mockResolvedValue(undefined)
|
||||
},
|
||||
notifications: {
|
||||
dispatch: vi.fn()
|
||||
@@ -627,7 +641,7 @@ describe('connectPanePty', () => {
|
||||
})
|
||||
|
||||
connectPanePty(pane as never, manager as never, deps as never)
|
||||
await Promise.resolve()
|
||||
await flushAsyncTicks(20)
|
||||
|
||||
expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[2J\x1b[3J\x1b[H', expect.any(Function))
|
||||
expect(pane.terminal.write).toHaveBeenCalledWith(
|
||||
@@ -669,7 +683,7 @@ describe('connectPanePty', () => {
|
||||
expect.objectContaining({ sessionId: 'pty-local-detached' })
|
||||
)
|
||||
expect(transport.attach).not.toHaveBeenCalled()
|
||||
await Promise.resolve()
|
||||
await flushAsyncTicks()
|
||||
expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'pty-local-detached')
|
||||
})
|
||||
|
||||
@@ -693,7 +707,7 @@ describe('connectPanePty', () => {
|
||||
})
|
||||
|
||||
connectPanePty(restartPane as never, restartManager as never, restartDeps as never)
|
||||
await Promise.resolve()
|
||||
await flushAsyncTicks()
|
||||
|
||||
expect(spawnedPtyId).toBe('pty-restarted')
|
||||
expect(restartDeps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(1, 'pty-restarted')
|
||||
@@ -888,9 +902,7 @@ describe('connectPanePty', () => {
|
||||
})
|
||||
|
||||
connectPanePty(pane as never, manager as never, deps as never)
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
await flushAsyncTicks(20)
|
||||
|
||||
const api = (
|
||||
globalThis as unknown as {
|
||||
@@ -945,9 +957,7 @@ describe('connectPanePty', () => {
|
||||
})
|
||||
|
||||
connectPanePty(pane as never, manager as never, deps as never)
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
await flushAsyncTicks(20)
|
||||
|
||||
expect(deps.onPtyErrorRef.current).not.toHaveBeenCalledWith(
|
||||
expect.any(Number),
|
||||
|
||||
@@ -11,6 +11,7 @@ import { shouldSeedCacheTimerOnInitialTitle } from './cache-timer-seeding'
|
||||
import type { PtyConnectionDeps } from './pty-connection-types'
|
||||
import { safeFit } from '@/lib/pane-manager/pane-tree-ops'
|
||||
import { getFitOverrideForPty, bindPanePtyId } from '@/lib/pane-manager/mobile-fit-overrides'
|
||||
import { isPtyLocked } from '@/lib/pane-manager/mobile-driver-state'
|
||||
import { isPaneReplaying, replayIntoTerminal, replayIntoTerminalAsync } from './replay-guard'
|
||||
import {
|
||||
paneLeafId,
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
} from './layout-serialization'
|
||||
import { warnTerminalLifecycleAnomaly } from './terminal-lifecycle-diagnostics'
|
||||
import { detectDeveloperPermissionHint } from './developer-permission-hints'
|
||||
import { registerPtySerializer } from './pty-buffer-serializer'
|
||||
import { registerPtySerializer, registerPtyTitleSource } from './pty-buffer-serializer'
|
||||
|
||||
const pendingSpawnByPaneKey = new Map<string, Promise<string | null>>()
|
||||
const developerPermissionHintKeys = new Set<string>()
|
||||
@@ -384,6 +385,16 @@ export function connectPanePty(
|
||||
if (isCodexPaneStale({ tabId: deps.tabId, panePtyId: currentPtyId })) {
|
||||
return
|
||||
}
|
||||
// Why: presence-lock input drop. While mobile is the driver for this
|
||||
// PTY, desktop keystrokes must not reach the shell — any input would
|
||||
// race the mobile session and is also dimensionally wrong (PTY is at
|
||||
// phone fit). Renderer-side guard belongs here so we don't even mark
|
||||
// the pane as "interacted" (no unread clear, no take-floor cascade).
|
||||
// The pty:write IPC has a defense-in-depth twin. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
if (currentPtyId && isPtyLocked(currentPtyId)) {
|
||||
return
|
||||
}
|
||||
// Why: a real keystroke into the terminal is the unambiguous "user is
|
||||
// here" signal that dismisses the bell (ghostty "show until interact").
|
||||
// Guarded by the replay and codex-stale checks above so synthetic xterm
|
||||
@@ -394,12 +405,17 @@ export function connectPanePty(
|
||||
})
|
||||
|
||||
const onResizeDisposable = pane.terminal.onResize(({ cols, rows }) => {
|
||||
// Why: when a mobile-fit override is active, the PTY is already at the
|
||||
// correct phone dimensions. Suppress resize forwarding to avoid spurious
|
||||
// SIGWINCH signals that could cause TUI flicker. Uses the transport's
|
||||
// ptyId directly to avoid pane ID collisions across tabs.
|
||||
// Why: when a mobile-fit override is active OR mobile is currently the
|
||||
// driver of this PTY, the PTY is already at phone dims and any desktop
|
||||
// resize is wrong. Suppress resize forwarding to avoid spurious SIGWINCH
|
||||
// signals (TUI flicker / wrap corruption). Both checks are needed:
|
||||
// - getFitOverrideForPty covers the "phone-fit dims" state.
|
||||
// - isPtyLocked covers the broader "mobile driving" state, including
|
||||
// transitions where override may not be set (e.g. legacy code paths).
|
||||
// The pty:resize IPC has a defense-in-depth twin. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
const currentPtyId = transport.getPtyId()
|
||||
if (currentPtyId && getFitOverrideForPty(currentPtyId)) {
|
||||
if (currentPtyId && (getFitOverrideForPty(currentPtyId) || isPtyLocked(currentPtyId))) {
|
||||
return
|
||||
}
|
||||
transport.resize(cols, rows)
|
||||
@@ -438,6 +454,60 @@ export function connectPanePty(
|
||||
// constant used for serialized scrollback capture.
|
||||
const MAX_PENDING_BYTES = 512 * 1024
|
||||
|
||||
// Why: shared registration so both fresh-spawn and reattach paths install
|
||||
// the same SerializeAddon-backed serializer plus the onTitleChange wrapper
|
||||
// that drives lastTitle parity for mobile subscribers. Wires the resulting
|
||||
// unregister into onDataDisposable.dispose so disposal stays a single
|
||||
// teardown point. See docs/mobile-prefer-renderer-scrollback.md.
|
||||
const registerPaneSerializerFor = (ptyId: string): void => {
|
||||
// Why: StrictMode mounts panes twice; the first mount is disposed
|
||||
// before the second runs, but its pty:spawn IPC may have resolved by
|
||||
// the time `disposed` flips. Without this guard, the disposed first
|
||||
// mount would register against a torn-down xterm and replace the live
|
||||
// second-mount registration via owner-token shadowing.
|
||||
if (disposed) {
|
||||
return
|
||||
}
|
||||
const unregisterSerializer = registerPtySerializer(ptyId, async (opts) => {
|
||||
try {
|
||||
const pending = deps.pendingWritesRef.current.get(pane.id)
|
||||
if (pending) {
|
||||
deps.pendingWritesRef.current.set(pane.id, '')
|
||||
// Why: hidden/background panes buffer PTY output instead of writing
|
||||
// to xterm. Mobile snapshots must include that pending output, and
|
||||
// replay guard prevents xterm query auto-replies from hitting stdin.
|
||||
await replayIntoTerminalAsync(pane, deps.replayingPanesRef, pending)
|
||||
}
|
||||
// Why: alt-screen TUIs (vim, claude-code) hold transient state in
|
||||
// the alternate screen. The hydration path requests
|
||||
// altScreenForcesZeroRows so normal-buffer scrollback isn't bled
|
||||
// into the seed when the user is mid-TUI; the read-fallback path
|
||||
// omits it because it wants the user's currently-visible content.
|
||||
const alt = pane.terminal.buffer.active.type === 'alternate'
|
||||
const data =
|
||||
opts?.altScreenForcesZeroRows && alt
|
||||
? pane.serializeAddon.serialize({ scrollback: 0 })
|
||||
: pane.serializeAddon.serialize({ scrollback: opts?.scrollbackRows })
|
||||
return {
|
||||
data,
|
||||
cols: pane.terminal.cols,
|
||||
rows: pane.terminal.rows
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
const unregisterTitleSource = registerPtyTitleSource(ptyId, (handler) =>
|
||||
pane.terminal.onTitleChange(handler)
|
||||
)
|
||||
const origOnDataDisposableDispose = onDataDisposable.dispose.bind(onDataDisposable)
|
||||
onDataDisposable.dispose = () => {
|
||||
unregisterTitleSource()
|
||||
unregisterSerializer()
|
||||
origOnDataDisposableDispose()
|
||||
}
|
||||
}
|
||||
|
||||
// Why: for local connections (connectionId === null) the local PTY provider
|
||||
// already writes the startup command via writeStartupCommandWhenShellReady,
|
||||
// which is shell-ready-aware and reliable. Re-sending it here would cause
|
||||
@@ -446,30 +516,56 @@ export function connectPanePty(
|
||||
let pendingStartupCommand = connectionId ? (paneStartup?.command ?? null) : null
|
||||
|
||||
const startFreshSpawn = (): void => {
|
||||
const spawnPromise = Promise.resolve(
|
||||
transport.connect({
|
||||
url: '',
|
||||
cols,
|
||||
rows,
|
||||
callbacks: {
|
||||
onData: dataCallback,
|
||||
onReplayData: replayDataCallback,
|
||||
onError: reportError
|
||||
}
|
||||
})
|
||||
)
|
||||
.then((spawnedPtyId) =>
|
||||
typeof spawnedPtyId === 'string' ? spawnedPtyId : transport.getPtyId()
|
||||
)
|
||||
// Why: pre-signal the main process so its cooperation gate suppresses
|
||||
// the daemon-snapshot seed for this paneKey. We issue declare and the
|
||||
// spawn back-to-back without awaiting, because Electron's
|
||||
// ipcRenderer→ipcMain channel preserves order across consecutive invoke
|
||||
// calls from the same renderer. The cooperation gate at pty:spawn time
|
||||
// sees pendingByPaneKey populated. Settle/clear later echoes the gen
|
||||
// token captured here. See docs/mobile-prefer-renderer-scrollback.md.
|
||||
const preSignalPromise = window.api.pty
|
||||
.declarePendingPaneSerializer(cacheKey)
|
||||
.catch(() => null)
|
||||
|
||||
const spawnedRaw = transport.connect({
|
||||
url: '',
|
||||
cols,
|
||||
rows,
|
||||
callbacks: {
|
||||
onData: dataCallback,
|
||||
onReplayData: replayDataCallback,
|
||||
onError: reportError
|
||||
}
|
||||
})
|
||||
|
||||
const trackedPromise: Promise<string | null> = Promise.resolve(spawnedRaw)
|
||||
.then(async (spawnedPtyId) => {
|
||||
const resolvedPtyId =
|
||||
typeof spawnedPtyId === 'string' ? spawnedPtyId : transport.getPtyId()
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number' && resolvedPtyId) {
|
||||
registerPaneSerializerFor(resolvedPtyId)
|
||||
void window.api.pty.settlePaneSerializer(cacheKey, gen).catch(() => {})
|
||||
} else if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
return resolvedPtyId
|
||||
})
|
||||
.catch(async () => {
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
return null
|
||||
})
|
||||
.finally(() => {
|
||||
if (pendingSpawnByPaneKey.get(pendingSpawnKey) === spawnPromise) {
|
||||
if (pendingSpawnByPaneKey.get(pendingSpawnKey) === trackedPromise) {
|
||||
pendingSpawnByPaneKey.delete(pendingSpawnKey)
|
||||
}
|
||||
})
|
||||
// Why: split panes in the same tab can spawn concurrently. Key by pane
|
||||
// as well as tab so a remount cannot attach to a sibling setup pane's PTY.
|
||||
pendingSpawnByPaneKey.set(pendingSpawnKey, spawnPromise)
|
||||
pendingSpawnByPaneKey.set(pendingSpawnKey, trackedPromise)
|
||||
}
|
||||
|
||||
// Why: replay bytes (eager-buffer flush, attach-time screen clear) must
|
||||
@@ -566,32 +662,10 @@ export function connectPanePty(
|
||||
deps.updateTabPtyId(deps.tabId, ptyId)
|
||||
|
||||
// Why: mobile terminal streaming needs the exact screen state from
|
||||
// xterm.js. Register a serializer for this ptyId so the main process
|
||||
// can request a buffer snapshot when a mobile client subscribes.
|
||||
const unregisterSerializer = registerPtySerializer(ptyId, async () => {
|
||||
try {
|
||||
const pending = deps.pendingWritesRef.current.get(pane.id)
|
||||
if (pending) {
|
||||
deps.pendingWritesRef.current.set(pane.id, '')
|
||||
// Why: hidden/background panes buffer PTY output instead of writing
|
||||
// to xterm. Mobile snapshots must include that pending output, and
|
||||
// replay guard prevents xterm query auto-replies from hitting stdin.
|
||||
await replayIntoTerminalAsync(pane, deps.replayingPanesRef, pending)
|
||||
}
|
||||
return {
|
||||
data: pane.serializeAddon.serialize(),
|
||||
cols: pane.terminal.cols,
|
||||
rows: pane.terminal.rows
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
const origOnDataDisposableDispose = onDataDisposable.dispose.bind(onDataDisposable)
|
||||
onDataDisposable.dispose = () => {
|
||||
unregisterSerializer()
|
||||
origOnDataDisposableDispose()
|
||||
}
|
||||
// xterm.js. The shared helper installs both the SerializeAddon-backed
|
||||
// serializer and the onTitleChange-driven lastTitle source so the
|
||||
// main-process hydration path has full status parity.
|
||||
registerPaneSerializerFor(ptyId)
|
||||
|
||||
if (connectResult?.coldRestore) {
|
||||
// Why: restoreScrollbackBuffers() already wrote the saved xterm
|
||||
@@ -774,6 +848,13 @@ export function connectPanePty(
|
||||
// Clear it before attach/fallback so remounts don't keep retrying
|
||||
// an expired session after a fresh shell has been created.
|
||||
useAppStore.getState().removeDeferredSshSessionId(deps.tabId)
|
||||
// Why: pre-signal also for SSH-deferred reattach so the
|
||||
// cooperation gate uniformly applies to remote sessions. Issue
|
||||
// declare and connect back-to-back; Electron preserves order. See
|
||||
// docs/mobile-prefer-renderer-scrollback.md.
|
||||
const preSignalPromise = window.api.pty
|
||||
.declarePendingPaneSerializer(cacheKey)
|
||||
.catch(() => null)
|
||||
const reattachPromise = transport.connect({
|
||||
url: '',
|
||||
cols,
|
||||
@@ -786,7 +867,7 @@ export function connectPanePty(
|
||||
}
|
||||
})
|
||||
void Promise.resolve(reattachPromise)
|
||||
.then((result) => {
|
||||
.then(async (result) => {
|
||||
console.warn(
|
||||
`[pty-connection] Reattach result for tab=${deps.tabId}:`,
|
||||
result
|
||||
@@ -797,8 +878,16 @@ export function connectPanePty(
|
||||
: 'undefined'
|
||||
)
|
||||
handleReattachResult(result, pendingSessionId)
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.settlePaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
.catch(async (err) => {
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
console.warn(`[pty-connection] Reattach FAILED for tab=${deps.tabId}:`, err)
|
||||
if (disposed) {
|
||||
return
|
||||
@@ -860,6 +949,18 @@ export function connectPanePty(
|
||||
`pane=${pane.id} → REATTACH`
|
||||
)
|
||||
|
||||
// Why: reattach also pre-signals so the cooperation gate suppresses
|
||||
// the daemon seed for this paneKey. Reattach paths register their
|
||||
// serializer in handleReattachResult (via registerPaneSerializerFor),
|
||||
// mirroring the fresh-spawn path. We issue declare and the reattach
|
||||
// connect back-to-back without awaiting; Electron's ipcRenderer→ipcMain
|
||||
// channel preserves order. See
|
||||
// docs/mobile-prefer-renderer-scrollback.md (Renderer-side prerequisite
|
||||
// requirement #4).
|
||||
const preSignalPromise = window.api.pty
|
||||
.declarePendingPaneSerializer(cacheKey)
|
||||
.catch(() => null)
|
||||
|
||||
const reattachPromise = transport.connect({
|
||||
url: '',
|
||||
cols,
|
||||
@@ -873,10 +974,18 @@ export function connectPanePty(
|
||||
})
|
||||
|
||||
void Promise.resolve(reattachPromise)
|
||||
.then((result) => {
|
||||
.then(async (result) => {
|
||||
handleReattachResult(result, deferredReattachSessionId)
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.settlePaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
.catch(async (err) => {
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
warnTerminalLifecycleAnomaly('restored PTY reattach threw', {
|
||||
tabId: deps.tabId,
|
||||
|
||||
@@ -203,7 +203,8 @@ describe('useIpcEvents updater integration', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
ssh: {
|
||||
listTargets: () => Promise.resolve([]),
|
||||
@@ -396,7 +397,8 @@ describe('useIpcEvents updater integration', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
ssh: {
|
||||
listTargets: () => Promise.resolve([]),
|
||||
@@ -591,7 +593,8 @@ describe('useIpcEvents updater integration', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
ssh: {
|
||||
listTargets: () => Promise.resolve([]),
|
||||
@@ -808,7 +811,8 @@ describe('useIpcEvents browser tab close routing', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
agentStatus: { onSet: () => () => {} }
|
||||
}
|
||||
@@ -999,7 +1003,8 @@ describe('useIpcEvents browser tab close routing', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
agentStatus: { onSet: () => () => {} }
|
||||
}
|
||||
@@ -1185,7 +1190,8 @@ describe('useIpcEvents browser tab close routing', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
agentStatus: { onSet: () => () => {} }
|
||||
}
|
||||
@@ -1369,7 +1375,8 @@ describe('useIpcEvents shortcut hint clearing', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
ssh: {
|
||||
listTargets: () => Promise.resolve([]),
|
||||
@@ -1582,7 +1589,8 @@ describe('useIpcEvents CLI-created worktree activation', () => {
|
||||
},
|
||||
runtime: {
|
||||
getTerminalFitOverrides: () => Promise.resolve([]),
|
||||
onTerminalFitOverrideChanged: () => () => {}
|
||||
onTerminalFitOverrideChanged: () => () => {},
|
||||
onTerminalDriverChanged: () => () => {}
|
||||
},
|
||||
agentStatus: { onSet: () => () => {} }
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { normalizeAgentStatusPayload } from '../../../shared/agent-status-types'
|
||||
import { isGitRepoKind } from '../../../shared/repo-kind'
|
||||
import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface'
|
||||
import { setFitOverride, hydrateOverrides } from '@/lib/pane-manager/mobile-fit-overrides'
|
||||
import { setDriverForPty } from '@/lib/pane-manager/mobile-driver-state'
|
||||
|
||||
export { resolveZoomTarget } from './resolve-zoom-target'
|
||||
|
||||
@@ -832,6 +833,16 @@ export function useIpcEvents(): void {
|
||||
})
|
||||
)
|
||||
|
||||
unsubs.push(
|
||||
// Why: presence-lock driver state mirror. Updates the renderer's
|
||||
// mobile-driver-state map so TerminalPane / pty-connection guards
|
||||
// know which PTYs are currently driven by mobile. See
|
||||
// docs/mobile-presence-lock.md.
|
||||
window.api.runtime.onTerminalDriverChanged((event) => {
|
||||
setDriverForPty(event.ptyId, event.driver)
|
||||
})
|
||||
)
|
||||
|
||||
return () => unsubs.forEach((fn) => fn())
|
||||
}, [])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Why: presence-based driver state for the mobile-presence lock. Mirrors
|
||||
// the runtime's `currentDriver` map. Keyed by ptyId. Updated by an IPC
|
||||
// listener (onTerminalDriverChanged) wired from main.
|
||||
//
|
||||
// While `getDriverForPty(ptyId).kind === 'mobile'` the renderer:
|
||||
// - drops xterm.onData (input lock)
|
||||
// - drops xterm.onResize (resize lock)
|
||||
// - mounts the lock banner with the "Take back" affordance
|
||||
//
|
||||
// See docs/mobile-presence-lock.md.
|
||||
|
||||
export type DriverState =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'desktop' }
|
||||
| { kind: 'mobile'; clientId: string }
|
||||
|
||||
const driverByPtyId = new Map<string, DriverState>()
|
||||
|
||||
type DriverChangeEvent = {
|
||||
ptyId: string
|
||||
driver: DriverState
|
||||
}
|
||||
type DriverChangeListener = (event: DriverChangeEvent) => void
|
||||
const changeListeners = new Set<DriverChangeListener>()
|
||||
|
||||
export function onDriverChange(listener: DriverChangeListener): () => void {
|
||||
changeListeners.add(listener)
|
||||
return () => changeListeners.delete(listener)
|
||||
}
|
||||
|
||||
function notifyChange(event: DriverChangeEvent): void {
|
||||
for (const listener of changeListeners) {
|
||||
listener(event)
|
||||
}
|
||||
}
|
||||
|
||||
export function setDriverForPty(ptyId: string, driver: DriverState): void {
|
||||
if (driver.kind === 'idle') {
|
||||
driverByPtyId.delete(ptyId)
|
||||
} else {
|
||||
driverByPtyId.set(ptyId, driver)
|
||||
}
|
||||
notifyChange({ ptyId, driver })
|
||||
}
|
||||
|
||||
export function getDriverForPty(ptyId: string): DriverState {
|
||||
return driverByPtyId.get(ptyId) ?? { kind: 'idle' }
|
||||
}
|
||||
|
||||
export function isPtyLocked(ptyId: string): boolean {
|
||||
return driverByPtyId.get(ptyId)?.kind === 'mobile'
|
||||
}
|
||||
Reference in New Issue
Block a user