cc-viewer 1.9.34 → 1.9.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/cli.js +355 -59
  2. package/dist/assets/{App-CjP88gbM.css → App-BJIeZQK0.css} +1 -1
  3. package/dist/assets/App-C_S65Ygt.js +2 -0
  4. package/dist/assets/{ArchivePreview-dQkBQGgg.js → ArchivePreview-ezRMkut5.js} +1 -1
  5. package/dist/assets/{AudioPreview-B6gJoe0v.js → AudioPreview-MxQVazDj.js} +1 -1
  6. package/dist/assets/{MdxEditorPanel-COJDASLB.js → MdxEditorPanel-CmG2jyvK.js} +1 -1
  7. package/dist/assets/{Mobile-Cq04x2pS.js → Mobile-BerOQqT4.js} +1 -1
  8. package/dist/assets/{ProxyStatsModal-BRtZRf0B.js → ProxyStatsModal-dqlP2r2c.js} +1 -1
  9. package/dist/assets/{SubtitlePreview-C67JiAyR.js → SubtitlePreview-CHRRgV95.js} +1 -1
  10. package/dist/assets/index-DBmXRTLE.js +2 -0
  11. package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +2 -0
  12. package/dist/index.html +1 -1
  13. package/package.json +1 -1
  14. package/server/i18n.js +4 -0
  15. package/server/interceptor.js +114 -25
  16. package/server/lib/anthropic-auth-placeholder.js +147 -0
  17. package/server/lib/continuation-args.js +25 -0
  18. package/server/lib/im/im-bridge-core.js +59 -14
  19. package/server/lib/im/im-permissions.js +48 -0
  20. package/server/lib/im/im-process-manager.js +6 -5
  21. package/server/lib/im-deny.js +4 -1
  22. package/server/lib/interceptor-core.js +51 -0
  23. package/server/lib/proxy-session-registry.js +156 -0
  24. package/server/lib/scheduled-task-executor.js +6 -3
  25. package/server/lib/sdk-manager.js +376 -88
  26. package/server/lib/session-start-bridge.js +7 -1
  27. package/server/lib/update-job.js +3 -3
  28. package/server/lib/v2/session-select.js +18 -2
  29. package/server/lib/v2/v2-writer.js +249 -21
  30. package/server/proxy.js +15 -7
  31. package/server/pty-manager.js +62 -41
  32. package/server/routes/events.js +16 -4
  33. package/server/routes/preferences.js +108 -24
  34. package/server/routes/resume.js +271 -27
  35. package/server/routes/update.js +15 -2
  36. package/server/routes/workspaces.js +112 -29
  37. package/server/server.js +60 -10
  38. package/dist/assets/App-CZ0L1Cvm.js +0 -2
  39. package/dist/assets/index-Cb1Ur9uR.js +0 -2
  40. package/dist/assets/seqResourceLoaders-BQo28rrY.js +0 -2
@@ -38,15 +38,17 @@
38
38
  // The aggregation itself lives in lib/v2/resume-list.js (pure, unit-tested);
39
39
  // this handler is a thin HTTP wrapper.
40
40
 
41
- import { realpathSync } from 'node:fs';
41
+ import { realpathSync, readFileSync, existsSync } from 'node:fs';
42
42
  import { join, dirname, basename } from 'node:path';
43
43
  import { LOG_DIR } from '../../findcc.js';
44
- import { _projectName, _v2Writer, initForWorkspace } from '../interceptor.js';
44
+ import { _projectName, _v2Writer, initForWorkspace, retireInstance, releaseInstance } from '../interceptor.js';
45
45
  // Static import (not the route-local dynamic import) so the close-rebind helper
46
46
  // can call listLivePtys synchronously — a static import keeps the single shared
47
47
  // module instance, and module state is shared either way.
48
48
  import { listLivePtys } from '../pty-manager.js';
49
49
  import { listResumeSessions } from '../lib/v2/resume-list.js';
