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.
@@ -9,11 +9,12 @@
9
9
  * - canUseTool callback for AskUserQuestion + permission approval
10
10
  * - Turn-end signaling (SDK 'result' message → Stop-hook equivalent)
11
11
  *
12
- * Registry (2026-10-12, PTY parity): one Session per cwd, kept alive across
13
- * workspace switches. `_activeKey` selects the session the composer/WS handlers
14
- * act on (the SDK analogue of pty-manager's activePtyKey). Each Session is a
15
- * factory closure — NO classes (avoids this-binding traps; the module's entire
16
- * history is arrow functions). GLOBAL, deliberately kept module-level: `_query`
12
+ * Registry (2026-11, multi-instance): keyed by instanceKey, so ONE cwd may host several
13
+ * concurrent Sessions (file-explorer "New Workspace (Session)" on the current root is a
14
+ * +1 sibling, not a replace). `_activeKey` holds the active session's instanceKey (the
15
+ * SDK analogue of pty-manager's activePtyKey). Sessions are kept alive across workspace
16
+ * switches. Each Session is a factory closure — NO classes (avoids this-binding traps).
17
+ * State is GLOBAL, deliberately kept module-level: `_query`
17
18
  * (test injection must be settable before any init — 161+ test cases depend on
18
19
  * set-then-init), `_onTurnEnd`/`_onQueryError`/`_broadcastWs`/`_runWaterfallHook`
19
20
  * (cli.js registers ONE wiring for the whole process; every session reuses it),
@@ -73,12 +74,15 @@ export function __ephemeralHostCountForTests() { return _ephemeralHosts.size; }
73
74
  export function __ephemeralAbortCountForTests() { return _ephemeralAborts.size; }
74
75
 
75
76
  // ── Session registry ─────────────────────────────────────────────────────────
76
- // Keyed by path.resolve(cwd) — normalize only, NO realpath (house exact-string
77
- // convention, routes/resume.js, so `/tmp` vs `/private/tmp` stay distinct). The
78
- // per-session state machine lives in each _createSession closure; `_activeKey`
79
- // selects which session the SDK composer and WS handlers act on.
80
- const _sessions = new Map();
81
- let _activeKey = null;
77
+ // Multi-instance (2026-11): keyed by instanceKey (NOT cwd) so one cwd may host
78
+ // several concurrent Sessions (file-explorer "New Workspace (Session)" on the
79
+ // current root is +1, not a replace). Each Session records its own `cwd`; cwd
80
+ // lookups scan _sessions.values() (n is tiny — a second index would just be a
81
+ // second source of truth). `_activeKey` holds the active session's instanceKey —
82
+ // the SDK analogue of pty-manager's activePtyKey. cwd is normalized only, NO
83
+ // realpath (house exact-string convention, routes/resume.js).
84
+ const _sessions = new Map(); // Map<instanceKey, Session>
85
+ let _activeKey = null; // instanceKey of the active session
82
86
  // Ephemeral-turn hosts (scheduled-task spawn): sessions whose approval plumbing is
83
87
  // currently borrowed by a standalone run. resolveApproval/cancelApproval/
84
88
  // getPendingApprovals scan the UNION of _sessions and this set, so an ephemeral run's
@@ -93,12 +97,41 @@ function _normalizeCwd(cwd) {
93
97
  try { return _pathResolve(cwd); } catch { return String(cwd); }
94
98
  }
95
99
 
96
- // Get-or-create the per-cwd Session. The record holds the launch config so a
97
- // kept-alive background session can reconstruct with ITS OWN config.
100
+ // The PRIMARY session for a cwd: the active one when it lives in that cwd, else the
101
+ // deterministic boot session (its key is re-created on relaunch — the stable identity a
102
+ // plain launch/bound view should land on), else the most-recently-registered. A plain
103
+ // launch (non-forceNew) reuses this session rather than spawning a sibling.
104
+ // The deterministic-boot-first / newest-fallback scan shared by _primaryForCwd and
105
+ // resolveBoundPrimaryInstanceKey — the two MUST agree on the "which session is the cwd's
106
+ // stable primary" tie-break, so the loop body lives here once (a future weighting change
107
+ // then can't drift them apart). `_primaryForCwd` prepends an active-first head on top.
108
+ function _deterministicOrLatestForCwd(n) {
109
+ let det = null; let latest = null;
110
+ for (const s of _sessions.values()) {
111
+ if (_normalizeCwd(s.cwd) !== n) continue;
112
+ latest = s; // Map insertion order → last match is the newest
113
+ if (!s.isFreshKey) det = s;
114
+ }
115
+ return det || latest;
116
+ }
117
+
118
+ function _primaryForCwd(cwd) {
119
+ const n = _normalizeCwd(cwd);
120
+ if (!n) return null;
121
+ const active = _active();
122
+ if (active && _normalizeCwd(active.cwd) === n) return active;
123
+ return _deterministicOrLatestForCwd(n);
124
+ }
125
+
126
+ // Get-or-create the cwd's PRIMARY Session (deterministic key). Only creates when the
127
+ // cwd has no session at all — never spawns a sibling. Used by initSdkSession (plain
128
+ // launch). The record holds the launch config so a kept-alive background session can
129
+ // reconstruct with ITS OWN config.
98
130
  function _getOrCreateSession(cwd) {
99
- const key = _normalizeCwd(cwd);
100
- let s = _sessions.get(key);
101
- if (!s) { s = _createSession(key, cwd); _sessions.set(key, s); }
131
+ const existing = _primaryForCwd(cwd);
132
+ if (existing) return existing;
133
+ const s = _createSession(cwd); // deterministic boot key
134
+ _sessions.set(s.instanceKey, s);
102
135
  return s;
103
136
  }
104
137
 
@@ -114,26 +147,24 @@ function _matchesProject(sess, project) {
114
147
  // A project stamp matches a session when it names the session's exact normalized cwd
115
148
  // (absolute-path form) or its sanitized/raw basename (the web client's usual form).
116
149
  function _sessionMatchesProject(sess, project) {
117
- return sess.key === _normalizeCwd(project) || _matchesProject(sess, project);
150
+ return _normalizeCwd(sess.cwd) === _normalizeCwd(project) || _matchesProject(sess, project);
118
151
  }
119
152
 
120
- // Resolve an anchor { instanceKey|cwd|project } to a Session WITHOUT switching active (read ops).
121
- // `cwd` is an absolute path (exact key match); `project` is the SANITIZED project name the
122
- // web client sends (ChatView stamps `viewProject || projectName`, where projectName =
123
- // projectKeyForCwd(cwd) — non [a-zA-Z0-9_-] chars become `_`, so a dir with spaces/CJK sends
124
- // the sanitized name, NOT the raw basename). Match each session by projectKeyForCwd(s.cwd)
125
- // (with a raw-basename fallback for exact-dir callers). Same-name collision → null (never
126
- // guess). Returns null when the anchor resolves to no registered session.
127
- function _sessionForAnchor(anchor) {
153
+ // Resolve an anchor { instanceKey|cwd|project } to a Session WITHOUT switching active.
154
+ // `cwd` is an absolute path; `project` is the SANITIZED project name the web client sends
155
+ // (ChatView stamps `viewProject || projectName`). Multi-instance: instanceKey is the only
156
+ // unambiguous anchor.
157
+ // Ambiguity policy (2026-11): for an ACTION (a user message/Stop — better routed to the
158
+ // workspace's default session than dropped), a cwd/project matching 2+ same-cwd siblings
159
+ // resolves to that cwd's PRIMARY (`allowPrimaryFallback: true`); for a DESTRUCTIVE op
160
+ // (close/attach — never guess), it resolves to null. Returns null when nothing resolves.
161
+ function _sessionForAnchor(anchor, { allowPrimaryFallback = false } = {}) {
128
162
  if (!anchor || typeof anchor !== 'object') return null;
129
163
  const instanceKey = (typeof anchor.instanceKey === 'string' && anchor.instanceKey) || null;
130
164
  const cwd = (typeof anchor.cwd === 'string' && anchor.cwd) || null;
131
165
  const project = (typeof anchor.project === 'string' && anchor.project) || null;
132
166
  if (instanceKey) {
133
- let byInstance = null;
134
- for (const s of _sessions.values()) {
135
- if (s.instanceKey === instanceKey) { byInstance = s; break; }
136
- }
167
+ const byInstance = _sessions.get(instanceKey) || null;
137
168
  // An exact instance that no longer exists must never fall back to a
138
169
  // same-basename sibling — that would execute the user's action in the
139
170
  // wrong workspace. The caller's unknown-anchor path drops + reports it.
@@ -145,33 +176,60 @@ function _sessionForAnchor(anchor) {
145
176
  if (project && !_sessionMatchesProject(byInstance, project)) return null;
146
177
  return byInstance;
147
178
  }
148
- if (cwd) return _sessions.get(_normalizeCwd(cwd)) || null;
149
- if (!project) return null;
150
- // exact-path form of a project (an absolute path was passed as `project`) — try key first.
151
- const byKey = _sessions.get(_normalizeCwd(project));
152
- if (byKey) return byKey;
153
- let found = null;
154
- for (const s of _sessions.values()) {
155
- if (_matchesProject(s, project)) { if (found) return null; found = s; } // ambiguous → null
179
+ // Multi-match helper for an ACTION anchor (allowPrimaryFallback): exact sole match → it;
180
+ // several matches IN THE SAME cwd → that cwd's primary (a same-cwd sibling set). Matches
181
+ // spanning DIFFERENT cwds (two same-named dirs) are genuinely ambiguous — the anchor named
182
+ // no directory, so never guess across workspaces → null. Destructive anchors never guess.
183
+ const pick = (matches) => {
184
+ if (matches.length === 1) return matches[0];
185
+ if (matches.length > 1) {
186
+ if (!allowPrimaryFallback) return null;
187
+ const cwds = new Set(matches.map((s) => _normalizeCwd(s.cwd)));
188
+ if (cwds.size !== 1) return null; // same project name across different directories — ambiguous
189
+ const p = _primaryForCwd(matches[0].cwd);
190
+ return (p && matches.includes(p)) ? p : matches[0];
191
+ }
192
+ return null;
193
+ };
194
+ if (cwd) {
195
+ const n = _normalizeCwd(cwd);
196
+ return pick([..._sessions.values()].filter((s) => _normalizeCwd(s.cwd) === n));
156
197
  }
157
- return found;
198
+ if (!project) return null;
199
+ const matches = [..._sessions.values()].filter((s) => _sessionMatchesProject(s, project));
200
+ return pick(matches);
158
201
  }
159
202
 
160
203
  // Test seams (house `__…ForTests` convention) — assert registry behavior without a real SDK query.
161
- export function __listSessionsForTests() { return [..._sessions.keys()]; }
162
- export function __getSessionKeyForTests(cwd) { return _normalizeCwd(cwd); }
163
-
164
- /** Enumerate the per-cwd SDK session registry for live workspace routing. Each entry:
165
- * { key, cwd, active, instanceKey }. Read-only. NOTE: `key` is the registry's
166
- * normalized-cwd key; attach/close responses instead alias `key` to the instanceKey
167
- * for killPtyFor-shape parity (resume.js consumes `r.key === reattachedTo`). Callers
168
- * must not mix the two namespaces. */
204
+ export function __listSessionsForTests() { return [..._sessions.keys()]; } // instanceKeys
205
+
206
+ /** Enumerate the SDK session registry for live workspace routing. Each entry:
207
+ * { key, cwd, active, instanceKey, freshLaunch, isFreshKey }. Read-only. `key` IS the
208
+ * instanceKey (multi-instance registry; matches the attach/close responses' key alias,
209
+ * which resume.js consumes as `r.key === reattachedTo`). */
169
210
  export function listSdkSessions() {
170
- return [..._sessions.values()].map((s) => ({ key: s.key, cwd: s.cwd, active: s.key === _activeKey, instanceKey: s.instanceKey }));
211
+ return [..._sessions.values()].map((s) => ({ key: s.instanceKey, cwd: s.cwd, active: s.instanceKey === _activeKey, instanceKey: s.instanceKey, freshLaunch: s.freshLaunch === true, isFreshKey: s.isFreshKey === true, sessionId: s.getSessionId() }));
171
212
  }
172
213
 
173
214
  registerSdkSessionLister(listSdkSessions);
174
215
 
216
+ /**
217
+ * The BOUND cwd's primary session instanceKey (2026-11, WS attach-stamp coherence).
218
+ * The single source of truth for the bound identity: resume.js's `/api/live-processes`
219
+ * `currentInstanceKey` delegates here, and server.js's WS `_ccvViewInstance` coherence
220
+ * (`_cohereAttachInstance`) resolves through it, so the header's `boundInstance` and the WS
221
+ * stamp always agree on the same instance for the same cwd. Returns the deterministic boot
222
+ * session (non-fresh key) — NOT the ACTIVE sibling (`_primaryForCwd` is active-first for
223
+ * input-side routing; the bound identity must stay stable while a fresh sibling is active).
224
+ * Falls back to the newest same-cwd row; null when the cwd has no live session. Read-only.
225
+ */
226
+ export function resolveBoundPrimaryInstanceKey(boundCwd) {
227
+ const n = _normalizeCwd(boundCwd);
228
+ if (!n) return null;
229
+ const primary = _deterministicOrLatestForCwd(n);
230
+ return primary ? primary.instanceKey : null;
231
+ }
232
+
175
233
  // The turn can legally wait on approval ceilings: perm/plan = 5min, AskUserQuestion =
176
234
  // 24h ("GUI effectively has no timeout" is a product contract). A pending approval
177
235
  // exempts the turn from probing entirely (the child is parked awaiting our response).
@@ -436,8 +494,22 @@ function _foldSdkTask(prev, frame) {
436
494
  // that are process-global by contract (see file header). Arrays stay closure
437
495
  // `let` (rebinding, not a frozen property) so assignment paths like
438
496
  // `_messageQueue = []` keep working.
439
- function _createSession(key, cwd) {
440
- const instanceKey = `ccv-${createHash('sha256').update(key).digest('hex').slice(0, 32)}`;
497
+ function _createSession(cwd, { freshKey = false } = {}) {
498
+ // instanceKey identity: deterministic `ccv-sha256(normalizedCwd)` for the cwd's primary
499
+ // (boot) session so a close/restart re-registers the same identity (pre-existing dirs
500
+ // stay resolvable); a forceNew "New Workspace (Session)" generation and an isolated
501
+ // ephemeral host get a FRESH random key (freshKey) so their dirs/frames are
502
+ // distinguishable from the resident sibling's — the same identity separation PTY gets
503
+ // from _mintInstanceKey.
504
+ const instanceKey = freshKey
505
+ ? `ccv-${randomBytes(16).toString('hex')}`
506
+ : `ccv-${createHash('sha256').update(_normalizeCwd(cwd)).digest('hex').slice(0, 32)}`;
507
+ // Whether this generation's instanceKey is a random per-generation key (forceNew) rather
508
+ // than the deterministic cwd-derived one. The deterministic key is RE-CREATED whenever the
509
+ // registry slot is rebuilt (close + normal relaunch), so it must NEVER be writer-retired —
510
+ // retiring it would permanently gate the legitimate recreated session. Only random fresh
511
+ // keys (never reused) are safe to retire.
512
+ const _isFreshKey = freshKey === true;
441
513
  // Launch config (per-session identity; adopted on lazy reconstruction)
442
514
  let _cwd = cwd;
443
515
  let _permissionMode = 'default';
@@ -496,6 +568,13 @@ function _createSession(key, cwd) {
496
568
  let _suspectGeneration = false;
497
569
  let _lastFailedTurn = null; // { turnId, retryable, apiStatus, attempt, maxRetries, code, ts } — drives the manual [retry] affordance
498
570
  let _sessionId = null;
571
+ // forceNew (2026-11): true while this is a freshly forceNew'd generation that has not yet
572
+ // written its own main-turn session. events.js reads it (via the listSdkSessions projection)
573
+ // to suppress the same-cwd cold-load fallback so the new conversation starts EMPTY. Cleared
574
+ // when the writer binds this generation's first session (see setOnSessionResolved wiring in
575
+ // server.js → clearSdkFreshLaunch) and on switchToSession. NOT cleared by _resetFullState —
576
+ // a re-init/self-heal of a still-fresh generation must keep suppressing the OLD twin's history.
577
+ let _freshLaunch = false;
499
578
  let _initAnnouncedSid = ''; // sessionId whose slash-command surface was already announced (reset on full reset)
500
579
  let _lastInitSnapshot = null; // last sdk-init payload for WS reconnect replay
501
580
  // Last sdk-skills frame (supportedCommands() result) for WS reconnect replay, and the
@@ -966,8 +1045,22 @@ function _createSession(key, cwd) {
966
1045
  // spinner/queue bubbles) and cold-load instance filters never match SDK sessions.
967
1046
  const instanceHeader = `x-ccv-instance: ${instanceKey}`;
968
1047
  const injected = `${projectHeader}\n${instanceHeader}`;
969
- options.env.ANTHROPIC_CUSTOM_HEADERS = options.env.ANTHROPIC_CUSTOM_HEADERS
970
- ? `${options.env.ANTHROPIC_CUSTOM_HEADERS}\n${injected}` : injected;
1048
+ // Strip-then-append (forceNew / re-init hygiene): options.env is the SHARED launch
1049
+ // env object (cli.js hands the same childEnv to the boot session and every new cwd),
1050
+ // so without stripping, a re-mint / re-construction would stack a SECOND
1051
+ // x-ccv-project-dir/x-ccv-instance pair. The interceptor validates instance against
1052
+ // /^ccv-[0-9a-f]+$/ and DROPS a combined value (interceptor.js) — the fresh
1053
+ // generation's requests would fall back to project/_currentSid routing and write into
1054
+ // the OLD generation's dir. Strip stale ccv routing lines (case-insensitive,
1055
+ // CRLF-tolerant), keep every unrelated header, then append exactly one fresh pair.
1056
+ const prior = typeof options.env.ANTHROPIC_CUSTOM_HEADERS === 'string'
1057
+ ? options.env.ANTHROPIC_CUSTOM_HEADERS
1058
+ .split('\n')
1059
+ .filter((l) => !/^x-ccv-(project-dir|instance)\s*:/i.test(l.trim()))
1060
+ .join('\n')
1061
+ .trim()
1062
+ : '';
1063
+ options.env.ANTHROPIC_CUSTOM_HEADERS = prior ? `${prior}\n${injected}` : injected;
971
1064
  }
972
1065
  }
973
1066
  if (_settings) options.settings = _settings;
@@ -2745,6 +2838,9 @@ function _createSession(key, cwd) {
2745
2838
  }
2746
2839
  _sessionId = sessionId;
2747
2840
  _launchResume = null;
2841
+ // Switching INTO a concrete existing conversation lifts the forceNew empty-view
2842
+ // suppression — this generation now owns real content (the resumed one).
2843
+ _freshLaunch = false;
2748
2844
  _initAnnouncedSid = '';
2749
2845
  _lastInitSnapshot = null; // don't replay the OLD session's sdk-init to the new one
2750
2846
  _lastSkillsSnapshot = null; // same for the skill surface
@@ -2817,9 +2913,15 @@ function _createSession(key, cwd) {
2817
2913
  // `teardown` = _teardownResident + _resetFullState (the old module-level stopSession
2818
2914
  // body, now per-session). `init` = config adoption + that teardown/reset pair.
2819
2915
  return {
2820
- key,
2821
2916
  instanceKey,
2822
2917
  get cwd() { return _cwd; },
2918
+ // forceNew (2026-11): whether this generation is a fresh "New Workspace (Session)"
2919
+ // instance that has not yet written its own main-turn session. Read live (getter) —
2920
+ // events.js / resume.js see it through the listSdkSessions projection.
2921
+ get freshLaunch() { return _freshLaunch === true; },
2922
+ // True when this generation's instanceKey is a random per-generation key (safe to retire);
2923
+ // false for the deterministic cwd-derived key (re-created on relaunch — never retire it).
2924
+ get isFreshKey() { return _isFreshKey; },
2823
2925
  get config() {
2824
2926
  return {
2825
2927
  permissionMode: _permissionMode,
@@ -2887,6 +2989,12 @@ function _createSession(key, cwd) {
2887
2989
  },
2888
2990
  switchToSession: _switchToSession,
2889
2991
  getSessionId: () => _sessionId,
2992
+ // forceNew (2026-11): the writer's main-turn `_onSessionResolved` calls this once the
2993
+ // new generation owns its first session dir — the empty-view suppression lifts (PTY
2994
+ // parity with setPtySessionIdForInstance clearing the PTY record's freshLaunch).
2995
+ clearFreshLaunch: () => { _freshLaunch = false; },
2996
+ // createSdkSession marks the freshly-ADDED sibling generation (NOT a method for general use).
2997
+ _markFreshLaunch: () => { _freshLaunch = true; },
2890
2998
  retryInterruptedTurn: _retryInterruptedTurn,
2891
2999
  runEphemeralTurn: _runEphemeralTurn,
2892
3000
  close: () => {
@@ -2949,12 +3057,18 @@ export async function spawnEphemeralSession(prompt, { cwd, project, timeoutMs =
2949
3057
  if (!cwd) return { ok: false, reason: 'not_initialized' };
2950
3058
 
2951
3059
  const key = _normalizeCwd(cwd);
2952
- let host = _sessions.get(key) || null;
3060
+ // Borrow the cwd's resident session to carry approvals (its canUseTool plumbing).
3061
+ // Active-first so a same-cwd sibling set resolves to the foreground workspace. No
3062
+ // resident session → an isolated, unregistered host is created below.
3063
+ let host = _primaryForCwd(cwd);
2953
3064
  let created = false;
2954
3065
  if (!host) {
2955
3066
  // No resident session for this cwd in this boot: create an isolated host purely to
2956
- // carry approvals (its canUseTool plumbing). It is NOT registered in _sessions.
2957
- host = _createSession(`__ephemeral_host__:${key}`, cwd);
3067
+ // carry approvals (its canUseTool plumbing). It is NOT registered in _sessions. A fresh
3068
+ // random key keeps its approval frames distinct from any FUTURE resident boot session
3069
+ // for this cwd (a deterministic key would alias them).
3070
+ host = _createSession(cwd, { freshKey: true });
3071
+ host.__ephemeralCwd = key; // test seam marker (isolated host for an unregistered cwd)
2958
3072
  try { host.init({ ...cfg }); }
2959
3073
  catch (err) { reportSwallowed('sdk-manager.ephemeral-init', err); return { ok: false, reason: 'not_initialized', error: String(err?.message || err) }; }
2960
3074
  created = true;
@@ -2974,7 +3088,7 @@ export async function spawnEphemeralSession(prompt, { cwd, project, timeoutMs =
2974
3088
  export function __isEphemeralHostForTests(cwd) {
2975
3089
  const key = _normalizeCwd(cwd);
2976
3090
  for (const host of _ephemeralHosts) {
2977
- if (host.key === key || host.key === `__ephemeral_host__:${key}`) return true;
3091
+ if (host.__ephemeralCwd === key || _normalizeCwd(host.cwd) === key) return true;
2978
3092
  }
2979
3093
  return false;
2980
3094
  }
@@ -3022,12 +3136,69 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
3022
3136
  // registration). A workspace stop→relaunch omits these callbacks, so without this every
3023
3137
  // sdk-* frame would silently stop broadcasting after returning to the workspace list.
3024
3138
  _adoptProcessWiring();
3025
- // Register this workspace's session (per-cwd, re-using the record on re-init) and make
3026
- // it active. init() adopts the launch config and tears down ONLY this session's prior
3027
- // generation (tests / hot reload) — other workspaces' sessions are untouched.
3139
+ // Register this cwd's PRIMARY session (re-using the record on re-init — a plain launch
3140
+ // never spawns a same-cwd sibling) and make it active. init() adopts the launch config
3141
+ // and tears down ONLY this session's prior generation (tests / hot reload) — other
3142
+ // workspaces' sessions (and same-cwd siblings) are untouched.
3028
3143
  const sess = _getOrCreateSession(cwd);
3029
3144
  sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable });
3030
- _activeKey = sess.key;
3145
+ _activeKey = sess.instanceKey;
3146
+ }
3147
+
3148
+ /**
3149
+ * "New Workspace (Session)" on the CURRENT root for SDK mode (2026-11) — a same-cwd
3150
+ * SIBLING, not a replacement. The resident registry is keyed by instanceKey so one cwd
3151
+ * may host several concurrent Sessions. This APPENDS a fresh Session carrying a random
3152
+ * instanceKey (PTY-style generation identity) and leaves every existing same-cwd session
3153
+ * alive (its resident query, conversation, and writer routing untouched). The new
3154
+ * generation's dirs/frames are distinguishable via the new meta.instance key; the old
3155
+ * sibling's dirs keep the OLD key, so instance-scoped readers (cold-load picker, live
3156
+ * feed, SSE attach) keep each view on its own conversation.
3157
+ *
3158
+ * Unlike PTY's retired-generation model, the old sibling stays live — so the route must
3159
+ * NOT retireInstance the old key (retirement freezes a LIVE session's routing). The new
3160
+ * session is marked freshLaunch so its cold-load starts EMPTY instead of falling back to
3161
+ * the sibling's history; the mark lifts on its first main-turn bind.
3162
+ *
3163
+ * Returns { instanceKey } for the route to pin the client view to the new instance.
3164
+ */
3165
+ export function createSdkSession(cwd, cfg) {
3166
+ const key = _normalizeCwd(cwd);
3167
+ if (!key) return null;
3168
+ // Capture a same-cwd sibling's config BEFORE registering the new one (fallback for
3169
+ // direct/test callers with no process template registered).
3170
+ const sibling = _primaryForCwd(cwd);
3171
+ const sess = _createSession(cwd, { freshKey: true }); // random per-generation key
3172
+ _sessions.set(sess.instanceKey, sess);
3173
+ // Adopt the process-level launch config template so the fresh query gets the proxy env /
3174
+ // model / permission / executable; launchResume is forced null (a boot -c/-r intent must
3175
+ // never resume into a forceNew conversation).
3176
+ const base = cfg || _launchConfigTemplate || (sibling && sibling.config) || {};
3177
+ try {
3178
+ sess.init({ ...base, launchResume: null });
3179
+ } catch (err) {
3180
+ // init failed — roll back the registration so the registry never holds a half-init'd
3181
+ // session, and leave _activeKey on the previous session.
3182
+ _sessions.delete(sess.instanceKey);
3183
+ reportSwallowed('sdk-manager.create-session-init', err);
3184
+ return null;
3185
+ }
3186
+ sess._markFreshLaunch();
3187
+ _adoptProcessWiring();
3188
+ _activeKey = sess.instanceKey;
3189
+ return { instanceKey: sess.instanceKey };
3190
+ }
3191
+
3192
+ /**
3193
+ * Lift a forceNew generation's empty-view suppression. Called from server.js's
3194
+ * v2-writer `_onSessionResolved` wiring (the main-turn gate) once the instance owns its
3195
+ * first session dir — PTY parity with setPtySessionIdForInstance clearing the PTY mark.
3196
+ */
3197
+ export function clearSdkFreshLaunch(instanceKey) {
3198
+ if (typeof instanceKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instanceKey)) return;
3199
+ for (const s of _sessions.values()) {
3200
+ if (s.instanceKey === instanceKey && typeof s.clearFreshLaunch === 'function') { s.clearFreshLaunch(); return; }
3201
+ }
3031
3202
  }
3032
3203
 
3033
3204
  /**
@@ -3041,7 +3212,10 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
3041
3212
  export async function sendUserMessage(text, anchor) {
3042
3213
  if (!_query) throw new Error('Agent SDK not available');
3043
3214
  if (anchor && (anchor.cwd || anchor.project || anchor.instanceKey)) {
3044
- const target = _sessionForAnchor(anchor);
3215
+ // An action anchor: a same-cwd ambiguous cwd/project resolves to the cwd's PRIMARY
3216
+ // rather than dropping the user's message (Mobile / pre-poll desktop sends carry no
3217
+ // instanceKey).
3218
+ const target = _sessionForAnchor(anchor, { allowPrimaryFallback: true });
3045
3219
  if (!target) {
3046
3220
  // A mis-resolved anchor must not silently drop the user's message — log + report,
3047
3221
  // and surface a toast through the same channel query errors use (the composer was
@@ -3059,8 +3233,8 @@ export async function sendUserMessage(text, anchor) {
3059
3233
  }
3060
3234
  return;
3061
3235
  }
3062
- if (target.key !== _activeKey) {
3063
- _activeKey = target.key; // an action re-routes the active session (lazy: no teardown)
3236
+ if (target.instanceKey !== _activeKey) {
3237
+ _activeKey = target.instanceKey; // an action re-routes the active session (lazy: no teardown)
3064
3238
  }
3065
3239
  return target.sendUserMessage(text);
3066
3240
  }
@@ -3131,9 +3305,11 @@ export function getPendingApprovals(anchor) {
3131
3305
  * cancelled-approval list (see the Session factory's interruptTurn). */
3132
3306
  export function interruptTurn(anchor) {
3133
3307
  if (anchor) {
3134
- const target = _sessionForAnchor(anchor);
3308
+ // An action anchor: an ambiguous cwd/project resolves to the cwd's primary so a
3309
+ // Stop without an instanceKey (Mobile) still halts the workspace's default session.
3310
+ const target = _sessionForAnchor(anchor, { allowPrimaryFallback: true });
3135
3311
  if (target) {
3136
- if (target.key !== _activeKey) _activeKey = target.key;
3312
+ if (target.instanceKey !== _activeKey) _activeKey = target.instanceKey;
3137
3313
  return target.interruptTurn();
3138
3314
  }
3139
3315
  // Unknown anchor: nothing to interrupt — same empty array the idle path returns.
@@ -3146,8 +3322,8 @@ export function interruptTurn(anchor) {
3146
3322
  /** Send-now on a queued bubble of the ACTIVE session (or an anchor's session —
3147
3323
  * an action, switches active). Returns the cancelled-approval list. */
3148
3324
  export function sendQueuedNow(id, anchor) {
3149
- const sess = anchor ? _sessionForAnchor(anchor) : _active();
3150
- if (anchor && sess && sess.key !== _activeKey) _activeKey = sess.key;
3325
+ const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
3326
+ if (anchor && sess && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
3151
3327
  return sess ? sess.sendQueuedNow(id) : [];
3152
3328
  }
3153
3329
 
@@ -3212,9 +3388,9 @@ export function stopSession() {
3212
3388
  * captured sessionId). Unknown cwd → false (no switch); already-active → true (no-op).
3213
3389
  */
3214
3390
  export function setActiveSdkSession(cwd) {
3215
- const key = _normalizeCwd(cwd);
3216
- if (!key || !_sessions.has(key)) return false;
3217
- _activeKey = key; // lazy switch: the target's state machine is intact by construction
3391
+ const sess = _primaryForCwd(cwd);
3392
+ if (!sess) return false;
3393
+ _activeKey = sess.instanceKey; // lazy switch: the target's state machine is intact by construction
3218
3394
  return true;
3219
3395
  }
3220
3396
 
@@ -3232,9 +3408,8 @@ export function attachSdkSession(anchor) {
3232
3408
  }
3233
3409
  const sess = _sessionForAnchor(anchor);
3234
3410
  if (!sess) return { ok: false, reason: 'not-found' };
3235
- const switched = sess.key !== _activeKey;
3236
- _activeKey = sess.key;
3237
- // `key` aliases instanceKey for killPtyFor-shape parity (NOT the registry cwd key).
3411
+ const switched = sess.instanceKey !== _activeKey;
3412
+ _activeKey = sess.instanceKey;
3238
3413
  return { ok: true, key: sess.instanceKey, instanceKey: sess.instanceKey, cwd: sess.cwd, switched };
3239
3414
  }
3240
3415
 
@@ -3249,7 +3424,14 @@ export function closeSdkSession(anchor = {}) {
3249
3424
  sess = _sessionForAnchor({ instanceKey });
3250
3425
  if (!sess) return { ok: false, reason: 'not-found' };
3251
3426
  } else if (anchor.cwd) {
3252
- sess = _sessionForAnchor({ cwd: anchor.cwd });
3427
+ // cwd anchor: refuse same-cwd ambiguity (a same-cwd sibling must be addressed by
3428
+ // instanceKey — closing the wrong twin would kill a live conversation).
3429
+ const n = _normalizeCwd(anchor.cwd);
3430
+ const matches = [..._sessions.values()].filter((s) => _normalizeCwd(s.cwd) === n);
3431
+ if (matches.length > 1) {
3432
+ return { ok: false, reason: 'ambiguous', candidates: matches.map((s) => ({ key: s.instanceKey, instanceKey: s.instanceKey, cwd: s.cwd })) };
3433
+ }
3434
+ sess = matches[0] || null;
3253
3435
  } else if (anchor.project) {
3254
3436
  const matches = [..._sessions.values()].filter((s) => _matchesProject(s, anchor.project));
3255
3437
  if (matches.length > 1) {
@@ -3263,25 +3445,33 @@ export function closeSdkSession(anchor = {}) {
3263
3445
  }
3264
3446
  if (!sess) return { ok: false, reason: 'not-found' };
3265
3447
 
3266
- const killedActive = sess.key === _activeKey;
3448
+ const killedActive = sess.instanceKey === _activeKey;
3267
3449
  const result = {
3268
3450
  ok: true,
3269
- // `key` aliases instanceKey here (killPtyFor-shape parity: resume.js matches
3270
- // `p.key === killResult.reattachedTo`). It is NOT the registry's cwd key —
3271
- // the registry key is `sess.key`, a different namespace. Do not conflate.
3451
+ // `key` aliases instanceKey (killPtyFor-shape parity: resume.js matches
3452
+ // `p.key === killResult.reattachedTo`).
3272
3453
  key: sess.instanceKey,
3273
3454
  instanceKey: sess.instanceKey,
3274
3455
  cwd: sess.cwd,
3456
+ // Tells the route how to retire the closed instance's writer routing: a random
3457
+ // per-generation key is safe to retire; the deterministic cwd key is RE-created on a
3458
+ // normal relaunch, so it must be RELEASED (cleared), never retired (permanently frozen).
3459
+ wasFreshKey: sess.isFreshKey === true,
3275
3460
  killedActive,
3276
3461
  reattachedTo: null,
3277
3462
  };
3278
3463
  // Remove the registry identity BEFORE user-callback-facing teardown frames. A
3279
3464
  // close/relaunch triggered by one of those frames must register a fresh session,
3280
3465
  // never be deleted by the tail of the older close operation.
3281
- _sessions.delete(sess.key);
3466
+ _sessions.delete(sess.instanceKey);
3282
3467
  if (killedActive) {
3283
- const survivor = _sessions.values().next().value || null;
3284
- _activeKey = survivor ? survivor.key : null;
3468
+ // Prefer a SAME-CWD sibling (the twin the user most likely wants next), else fall
3469
+ // back to the next registered session (Map insertion order).
3470
+ const n = _normalizeCwd(sess.cwd);
3471
+ let survivor = null;
3472
+ for (const s of _sessions.values()) { if (_normalizeCwd(s.cwd) === n) { survivor = s; break; } }
3473
+ if (!survivor) survivor = _sessions.values().next().value || null;
3474
+ _activeKey = survivor ? survivor.instanceKey : null;
3285
3475
  result.reattachedTo = survivor ? survivor.instanceKey : null;
3286
3476
  }
3287
3477
  try {
@@ -3306,9 +3496,9 @@ export function getActiveSdkCwd() {
3306
3496
  */
3307
3497
  export function switchToSession(sessionId, anchor) {
3308
3498
  if (!_query) return { ok: false, reason: 'unavailable' }; // route maps this to 409 — must fire BEFORE any session lookup
3309
- const sess = anchor ? _sessionForAnchor(anchor) : _active();
3499
+ const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
3310
3500
  if (!sess) return { ok: false, reason: 'bad-id' };
3311
- if (anchor && sess.key !== _activeKey) _activeKey = sess.key;
3501
+ if (anchor && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
3312
3502
  return sess.switchToSession(sessionId);
3313
3503
  }
3314
3504
 
@@ -3318,6 +3508,16 @@ export function getSessionId(anchor) {
3318
3508
  return sess ? sess.getSessionId() : null;
3319
3509
  }
3320
3510
 
3511
+ /** The sessionId a SPECIFIC instance currently holds (SDK-side, generation-scoped: cleared
3512
+ * on teardown/reset), or null. Unlike the writer's per-instance routing pointer, this
3513
+ * cannot survive a stopSession/rebuild — so it is the safe "is this instance actively on
3514
+ * this conversation NOW" check for the resume twin-ownership guard. */
3515
+ export function getSessionIdForInstance(instanceKey) {
3516
+ if (typeof instanceKey !== 'string' || !instanceKey) return null;
3517
+ const s = _sessions.get(instanceKey);
3518
+ return s ? s.getSessionId() : null;
3519
+ }
3520
+
3321
3521
  /**
3322
3522
  * Manual [retry] of the last failed turn on the active (or anchored) session. Pushes a
3323
3523
  * synthetic continue instruction instead of resending the user's original message.
@@ -3330,7 +3530,7 @@ export async function retryInterruptedTurn(turnId, anchor) {
3330
3530
  const r = await sess.retryInterruptedTurn(turnId);
3331
3531
  // Only a SUCCESSFUL retry re-routes the process-wide active session — a rejected retry
3332
3532
  // (busy/stale/no-session) must not steal the active anchor from the foreground view.
3333
- if (r && r.ok && anchor && sess.key !== _activeKey) _activeKey = sess.key;
3533
+ if (r && r.ok && anchor && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
3334
3534
  return r;
3335
3535
  }
3336
3536
 
@@ -74,7 +74,13 @@ try {
74
74
  debug(`payload source=${source} session_id=${sessionId} transcript=${transcriptPath}`);
75
75
 
76
76
  const internalToken = process.env.CCVIEWER_INTERNAL_TOKEN || '';
77
- const body = JSON.stringify({ source, sessionId, transcriptPath, cwd, agentId, ts: Date.now() });
77
+ // Same-cwd twin routing (R1): the PTY that spawned this claude stamped its
78
+ // instanceKey into the env. Forward it so an in-terminal /resume is routed to
79
+ // THIS instance's pending switch, not a sibling twin sharing the same project.
80
+ // Validate the shape — a stale/foreign value must never steer routing.
81
+ const rawInstance = process.env.CCVIEWER_INSTANCE_KEY || '';
82
+ const instanceKey = /^ccv-[0-9a-f]+$/.test(rawInstance) ? rawInstance : null;
83
+ const body = JSON.stringify({ source, sessionId, transcriptPath, cwd, agentId, instanceKey, ts: Date.now() });
78
84
  const reqOpts = {
79
85
  hostname: '127.0.0.1',
80
86
  port: parseInt(port, 10),
@@ -302,9 +302,16 @@ export function isDiscardableSession(dir, meta) {
302
302
  * cross-instance FALLBACK pool to sessions stamped with this cwd (or with NO meta.cwd —
303
303
  * keep-missing). Applies ONLY to the fallback pool, never the instance filter; an empty
304
304
  * value disables the cwd filter. No effect without `instanceKey`.
305
+ * `suppressFallback` (forceNew, 2026-11): when set WITH `instanceKey`, skip the
306
+ * cross-instance fallback entirely — a deliberately brand-new instance ("New Workspace
307
+ * (Session)") has NO conversation yet, and the fallback would serve the live twin's OLD
308
+ * one. Returns null when the instance has no own main-turn session (events.js then serves
309
+ * the empty-view contract). The instance's OWN main turn always wins (the `own` check
310
+ * above runs first). No effect without `instanceKey`; default false preserves today's
311
+ * fallback for reused/rebuilt instances and header chip clicks.
305
312
  * @returns {{dir:string, sessionId:string}|null}
306
313
  */
307
- export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive = false, instanceKey = '', targetCwd = '' } = {}) {
314
+ export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive = false, instanceKey = '', targetCwd = '', suppressFallback = false } = {}) {
308
315
  if (!projectDir) return null;
309
316
  const instanceCandidates = []; // session dirs stamped with the requested instanceKey
310
317
  const projectCandidates = []; // every eligible session dir of the project (any/no instance)
@@ -352,6 +359,15 @@ export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive
352
359
  if (instanceKey) {
353
360
  const own = newestWithMainTurn(instanceCandidates);
354
361
  if (own) return own;
362
+ // forceNew (2026-11): a deliberately brand-new instance has no conversation yet. The
363
+ // cross-instance fallback below would serve the project's newest content-bearing
364
+ // session — the live twin's OLD conversation — which is exactly the "new workspace
365
+ // still shows the OLD conversation" bug. Return null so events.js serves the empty
366
+ // view (load_start{empty:true}); the live feed streams the first turn in place.
367
+ // NOTE: we must NOT degrade to `ownAny` here — a launch-time quota probe writes a
368
+ // session dir stamped with this instance but no main turn, and serving it would
369
+ // defeat the empty view. `own` above already guarantees a real main turn wins.
370
+ if (suppressFallback) return null;
355
371
  // Same-name isolation (2026-10-07): scope the cross-instance fallback to the
356
372
  // TARGET cwd so a cross-dir same-basename project sharing this pool can't be
357
373
  // served. Keep-missing: legacy dirs with NO meta.cwd (null) stay eligible —
@@ -379,7 +395,7 @@ export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive
379
395
  * Absolute dir of the newest readable, non-teammate session that HAS a main
380
396
  * turn, or '' if there is none. Thin wrapper over {@link latestMainSession}.
381
397
  * @param {string} projectDir - absolute LOG_DIR/<project>
382
- * @param {{excludeDir?: string, skipForeignLive?: boolean, instanceKey?: string, targetCwd?: string}} [opts] - see {@link latestMainSession}
398
+ * @param {{excludeDir?: string, skipForeignLive?: boolean, instanceKey?: string, targetCwd?: string, suppressFallback?: boolean}} [opts] - see {@link latestMainSession}
383
399
  * @returns {string} absolute session dir, or ''
384
400
  */
385
401
  export function latestMainSessionDir(projectDir, opts) { return latestMainSession(projectDir, opts)?.dir || '';