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
@@ -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 () => {
package/server/server.js CHANGED
@@ -677,6 +677,17 @@ function startLogWatch() {
677
677
  } catch (err) { reportSwallowed('server.sid-pin', err); }
678
678
  })
679
679
  .catch((err) => { reportSwallowed('server.sid-pin-import', err); });
680
+ // SDK forceNew (2026-11): this main-turn gate is the exact moment the instance owns its
681
+ // first session dir. Lift the freshLaunch empty-view suppression (PTY parity with
682
+ // setPtySessionIdForInstance clearing the PTY record's mark). SDK sessions are not in
683
+ // pty-manager, so their clear path is separate; a no-op for PTY / non-fresh instances.
684
+ // Gated on isSdkMode: importing sdk-manager eagerly loads the Agent SDK (hard dep), which
685
+ // must NOT happen in a PTY-only install (sdk-session-index.js's stated rule).
686
+ if (isSdkMode && instanceKey) {
687
+ import('./lib/sdk-manager.js')
688
+ .then((sdk) => { try { sdk.clearSdkFreshLaunch?.(instanceKey); } catch (err) { reportSwallowed('server.sdk-fresh-clear', err); } })
689
+ .catch((err) => { reportSwallowed('server.sdk-fresh-clear-import', err); });
690
+ }
680
691
  });
681
692
  }
682
693
 
@@ -1694,11 +1705,13 @@ async function _doStart() {
1694
1705
  interactions,
1695
1706
  });
1696
1707
  // IM adapters no longer run in the main ccv. Each enabled IM runs as an independent,
