Skip to content

fix(editor): fold duplicate open-file owner tuples on session persist - #24191

Open
ggbdpq wants to merge 4 commits into
stablyai:mainfrom
ggbdpq:fix/openfiles-persist-tuple-dedupe
Open

ggbdpq wants to merge 4 commits into
stablyai:mainfrom
ggbdpq:fix/openfiles-persist-tuple-dedupe

Conversation

@ggbdpq

@ggbdpq ggbdpq commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Summary

Editor tabs multiply on every session save (#23967: 79 persisted rows for 5 real files). The claim comment on the issue pins the write path: an open file's identity is the raw path string x runtimeEnvironmentId, hydration recasts every persisted row to an owned id (editor:<wt>:<env>:<encoded path>), so the session mirror's lookup by raw path always misses and re-appends a (raw path, current env) row on each launch, while rows from older environments are never re-keyed or culled.

This PR is the stop-the-bleeding half of the plan, not the full fix:

  • buildEditorSessionData (persist side) now folds repeated (filePath, worktreeId, runtimeOwnerKey) tuples, first occurrence wins. Empty/whitespace environment ids collapse to the same local owner via runtimeOwnerKey, matching how hydration resolves the owner.
  • This is lossless for restore: hydrateEditorSession already treats repeated records for the same owner as corruption and keeps the first row (#17370), so the folded rows are exactly the ones restore discarded anyway. Split-tab sharing is unaffected — it lives in unifiedTabs (multiple tabs sharing one OpenFile's entityId), not in repeated open-file rows.
  • Effect: new duplicate rows stop being written, and existing duplicates already in orca-data.json are cleaned up on the next save.

Out of scope (needs a maintainer decision, follow-up to come): converging identity across runtime-environment changes — re-keying old-owner rows to the current owner at env transitions or mirror apply — plus path-separator normalization (%5C vs %2F, defect 2 in the issue). One caution on the issue's "dedupe by normalized path regardless of runtimeEnvironmentId" proposal: the same absolute path on a different machine's runtime is a genuinely different file, so cross-environment folding must be limited to a same-worktree ownership migration, not applied globally by path.

Verification

Check Result
New regression workspace-session.test.ts > folds repeated open-file rows for the same (path, worktree, runtime) tuple, dedupe wiring reverted FAIL — 1 failed | 18 passed (red evidence)
Same suite with the fix restored 19/19 passed
New unit suite workspace-session-openfile-tuple-dedupe.test.ts (fold, cross-env kept, worktree/path kept, empty-env owners collapse) 4/4 passed
16 adjacent suites touching buildEditorSessionData/buildWorkspaceSessionPayload (incl. editor-session-duplicate-restore, restored-editor-owner-reparent, workspace-session-patch, terminals hydration) 108/108 passed (re-run after formatting)
tsc --noEmit -p config/tsconfig.tc.web.json exit 0
oxlint on the 4 touched files 0 warnings, 0 errors
oxfmt --check on the 4 touched files pass
check:max-lines-ratchet OK, no new bypasses

Windows 11, Node 24. No orca-runtime-tests spec touches buildWorkspaceSessionPayload/openFilesByWorktree (verified by grep), so no scratch-config spec run needed.

AI use

Implemented with GLM-5.3-Flash (ZCode): store-probe investigation, patch and tests; human reviewed and ran the verification matrix.

Checklist

  • Tests added/updated and passing locally (red -> green regression + unit suite)
  • oxlint and typecheck:web clean
  • No new max-lines ratchet bypass
  • Comments in English, new module follows the no-helpers/utils naming rule

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

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

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The change adds foldOpenFilesByOwnerTuple and uses it to deduplicate edit-mode files before session data is persisted. The helper retains the first file for each path, worktree, and runtime owner tuple. Session data remaps an active-file ID when folding removes its row, unless that ID already identifies a retained file in the same worktree. Tests cover duplicate and distinct tuples, empty runtime environments, and worktree-scoped ID mapping.

Merge Risk: Minimal · previous review 937d5

This change folds duplicate open-file rows when the editor session is saved and keeps the active-file pointer on a retained row. Earlier concerns about losing or redirecting the active tab are reported as fixed and covered by tests. No merge-blocking risk is identified.

Security architecture risk: Low · up to 937d5

The change preserves separate worktree and runtime owners and follows the existing restore policy of retaining the first duplicate. No new file-operation authority or externally reachable interface was identified. Complete guarantees for mirrored SSH ownership and interrupted saves remain unconfirmed.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated effect is on editor-session records and active selections. Identical paths in different worktrees or normalized runtime owners remain separate. The helper neither chooses a filesystem execution host nor grants credentials or file-operation privileges.

Trust Boundaries and Controls

  • observed — Persisted ownership metadata is not sufficient by itself to authorize mutation. File-operation context validates current provenance and rejects an external SSH target unless the route is SSH, has no runtime owner, and matches that target. SSH mutations also require a connection generation. The folding helper does not remove these controls.
  • observed — Normal open-file admission reuses a matching path/worktree/runtime owner and updates its SSH target and provenance rather than adding a separate target-owned row. This supports the tuple contract for that producer, but does not prove it for every session-mirror producer.

Resilience and Maintainability Implications

  • observed — The existing save transport partitions session state by execution host. Full saves await partition writes and a flush; patch saves isolate nonlocal failures from the local promise. These inspected orchestration paths do not establish atomic publication across hosts or complete interruption recovery.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)

Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: folding duplicate open-file owner tuples during session persistence.
Description check ✅ Passed The description is mostly complete. It explains the problem, implementation, scope, rationale, testing, AI use, and checklist status. It does not follow every template heading and does not explicitly …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.

ℹ️ Recent review info

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: aa16c469-383e-4875-8791-d46c82b3866b

📥 Commits

Reviewing files that changed from the base of the PR and between 86b1beaed84b72c2f0fd53b9c01cab3438eb1156 and 937d551cb5e97c734c4cfa155edb1bcefd208465.

📒 Files selected for processing (4)

  • src/renderer/src/lib/workspace-session-openfile-tuple-dedupe.test.ts
  • src/renderer/src/lib/workspace-session-openfile-tuple-dedupe.ts
  • src/renderer/src/lib/workspace-session.test.ts
  • src/renderer/src/lib/workspace-session.ts

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2e12407a-c17e-431b-bfb6-f5f5d7a95769

📥 Commits

Reviewing files that changed from the base of the PR and between 46d6b76 and 306f77c92a6c73bd6800087e9b6fb074f219bcff.

📒 Files selected for processing (4)
  • src/renderer/src/lib/workspace-session-openfile-tuple-dedupe.test.ts
  • src/renderer/src/lib/workspace-session-openfile-tuple-dedupe.ts
  • src/renderer/src/lib/workspace-session.test.ts
  • src/renderer/src/lib/workspace-session.ts

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

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Deduplicates repeated open files in session persistence.

The PR appears safe to merge under this review; no new, non-duplicate finding remains.

Summary

The PR folds duplicate persisted open-file rows by path, worktree, and runtime owner, then remaps active-file selections when a duplicate row is removed. The latest changes scope that remap by worktree and prefer an ID that still names a retained row.

Reviews (3) · Last reviewed commit: "fix(editor): scope the open-file fold's ..."

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Persist-side owner-tuple fold — buildEditorSessionData now routes edit-mode open files through dedupeOpenFilesByOwnerTuple, keeping the first row per (filePath, worktreeId, runtimeOwnerKey(runtimeEnvironmentId)) (src/renderer/src/lib/workspace-session.ts:131).
  • New helper module — workspace-session-openfile-tuple-dedupe.ts documents why the fold is lossless against hydration's first-wins owner dedupe (issue #17370) and normalizes empty/whitespace env ids via the shared runtimeOwnerKey.
  • Regression coverage — a payload-level test folds 5 store rows (owned id, raw path, other env, other file) to 3 persisted rows with order and activeFileIdByWorktree preserved; a 4-case unit suite covers cross-env/worktree/path retention and empty-env collapse.

I verified the fold tuple matches hydration's identity model (LegacyHydratedEditorFileIndex.hasOwner) exactly, so the surviving row is the same one restore would keep — drafts, readOnly, and liveTail are unaffected. I also traced the runtime mirror's active-file reconciliation (apply-preparation-unified.ts): currentActiveEditorStillExists keeps the retained owned row as the active id, so the first-occurrence survivor is the referenced one and the persisted active selection is not dropped. The two touched suites plus five adjacent persist/hydration suites pass locally (89 tests).

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The removed→retained map is keyed by file.id alone, which is not unique per owner tuple, so in the local + paired-remote state #23967 measured it can silently re-point the restored active file to the other environment's row. Details inline.

Reviewed changes

This run re-reviewed commit 86b1beaed8 (the delta since the prior pullfrog review at 306f77c92a).

  • Removed→retained mapping returned from the fold — foldOpenFilesByOwnerTuple now returns { files, retainedIdByRemovedId }, recording each folded row's id against the id of the row that survived.
  • Active-file pointer remapped before the whitelist check — buildEditorSessionData resolves each worktree's active id through that mapping so a selected duplicate is preserved on the retained row, and the 'editor' tab-type marker gated on it survives.
  • Coverage added — a payload regression for the selected-duplicate case plus a unit case asserting the removed→retained mapping contract.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@greptile-apps

greptile-apps Bot commented Sep 30, 2026

Copy link
Copy Markdown

Want your agent to iterate on Greptile's feedback? Try greploops.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This run re-reviewed commit 937d551cb5 (the delta since the prior pullfrog review at 86b1beaed8).

  • Owner-tuple fold mapping scoped per worktree — foldOpenFilesByOwnerTuple now returns retainedIdByRemovedId as Map<worktreeId, Map<removedId, retainedId>>, so a removed row's raw-path id can no longer leak across a worktree boundary (src/renderer/src/lib/workspace-session-openfile-tuple-dedupe.ts:28).
  • Live retained id wins over the mapping — buildEditorSessionData remaps an active pointer only when the id is no longer a retained row in its own worktree (src/renderer/src/lib/workspace-session.ts:171), so a pointer naming a surviving local raw-path row is never slid onto the remote owned row.
  • Coverage added — two payload regressions: a live raw-path id in a second worktree is not remapped, and a live local row is preferred over the fold mapping when both claim the active id; the fold's unit contract case now asserts the mapping per worktree.

I traced both prior failure modes against the new branch. For the cross-worktree case, editFileIdsByWorktree['wt-2'].has(fileId) is now checked before the mapping, so the pointer stays on its own live row instead of being re-pointed to wt-1's retained id and then dropped by the whitelist. For the same-worktree local + paired-remote case, the local raw-path row is a retained id, so the pointer stays on it rather than following the removed duplicate to the remote owned row. Both tests fail on 86b1beaed8 and pass on the fix. The prior pullfrog thread on workspace-session.ts:169 is resolved.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@ggbdpq

ggbdpq commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto 7d18e19907 today. The one mid-rebase conflict was upstream folding the fileId guard into the loop condition; both sides' semantics are preserved, and the active-file remap now lives in workspace-session-openfile-tuple-dedupe.ts next to the fold (upstream growth had pushed workspace-session.ts over the 300-line lint ratchet). All review threads are resolved — each bot finding landed with a red-test-first fix (the per-worktree remap scoping was the last one, 937d551cb5). Verification on the rebased head: workspace-session.test.ts + workspace-session-openfile-tuple-dedupe.test.ts pass 24/24, and oxlint is clean on the touched files.

@nwparker gentle ping — happy to adjust anything.

orca-data.json grew without bound (79 persisted rows for 5 real files)
because an open file's identity is the raw path string x runtime env id:
hydration recasts every persisted row to an owned id
(editor:<wt>:<env>:<encoded path>), so the session mirror's lookup by raw
path always misses and re-appends a (path, worktree, runtime) row on each
launch, while rows from older environments are never re-keyed or culled.

Stop the bleeding on the persist side: buildEditorSessionData now keeps
only the first row per (filePath, worktreeId, runtimeOwnerKey) tuple.
This is lossless for restore - hydrateEditorSession already treats
repeated records for the same owner as corruption and keeps the first
(stablyai#17370) - so restore output is unchanged, new duplicate rows stop being
written, and existing ones are cleaned up on the next save. Rows owned by
a different runtime environment stay distinct; converging identity across
environment changes plus path-separator normalization is a separate
follow-up that needs a maintainer decision.

Refs stablyai#23967

Generated-by: GLM-5.3-Flash (ZCode)
Review follow-up to 306f77c92a: first-occurrence-wins tuple folding could
fold away the very row a worktree's active-file pointer names - when the
session mirror's raw-path duplicate is the selected one (owned-id row
first), the whitelist for activeFileIdByWorktree no longer contained its
id, so persistence dropped the active pointer and, gated on it, the
'editor' tab-type marker; the next launch then reopened the worktree on a
terminal tab instead of the editor.

foldOpenFilesByOwnerTuple now also returns the fold's removed-to-retained
id mapping, and buildEditorSessionData re-points each worktree's active
id through it before the whitelist check, so the selection and its
tab-type marker survive. Rows themselves are unchanged, so no duplicate
ids can be introduced; hydrate and the mirror are untouched.

Refs stablyai#23967

Generated-by: GLM-5.3-Flash (ZCode)
The duplicate-tuple fold keyed its removed->retained id map by the bare
row id, but a raw-path id is just the absolute file path, which is not
unique across owners or worktrees. Two problems followed: the active-file
remap in buildEditorSessionData consulted the map before the whitelist
check, and the lookup ignored which worktree the pointer belonged to. A
raw-path id that was still a live row elsewhere (another worktree, or the
local row beside the mirror's remote-tuple duplicate) got re-pointed at a
foreign retained row - the cross-worktree case then failed the whitelist
and dropped the pointer (and the 'editor' tab-type marker with it).

Fix both: the fold returns its mapping scoped per worktree (a tuple never
spans worktrees), and the pointer is only remapped when it no longer
names a retained row in its own worktree.

Generated-by: GLM-5.3-Flash (ZCode)
…dule

Upstream growth pushed workspace-session.ts over the 300-line ratchet; the
persist-side active-pointer projection moves next to the fold it pairs with.

Generated-by: GLM-5.3-Flash (ZCode)
@ggbdpq
ggbdpq force-pushed the fix/openfiles-persist-tuple-dedupe branch from 42027e1 to d3e1c35 Compare November 5, 2026 21:23
@ggbdpq

ggbdpq commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and force-pushed. Upstream's cleanup deleted workspace-session.test.ts — this PR's integration-level regression pin for the openfile tuple dedupe (#23967) is kept (the deletion is noted in its header, and the dedicated pin file covers the unit side). One import follows upstream's move of terminal-tab-types into shared/workspace-layout/.

Verified after the rebase: workspace-session suites 50/50, typecheck:node, typecheck:web, format check, and the max-lines ratchet all clean.

@nwparker gentle ping — happy to adjust anything.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant