cc-viewer 1.9.34 → 1.9.35

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.
@@ -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) {
@@ -5,6 +5,17 @@ import { initForWorkspace, resetWorkspace, getLiveLogSource, markContinuedLaunch
5
5
  import { LOG_DIR } from '../../findcc.js';
6
6
  import { migrationStatus } from '../lib/v2/migrate-prompt.js';
7
7
  import { reportSwallowed } from '../lib/error-report.js';
8
+ import { stripContinuationArgs } from '../lib/continuation-args.js';
9
+ import { isAdminReq } from '../lib/is-admin.js';
10
+ import { isSameOriginBrowserRequest } from '../lib/same-origin.js';
11
+ import { unwatchAllWorkflows } from '../lib/workflow-watcher.js';
12
+ import { readClaudeProjectModel } from '../lib/context-watcher.js';
13
+ import { countLogEntries, streamRawEntriesAsync } from '../lib/log-stream.js';
14
+ import { sseWrite } from '../lib/wire-compress.js';
15
+
16
+ // Re-exported for the existing test import surface; the implementation lives in
17
+ // lib/continuation-args.js (shared with the Electron main process).
18
+ export { stripContinuationArgs };
8
19
 
9
20
  // P2: claude continuation flags — the workspace launcher injects `-c` itself
10
21
  // (WorkspaceList's logCount heuristic), so argv scanning in cli.js never sees
@@ -14,10 +25,6 @@ const CONTINUE_FLAGS = new Set(['-c', '--continue', '-r', '--resume']);
14
25
  // adoption must NOT fire (it targets the latest main session, not the user's
15
26
  // chosen one). Mirrors cli.js's CCV_CLAUDE_RESUME channel.
16
27
  const RESUME_FLAGS = new Set(['-r', '--resume']);
17
- import { unwatchAllWorkflows } from '../lib/workflow-watcher.js';
18
- import { readClaudeProjectModel } from '../lib/context-watcher.js';
19
- import { countLogEntries, streamRawEntriesAsync } from '../lib/log-stream.js';
20
- import { sseWrite } from '../lib/wire-compress.js';
21
28
 
22
29
  function workspacesList(req, res, parsedUrl, isLocal, deps) {
23
30
  import('../workspace-registry.js').then(async ({ getWorkspaces }) => {
@@ -37,11 +44,26 @@ function workspacesList(req, res, parsedUrl, isLocal, deps) {
37
44
  }
38
45
 
39
46
  function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
47
+ // Two gates, both required (same as live-processes/close, routes/resume.js):
48
+ // admin identity AND same-origin browser context. The server answers CORS
49
+ // preflight permissively (ACAO: *) and loopback is auth-exempt, so without
50
+ // this a cross-site page could spawn claude processes in arbitrary host
51
+ // directories through the user's browser — and forceNew makes every accepted
52
+ // request a NEW process (no dedupe throttle).
53
+ if (!isAdminReq(req, isLocal) || !isSameOriginBrowserRequest(req, parsedUrl)) {
54
+ res.writeHead(403, { 'Content-Type': 'application/json' });
55
+ res.end(JSON.stringify({ error: 'forbidden' }));
56
+ return;
57
+ }
40
58
  let body = '';
41
59
  req.on('data', chunk => { body += chunk; if (body.length > deps.MAX_POST_BODY) req.destroy(); });
42
60
  req.on('end', async () => {
43
61
  try {
44
- const { path: wsPath, extraArgs: launchExtraArgs } = JSON.parse(body);
62
+ const { path: wsPath, extraArgs: launchExtraArgs, forceNew: rawForceNew } = JSON.parse(body);
63
+ // forceNew (file explorer "New Workspace (Session)" on the CURRENT root): spawn a
64
+ // brand-new claude instance in the same cwd instead of re-attaching to the live
65
+ // one — and never continue its conversation.
66
+ const forceNew = rawForceNew === true;
45
67
  if (!wsPath || !existsSync(wsPath) || !statSync(wsPath).isDirectory()) {
46
68
  res.writeHead(400, { 'Content-Type': 'application/json' });
47
69
  res.end(JSON.stringify({ error: 'Invalid directory path' }));
@@ -55,7 +77,12 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
55
77
  // 所有日志相关操作(initForWorkspace、watchLogFile、spawnClaude)由 tab-worker 子进程负责
56
78
  if (process.env.CCV_ELECTRON_MULTITAB === '1') {
57
79
  if (deps.launchCallback) {
58
- deps.launchCallback(wsPath, Array.isArray(launchExtraArgs) ? launchExtraArgs : []);
80
+ // Forward forceNew so main's createTab skips its same-realpath dedupe
81
+ // (a second tab on the current directory is the intended outcome). Strip
82
+ // continuation flags here too — the IPC handler is not the only entry
83
+ // (a non-Electron browser can POST the mgmt server directly).
84
+ const forwardedArgs = Array.isArray(launchExtraArgs) ? launchExtraArgs : [];
85
+ deps.launchCallback(wsPath, forceNew ? stripContinuationArgs(forwardedArgs) : forwardedArgs, forceNew);
59
86
  }
60
87
  deps.setWorkspaceLaunched(true);
61
88
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -64,7 +91,21 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
64
91
  }
65
92
 
66
93
  // 非 Electron 模式(web / CLI):完整逻辑
67
- const result = initForWorkspace(wsPath);
94
+ // forceNew is forwarded: when spawning a second same-cwd instance,
95
+ // initForWorkspace must keep the live twin's session bindings/owner.lock and
96
+ // clear only launch-boundary state (see interceptor).
97
+ // Hoisted: the SDK forceNew branch (below) and the PTY branch both assign this, and
98
+ // the response reads it — declaring it here keeps the SDK assignment out of TDZ.
99
+ let launchedInstanceKey = null;
100
+ // SDK +1 keeps the same-cwd sibling LIVE (and the new child always carries
101
+ // x-ccv-instance), so initForWorkspace must NOT run resetForLiveRelaunch's
102
+ // project-level clear — that would drain the surviving sibling's in-flight
103
+ // `_pendingNoSidByInstance`/`_lateHandles`. preserveLiveTwin skips the writer reset.
104
+ // Gate on the EXACT cwd (not the sanitized basename): a same-named DIFFERENT directory
105
+ // is a different project and must still reset.
106
+ const prevCwd = process.env.CCV_PROJECT_DIR || '';
107
+ const isSameCwdSdkForceNew = !!(deps.isSdkMode && forceNew) && prevCwd === wsPath;
108
+ const result = initForWorkspace(wsPath, { forceNew, preserveLiveTwin: isSameCwdSdkForceNew });
68
109
  process.env.CCV_PROJECT_DIR = wsPath;
69
110
 
70
111
  // 启动日志监听(S6b: v2 live feed when the v2 writer is active)
@@ -77,21 +118,40 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
77
118
  // P2 检测通道②:workspace 启动器注入的 -c/--continue/-r/--resume(无论
78
119
  // 是否走 PTY 分支都要打标——迁移提示的 continued 语义只取决于参数本身)。
79
120
  const mergedArgs = [...deps.workspaceClaudeArgs, ...(Array.isArray(launchExtraArgs) ? launchExtraArgs : [])];
80
- if (mergedArgs.some((a) => CONTINUE_FLAGS.has(a))) markContinuedLaunch();
81
- // `--fork-session`: a continuation that mints a NEW session id on purpose —
82
- // `-c` folder adoption must NOT fire for it.
83
- if (mergedArgs.includes('--fork-session')) markForkSession();
84
- // `-r`/`--resume`: user-chosen target session — adoption must not redirect
85
- // it to the latest main session.
86
- if (mergedArgs.some((a) => RESUME_FLAGS.has(a))) markResumeSession();
121
+ // forceNew: a clean conversation in a folder that already has logs — never continue.
122
+ // Strip the continuation family from the merged args too (defense in depth:
123
+ // process-wide workspaceClaudeArgs could carry one, e.g. `ccv -r <uuid>`) and
124
+ // skip the continuation markers so the migrate prompt is not told this launch
125
+ // continued.
126
+ const effectiveArgs = forceNew ? stripContinuationArgs(mergedArgs) : mergedArgs;
127
+ if (!forceNew) {
128
+ if (mergedArgs.some((a) => CONTINUE_FLAGS.has(a))) markContinuedLaunch();
129
+ // `--fork-session`: a continuation that mints a NEW session id on purpose —
130
+ // `-c` folder adoption must NOT fire for it.
131
+ if (mergedArgs.includes('--fork-session')) markForkSession();
132
+ // `-r`/`--resume`: user-chosen target session — adoption must not redirect
133
+ // it to the latest main session.
134
+ if (mergedArgs.some((a) => RESUME_FLAGS.has(a))) markResumeSession();
135
+ }
87
136
 
88
137
  // SDK mode (2026-10-12, per-cwd multi-session): launch = register/activate this cwd's
89
138
  // resident SDK session — NOT a phantom claude PTY the SDK UI never consumes. PTY mode is
90
139
  // untouched (the proxyPort branch below stays PTY-only).
140
+ // forceNew (2026-11): APPEND a same-cwd sibling session with a fresh random instanceKey
141
+ // (createSdkSession) — the existing session(s) stay LIVE (no teardown, no retire). The
142
+ // returned instanceKey lets the client pin the new sibling's empty view.
91
143
  if (deps.isSdkMode) {
92
144
  try {
93
145
  const sdk = await import('../lib/sdk-manager.js');
94
- if (!sdk.setActiveSdkSession(wsPath)) {
146
+ if (forceNew) {
147
+ // +1 SIBLING (2026-11): append a fresh same-cwd session, leaving the existing
148
+ // one(s) alive. The old sibling stays live, so it must NOT be retired —
149
+ // retirement would freeze a live session's writer routing (cold-load, the
150
+ // "current" pointer, fresh-launch clearing). retireInstance only ever runs on
151
+ // an EXPLICIT close (routes/resume.js), and only for a random fresh key.
152
+ const r = sdk.createSdkSession(wsPath, sdk.getSdkLaunchConfig() || undefined);
153
+ launchedInstanceKey = (r && r.instanceKey) || null;
154
+ } else if (!sdk.setActiveSdkSession(wsPath)) {
95
155
  // New cwd: register a session carrying the PROCESS-LEVEL launch config template
96
156
  // (registered by cli.js at boot) so its query gets the proxy env / model /
97
157
  // permission / executable — without it the child would bypass the ccv proxy
@@ -109,14 +169,25 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
109
169
  // no longer kills an existing same-cwd record, so re-launching an ALREADY-LIVE cwd
110
170
  // here would silently start a duplicate claude. ensurePtyForCwd restores the intended
111
171
  // "re-open = reuse" semantics: attach to the live record instead of re-spawning.
172
+ // forceNew skips the reuse scan on purpose (fresh session on the current root).
112
173
  const { ensurePtyForCwd } = await import('../pty-manager.js');
113
- await ensurePtyForCwd({ cwd: wsPath, proxyPort: parseInt(proxyPort), extraArgs: mergedArgs, claudePath: deps.workspaceClaudePath, isNpmVersion: deps.workspaceIsNpmVersion, serverPort: deps.actualPort, serverProtocol: deps.protocol, internalToken: deps.INTERNAL_TOKEN });
174
+ const launched = await ensurePtyForCwd({ cwd: wsPath, proxyPort: parseInt(proxyPort), extraArgs: effectiveArgs, claudePath: deps.workspaceClaudePath, isNpmVersion: deps.workspaceIsNpmVersion, serverPort: deps.actualPort, serverProtocol: deps.protocol, internalToken: deps.INTERNAL_TOKEN, forceNew });
175
+ // Only a forceNew launch may pin the client to the spawned instance —
176
+ // ordinary launches keep the legacy bound-channel replay (attaching to a
177
+ // reused record returns its key too, but pinning there would bypass the
178
+ // workspace_started reset path for no benefit).
179
+ launchedInstanceKey = forceNew ? (launched.key || null) : null;
114
180
  }
115
181
 
116
182
  deps.setWorkspaceLaunched(true);
117
183
 
118
184
  // 通知所有 SSE 客户端
119
- const startedPayload = `event: workspace_started\ndata: ${JSON.stringify({ projectName: result.projectName, path: wsPath, claudeProjectModel: readClaudeProjectModel(wsPath) })}\n\n`;
185
+ // SDK +1 (sibling launch): the workspace_started carries `sibling:true` + the new
186
+ // instanceKey so a NON-launching client does NOT hard-reset the live sibling it is
187
+ // currently viewing. Only a SAME-cwd forceNew is a sibling — a forceNew into a
188
+ // DIFFERENT directory changes the bound project and must keep the normal reset+reload.
189
+ const isSiblingLaunch = isSameCwdSdkForceNew && !!launchedInstanceKey;
190
+ const startedPayload = `event: workspace_started\ndata: ${JSON.stringify({ projectName: result.projectName, path: wsPath, claudeProjectModel: readClaudeProjectModel(wsPath), ...(isSiblingLaunch ? { sibling: true, instanceKey: launchedInstanceKey } : {}) })}\n\n`;
120
191
  deps.clients.forEach(client => {
121
192
  try {
122
193
  sseWrite(client, startedPayload);
@@ -128,19 +199,24 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
128
199
  // active (a fresh workspace has no session yet → empty stream, the live
129
200
  // feed picks up from the first request). Legacy-shaped reload frames —
130
201
  // serveInFlight follows the wire flag, same as /events.
131
- const wsReloadSource = getLiveLogSource({ serveInFlight: !!deps.wireV3 });
132
- const wsReloadTotal = await countLogEntries(wsReloadSource);
133
- deps.clients.forEach(client => {
134
- try { sseWrite(client, `event: load_start\ndata: ${JSON.stringify({ total: wsReloadTotal, incremental: false })}\n\n`); } catch {}
135
- });
136
- await streamRawEntriesAsync(wsReloadSource, (raw) => {
202
+ // SDK +1 (sibling): do NOT broadcast a reload at all — the other clients are still
203
+ // viewing the LIVE sibling's conversation, and a global empty reload would blank it.
204
+ // The launcher's own empty view is delivered by its ?instance= cold-load (freshLaunch).
205
+ const wsReloadSource = isSiblingLaunch ? '' : getLiveLogSource({ serveInFlight: !!deps.wireV3 });
206
+ const wsReloadTotal = isSiblingLaunch ? 0 : await countLogEntries(wsReloadSource);
207
+ if (!isSiblingLaunch) {
137
208
  deps.clients.forEach(client => {
138
- try { sseWrite(client, 'event: load_chunk\ndata: ['); sseWrite(client, raw.replace(/\n/g, '')); sseWrite(client, ']\n\n'); } catch {}
209
+ try { sseWrite(client, `event: load_start\ndata: ${JSON.stringify({ total: wsReloadTotal, incremental: false })}\n\n`); } catch {}
139
210
  });
140
- });
141
- deps.clients.forEach(client => {
142
- try { sseWrite(client, `event: load_end\ndata: {}\n\n`); } catch {}
143
- });
211
+ await streamRawEntriesAsync(wsReloadSource, (raw) => {
212
+ deps.clients.forEach(client => {
213
+ try { sseWrite(client, 'event: load_chunk\ndata: ['); sseWrite(client, raw.replace(/\n/g, '')); sseWrite(client, ']\n\n'); } catch {}
214
+ });
215
+ });
216
+ deps.clients.forEach(client => {
217
+ try { sseWrite(client, `event: load_end\ndata: {}\n\n`); } catch {}
218
+ });
219
+ }
144
220
 
145
221
  // 1.7.0 迁移引导(P2):切进的项目仍有未转换 v1 日志 → 对存量连接广播
146
222
  // migrate_prompt(新连接由 /events 的连接帧覆盖)。
@@ -153,7 +229,7 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
153
229
  } catch (e) { reportSwallowed('sse.migrate_prompt', e); }
154
230
 
155
231
  res.writeHead(200, { 'Content-Type': 'application/json' });
156
- res.end(JSON.stringify({ ok: true, projectName: result.projectName }));
232
+ res.end(JSON.stringify({ ok: true, projectName: result.projectName, ...(launchedInstanceKey ? { instanceKey: launchedInstanceKey } : {}) }));
157
233
  } catch (err) {
158
234
  res.writeHead(500, { 'Content-Type': 'application/json' });
159
235
  res.end(JSON.stringify({ error: err.message }));
@@ -162,6 +238,13 @@ function workspacesLaunch(req, res, parsedUrl, isLocal, deps) {
162
238
  }
163
239
 
164
240
  function workspacesAdd(req, res, parsedUrl, isLocal, deps) {
241
+ // Same gate as workspacesLaunch (it registers arbitrary host directories into the
242
+ // picker history): admin + same-origin browser, or a cross-site page could add them.
243
+ if (!isAdminReq(req, isLocal) || !isSameOriginBrowserRequest(req, parsedUrl)) {
244
+ res.writeHead(403, { 'Content-Type': 'application/json' });
245
+ res.end(JSON.stringify({ error: 'forbidden' }));
246
+ return;
247
+ }
165
248
  let body = '';
166
249
  req.on('data', chunk => { body += chunk; if (body.length > deps.MAX_POST_BODY) req.destroy(); });
167
250
  req.on('end', async () => {