1697
- // detached worker process (im-process-manager). Two CLI-mode cases:
1698
- // - WORKER (CCV_IM_PLATFORM set): connect ONLY this one platform to the singleton PTY.
1699
- // - MAIN ccv: connect NOTHING in-process; reconcile spawns/adopts the enabled IM workers.
1700
- // (Non-CLI workspace/SDK modes do neither — IM only makes sense with the singleton PTY.)
1701
- if (isCliMode && process.env.CCV_IM_PLATFORM) {
1708
+ // detached worker process (im-process-manager). Three CLI-mode cases:
1709
+ // - PTY WORKER (CCV_IM_PLATFORM set, !CCV_SDK_MODE): connect ONLY this one platform to the singleton PTY.
1710
+ // - SDK WORKER (CCV_IM_PLATFORM set, CCV_SDK_MODE): cli.js starts the bridge itself AFTER
1711
+ // initSdkSession (see runImSdkMode) — starting it here would race inbound messages
1712
+ // against an unregistered SDK session.
1713
+ // - MAIN ccv (no CCV_IM_PLATFORM): connect NOTHING in-process; reconcile spawns/adopts the enabled IM workers.
1714
+ if (isCliMode && !isSdkMode && process.env.CCV_IM_PLATFORM) {
1702
1715
  const id = process.env.CCV_IM_PLATFORM;
1703
1716
  const pmb = await import('./pty-manager.js');
1704
1717
  try {
@@ -1719,9 +1732,10 @@ async function _doStart() {
1719
1732
  } catch (e) {
1720
1733
  console.error(`[CC Viewer] IM worker startBridge(${id}) failed:`, e?.message || e);
1721
1734
  }
1722
- } else if (isCliMode) {
1735
+ } else if (isCliMode && !process.env.CCV_IM_PLATFORM) {
1723
1736
  // 主 ccv:先 stopAll(无在进程实例时为 no-op,防御升级残留)再 reconcile,
1724
1737
  // 杜绝"旧在进程连接 + 新 detached worker"同时连同一机器人导致丢/重消息。
1738
+ // (SDK worker 已被第一分支的 !isSdkMode 排除,不会走到这里误 reconcile 自己。)
1725
1739
  try { await imCore.stopAll(); } catch { /* no in-process instances */ }
1726
1740
  imProcMgr.reconcileImProcesses().catch((e) => console.error('[CC Viewer] IM reconcile failed:', e?.message || e));
1727
1741
  }
@@ -2026,7 +2040,10 @@ async function setupTerminalWebSocket(httpServer) {
2026
2040
  // unstamped (receiving all workspaces' frames).
2027
2041
  wss.handleUpgrade(req, socket, head, (ws) => {
2028
2042
  try { ws._ccvViewProject = viewProject || null; } catch {}
2029
- try { ws._ccvViewInstance = viewInstance || null; } catch {}
2043
+ // Twin-window coherence applies at the initial upgrade too, not just on re-attach:
2044
+ // connect precedes the first attach, so without it the null stamp (and the cross-twin
2045
+ // frame delivery) persists for the whole pre-poll window.
2046
+ try { ws._ccvViewInstance = _cohereAttachInstance(viewProject || null, viewInstance); } catch {}
2030
2047
  wss.emit('connection', ws, req);
2031
2048
  });
2032
2049
  });
@@ -2628,7 +2645,7 @@ async function setupTerminalWebSocket(httpServer) {
2628
2645
  // 新视图的 sdk-session-state/审批/队列帧会被静默丢弃。
2629
2646
  if (msg.type === 'attach') {
2630
2647
  try { ws._ccvViewProject = (typeof msg.project === 'string' && msg.project) || null; } catch {}
2631
- try { ws._ccvViewInstance = (typeof msg.instanceKey === 'string' && msg.instanceKey) || null; } catch {}
2648
+ try { ws._ccvViewInstance = _cohereAttachInstance(ws._ccvViewProject, msg.instanceKey); } catch {}
2632
2649
  if (isSdkMode) {
2633
2650
  // Re-attach switched the viewed workspace — re-send that view's sdk-skills
2634
2651
  // surface so the `/` menu isn't stuck on the /api/skills fallback until the next
@@ -2800,7 +2817,7 @@ async function setupTerminalWebSocket(httpServer) {
2800
2817
  try { res = (target || targetInstance) ? attachPtyFor({ project: target || undefined, instanceKey: targetInstance || undefined }) : null; } catch { res = null; }
2801
2818
  if (res && res.ok) {
2802
2819
  ws._ccvViewProject = target || null;
2803
- ws._ccvViewInstance = targetInstance || null;
2820
+ ws._ccvViewInstance = _cohereAttachInstance(ws._ccvViewProject, targetInstance);
2804
2821
  replayQueueSnapshot();
2805
2822
  try { ws.send(JSON.stringify({ type: 'attached', project: target, running: res.running, ptyKind: res.ptyKind, exitCode: res.exitCode })); } catch { }
2806
2823
  const snap = getOutputBuffer();
@@ -2811,7 +2828,7 @@ async function setupTerminalWebSocket(httpServer) {
2811
2828
  // The queue belongs to the view, not to a live PTY. A history view or
2812
2829
  // a dead instance still needs its own queue snapshot after re-stamping.
2813
2830
  ws._ccvViewProject = target || null;
2814
- ws._ccvViewInstance = targetInstance || null;
2831
+ ws._ccvViewInstance = _cohereAttachInstance(ws._ccvViewProject, targetInstance);
2815
2832
  replayQueueSnapshot();
2816
2833
  // Multi-instance: surface an ambiguous project-name attach (with the live
2817
2834
  // candidates) so the client re-issues with an instanceKey instead of silently
@@ -4235,6 +4252,39 @@ export function setSdkGetSessionStateSnapshot(fn) { _sdkGetSessionStateSnapshot
4235
4252
  let _sdkGetSdkTaskSnapshot = null;
4236
4253
  export function setSdkGetSdkTaskSnapshot(fn) { _sdkGetSdkTaskSnapshot = fn; }
4237
4254
 
4255
+ /** Reference to sdk-manager's resolveBoundPrimaryInstanceKey (set by cli.js after import). */
4256
+ let _sdkResolveBoundPrimaryInstanceKey = null;
4257
+ export function setSdkResolveBoundPrimaryInstanceKey(fn) { _sdkResolveBoundPrimaryInstanceKey = fn; }
4258
+
4259
+ /**
4260
+ * Cohere a WS attach's `_ccvViewInstance` stamp for the same-cwd twin window (2026-11).
4261
+ * A bound-project client whose `boundInstance` hasn't hydrated yet attaches with NO
4262
+ * instanceKey, so the stamp would be null and broadcastWsMessage's instance narrowing
4263
+ * ("exclude only the differently-stamped") would deliver EVERY same-cwd twin's frames to
4264
+ * it. The bound identity is a deterministic function of the cwd, so resolve it HERE at
4265
+ * attach time instead of waiting for the client's first /api/live-processes poll.
4266
+ * Only ever NARROWS (null → the bound primary): an explicit instanceKey is returned
4267
+ * untouched, a non-bound project is left alone (parallel views keep their own anchor), and
4268
+ * a single-instance cwd resolves to its only session (narrowing to it is behaviorally
4269
+ * identical to project-level for that cwd — no twin frames exist to drop). PTY mode is
4270
+ * untouched (isSdkMode gate). Resolution failure / no live session → null (unchanged).
4271
+ */
4272
+ function _cohereAttachInstance(viewProject, sentInstanceKey) {
4273
+ const sent = (typeof sentInstanceKey === 'string' && sentInstanceKey) ? sentInstanceKey : null;
4274
+ if (sent) return sent;
4275
+ if (!isSdkMode || typeof _sdkResolveBoundPrimaryInstanceKey !== 'function') return null;
4276
+ if (!viewProject || viewProject !== (_projectName || '')) return null;
4277
+ try {
4278
+ const boundCwd = process.env.CCV_PROJECT_DIR || process.cwd();
4279
+ return _sdkResolveBoundPrimaryInstanceKey(boundCwd) || null;
4280
+ } catch (err) {
4281
+ reportSwallowed('server.attach-cohere-instance', err);
4282
+ return null;
4283
+ }
4284
+ }
4285
+ // Test seam: exercise _cohereAttachInstance's resolution logic without a live socket.
4286
+ export { _cohereAttachInstance };
4287
+
4238
4288
  /** Reference to sdk-manager's sendQueuedNow (set by cli.js after import). */
4239
4289
  let _sdkSendQueuedNow = null;
4240
4290
  export function setSdkSendQueuedNow(fn) { _sdkSendQueuedNow = fn; }