Repository navigation
fix(remote-workspace): stop stale snapshot applies from erasing freshly created terminal tabs - #13013
robertnisipeanu wants to merge 24 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe changes add direct SSH tab observation and authority validation across the main process, preload bridge, and renderer. The main process retains bounded tab intents, reconciles snapshots, and acknowledges patch results. The renderer preserves local tab additions and deletions during snapshot application. Session writes remain pending during suppression and flush after readiness or a bounded deadline. Tests cover ownership, ordering, retention, scale, persistence, and end-to-end snapshot races. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-apply.ts (1)
78-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCondense the new rationale comments.
Keep each comment to one concise statement of the non-obvious reason.
src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L78-L84: Reduce the stale-snapshot rationale to one line.src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L101-L106: Reduce the graft-and-merge rationale to one line.src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L165-L167: Reduce the recovery and live-PTY distinction to one line.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 527bd11a-3c5a-4c91-9235-7246a9c00c4d
📥 Commits
Reviewing files that changed from the base of the PR and between f057cbc and 587ea496d48b60f9c9473f47092f1246e66687eb.
📒 Files selected for processing (5)
src/renderer/src/hooks/remote-workspace-snapshot-apply.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.tssrc/renderer/src/hooks/remote-workspace-target-sync.test.tssrc/renderer/src/lib/session-write-subscriber.test.tssrc/renderer/src/lib/session-write-subscriber.ts
587ea49 to
b425e87
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 12
🧹 Nitpick comments (9)
tests/e2e/helpers/remote-workspace-snapshot-request-barrier.ts (1)
15-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract a shared invoke-handler barrier helper.
Both barrier files duplicate installation, state management, release, and restoration for different channels. Parameterize the helper with the channel name and request predicate while preserving each barrier’s capture timing.
tests/e2e/global-teardown.ts (1)
28-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStrip trailing carriage returns from parsed worktree paths.
Line 28 splits only on
\n. If the Git output uses CRLF on Windows,worktreePathkeeps a trailing\r.path.basenamethen returns a name ending in\r, the prefix check at line 36 still matches, andrmSynctargets a nonexistent path. The removal then fails silently becauseforce: truesuppresses the error.The repository requires cleanup scripts to work on macOS, Linux, and Windows, so normalize the line ending.
♻️ Proposed change
- for (const line of worktreeList.split('\n')) { + for (const rawLine of worktreeList.split('\n')) { + const line = rawLine.replace(/\r$/, '') if (!line.startsWith('worktree ')) { continue }Source: Coding guidelines
src/main/ipc/remote-workspace-tab-intent-reconciliation.ts (1)
111-115: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueAvoid creating an empty worktree-path key for a no-op absent intent.
If
tabsByWorktreePathhas no key forworktree.worktreePath,tabsis[]and line 113 writes an empty array under a key the remote snapshot never had. The reconciled snapshot then carries a path entry that the remote session does not carry.sessionMatchesTabObservationcompares path sets by exact size and membership, so the extra key can make a later full-snapshot match fail.Skip the assignment when the removal changes nothing.
♻️ Proposed guard
} else if (intent.presence === 'absent' && !currentTab) { const remaining = tabs.filter((tab) => !remoteTabIdentityMatches(tab, intent.tab.tab)) - reconciled.session.tabsByWorktreePath[worktree.worktreePath] = remaining + if (remaining.length !== tabs.length) { + reconciled.session.tabsByWorktreePath[worktree.worktreePath] = remaining + }src/main/ipc/remote-workspace-tab-intent-retention.ts (1)
22-24: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winCompute the intent byte sizes once per
retaincall.
retaincallsintentBytesup to four times: lines 60, 61, 66, and 67. Each call runsJSON.stringify(intent)over the whole intent, which embeds the observed tab and its optionallayout.layout.buffersByLeafIdcan hold serialized terminal buffers up to the per-target observation bound. The renderer sends observations on every tab change, andRemoteWorkspaceTabIntentStore.observecallsretainonce per changed tab slot. The repeated serialization runs on the main process thread.Hoist the two sizes into locals.
⚡ Proposed change
const previous = state.intents.get(slot) + const previousBytes = previous ? intentBytes(slot, previous) : 0 + const nextBytes = intentBytes(slot, intent) - const retainedBytes = - state.retainedIntentBytes - - (previous ? intentBytes(slot, previous) : 0) + - intentBytes(slot, intent) + const retainedBytes = state.retainedIntentBytes - previousBytes + nextBytes if ( state.intents.size + (previous ? 0 : 1) > MAX_REMOTE_WORKSPACE_TAB_INTENTS_PER_TARGET || retainedBytes > MAX_REMOTE_WORKSPACE_TAB_INTENT_BYTES_PER_TARGET || - this.retainedBytes - - (previous ? intentBytes(slot, previous) : 0) + - intentBytes(slot, intent) > - MAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES + this.retainedBytes - previousBytes + nextBytes > MAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES ) {Also applies to: 58-72
src/main/ipc/remote-workspace.ts (1)
596-618: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGuard
argsbefore readingrendererGeneration.Line 597 casts
argsand line 601 readsinput.rendererGeneration. Line 609 and line 613 do the same. If a caller invokes the channel with no payload,argsisundefinedand the property read throws aTypeError.ipcMain.handleconverts the throw into a rejected invoke promise, so the renderer call fails instead of becoming a no-op.Line 585 already uses optional chaining for the same field on
remoteWorkspace:observeTabState. Apply the same handling here.🛡️ Proposed guard
ipcMain.handle('remoteWorkspace:forgetTabState', (event, args) => { - const input = args as { rendererGeneration?: number; targetId?: string } + const input = (args ?? {}) as { rendererGeneration?: number; targetId?: string } const authority = remoteWorkspaceTabObservationOwners.resolve( event.sender, event.processId, input.rendererGeneration ) if (isMainRenderer(event) && authority && input.targetId) { remoteWorkspaceTabIntents.forgetTarget(input.targetId, authority) } }) ipcMain.handle('remoteWorkspace:forgetAllTabState', (event, args) => { - const input = args as { rendererGeneration?: number } + const input = (args ?? {}) as { rendererGeneration?: number }src/main/ipc/remote-workspace-tab-intent-store.test.ts (1)
421-478: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDerive the over-capacity target id from the constant.
The loop at line 425 runs to
MAX_REMOTE_WORKSPACE_TAB_INTENT_TARGETS, but lines 443-476 hardcode'target-65'and'worktree-65'. The same pattern appears at lines 502-510, 558-568, 614-627, and 701-734. The literals assume the constant equals 64.If the constant changes, these tests keep passing but stop exercising the over-capacity path. They would instead operate on an already-retained target.
Bind the id to the constant.
♻️ Proposed change
+const OVER_CAPACITY_TARGET = `target-${MAX_REMOTE_WORKSPACE_TAB_INTENT_TARGETS + 1}` +const OVER_CAPACITY_WORKTREE = `worktree-${MAX_REMOTE_WORKSPACE_TAB_INTENT_TARGETS + 1}`src/main/ipc/remote-workspace-tab-observation-owner.ts (1)
75-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReset the owner registry and the intent store together in tests.
resetForTestssetsnextGeneration = 0, so laterstartcalls reissue generation numbers that were already handed out. The newWeakMapprevents stale lease resolution inside this registry. However,RemoteWorkspaceTabIntentStoreandRemoteWorkspaceUntrackedIntentFenceshold copied authority objects that keep the old generation numbers. A test that resets only this registry can produce an authority that compares equal to retained state.Document or enforce that callers reset all three together.
src/main/ipc/remote-workspace-tab-intent-store.ts (1)
241-254: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCopy
state.authorityinto the capture.Line 252 stores a live reference to
state.authority. Todayobserveat line 119 reassigns the field with a new object rather than mutating it, so the capture stays stable andacknowledgePatchcompares the intended values. The invariant is implicit. A future in-place mutation ofstate.authoritywould silently make every outstanding capture compare equal.Copy the value, as
RemoteWorkspaceUntrackedIntentFences.capturealready does at line 67 ofremote-workspace-untracked-intent-fences.ts.♻️ Proposed change
- tracked: { authority: state.authority, lifecycle: state.lifecycle }, + tracked: { authority: { ...state.authority }, lifecycle: state.lifecycle },src/main/ipc/remote-workspace-tab-intent-retention.test.ts (1)
95-107: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe aggregate-budget assertion sits close to the boundary.
Line 95 sets
layoutBytesto one tenth ofMAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES. Each of the five targets retains the layout twice: once in the observed worktree baseline and once in the derived intent. That is about one fifth of the budget per target, so five targets land near the limit exactly.Line 107 expects
target-4to overflow. A small change to per-intent serialization overhead can move the crossing point and flip this assertion. Widen the margin, for example by usingMAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES / 4, so the overflow point is unambiguous.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: be03c2f8-d450-4e56-b11a-7749803538ec
📥 Commits
Reviewing files that changed from the base of the PR and between a70291a and b425e87eb9710d14a090f6cf8ece8b1cde8b8c5a.
📒 Files selected for processing (44)
config/reliability-gates.jsoncsrc/main/ipc/pty-process-incarnation-registry.tssrc/main/ipc/pty.tssrc/main/ipc/remote-workspace-patch-queue.test.tssrc/main/ipc/remote-workspace-tab-intent-reconciliation.tssrc/main/ipc/remote-workspace-tab-intent-retention.test.tssrc/main/ipc/remote-workspace-tab-intent-retention.tssrc/main/ipc/remote-workspace-tab-intent-store.test.tssrc/main/ipc/remote-workspace-tab-intent-store.tssrc/main/ipc/remote-workspace-tab-intent-types.tssrc/main/ipc/remote-workspace-tab-observation-bounds.tssrc/main/ipc/remote-workspace-tab-observation-owner.test.tssrc/main/ipc/remote-workspace-tab-observation-owner.tssrc/main/ipc/remote-workspace-untracked-intent-fences.tssrc/main/ipc/remote-workspace.test.tssrc/main/ipc/remote-workspace.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/App.tsxsrc/renderer/src/hooks/direct-ssh-tab-intent-observer.test.tssrc/renderer/src/hooks/direct-ssh-tab-intent-observer.tssrc/renderer/src/hooks/direct-ssh-tab-observation-scope.tssrc/renderer/src/hooks/direct-ssh-tab-process-inputs.tssrc/renderer/src/hooks/remote-workspace-bidirectional-race-oracle.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.tssrc/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.tssrc/renderer/src/hooks/remote-workspace-tab-presence-reconciliation.tssrc/renderer/src/hooks/remote-workspace-target-sync.test.tssrc/renderer/src/hooks/remote-workspace-target-sync.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/lib/direct-ssh-target-scope-types.tssrc/renderer/src/lib/direct-ssh-target-scope.test.tssrc/renderer/src/lib/direct-ssh-target-scope.tssrc/renderer/src/lib/direct-ssh-worktree-owner-evidence.tssrc/renderer/src/lib/session-write-subscriber.test.tssrc/renderer/src/lib/session-write-subscriber.tssrc/shared/remote-workspace-types.tstests/e2e/global-setup.tstests/e2e/global-teardown.tstests/e2e/helpers/remote-workspace-snapshot-request-barrier.tstests/e2e/remote-workspace-tab-observation-scale.spec.tstests/e2e/ssh-remote-workspace-snapshot-race.spec.tstests/playwright.config.ts
| customTitle: null, | ||
| color: null, | ||
| sortOrder: 0, | ||
| createdAt: Number(id.split('-').at(-1)) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
tab('tab-recovered', …) produces createdAt: NaN.
Line 26 derives createdAt from the trailing id segment. For tab-0 through tab-7 this yields 0–7. For tab-recovered at line 125 it yields Number('recovered'), which is NaN.
The test still passes. The observation at line 124-127 is authoritative: true, so observe replaces the baseline and derives no intents, and NaN never reaches remoteWorkspaceTabSlotKey. The fixture is still wrong, and it will produce a slot key of null for the createdAt position if this test is extended to a non-authoritative observation.
Give the helper an explicit createdAt parameter.
🐛 Proposed fix
-function tab(id: string, layoutBytes: number): RemoteWorkspaceObservedTab {
+function tab(id: string, layoutBytes: number, createdAt = 0): RemoteWorkspaceObservedTab {
return {
processIdentity: `process-${id}`,
tab: {
id,
worktreePath: '/remote/work',
ptyId: `pty-${id}`,
title: id,
customTitle: null,
color: null,
sortOrder: 0,
- createdAt: Number(id.split('-').at(-1))
+ createdAt
},Then pass the index at the call sites, for example tab(\tab-${index}`, layoutBytes, index)at line 64 and line 103, andtab('tab-recovered', 1_024, 99)` at line 125.
Also applies to: 124-127
| if (!this.overflowAuthority || this.canReplace(this.overflowAuthority, authority)) { | ||
| this.overflowAuthority = { ...authority } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
overflowAuthority is sticky and blocks every untracked target until renderer teardown.
record sets overflowAuthority when the target map is full. blocks(targetId) then returns true for every targetId that has no tracked fence, because the check is this.overflowAuthority !== null and is not scoped to a target.
No method clears overflowAuthority for the same authority except forgetAll and reset. acknowledge, clear, and forget leave it set. So one overflow event permanently blocks RemoteWorkspaceTabIntentStore.reconcile (line 216-218 of remote-workspace-tab-intent-store.ts) for all untracked targets for the remaining lifetime of that renderer generation, even after the target map drops below MAX_REMOTE_WORKSPACE_UNTRACKED_INTENT_TARGETS.
Add a recovery path. One option: track the overflowed target ids in a bounded set and clear overflowAuthority when that set is acknowledged or when capacity frees up.
🩹 Sketch of a bounded recovery path
private overflowAuthority: RemoteWorkspaceTabObservationAuthority | null = null
+ private overflowCount = 0
@@
if (!this.overflowAuthority || this.canReplace(this.overflowAuthority, authority)) {
this.overflowAuthority = { ...authority }
+ this.overflowCount += 1
}
}
@@
clear(targetId: string): void {
this.targets.delete(targetId)
+ this.releaseOverflowIfDrained()
}
@@
acknowledge(targetId: string, capture: RemoteWorkspaceUntrackedIntentFence | null): void {
@@
this.targets.delete(targetId)
+ this.releaseOverflowIfDrained()
}
}
+
+ private releaseOverflowIfDrained(): void {
+ if (this.targets.size === 0) {
+ this.overflowAuthority = null
+ this.overflowCount = 0
+ }
+ }Also applies to: 61-63
| ipcMain.handle('remoteWorkspace:flushTabState', () => undefined) | ||
|
|
||
| ipcMain.handle( | ||
| 'remoteWorkspace:reconcileSnapshot', | ||
| ( | ||
| _event, | ||
| args: { targetId: string; snapshot: RemoteWorkspaceSnapshot } | ||
| ): RemoteWorkspaceSnapshot | null => | ||
| remoteWorkspaceTabIntents.reconcile(args.targetId, args.snapshot) | ||
| ) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
remoteWorkspace:reconcileSnapshot accepts any sender and any payload. The handler is the only tab-state channel added in this change that omits the isMainRenderer(event) gate used at lines 573, 587, 603, and 615, and it reads args.targetId and args.snapshot without validation. Any webContents that reaches the channel can probe the main renderer's retained tab-intent state for an arbitrary targetId, and an omitted payload throws a TypeError. The test call site depends on that missing gate.
src/main/ipc/remote-workspace.ts#L620-L629: add theisMainRenderer(event)check and validate thatargs.targetIdis a string andargs.snapshotis present; returnnullotherwise.src/main/ipc/remote-workspace-patch-queue.test.ts#L355-L370: replace thenullevent argument at lines 357 and 366 withmainEventso the handler passes the sender check.
📍 Affects 2 files
src/main/ipc/remote-workspace.ts#L620-L629(this comment)src/main/ipc/remote-workspace-patch-queue.test.ts#L355-L370
| await app.evaluate(async () => { | ||
| const state = ( | ||
| globalThis as typeof globalThis & { | ||
| __remoteWorkspaceSnapshotRequestBarrier?: BarrierState | ||
| } | ||
| ).__remoteWorkspaceSnapshotRequestBarrier | ||
| if (state && !state.released) { | ||
| state.released = true | ||
| state.release() | ||
| } | ||
| await state?.handlerReturned | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard the handlerReturned await on captured.
handlerReturned resolves only inside the replacement handler, after a matching request reaches the barrier. If no request for state.targetId was ever captured, release() resolves nothing and line 86 waits forever. The test then fails on an opaque Playwright timeout instead of a clear assertion.
restoreRemoteWorkspaceSnapshotRequestHandler does not have this problem because it never awaits handlerReturned.
🛡️ Proposed fix to avoid an unbounded wait
if (state && !state.released) {
state.released = true
state.release()
}
- await state?.handlerReturned
+ if (state?.captured) {
+ await state.handlerReturned
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| await app.evaluate(async () => { | |
| const state = ( | |
| globalThis as typeof globalThis & { | |
| __remoteWorkspaceSnapshotRequestBarrier?: BarrierState | |
| } | |
| ).__remoteWorkspaceSnapshotRequestBarrier | |
| if (state && !state.released) { | |
| state.released = true | |
| state.release() | |
| } | |
| await state?.handlerReturned | |
| }) | |
| await app.evaluate(async () => { | |
| const state = ( | |
| globalThis as typeof globalThis & { | |
| __remoteWorkspaceSnapshotRequestBarrier?: BarrierState | |
| } | |
| ).__remoteWorkspaceSnapshotRequestBarrier | |
| if (state && !state.released) { | |
| state.released = true | |
| state.release() | |
| } | |
| if (state?.captured) { | |
| await state.handlerReturned | |
| } | |
| }) |
| await api.forgetTabState({ rendererGeneration: generation, targetId: 'target-999' }) | ||
| await observe('target-1000', [existing]) | ||
| await observe('target-1000', [existing, created]) | ||
| const unrelatedMutation = await api.reconcileSnapshot({ | ||
| targetId: 'target-1000', | ||
| snapshot: snapshot(3, [existing]) | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Inspect forgetTabState and admission/eviction semantics to confirm the cleanup step is inert here.
set -euo pipefail
rg -n -C8 'forgetTabState' -g '!**/node_modules/**'
ast-grep run --pattern 'forget($$$) { $$$ }' --lang typescript src/main/ipc/remote-workspace-tab-intent-store.ts
rg -n -C10 'evictBaseline' src/main/ipc/ -g '*.ts'Repository: stablyai/orca
Length of output: 151
🏁 Script executed:
set -euo pipefail
printf '%s\n' '--- candidate files ---'
git ls-files | rg 'remote-workspace-tab-observation-scale\.spec\.ts|remote-workspace-tab-intent-store|reliability-gates\.jsonc'
printf '%s\n' '--- test context ---'
test_file="$(git ls-files | rg '(^|/)remote-workspace-tab-observation-scale\.spec\.ts$' | head -n1)"
if [ -n "${test_file}" ]; then
sed -n '45,100p' "$test_file"
fi
printf '%s\n' '--- forgetTabState references ---'
rg -n -C10 'forgetTabState|forgetTab|evictBaseline|admission|readmission' tests src config -g '*.{ts,tsx,js,jsx,json,jsonc}' || trueRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
set -euo pipefail
test_file="$(git ls-files '*remote-workspace-tab-observation-scale.spec.ts')"
printf '%s\n' "$test_file"
sed -n '1,120p' "$test_file"
printf '%s\n' '--- exact implementation and test references ---'
rg -n -C6 'forgetTabState' "$test_file" src tests config -g '*.{ts,tsx,js,jsx,json,jsonc}' | head -n 240
printf '%s\n' '--- relevant filenames ---'
git ls-files | rg 'remote-workspace-tab|reliability-gates'Repository: stablyai/orca
Length of output: 19880
🏁 Script executed:
set -euo pipefail
printf '%s\n' '--- IPC handler ---'
sed -n '570,625p' src/main/ipc/remote-workspace.ts
printf '%s\n' '--- store outline ---'
ast-grep outline src/main/ipc/remote-workspace-tab-intent-store.ts
printf '%s\n' '--- store implementation ---'
sed -n '1,280p' src/main/ipc/remote-workspace-tab-intent-store.ts
printf '%s\n' '--- retention implementation ---'
sed -n '1,320p' src/main/ipc/remote-workspace-tab-intent-retention.ts
printf '%s\n' '--- scale-related tests and gate entry ---'
rg -n -C8 'remote-workspace-tab-observation-scale|target-65|target-999|target-1000|scoped|cleanup|readmission' config/reliability-gates.jsonc tests/e2e src/main/ipc/remote-workspace-tab-intent-*.test.tsRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
set -euo pipefail
printf '%s\n' '--- IPC forget handler ---'
sed -n '596,620p' src/main/ipc/remote-workspace.ts
printf '%s\n' '--- intent store ---'
wc -l src/main/ipc/remote-workspace-tab-intent-store.ts
sed -n '1,260p' src/main/ipc/remote-workspace-tab-intent-store.ts
printf '%s\n' '--- retention ---'
wc -l src/main/ipc/remote-workspace-tab-intent-retention.ts
sed -n '1,260p' src/main/ipc/remote-workspace-tab-intent-retention.ts
printf '%s\n' '--- gate references only ---'
rg -n -C5 'remote-workspace-tab-observation-scale|scoped-cleanup|readmission|target-65|target-999|target-1000' config/reliability-gates.jsoncRepository: stablyai/orca
Length of output: 28223
🏁 Script executed:
set -euo pipefail
printf '%s\n' '--- unit coverage for cleanup and readmission ---'
rg -n -C12 'readmission|post-forget|forgetTarget|explicit cleanup|connection-only observations' \
src/main/ipc/remote-workspace-tab-intent-store.test.ts \
src/main/ipc/remote-workspace-tab-intent-retention.test.ts
printf '%s\n' '--- standalone admission check for the E2E sequence ---'
python3 - <<'PY'
MAX_TARGETS = 64
targets = set()
def authoritative_observe(target):
if target not in targets:
if len(targets) >= MAX_TARGETS:
# Every target created by this sequence has an empty baseline,
# except target-65, which has a pending intent.
candidates = sorted(t for t in targets if t != "target-65")
if not candidates:
return False
targets.remove(candidates[0])
targets.add(target)
return True
for i in range(1, 65):
assert authoritative_observe(f"target-{i}")
assert authoritative_observe("target-65")
pending = {"target-65"}
for i in range(66, 1001):
assert authoritative_observe(f"target-{i}")
assert len(targets) == MAX_TARGETS
before = "target-1000" in targets
forget999_removed = "target-999" in targets
targets.remove("target-999")
observe1000_is_existing = "target-1000" in targets
print({
"target_1000_tracked_before_cleanup": before,
"target_999_was_tracked": forget999_removed,
"target_1000_observation_requests_admission": not observe1000_is_existing,
"tracked_target_count_after_forget": len(targets),
})
PYRepository: stablyai/orca
Length of output: 18153
Scope cleanup to target-1000 or remove it. target-1000 is already tracked before the cleanup call, so forgetting target-999 does not affect the following observations or reconciliation. Use target-1000 to cover cleanup followed by readmission.
| target = startDockerSshRelayTarget(testInfo) | ||
| registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(target)) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Capture the target value for the post-shutdown cleanup.
The cleanup closure reads the target variable, not its value. Line 221 sets target = null before the post-Electron-shutdown cleanup runs. The deferred cleanup therefore always receives null, and the safety net cannot remove the Docker container if the in-finally cleanup at line 220 does not complete.
Also, line 220 is the only step in finally without error suppression. If cleanupDockerSshRelayTarget throws there, it masks the original test failure and skips line 221.
🧹 Proposed fix
- target = startDockerSshRelayTarget(testInfo)
- registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(target))
+ const startedTarget = startDockerSshRelayTarget(testInfo)
+ target = startedTarget
+ registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(startedTarget))Apply this diff in the finally block:
- cleanupDockerSshRelayTarget(target)
- target = null
+ try {
+ cleanupDockerSshRelayTarget(target)
+ } catch {
+ // Best-effort cleanup; the post-shutdown hook retries.
+ }
+ target = null📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| target = startDockerSshRelayTarget(testInfo) | |
| registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(target)) | |
| const startedTarget = startDockerSshRelayTarget(testInfo) | |
| target = startedTarget | |
| registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(startedTarget)) |
…ly created terminal tabs A terminal tab created around a direct-SSH snapshot apply could be permanently lost: the session-write subscriber dropped its pending write during the apply's suppression window, so the remote store never learned the tab existed, and the applied snapshot (fetched before the tab was created) replaced the worktree's tab list without it — leaving the tab's pty running unreachable on the host, with any sleeping-agent record for it stranded against a tab id that no longer exists. Three changes close this: - The session-write subscriber holds suppressed writes and retries until the suppression lifts instead of clearing the pending field set, so a tab created during an apply still reaches the local session and the remote push. A 60s hold ceiling bounds the retry: past it the write proceeds, so back-to-back applies (or a misbehaving remote streaming snapshot revisions) cannot starve local persistence indefinitely. - A snapshot whose in-scope tab lists are missing a tab that is live locally — mid-reattach per the recovery ledger, or with an attached pty per ptyIdsByTabId — is treated as predating that tab: the tab is grafted into the snapshot's tab list for its worktree before the merge, and its id joins the merge's preserve set so its layout and session ids survive. Remote-only tabs from other clients still apply unchanged, and tabs without a live pty are still removed when the remote store says so. - The stale-tab detection and the graft are exported as pure helpers with unit tests, plus an integration test covering a live local tab omitted by an incoming snapshot alongside a remote-only tab. Co-Authored-By: Claude Fable 5 <[email protected]>
This reverts commit 5e23ca40978cd91c475f2c261ba5ee8ccdf597d0.
This reverts commit 52900bdadaa379568735e00ec7ff910b17a3215c.
0a88168 to
4f4a085
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-apply.test.ts (1)
70-121: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winExtend the direct-SSH retention test.
remote-workspace-target-sync.test.tsasserts the tab andterminalLayoutsByTabId, but notremoteSessionIdsByTabId. Add an assertion thatfresh-tabretainsssh:target-a@@pty-freshafter snapshot hydration.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c43bf280-aef6-40b0-9569-7a74b8f7780f
📒 Files selected for processing (43)
config/reliability-gates.jsoncsrc/main/ipc/pty-process-incarnation-registry.tssrc/main/ipc/pty.tssrc/main/ipc/remote-workspace-patch-queue.test.tssrc/main/ipc/remote-workspace-tab-intent-reconciliation.tssrc/main/ipc/remote-workspace-tab-intent-retention.test.tssrc/main/ipc/remote-workspace-tab-intent-retention.tssrc/main/ipc/remote-workspace-tab-intent-store.test.tssrc/main/ipc/remote-workspace-tab-intent-store.tssrc/main/ipc/remote-workspace-tab-intent-types.tssrc/main/ipc/remote-workspace-tab-observation-bounds.tssrc/main/ipc/remote-workspace-tab-observation-owner.test.tssrc/main/ipc/remote-workspace-tab-observation-owner.tssrc/main/ipc/remote-workspace-untracked-intent-fences.tssrc/main/ipc/remote-workspace.test.tssrc/main/ipc/remote-workspace.tssrc/preload/api/workspace-session-api.tssrc/preload/index.tssrc/renderer/src/App.tsxsrc/renderer/src/hooks/direct-ssh-tab-intent-observer.test.tssrc/renderer/src/hooks/direct-ssh-tab-intent-observer.tssrc/renderer/src/hooks/direct-ssh-tab-observation-scope.tssrc/renderer/src/hooks/direct-ssh-tab-process-inputs.tssrc/renderer/src/hooks/ipc-events-test-harness.tssrc/renderer/src/hooks/remote-workspace-bidirectional-race-oracle.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.tssrc/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.tssrc/renderer/src/hooks/remote-workspace-tab-presence-reconciliation.tssrc/renderer/src/hooks/remote-workspace-target-sync.test.tssrc/renderer/src/hooks/remote-workspace-target-sync.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/lib/direct-ssh-target-scope-types.tssrc/renderer/src/lib/direct-ssh-target-scope.test.tssrc/renderer/src/lib/direct-ssh-target-scope.tssrc/renderer/src/lib/direct-ssh-worktree-owner-evidence.tssrc/renderer/src/lib/session-write-subscriber.test.tssrc/renderer/src/lib/session-write-subscriber.tssrc/shared/remote-workspace-types.tstests/e2e/global-teardown.tstests/e2e/helpers/remote-workspace-snapshot-request-barrier.tstests/e2e/remote-workspace-tab-observation-scale.spec.tstests/e2e/ssh-remote-workspace-snapshot-race.spec.ts
🚧 Files skipped from review as they are similar to previous changes (38)
- src/main/ipc/remote-workspace-tab-intent-retention.test.ts
- src/main/ipc/remote-workspace-tab-observation-owner.test.ts
- src/preload/index.ts
- src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts
- src/main/ipc/remote-workspace-tab-intent-store.test.ts
- tests/e2e/helpers/remote-workspace-snapshot-request-barrier.ts
- src/renderer/src/lib/direct-ssh-target-scope.test.ts
- tests/e2e/global-teardown.ts
- src/renderer/src/hooks/direct-ssh-tab-intent-observer.test.ts
- src/renderer/src/hooks/remote-workspace-tab-presence-reconciliation.ts
- tests/e2e/remote-workspace-tab-observation-scale.spec.ts
- src/renderer/src/lib/session-write-subscriber.test.ts
- config/reliability-gates.jsonc
- src/renderer/src/lib/direct-ssh-target-scope-types.ts
- src/main/ipc/pty-process-incarnation-registry.ts
- src/main/ipc/remote-workspace.test.ts
- src/main/ipc/remote-workspace-tab-intent-types.ts
- src/main/ipc/remote-workspace-patch-queue.test.ts
- src/renderer/src/hooks/remote-workspace-target-sync.test.ts
- src/main/ipc/remote-workspace-untracked-intent-fences.ts
- src/renderer/src/lib/direct-ssh-target-scope.ts
- src/renderer/src/lib/direct-ssh-worktree-owner-evidence.ts
- src/renderer/src/hooks/remote-workspace-bidirectional-race-oracle.test.ts
- src/main/ipc/remote-workspace-tab-intent-retention.ts
- src/renderer/src/App.tsx
- src/main/ipc/remote-workspace-tab-observation-owner.ts
- src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
- src/renderer/src/hooks/direct-ssh-tab-process-inputs.ts
- src/main/ipc/remote-workspace-tab-intent-reconciliation.ts
- src/renderer/src/hooks/ipc-events-test-harness.ts
- src/renderer/src/hooks/useIpcEvents.ts
- src/main/ipc/remote-workspace-tab-intent-store.ts
- src/main/ipc/remote-workspace.ts
- src/main/ipc/remote-workspace-tab-observation-bounds.ts
- src/main/ipc/pty.ts
- src/renderer/src/hooks/direct-ssh-tab-intent-observer.ts
- src/renderer/src/hooks/direct-ssh-tab-observation-scope.ts
- src/renderer/src/hooks/remote-workspace-target-sync.ts
| const status = Object.values(state.remoteWorkspaceSyncStatusByTargetId).find( | ||
| (entry) => entry.phase === 'synced' && entry.direction === 'pull' | ||
| ) | ||
| if (freshTabId && status) { | ||
| stop() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Wait for the delayed target pull to complete.
find() accepts a retained synced pull status from any target. It can set done when the new tab appears, before line 160 releases the snapshot barrier. Line 161 can then pass without observing completion of the delayed pull.
Track remote.targetId in installMutationChurn. Require an in-flight pull for that target and a later synced transition after the barrier release.
The tab-intent capture rides remote-workspace-relay-sync.ts, the shared store instance lives in remote-workspace-tab-intent-store.ts, the observation and reconcile handlers stay in remote-workspace.ts, and the session-write subscriber wiring moves to app-shell/use-app-session-persistence.ts (stablyai#14607 decomposed App.tsx). A live pre-request tab that a newer snapshot omits now survives the merge (stablyai#14844); the ledger continues to discriminate deliberate closes from never-uploaded creations at the apply boundary. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNqAZQTwmAkwGcHj5TYXk
|
Thanks @robertnisipeanu for the remote snapshot-erasure diagnosis and regression coverage. Completed issue #12748 and merged fix #14844 now own this behavior on current main, including the zero-tab union/graft case. We will retain your contribution as historical credit and request no rebase, retest, or other follow-up. Closing this superseded branch. |
Problem
A terminal tab created around a direct-SSH remote-workspace snapshot apply can be permanently lost:
createSessionWriteSubscriberdrops its pending write while an apply suppresses persistence (pendingChangedFields.clear()), so the tab never reaches the remote session store — the suppression window can last up to 30s of terminal reconnects plus a 1s trailing window.mergeDirectSshRemoteWorkspaceSessioniterates onlyremote.tabsByWorktree, so a local-only tab cannot survive it.remoteWorkspaceSessionMatchesSnapshot— the remote store never learns the tab existed.The tab's pty keeps running unreachable on the host, and any sleeping-agent record for the tab is stranded against a tab id that no longer exists. Observed in production: an agent launched into a fresh tab moments before a
wake-refreshapply; the tab was erased within seconds while itsclaudeprocess kept running on the host.Fix
ptyIdsByTabId— predates the session write that created that tab. The tab is appended to the snapshot's list for its worktree and added to the merge's preserve set, so its layout and session ids survive. Remote-only tabs from other clients still apply unchanged, and tabs without a live pty are still removed when the remote store says so — this cannot resurrect tabs deleted on another device.Tests
staleDirectSshSnapshotTabIdsandgraftLocalTabsIntoRemoteSessionunit tests.🤖 Generated with Claude Code