50
+ import { sanitizePathComponent } from '../lib/v2/layout.js';
51
+ import { resolveSessionDirName } from '../lib/v2/session-select.js';
50
52
  import { projectKeyForCwd } from '../lib/system-prompt-snapshots.js';
51
53
  import { readClaudeProjectModel } from '../lib/context-watcher.js';
52
54
  import { bumpWorkspacesVersion } from '../lib/file-access-policy.js';
@@ -61,6 +63,149 @@ function sendJson(res, code, obj) {
61
63
  res.end(JSON.stringify(obj));
62
64
  }
63
65
 
66
+ // In-flight resume reservations (concurrency): two concurrent resumes of the SAME session
67
+ // must not both pass the liveness guard before either binds its writer (a TOCTOU that would
68
+ // let two same-cwd instances share one journal). A sessionUuid is reserved synchronously at
69
+ // the guard and released in a finally; a second resume of an already-reserved uuid is refused.
70
+ const _inflightResumes = new Set();
71
+
72
+ // Active ownership registry (2026-11, in-memory): uuid → instanceKey of the instance that
73
+ // most recently resumed/bound that conversation. meta.json's `meta.instance` is
74
+ // first-write-wins (never rewritten on resume), so after a resume it names a possibly-DEAD
75
+ // prior owner — not the live writer. This registry is the live source of truth for "who is
76
+ // writing this uuid NOW"; it lets the guard (a) refuse a SECOND resume of a conversation a
77
+ // live sibling already holds (journal sharing), and (b) allow resuming a session whose
78
+ // recorded owner is alive but NOT currently writing it (the deterministic boot key is
79
+ // re-created every launch, so "owner live" alone would wrongly block every history resume).
80
+ // Populated on successful resume (route). An entry is authoritative while its owner instance
81
+ // is live AND still on this conversation (checked against the SDK session's own sessionId —
82
+ // generation-scoped, cleared on teardown/rebuild); a dead-owner or moved-on entry is dropped.
83
+ // Entries are also dropped on the owning instance's close.
84
+ const _activeOwners = new Map(); // uuid → instanceKey
85
+
86
+ // The set of LIVE claude-owned instance keys: live claude PTYs UNION live SDK sessions
87
+ // (2026-11 — SDK sessions are not PTYs, so listLivePtys alone can never see them; without
88
+ // this the guard fails OPEN for every SDK-owned conversation and two same-cwd SDK siblings
89
+ // could resume one journal). Best-effort: a probe failure just narrows the set.
90
+ function _liveClaudeInstanceKeys() {
91
+ const set = new Set(listLivePtys().filter(p => p.ptyKind === 'claude').map(p => p.instanceKey));
92
+ try {
93
+ for (const s of listSdkSessionInstances()) { if (s && s.instanceKey) set.add(s.instanceKey); }
94
+ } catch (err) { reportSwallowed('resume-route.twin-guard.sdk-live', err); }
95
+ return set;
96
+ }
97
+
98
+ // Same-cwd twin ownership guard (R7a): does the target conversation belong to a
99
+ // DIFFERENT live claude instance? The pid-level owner.lock cannot arbitrate two
100
+ // same-cwd twins (they share this process's pid), so liveness is judged by the live
101
+ // claude instance set (PTY ∪ SDK), keyed off the session dir's meta.instance. Returns
102
+ // {ownedByOther, ownerInstance} — fails OPEN (not owned) on any read error, so a
103
+ // torn meta never blocks a legitimate resume (the writer-side guard is the
104
+ // authoritative last line against journal sharing).
105
+ //
106
+ // Caller identity (H1): a caller with NO declared instanceKey is legitimately resuming
107
+ // its OWN conversation whenever the target project has exactly ONE live instance — that
108
+ // instance IS the caller (SDK single-session + Mobile never stamp an instanceKey). With
109
+ // 2+ live instances a bare caller is ambiguous → refused (must re-issue with an instanceKey).
110
+ async function twinOwnershipGuard({ sessionUuid, targetProject, callerInstanceKey }) {
111
+ try {
112
+ const san = targetProject ? sanitizePathComponent(targetProject) : '';
113
+ if (!san) return { ownedByOther: false };
114
+ const live = _liveClaudeInstanceKeys();
115
+ // A bare caller (no instanceKey — SDK single-session / Mobile) is the owner whenever it is
116
+ // the ONLY live instance for this project. Resolve this FIRST so the active-owner step below
117
+ // can compare against the RESOLVED caller (a bare caller that is the sole live instance must
118
+ // be allowed to re-resume its own conversation — review H1).
119
+ const projectKeys = [..._liveClaudeInstancesForProject(targetProject)];
120
+ let caller = callerInstanceKey;
121
+ if (!caller) {
122
+ if (projectKeys.length === 1) caller = projectKeys[0];
123
+ else if (projectKeys.length >= 2) {
124
+ // Ambiguous bare caller — but only refuse when the conversation is actually claimed
125
+ // (below); a fresh/unowned resume must not be blocked by ambiguity. We still need the
126
+ // meta, so continue and let the ownership checks decide.
127
+ }
128
+ }
129
+ // 1) Active-owner registry (live truth): a conversation a sibling resumed is owned by THAT
130
+ // instance. An entry stays authoritative while the owner is live AND still on this
131
+ // conversation (checked against the SDK session's own sessionId — generation-scoped,
132
+ // cleared on teardown/rebuild). A dead or moved-on owner entry is dropped so a later
133
+ // resume isn't wrongly blocked.
134
+ const activeOwner = _activeOwners.get(sessionUuid) || null;
135
+ if (activeOwner) {
136
+ if (!live.has(activeOwner)) {
137
+ _activeOwners.delete(sessionUuid); // owner is gone (closed / stopped) — release the hold
138
+ } else if (activeOwner === caller) {
139
+ return { ownedByOther: false }; // the caller IS the holder
140
+ } else {
141
+ let ownerSid = null;
142
+ try {
143
+ if (process.env.CCV_SDK_MODE === '1') {
144
+ const sdk = await import('../lib/sdk-manager.js');
145
+ ownerSid = sdk.getSessionIdForInstance(activeOwner);
146
+ }
147
+ } catch (err) { reportSwallowed('resume-route.twin-guard.sid', err); }
148
+ if (ownerSid === sessionUuid) {
149
+ return { ownedByOther: true, ownerInstance: activeOwner }; // actively held by a sibling
150
+ }
151
+ _activeOwners.delete(sessionUuid); // stale — owner no longer on this conversation
152
+ }
153
+ }
154
+ const projectDir = join(LOG_DIR, san);
155
+ // Resolve via the single-owner layout helper (exact-name, then meta.sessionId,
156
+ // then newest startTs) so the dir checked here is the SAME one the writer
157
+ // would adopt into — a bare readdir suffix-match could read the wrong meta
158
+ // when several dirs share one uuid.
159
+ const dirName = resolveSessionDirName(projectDir, sessionUuid, 'sessions');
160
+ if (!dirName) return { ownedByOther: false }; // never recorded — fresh resume
161
+ const metaPath = join(projectDir, 'sessions', dirName, 'meta.json');
162
+ if (!existsSync(metaPath)) return { ownedByOther: false };
163
+ const meta = JSON.parse(readFileSync(metaPath, 'utf-8'));
164
+ const owner = meta && typeof meta.instance === 'string' && meta.instance ? meta.instance : null;
165
+ if (!owner) return { ownedByOther: false }; // legacy / pre-multi-instance dir
166
+
167
+ // `caller` was resolved above (bare caller → sole live instance, or left null when
168
+ // ambiguous). An ambiguous bare caller reaching here means the conversation IS owned by a
169
+ // live instance — refuse with ambiguity so the client re-issues with an instanceKey.
170
+ if (!callerInstanceKey && !caller) {
171
+ return { ownedByOther: false, ambiguous: true, ownerInstance: owner };
172
+ }
173
+ if (caller && owner === caller) return { ownedByOther: false }; // own conversation
174
+ // The caller already holds this exact conversation (writer routing pointer) → safe.
175
+ if (caller) {
176
+ let holderSid = null;
177
+ try { holderSid = _v2Writer && typeof _v2Writer.currentSidForInstance === 'function' ? _v2Writer.currentSidForInstance(caller) : null; } catch (err) { reportSwallowed('resume-route.twin-guard.sid', err); }
178
+ if (holderSid === sessionUuid) return { ownedByOther: false };
179
+ }
180
+ // The caller does NOT hold it. A live owner puts the conversation off-limits to anyone
181
+ // else; a dead owner's dir is resumable.
182
+ if (!live.has(owner)) return { ownedByOther: false };
183
+ return { ownedByOther: true, ownerInstance: owner };
184
+ } catch (err) {
185
+ reportSwallowed('resume-route.twin-guard', err);
186
+ return { ownedByOther: false };
187
+ }
188
+ }
189
+
190
+ // Live claude instance keys belonging to ONE project (its sanitized name), PTY ∪ SDK.
191
+ // Used to resolve a bare caller's identity (sole live instance = the caller).
192
+ function _liveClaudeInstancesForProject(targetProject) {
193
+ // Normalize the incoming project (a raw basename may carry spaces/CJK) so it matches the
194
+ // sanitized form projectKeyForCwd produces — otherwise a raw-basename target yields an
195
+ // empty set and the "sole live = caller" fallback misfires into a false session-owned.
196
+ const target = sanitizePathComponent(targetProject || '');
197
+ const keys = new Set();
198
+ for (const p of listLivePtys()) {
199
+ if (p.ptyKind === 'claude' && projectKeyForCwd(p.cwd) === target && p.instanceKey) keys.add(p.instanceKey);
200
+ }
201
+ try {
202
+ for (const s of listSdkSessionInstances()) {
203
+ if (s && s.instanceKey && projectKeyForCwd(s.cwd) === target) keys.add(s.instanceKey);
204
+ }
205
+ } catch (err) { reportSwallowed('resume-route.twin-guard.proj', err); }
206
+ return keys;
207
+ }
208
+
64
209
  async function getSessionsHandler(req, res, parsedUrl) {
65
210
  // parsedUrl is a URL object (server.js handleRequest) — read via searchParams.
66
211
  const limitRaw = Number(parsedUrl.searchParams.get('limit'));
@@ -133,11 +278,14 @@ async function getLiveProcessesHandler(req, res, parsedUrl) {
133
278
  if (process.env.CCV_SDK_MODE === '1') {
134
279
  try {
135
280
  const sdk = await import('../lib/sdk-manager.js');
136
- for (const e of sdk.listSdkSessions()) {
281
+ const sdkRows = sdk.listSdkSessions();
282
+ const boundCwd = process.env.CCV_PROJECT_DIR || process.cwd();
283
+ for (const e of sdkRows) {
137
284
  if (!e || !e.cwd) continue;
138
- if (processes.some((p) => p && p.cwd === e.cwd)) continue; // a real PTY already covers this cwd
139
- const boundCwd = process.env.CCV_PROJECT_DIR || process.cwd();
140
- if (!currentInstanceKey && e.instanceKey && e.cwd === boundCwd) currentInstanceKey = e.instanceKey;
285
+ // Multi-instance (2026-11): dedupe only against a real PTY covering this cwd
286
+ // (a PTY owns the terminal surface). Do NOT dedupe against an already-pushed SDK
287
+ // row — a same-cwd sibling must surface as its own tab, so compare PTY rows only.
288
+ if (processes.some((p) => p && p.pid != null && p.cwd === e.cwd)) continue;
141
289
  processes.push({
142
290
  kind: 'main',
143
291
  project: projectKeyForCwd(e.cwd),
@@ -147,6 +295,15 @@ async function getLiveProcessesHandler(req, res, parsedUrl) {
147
295
  instanceKey: e.instanceKey || null,
148
296
  });
149
297
  }
298
+ // Bound identity = the cwd's STABLE primary (deterministic boot key), NOT the shared
299
+ // `active` pointer: active flips on every send/attach/switch, so keying the bound tab
300
+ // to it would yank every bound-view client to whatever instance spoke last. Delegate to
301
+ // the sdk-manager resolver so this HTTP identity and the WS `_ccvViewInstance` coherence
302
+ // (server.js `_cohereAttachInstance`) resolve the SAME instance for the same cwd —
303
+ // a duplicated inline derivation here would drift from it (normalization + pick order).
304
+ if (!currentInstanceKey) {
305
+ currentInstanceKey = sdk.resolveBoundPrimaryInstanceKey(boundCwd) || null;
306
+ }
150
307
  } catch (err) { reportSwallowed('resume-route.live-sdk', err); }
151
308
  }
152
309
  sendJson(res, 200, { processes, currentProject: _projectName || '', currentInstanceKey });
@@ -297,6 +454,26 @@ function postLiveProcessCloseHandler(req, res, parsedUrl, isLocal, deps) {
297
454
  try {
298
455
  rebound = _maybeRebindAfterClose(r, deps, survivorRecords);
299
456
  } catch (err) { reportSwallowed('resume-route.close-rebind', err); }
457
+ // Retire/release the closed SDK session's writer routing (M4): a closed RANDOM
458
+ // (fresh) key is retired so its draining traffic can't move the live pointers back;
459
+ // a DETERMINISTIC cwd key is only RELEASED (cleared), never retired — a later normal
460
+ // relaunch re-creates that key, and retiring it would permanently freeze the
461
+ // legitimate rebuilt session. SDK close only (r.wasFreshKey is set by closeSdkSession;
462
+ // PTY kills carry no wasFreshKey and are never retired here).
463
+ if (r.wasFreshKey === true && r.instanceKey) {
464
+ try { retireInstance(r.instanceKey); } catch (err) { reportSwallowed('resume-route.close-retire', err); }
465
+ } else if (r.wasFreshKey === false && r.instanceKey) {
466
+ try { releaseInstance(r.instanceKey); } catch (err) { reportSwallowed('resume-route.close-release', err); }
467
+ }
468
+ // Drop the closed instance's active-owner entries so a conversation it held becomes
469
+ // resumable by the survivor (the owner is no longer live).
470
+ if (r.instanceKey) {
471
+ for (const [uuid, owner] of _activeOwners) { if (owner === r.instanceKey) _activeOwners.delete(uuid); }
472
+ }
473
+ // A same-cwd SURVIVOR (PTY or SDK) still owns this project's scope bucket + scratch
474
+ // shells — do NOT reap them, or the surviving sibling loses its spinner/turn state and
475
+ // its mini-terminals. Compute once, guard both cleanups below.
476
+ const survivorSharesCwd = _hasSurvivorSharingCwd(r.cwd);
300
477
  // A PTY killed here fires no Stop POST, so its scope's streaming/turn
301
478
  // bucket would stay `active:true` forever — the heartbeat/streaming timer
302
479
  // keeps re-broadcasting it and the client's 30s staleness escape is
@@ -306,7 +483,7 @@ function postLiveProcessCloseHandler(req, res, parsedUrl, isLocal, deps) {
306
483
  // _resolveScopeForHookPayload), NOT the instanceKey — so resolve the same
307
484
  // project-scoped key here, collapsed to '' when it was the bound project.
308
485
  try {
309
- if (r.cwd && deps.clearScopeRuntimeFor) {
486
+ if (r.cwd && !survivorSharesCwd && deps.clearScopeRuntimeFor) {
310
487
  const { projectKeyForCwd } = await import('../lib/system-prompt-snapshots.js');
311
488
  const { normalizeProducerScope, scopeKeyOf } = await import('../lib/scope-router.js');
312
489
  const proj = projectKeyForCwd(r.cwd);
@@ -324,11 +501,7 @@ function postLiveProcessCloseHandler(req, res, parsedUrl, isLocal, deps) {
324
501
  // the cwd (a deliberate same-cwd second instance): its viewers still use those
325
502
  // shared scratch shells.
326
503
  try {
327
- if (r.cwd) {
328
- // listLivePtys() already only yields LIVE records (ptyProcess non-null), so a
329
- // cwd match here is a surviving instance sharing the dir.
330
- const survivorSharesCwd = listLivePtys().some((p) => p && p.cwd === r.cwd);
331
- if (!survivorSharesCwd) {
504
+ if (r.cwd && !survivorSharesCwd) {
332
505
  // Build the candidate set in BOTH path spaces (raw spawn cwd + realpath).
333
506
  // A deleted workspace dir makes realpathSync(raw) throw — then fall back to
334
507
  // realpath(dirname)+basename, which still resolves a deleted LEAF dir through
@@ -343,7 +516,6 @@ function postLiveProcessCloseHandler(req, res, parsedUrl, isLocal, deps) {
343
516
  }
344
517
  const { killScratchForCwd } = await import('../scratch-pty-manager.js');
345
518
  killScratchForCwd(cands);
346
- }
347
519
  }
348
520
  } catch (err) { reportSwallowed('resume-route.close-kill-scratch', err); }
349
521
  sendJson(res, 200, { ok: true, project, instanceKey: r.instanceKey || r.key || instanceKey || null, killedActive: r.killedActive === true, rebound });
@@ -354,6 +526,22 @@ function postLiveProcessCloseHandler(req, res, parsedUrl, isLocal, deps) {
354
526
  });
355
527
  }
356
528
 
529
+ // Does any LIVE claude instance (PTY or SDK) still share this cwd after a close? The
530
+ // killed record is already out of the registry by the time this runs, so a cwd match here
531
+ // is a SURVIVING sibling. Guards the scratch-reap AND the project-scope cleanup below:
532
+ // reaping either while a same-cwd sibling lives would kill the sibling's shells / reset
533
+ // its spinner+turn state (it shares the project scope bucket).
534
+ function _hasSurvivorSharingCwd(cwd) {
535
+ if (!cwd) return false;
536
+ // Claude instances only: a scratch/shell PTY sharing the cwd must NOT count as a sibling
537
+ // (it would suppress the scope cleanup and re-introduce the permanent-spinner leak).
538
+ if (listLivePtys().some((p) => p && p.ptyKind === 'claude' && p.cwd === cwd)) return true;
539
+ try {
540
+ for (const s of listSdkSessionInstances()) { if (s && s.cwd === cwd) return true; }
541
+ } catch (err) { reportSwallowed('resume-route.close-survivor', err); }
542
+ return false;
543
+ }
544
+
357
545
  // Bound-project rebound helper (2026-10). After killPtyFor removed the BOUND
358
546
  // project's PTY, pick a surviving live claude record and re-bind the server's
359
547
  // workspace identity to it. A full rebind additionally broadcasts
@@ -524,30 +712,78 @@ function postResumeSessionHandler(req, res, parsedUrl, isLocal, deps) {
524
712
  // switches the session identity directly (next user message resumes it).
525
713
  // Read the env at request time (not module top) so tests can flip it per case.
526
714
  if (process.env.CCV_SDK_MODE === '1') {
527
- const sdk = await import('../lib/sdk-manager.js');
528
- // Multi-session (2026-10-12): honor the requested workspace — resume the VIEWED
529
- // session, not always the active one. project is the workspace name from the client.
530
- const anchor = (project || instanceKey)
531
- ? { project: project || undefined, instanceKey: instanceKey || undefined }
532
- : undefined;
533
- const r = sdk.switchToSession(sessionUuid, anchor);
534
- if (r.ok) { sendJson(res, 200, { ok: true }); return; }
535
- if (r.reason === 'busy') { sendJson(res, 409, { ok: false, reason: 'busy' }); return; }
536
- if (r.reason === 'unavailable') { sendJson(res, 409, { ok: false, reason: 'unavailable' }); return; }
537
- sendJson(res, 400, { ok: false, reason: r.reason || 'bad-uuid' });
538
- return;
715
+ // Concurrency reservation (TOCTOU): two concurrent resumes of the SAME session must
716
+ // not both pass the ownership guard before either binds its writer — that would let
717
+ // two same-cwd instances share one journal. Reserve the uuid synchronously; a second
718
+ // resume of an already-reserved uuid is refused. Released in a finally below.
719
+ if (_inflightResumes.has(sessionUuid)) {
720
+ sendJson(res, 409, { ok: false, reason: 'busy' });
721
+ return;
722
+ }
723
+ _inflightResumes.add(sessionUuid);
724
+ try {
725
+ // Same-cwd twin ownership guard (R7a): same journal-sharing risk as PTY. The guard
726
+ // now sees SDK liveness AND resolves a bare caller (sole live instance = the caller).
727
+ const sdkGuard = await twinOwnershipGuard({
728
+ sessionUuid,
729
+ targetProject: project || (_projectName || ''),
730
+ callerInstanceKey: instanceKey || null,
731
+ });
732
+ if (sdkGuard.ambiguous) {
733
+ sendJson(res, 409, { ok: false, reason: 'ambiguous', owner: { instanceKey: sdkGuard.ownerInstance } });
734
+ return;
735
+ }
736
+ if (sdkGuard.ownedByOther) {
737
+ sendJson(res, 409, { ok: false, reason: 'session-owned', owner: { instanceKey: sdkGuard.ownerInstance } });
738
+ return;
739
+ }
740
+ const sdk = await import('../lib/sdk-manager.js');
741
+ // Multi-session (2026-10-12): honor the requested workspace — resume the VIEWED
742
+ // session, not always the active one. project is the workspace name from the client.
743
+ const anchor = (project || instanceKey)
744
+ ? { project: project || undefined, instanceKey: instanceKey || undefined }
745
+ : undefined;
746
+ const r = sdk.switchToSession(sessionUuid, anchor);
747
+ // Record the live owner so a LATER resume of this same conversation from a sibling
748
+ // is refused (the meta.instance author may be a dead prior owner). The SDK session's
749
+ // own sessionId now reflects the switch (switchToSession set it synchronously), so
750
+ // the guard's holder check reads generation-safe truth.
751
+ if (r.ok) {
752
+ const ownerKey = instanceKey || (sdk.listSdkSessions().find((s) => s.active) || {}).instanceKey || null;
753
+ if (ownerKey) _activeOwners.set(sessionUuid, ownerKey);
754
+ sendJson(res, 200, { ok: true });
755
+ return;
756
+ }
757
+ if (r.reason === 'busy') { sendJson(res, 409, { ok: false, reason: 'busy' }); return; }
758
+ if (r.reason === 'unavailable') { sendJson(res, 409, { ok: false, reason: 'unavailable' }); return; }
759
+ sendJson(res, 400, { ok: false, reason: r.reason || 'bad-uuid' });
760
+ return;
761
+ } finally {
762
+ _inflightResumes.delete(sessionUuid);
763
+ }
539
764
  }
540
765
  const pm = await import('../pty-manager.js');
541
766
  const targetProject = project || (_projectName || '');
542
767
  // Multi-instance: a project-name-only resume that matches 2+ live same-basename
543
768
  // instances is ambiguous — refuse with the candidates so the client re-issues
544
769
  // with an instanceKey (mirror of attach/close).
545
- if (!instanceKey && targetProject) {
770
+ let resolvedCallerInstance = instanceKey || null;
771
+ if (targetProject) {
546
772
  const live = pm.liveInstancesForProject(targetProject);
547
- if (live.length > 1) {
773
+ if (!instanceKey && live.length > 1) {
548
774
  sendJson(res, 409, { ok: false, reason: 'ambiguous', candidates: live });
549
775
  return;
550
776
  }
777
+ // Caller-identity fallback (review P0): when the client sends no instanceKey
778
+ // (single-instance bound view, Electron tabs, older bundles) and the project
779
+ // has exactly ONE live claude instance, that instance IS the caller. Without
780
+ // this the twin guard below would misread "no declared identity" as "another
781
+ // instance" and 409 a legitimate self-resume of the live instance's own
782
+ // conversation. Only a single live instance is unambiguous; 0 or 2+ leave it
783
+ // null (2+ already returned above).
784
+ if (!resolvedCallerInstance && live.length === 1) {
785
+ resolvedCallerInstance = live[0].instanceKey || null;
786
+ }
551
787
  }
552
788
  // Strict target-kind gate (no active-PTY fallback): never inject into the wrong
553
789
  // project's conversation when the anchor doesn't resolve, and never into a shell.
@@ -555,6 +791,14 @@ function postResumeSessionHandler(req, res, parsedUrl, isLocal, deps) {
555
791
  sendJson(res, 404, { ok: false, reason: 'not-found' });
556
792
  return;
557
793
  }
794
+ // Same-cwd twin ownership guard (R7a): refuse to resume a conversation that a
795
+ // DIFFERENT live claude instance is actively writing — two claude processes on
796
+ // one journal is certain corruption. Dead/legacy/own conversations pass.
797
+ const guard = await twinOwnershipGuard({ sessionUuid, targetProject, callerInstanceKey: resolvedCallerInstance });
798
+ if (guard.ownedByOther) {
799
+ sendJson(res, 409, { ok: false, reason: 'session-owned', owner: { instanceKey: guard.ownerInstance } });
800
+ return;
801
+ }
558
802
  const chatQueue = await import('../lib/chat-queue.js');
559
803
  const r = await chatQueue.injectResumeCommand(sessionUuid, { project: targetProject || undefined, instanceKey: instanceKey || undefined });
560
804
  if (r.ok) {
@@ -35,8 +35,21 @@ async function start(req, res, parsedUrl, isLocal, deps) {
35
35
  json(res, 200, deps.updateJob.getState());
36
36
  return;
37
37
  }
38
- deps.updateJob.start().catch((err) => reportSwallowed('update.start', err));
39
- json(res, 202, deps.updateJob.getState());
38
+ // Read an optional { force: true } body so the UI can let the user bypass the
39
+ // "another instance is running" guard after an explicit confirmation. Body
40
+ // parse failure / empty body / non-stream req (tests) all fall back to
41
+ // force=false (legacy behavior).
42
+ const finish = (body) => {
43
+ let force = false;
44
+ try { force = body ? JSON.parse(body)?.force === true : false; }
45
+ catch { /* tolerate non-JSON / empty body as force=false */ }
46
+ deps.updateJob.start({ force }).catch((err) => reportSwallowed('update.start', err));
47
+ json(res, 202, deps.updateJob.getState());
48
+ };
49
+ if (typeof req?.on !== 'function') { finish(''); return; }
50
+ let body = '';
51
+ req.on('data', (chunk) => { body += chunk; if (body.length > 64 * 1024) req.destroy(); });
52
+ req.on('end', () => finish(body));
40
53
  }
41
54
 
42
55
  async function restart(req, res, parsedUrl, isLocal, deps) {