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.
- package/cli.js +355 -59
- package/dist/assets/{App-CjP88gbM.css → App-BJIeZQK0.css} +1 -1
- package/dist/assets/App-C_S65Ygt.js +2 -0
- package/dist/assets/{ArchivePreview-dQkBQGgg.js → ArchivePreview-ezRMkut5.js} +1 -1
- package/dist/assets/{AudioPreview-B6gJoe0v.js → AudioPreview-MxQVazDj.js} +1 -1
- package/dist/assets/{MdxEditorPanel-COJDASLB.js → MdxEditorPanel-CmG2jyvK.js} +1 -1
- package/dist/assets/{Mobile-Cq04x2pS.js → Mobile-BerOQqT4.js} +1 -1
- package/dist/assets/{ProxyStatsModal-BRtZRf0B.js → ProxyStatsModal-dqlP2r2c.js} +1 -1
- package/dist/assets/{SubtitlePreview-C67JiAyR.js → SubtitlePreview-CHRRgV95.js} +1 -1
- package/dist/assets/index-DBmXRTLE.js +2 -0
- package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +2 -0
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/server/i18n.js +4 -0
- package/server/interceptor.js +114 -25
- package/server/lib/anthropic-auth-placeholder.js +147 -0
- package/server/lib/continuation-args.js +25 -0
- package/server/lib/im/im-bridge-core.js +59 -14
- package/server/lib/im/im-permissions.js +48 -0
- package/server/lib/im/im-process-manager.js +6 -5
- package/server/lib/im-deny.js +4 -1
- package/server/lib/interceptor-core.js +51 -0
- package/server/lib/proxy-session-registry.js +156 -0
- package/server/lib/scheduled-task-executor.js +6 -3
- package/server/lib/sdk-manager.js +376 -88
- package/server/lib/session-start-bridge.js +7 -1
- package/server/lib/update-job.js +3 -3
- package/server/lib/v2/session-select.js +18 -2
- package/server/lib/v2/v2-writer.js +249 -21
- package/server/proxy.js +15 -7
- package/server/pty-manager.js +62 -41
- package/server/routes/events.js +16 -4
- package/server/routes/preferences.js +108 -24
- package/server/routes/resume.js +271 -27
- package/server/routes/update.js +15 -2
- package/server/routes/workspaces.js +112 -29
- package/server/server.js +60 -10
- package/dist/assets/App-CZ0L1Cvm.js +0 -2
- package/dist/assets/index-Cb1Ur9uR.js +0 -2
- package/dist/assets/seqResourceLoaders-BQo28rrY.js +0 -2
package/server/pty-manager.js
CHANGED
|
@@ -3,12 +3,13 @@ import { normalizeSessionCwd } from './lib/v2/layout.js';
|
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { join, dirname, sep, resolve } from 'node:path';
|
|
5
5
|
import { chmodSync, statSync, existsSync } from 'node:fs';
|
|
6
|
-
import { platform, arch
|
|
6
|
+
import { platform, arch } from 'node:os';
|
|
7
7
|
import { createRequire } from 'node:module';
|
|
8
8
|
import { prepareEmbeddedShellSpawn, stripClaudeNoFlickerUnlessOptedIn, applyClaudeAltScreenPref } from './lib/terminal-env.js';
|
|
9
9
|
import { killPtyTree } from './lib/term-signals.js';
|
|
10
10
|
import { findSafeSliceStart, splitTrailingIncomplete } from './lib/ansi-safe-slice.js';
|
|
11
11
|
import { imDir } from './lib/im/im-lock.js';
|
|
12
|
+
import { buildImDenySettings } from './lib/im/im-permissions.js';
|
|
12
13
|
import { resolveSpawnModel } from './lib/spawn-model-resolver.js';
|
|
13
14
|
import { mergeSettingsIntoArgs } from './lib/settings-merge.js';
|
|
14
15
|
import { projectKeyForCwd } from './lib/system-prompt-snapshots.js';
|
|
@@ -101,6 +102,14 @@ function _getOrInit(key) {
|
|
|
101
102
|
batchBuffer: '',
|
|
102
103
|
batchScheduled: false,
|
|
103
104
|
sessionId: null, // claude session uuid once its first turn mints one (fed via setPtySessionId)
|
|
105
|
+
// forceNew "brand-new conversation" launch mark (2026-11): set only by
|
|
106
|
+
// ensurePtyForCwd({forceNew:true}) (file explorer "New Workspace (Session)"
|
|
107
|
+
// on the current root). routes/events.js reads it to suppress the same-cwd
|
|
108
|
+
// cold-load fallback while this instance has no main turn of its own.
|
|
109
|
+
// Cleared in setPtySessionIdForInstance (first main turn binds a session);
|
|
110
|
+
// NEVER reset in _spawnClaudeImpl/_respawnInto (a self-heal respawn is still
|
|
111
|
+
// the same fresh instance).
|
|
112
|
+
freshLaunch: false,
|
|
104
113
|
};
|
|
105
114
|
ptys.set(key, s);
|
|
106
115
|
}
|
|
@@ -341,7 +350,12 @@ export async function spawnClaude(proxyPort, cwd, extraArgs = [], claudePath = n
|
|
|
341
350
|
while (_spawnInflight.has(key)) { try { await _spawnInflight.get(key); } catch { } }
|
|
342
351
|
const p = _spawnClaudeImpl(key, proxyPort, cwd, extraArgs, claudePath, isNpmVersion, serverPort, serverProtocol, internalToken);
|
|
343
352
|
_spawnInflight.set(key, p);
|
|
344
|
-
try {
|
|
353
|
+
try {
|
|
354
|
+
// Resolve with the record's OWN instanceKey (never activePtyKey — a concurrent spawn
|
|
355
|
+
// for another cwd can re-point the shared pointer before this spawn settles).
|
|
356
|
+
const ptyProcess = await p;
|
|
357
|
+
return { key, ptyProcess };
|
|
358
|
+
} finally { if (_spawnInflight.get(key) === p) _spawnInflight.delete(key); }
|
|
345
359
|
}
|
|
346
360
|
|
|
347
361
|
// Self-heal respawn: re-run claude in the SAME record (same instanceKey) after a boot crash
|
|
@@ -477,6 +491,11 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
|
|
|
477
491
|
env.CCV_EDITOR_PORT = String(serverPort);
|
|
478
492
|
env.CCVIEWER_PORT = String(serverPort); // For ask-hook bridge
|
|
479
493
|
env.CCVIEWER_PROTOCOL = serverProtocol; // For ask/perm-bridge (http vs https)
|
|
494
|
+
// Per-spawn instance key for the SessionStart hook bridge (R1): lets the
|
|
495
|
+
// in-terminal /resume signal be routed to THIS exact same-cwd instance
|
|
496
|
+
// instead of any sibling twin sharing the project. `key` is the record's
|
|
497
|
+
// instanceKey, stable across self-heal respawns of the same record.
|
|
498
|
+
env.CCVIEWER_INSTANCE_KEY = key;
|
|
480
499
|
if (internalToken) {
|
|
481
500
|
// Anti-CSRF token for bridge → server calls (round-3 P1). Same shared
|
|
482
501
|
// secret across ask / perm / turn-end bridges so server can route-check
|
|
@@ -504,34 +523,8 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
|
|
|
504
523
|
// Note: under bypass mode whether deny is still honored depends on Claude Code's
|
|
505
524
|
// behavior; the truly reliable enforcement layer is perm-bridge.js's PreToolUse deny
|
|
506
525
|
// (CCV_IM_DENY). This is a best-effort defense-in-depth layer.
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
settingsObj.permissions = {
|
|
510
|
-
deny: [
|
|
511
|
-
'Bash(sudo:*)', 'Bash(rm -rf:*)', 'Bash(rm -fr:*)',
|
|
512
|
-
'Bash(git push:*)', 'Bash(npm publish:*)', 'Bash(ssh:*)', 'Bash(scp:*)',
|
|
513
|
-
`Read(${home}/.ssh/**)`, `Edit(${home}/.ssh/**)`, `Write(${home}/.ssh/**)`,
|
|
514
|
-
`Read(${home}/.aws/**)`, `Edit(${home}/.aws/**)`, `Write(${home}/.aws/**)`,
|
|
515
|
-
// File-precise: protect the deny mechanism itself (settings/hooks), the IM
|
|
516
|
-
// credential store (preferences.json), and the credential vault (credentials.json +
|
|
517
|
-
// master.key), but do not block all of ~/.claude — the worker's working directory
|
|
518
|
-
// sits under ~/.claude/cc-viewer/IM_<id>/ and must stay writable.
|
|
519
|
-
`Edit(${home}/.claude/settings.json)`, `Write(${home}/.claude/settings.json)`,
|
|
520
|
-
`Edit(${home}/.claude/settings.local.json)`, `Write(${home}/.claude/settings.local.json)`,
|
|
521
|
-
`Edit(${home}/.claude/cc-viewer/preferences.json)`, `Write(${home}/.claude/cc-viewer/preferences.json)`,
|
|
522
|
-
// preferences.json 现承载定时任务定义(含 prompt);运行历史/旧版任务文件同理拒读拒写。
|
|
523
|
-
`Read(${home}/.claude/cc-viewer/preferences.json)`,
|
|
524
|
-
`Read(${home}/.claude/cc-viewer/scheduled-task-runs.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-task-runs.json)`, `Write(${home}/.claude/cc-viewer/scheduled-task-runs.json)`,
|
|
525
|
-
`Read(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Write(${home}/.claude/cc-viewer/scheduled-tasks.json)`,
|
|
526
|
-
`Read(${home}/.claude/cc-viewer/credentials.json)`, `Edit(${home}/.claude/cc-viewer/credentials.json)`, `Write(${home}/.claude/cc-viewer/credentials.json)`,
|
|
527
|
-
`Read(${home}/.claude/cc-viewer/master.key)`, `Edit(${home}/.claude/cc-viewer/master.key)`, `Write(${home}/.claude/cc-viewer/master.key)`,
|
|
528
|
-
// Backup copies of the vault (cc-viewer-config-backups/<ts>/) hold the same decryption
|
|
529
|
-
// kit (credentials.json + master.key) — deny the whole subtree or an IM worker could read
|
|
530
|
-
// a rolled backup and decrypt every secret.
|
|
531
|
-
`Read(${home}/.claude/cc-viewer-config-backups/**)`, `Edit(${home}/.claude/cc-viewer-config-backups/**)`, `Write(${home}/.claude/cc-viewer-config-backups/**)`,
|
|
532
|
-
],
|
|
533
|
-
};
|
|
534
|
-
}
|
|
526
|
+
// Shared with the SDK IM worker (runImSdkMode) via buildImDenySettings().
|
|
527
|
+
Object.assign(settingsObj, buildImDenySettings());
|
|
535
528
|
// Inject --thinking-display summarized; skip injection when either of these holds:
|
|
536
529
|
// - the path is in the rejection set (it crashed because of this last time)
|
|
537
530
|
// - env CCV_SKIP_THINKING_DISPLAY=1 (user global opt-out, consistent with cli.js)
|
|
@@ -971,6 +964,7 @@ async function _spawnShellImpl(key) {
|
|
|
971
964
|
delete shellEnv.CCV_EDITOR_PORT;
|
|
972
965
|
delete shellEnv.CCVIEWER_PROTOCOL;
|
|
973
966
|
delete shellEnv.CCVIEWER_INTERNAL_TOKEN;
|
|
967
|
+
delete shellEnv.CCVIEWER_INSTANCE_KEY; // a hand-typed claude is not this record's instance
|
|
974
968
|
// Also disable the mouse for claude typed by hand in the interactive shell; same reason
|
|
975
969
|
// as spawnClaude.
|
|
976
970
|
shellEnv.CLAUDE_CODE_DISABLE_MOUSE ??= '1';
|
|
@@ -1239,6 +1233,12 @@ export function setPtySessionIdForInstance(instanceKey, sessionId) {
|
|
|
1239
1233
|
if (s.sessionId && s.sessionId !== sessionId) sidToKey.delete(s.sessionId);
|
|
1240
1234
|
s.sessionId = sessionId;
|
|
1241
1235
|
sidToKey.set(sessionId, instanceKey);
|
|
1236
|
+
// forceNew lifecycle (2026-11): the mark's job ends once this instance owns a real
|
|
1237
|
+
// session. Binding a session id means a main turn landed (v2-writer only calls this
|
|
1238
|
+
// on a main-turn gate), so the instance now has its own conversation and the cold-load
|
|
1239
|
+
// fallback suppression must lift — a later chip-click / reload serves that conversation,
|
|
1240
|
+
// and a /resume adopted into this instance stops being hidden behind an empty view.
|
|
1241
|
+
s.freshLaunch = false;
|
|
1242
1242
|
return true;
|
|
1243
1243
|
}
|
|
1244
1244
|
|
|
@@ -1447,11 +1447,11 @@ export function attachPtyFor({ cwd, project, instanceKey } = {}) {
|
|
|
1447
1447
|
}
|
|
1448
1448
|
|
|
1449
1449
|
/**
|
|
1450
|
-
* parallel-project chips. Returns [{ key, instanceKey, cwd, ptyKind, pid, isActive }] for
|
|
1450
|
+
* parallel-project chips. Returns [{ key, instanceKey, cwd, ptyKind, pid, isActive, freshLaunch }] for
|
|
1451
1451
|
* records whose process is still running (ptyProcess != null); exited-but-
|
|
1452
1452
|
* unreaped records are excluded. `key`/`instanceKey` are the opaque per-spawn instanceKey
|
|
1453
1453
|
* the Map is keyed on; `cwd` is the record's real working dir (never the key). `isActive`
|
|
1454
|
-
* marks the PTY the main view is attached to. Read-only.
|
|
1454
|
+
* marks the PTY the main view is attached to. `freshLaunch` is the forceNew mark. Read-only.
|
|
1455
1455
|
*/
|
|
1456
1456
|
export function listLivePtys() {
|
|
1457
1457
|
const out = [];
|
|
@@ -1464,6 +1464,10 @@ export function listLivePtys() {
|
|
|
1464
1464
|
ptyKind: s.ptyKind || null,
|
|
1465
1465
|
pid: s.ptyProcess.pid,
|
|
1466
1466
|
isActive: key === activePtyKey,
|
|
1467
|
+
// forceNew mark (2026-11): routes/events.js reads this to suppress the same-cwd
|
|
1468
|
+
// cold-load fallback for a deliberately brand-new instance. Additive; consumers
|
|
1469
|
+
// that build their own rows (resume.js) are unaffected.
|
|
1470
|
+
freshLaunch: s.freshLaunch === true,
|
|
1467
1471
|
});
|
|
1468
1472
|
}
|
|
1469
1473
|
return out;
|
|
@@ -1644,7 +1648,7 @@ export function getPtyBootState() {
|
|
|
1644
1648
|
*
|
|
1645
1649
|
* @returns {Promise<{ spawned:boolean, attached:boolean, key:string|null, running:boolean }>}
|
|
1646
1650
|
*/
|
|
1647
|
-
export async function ensurePtyForCwd({ cwd, proxyPort, extraArgs = [], claudePath = null, isNpmVersion = false, serverPort = null, serverProtocol = 'http', internalToken = null } = {}) {
|
|
1651
|
+
export async function ensurePtyForCwd({ cwd, proxyPort, extraArgs = [], claudePath = null, isNpmVersion = false, serverPort = null, serverProtocol = 'http', internalToken = null, forceNew = false } = {}) {
|
|
1648
1652
|
if (typeof cwd !== 'string' || !cwd) return { spawned: false, attached: false, key: null, running: false };
|
|
1649
1653
|
// Serialize concurrent launches for the SAME cwd (review P1 / TOCTOU): the live-scan below
|
|
1650
1654
|
// + `spawnClaude` are two separate steps, so two simultaneous launches of one cwd could both
|
|
@@ -1653,19 +1657,36 @@ export async function ensurePtyForCwd({ cwd, proxyPort, extraArgs = [], claudePa
|
|
|
1653
1657
|
// in-flight promise here — the second caller waits for the first, then re-scans and finds
|
|
1654
1658
|
// the now-live record (attaching instead of spawning).
|
|
1655
1659
|
while (_cwdLaunchInflight.has(cwd)) { try { await _cwdLaunchInflight.get(cwd); } catch { } }
|
|
1656
|
-
//
|
|
1657
|
-
//
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1660
|
+
// forceNew (context menu "New Workspace (Session)" on the CURRENT root): a second
|
|
1661
|
+
// concurrent claude in the same cwd is the whole point — skip the reuse scan. The per-cwd
|
|
1662
|
+
// in-flight slot is still taken, so a concurrent normal launch cannot re-attach mid-spawn.
|
|
1663
|
+
if (!forceNew) {
|
|
1664
|
+
// Prefer an already-LIVE claude for this exact cwd (not a shell). Re-attaching rather than
|
|
1665
|
+
// re-spawning preserves the running session and avoids a duplicate process.
|
|
1666
|
+
for (const [k, s] of ptys) {
|
|
1667
|
+
if (s && s.cwd === cwd && s.ptyProcess && s.ptyKind === 'claude') {
|
|
1668
|
+
activePtyKey = k; // attach the main view to the live record
|
|
1669
|
+
return { spawned: false, attached: true, key: k, running: true };
|
|
1670
|
+
}
|
|
1662
1671
|
}
|
|
1663
1672
|
}
|
|
1664
1673
|
const p = spawnClaude(proxyPort, cwd, extraArgs, claudePath, isNpmVersion, serverPort, serverProtocol, internalToken);
|
|
1665
1674
|
_cwdLaunchInflight.set(cwd, p);
|
|
1666
1675
|
try {
|
|
1667
|
-
await p;
|
|
1668
|
-
|
|
1676
|
+
const { key } = await p; // the SPAWNED record's key — not activePtyKey (race-safe)
|
|
1677
|
+
// forceNew: this record's conversation starts EMPTY by design. Mark it (the record
|
|
1678
|
+
// exists: _spawnClaudeImpl set ptyProcess before resolving) so every later
|
|
1679
|
+
// `?project&instance` cold-load — including a reload or another tab — suppresses the
|
|
1680
|
+
// cross-instance fallback that would otherwise serve the live twin's OLD conversation.
|
|
1681
|
+
// The client only learns this key from the launch HTTP response (sent after this
|
|
1682
|
+
// resolves), so the mark is always in place before any reader. Gate on forceNew: the
|
|
1683
|
+
// `await p` above is shared with the non-forceNew cold-launch path (the reuse scan
|
|
1684
|
+
// found nothing), and marking that would wrongly blank a normal re-opened instance.
|
|
1685
|
+
if (forceNew) {
|
|
1686
|
+
const rec = ptys.get(key);
|
|
1687
|
+
if (rec) rec.freshLaunch = true;
|
|
1688
|
+
}
|
|
1689
|
+
return { spawned: true, attached: false, key, running: true };
|
|
1669
1690
|
} finally {
|
|
1670
1691
|
if (_cwdLaunchInflight.get(cwd) === p) _cwdLaunchInflight.delete(cwd);
|
|
1671
1692
|
}
|
package/server/routes/events.js
CHANGED
|
@@ -427,14 +427,23 @@ export async function serveEventStream(sink, params, deps) {
|
|
|
427
427
|
// Instance dead / no live record / lookup failure → '' → no cwd filter
|
|
428
428
|
// (conservative, identical to today's whole-pool fallback; never mis-excludes history).
|
|
429
429
|
let targetCwd = '';
|
|
430
|
+
// forceNew (2026-11): a brand-new instance ("New Workspace (Session)") carries the
|
|
431
|
+
// `freshLaunch` mark — on its PTY record (PTY mode) or its SDK session row (SDK mode,
|
|
432
|
+
// projected through listSdkSessions). Suppress the same-cwd cold-load fallback for it
|
|
433
|
+
// so the view starts EMPTY instead of serving the old conversation. Server-authoritative,
|
|
434
|
+
// so it holds for a reload or a second tab, not just the launching client. Lookup
|
|
435
|
+
// failure / dead record → false → today's fallback (sid-not-found handles a dead one).
|
|
436
|
+
let suppressFallback = false;
|
|
430
437
|
if (instanceParam) {
|
|
431
438
|
try {
|
|
432
|
-
const
|
|
433
|
-
|
|
439
|
+
const ptyRec = listLivePtys().find((p) => p && p.instanceKey === instanceParam);
|
|
440
|
+
const sdkRec = findSdkSessionByInstance(instanceParam);
|
|
441
|
+
const rec = ptyRec || sdkRec;
|
|
434
442
|
targetCwd = rec && rec.cwd ? normalizeSessionCwd(rec.cwd) : '';
|
|
435
|
-
|
|
443
|
+
suppressFallback = !!((ptyRec && ptyRec.freshLaunch) || (sdkRec && sdkRec.freshLaunch));
|
|
444
|
+
} catch (err) { targetCwd = ''; suppressFallback = false; reportSwallowed('events.target-cwd', err); }
|
|
436
445
|
}
|
|
437
|
-
return latestMainSessionDir(join(LOG_DIR, sanitizePathComponent(projectParam)), { skipForeignLive: true, instanceKey: instanceParam || '', targetCwd }) || null;
|
|
446
|
+
return latestMainSessionDir(join(LOG_DIR, sanitizePathComponent(projectParam)), { skipForeignLive: true, instanceKey: instanceParam || '', targetCwd, suppressFallback }) || null;
|
|
438
447
|
} catch (err) {
|
|
439
448
|
reportSwallowed('events.project-resolve', err, { project: projectParam });
|
|
440
449
|
return null;
|
|
@@ -466,6 +475,9 @@ export async function serveEventStream(sink, params, deps) {
|
|
|
466
475
|
// per-project live feed streams its first turn in place the moment the PTY writes its
|
|
467
476
|
// first session dir. Only a DEAD instance keeps the explicit sid-not-found posture (the
|
|
468
477
|
// client toasts + auto-detaches to the bound view — unchanged from before this fix).
|
|
478
|
+
// forceNew (2026-11) reaches this same empty view a third way: the freshLaunch mark makes
|
|
479
|
+
// resolveColdSource return null (suppressFallback), so a same-cwd twin's OLD conversation
|
|
480
|
+
// is never served to the brand-new instance.
|
|
469
481
|
const instanceNoSession = !!(instanceParam && !sidParam && !viewColdDir);
|
|
470
482
|
let instanceAlive = false;
|
|
471
483
|
if (instanceNoSession) {
|
|
@@ -3,8 +3,10 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync, unlin
|
|
|
3
3
|
import { join, dirname } from 'node:path';
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
5
|
import { LOG_DIR, setLogDir, getClaudeConfigDir, discoverClaudeExecutables, resolveExplicitClaudePath, CLAUDE_EXECUTABLE_PREF_KEY } from '../../findcc.js';
|
|
6
|
-
import { PROFILE_PATH, _defaultConfig, getActiveProfileId, getStoredRoles, isOfficialDefaultEndpoint, setActiveProfileForWorkspace, _loadProxyProfile, hydrateProfilesWithApiKeys, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState } from '../interceptor.js';
|
|
6
|
+
import { PROFILE_PATH, _defaultConfig, getActiveProfileId, getStoredRoles, isOfficialDefaultEndpoint, setActiveProfileForWorkspace, _loadProxyProfile, getGlobalDefaultProfileId, hydrateProfilesWithApiKeys, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState } from '../interceptor.js';
|
|
7
7
|
import { migrateProxyProfileList, isValidRoleValue, PROXY_ROLE_KEYS } from '../lib/interceptor-core.js';
|
|
8
|
+
import { getSessionProxy, setSessionProxyProfile, pruneSessionProxyProfiles } from '../lib/proxy-session-registry.js';
|
|
9
|
+
import { filterClientsByInstance } from '../lib/v2/view-router.js';
|
|
8
10
|
import { DEFAULT_RETRY_CONFIG, validateRetryConfig, resolveRetryConfig } from '../lib/proxy/proxy-retry.js';
|
|
9
11
|
import { discoverCcSwitchProviders, mergeImportedProfiles } from '../lib/ccswitch-import.js';
|
|
10
12
|
import { reportSwallowed } from '../lib/error-report.js';
|
|
@@ -319,6 +321,22 @@ function claudeSettingsPost(req, res, parsedUrl, isLocal, deps) {
|
|
|
319
321
|
});
|
|
320
322
|
}
|
|
321
323
|
|
|
324
|
+
// ── Per-session proxy binding helpers (GET /api/proxy-profiles?instanceKey=) ──────
|
|
325
|
+
// A binding counts as "session-scoped" only when its main is still resolvable: 'max'
|
|
326
|
+
// (explicit Default) or a profile id present in the served list. A dangling binding
|
|
327
|
+
// (profile deleted out from under it) falls back to the global view instead of
|
|
328
|
+
// surfacing an id the UI can't render.
|
|
329
|
+
function sessionScopedBindingPresent(binding, data) {
|
|
330
|
+
if (!binding || typeof binding.main !== 'string' || !binding.main) return false;
|
|
331
|
+
if (binding.main === 'max') return true;
|
|
332
|
+
const list = data && Array.isArray(data.profiles) ? data.profiles : [];
|
|
333
|
+
return list.some((p) => p && p.id === binding.main);
|
|
334
|
+
}
|
|
335
|
+
function sessionBindingActive(binding) { return binding.main; }
|
|
336
|
+
function sessionBindingRoles(binding) {
|
|
337
|
+
return { subagent: binding.roles?.subagent || 'follow', teammate: binding.roles?.teammate || 'follow' };
|
|
338
|
+
}
|
|
339
|
+
|
|
322
340
|
function proxyProfilesGet(req, res, parsedUrl, isLocal, deps) {
|
|
323
341
|
try {
|
|
324
342
|
let data = existsSync(PROFILE_PATH) ? JSON.parse(readFileSync(PROFILE_PATH, 'utf-8')) : deps.defaultProxyProfiles;
|
|
@@ -349,13 +367,24 @@ function proxyProfilesGet(req, res, parsedUrl, isLocal, deps) {
|
|
|
349
367
|
data = { ...data, profiles: hydrateProfilesWithApiKeys(data.profiles) };
|
|
350
368
|
}
|
|
351
369
|
// 用 interceptor.getActiveProfileId() 返回 effective active(workspace > profile.json.active > 'max')
|
|
352
|
-
|
|
370
|
+
// Per-session override: ?instanceKey= with an existing binding resolves that session's
|
|
371
|
+
// OWN main/roles (and marks sessionScoped) instead of the process-global value.
|
|
372
|
+
const globalActive = getGlobalDefaultProfileId();
|
|
373
|
+
const reqInstance = (() => {
|
|
374
|
+
const v = parsedUrl && parsedUrl.searchParams && typeof parsedUrl.searchParams.get === 'function'
|
|
375
|
+
? parsedUrl.searchParams.get('instanceKey') : null;
|
|
376
|
+
return (typeof v === 'string' && /^ccv-[0-9a-f]+$/.test(v)) ? v : null;
|
|
377
|
+
})();
|
|
378
|
+
const sessionBinding = reqInstance ? getSessionProxy(reqInstance) : undefined;
|
|
379
|
+
const sessionScoped = sessionScopedBindingPresent(sessionBinding, data);
|
|
380
|
+
const effectiveActive = sessionScoped ? sessionBindingActive(sessionBinding) : getActiveProfileId();
|
|
381
|
+
const effectiveRoles = sessionScoped ? sessionBindingRoles(sessionBinding) : getStoredRoles();
|
|
353
382
|
// 本机(127.0.0.1)= admin:下发明文 profile.apiKey 供本人在编辑表单(👁 折叠)里查阅/复制;已授权
|
|
354
383
|
// 的远程客户端只拿脱敏值(****+后4位)。保存时若回传脱敏值,POST 侧 isMasked() 会保留磁盘原值。
|
|
355
384
|
// 镜像 /api/auth/state 的密码、/api/dingtalk/status 的 appSecret 策略。
|
|
356
385
|
// roles 返回**存储值**(不做休眠调整):休眠只是请求侧不生效,若返回有效值,UI 缓存后
|
|
357
386
|
// 在下次无关 POST 回写会把休眠中的分配清掉。officialDefault 驱动 UI 隐藏角色分配区。
|
|
358
|
-
const full = { ...data, active: effectiveActive, roles:
|
|
387
|
+
const full = { ...data, active: effectiveActive, roles: effectiveRoles, officialDefault: isOfficialDefaultEndpoint(), globalActive, sessionScoped, ...(reqInstance ? { instanceKey: reqInstance } : {}) };
|
|
359
388
|
const payload = isLocal ? full : deps.maskProfiles(full);
|
|
360
389
|
// defaultConfig.apiKey 始终脱敏:它在列表里是常显文本(无 👁 折叠),且 Max/OAuth 默认配置的 key
|
|
361
390
|
// 可能是 OAuth token;只有可编辑 profile 的 key 才按 isLocal 明文下发。
|
|
@@ -371,7 +400,7 @@ function proxyProfilesGet(req, res, parsedUrl, isLocal, deps) {
|
|
|
371
400
|
function proxyProfilesPost(req, res, parsedUrl, isLocal, deps) {
|
|
372
401
|
let body = '';
|
|
373
402
|
req.on('data', chunk => { body += chunk; if (body.length > deps.MAX_POST_BODY) req.destroy(); });
|
|
374
|
-
req.on('end', () => {
|
|
403
|
+
req.on('end', async () => {
|
|
375
404
|
try {
|
|
376
405
|
const incoming = JSON.parse(body);
|
|
377
406
|
if (!incoming || typeof incoming !== 'object' || !Array.isArray(incoming.profiles)) {
|
|
@@ -379,10 +408,53 @@ function proxyProfilesPost(req, res, parsedUrl, isLocal, deps) {
|
|
|
379
408
|
res.end(JSON.stringify({ error: 'Invalid profile data: profiles must be an array' }));
|
|
380
409
|
return;
|
|
381
410
|
}
|
|
411
|
+
// active/roles 作用域:'session'(按 instanceKey 写会话映射,不落盘)/
|
|
412
|
+
// 'global'(设为全局默认 + workspace)/ 缺省(旧客户端 = 现状,workspace+全局回退)。
|
|
413
|
+
// 在读/校验阶段只确定 scope 与 instanceKey;active/roles 的具体校验在 sanitizedRoles
|
|
414
|
+
// 之后、落盘之前(见下),以便 roles-only 会话调用也有合法判定依据。
|
|
415
|
+
const scope = incoming.scope === 'session' || incoming.scope === 'global' ? incoming.scope : null;
|
|
416
|
+
const hasActive = typeof incoming.active === 'string' && incoming.active;
|
|
417
|
+
let sessionKey = (typeof incoming.instanceKey === 'string' && /^ccv-[0-9a-f]+$/.test(incoming.instanceKey)) ? incoming.instanceKey : null;
|
|
382
418
|
// 确保 max profile 始终存在
|
|
383
419
|
if (!incoming.profiles.some(p => p.id === 'max')) {
|
|
384
420
|
incoming.profiles = [{ id: 'max', name: 'Default' }, ...(incoming.profiles || [])];
|
|
385
421
|
}
|
|
422
|
+
// 角色分配校验:只认 subagent/teammate 两个 key(roles.main 之类的杂键直接丢弃);
|
|
423
|
+
// 值必须是 follow / max / 入参 profiles 里存在的 id(按将落盘的列表校验,而非旧文件),
|
|
424
|
+
// 非法值归 'follow'(宽容风格,不 400)。被删 profile 的悬空角色由读取时归 follow 兜底。
|
|
425
|
+
let sanitizedRoles;
|
|
426
|
+
if (incoming.roles && typeof incoming.roles === 'object' && !Array.isArray(incoming.roles)) {
|
|
427
|
+
const byId = new Map(incoming.profiles.map(p => [p.id, p]));
|
|
428
|
+
sanitizedRoles = {};
|
|
429
|
+
for (const k of PROXY_ROLE_KEYS) {
|
|
430
|
+
if (!(k in incoming.roles)) continue; // 未提交的 key 不进 patch → 合并时保留存储值
|
|
431
|
+
const v = incoming.roles[k];
|
|
432
|
+
// key 提交了但值非法(非字符串 / 悬空 id)→ 归 'follow'(显式纠正,不是保留)
|
|
433
|
+
sanitizedRoles[k] = (typeof v === 'string' && v && isValidRoleValue(v, byId)) ? v : 'follow';
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
// session 作用域的兜底寻址 + 校验。必须在落盘之前完成——被拒(400)的请求不得改写
|
|
437
|
+
// profile.json / vault。
|
|
438
|
+
if (scope === 'session' && !sessionKey) {
|
|
439
|
+
// Fallback: an older/again-loading frontend may legitimately lack the key on the
|
|
440
|
+
// bound view. Resolve the bound session's primary instance server-side (dynamic
|
|
441
|
+
// import — never eagerly load the Agent SDK in PTY mode) instead of silently
|
|
442
|
+
// degrading to a global write that wouldn't reach the (already-seeded) session.
|
|
443
|
+
try {
|
|
444
|
+
const boundCwd = process.env.CCV_PROJECT_DIR || process.cwd();
|
|
445
|
+
const sdk = await import('../lib/sdk-manager.js');
|
|
446
|
+
const resolved = sdk.resolveBoundPrimaryInstanceKey(boundCwd);
|
|
447
|
+
if (typeof resolved === 'string' && /^ccv-[0-9a-f]+$/.test(resolved)) sessionKey = resolved;
|
|
448
|
+
} catch (err) { reportSwallowed('proxy-profiles.resolve-session-key', err); }
|
|
449
|
+
}
|
|
450
|
+
if (scope === 'session') {
|
|
451
|
+
const byId = new Map(incoming.profiles.map(p => [p.id, p]));
|
|
452
|
+
if (!sessionKey || (hasActive && !isValidRoleValue(incoming.active, byId)) || (!hasActive && !sanitizedRoles)) {
|
|
453
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
454
|
+
res.end(JSON.stringify({ error: 'Invalid instanceKey/profile for session scope' }));
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
386
458
|
// Only the profiles list is written to profile.json; `active` is no longer persisted here
|
|
387
459
|
// (avoids cross-process clobbering). The existing file's `active` field is preserved so an
|
|
388
460
|
// older ccv or a hand editor can still fall back to it. Read-merge-write INSIDE the lock
|
|
@@ -398,34 +470,46 @@ function proxyProfilesPost(req, res, parsedUrl, isLocal, deps) {
|
|
|
398
470
|
existing.profiles = strippedProfiles;
|
|
399
471
|
return existing;
|
|
400
472
|
}, { mode: 0o600, strictCorrupt: true, fallback: {} });
|
|
401
|
-
// 角色分配校验:只认 subagent/teammate 两个 key(roles.main 之类的杂键直接丢弃);
|
|
402
|
-
// 值必须是 follow / max / 入参 profiles 里存在的 id(按将落盘的列表校验,而非旧文件),
|
|
403
|
-
// 非法值归 'follow'(宽容风格,不 400)。被删 profile 的悬空角色由读取时归 follow 兜底。
|
|
404
|
-
let sanitizedRoles;
|
|
405
|
-
if (incoming.roles && typeof incoming.roles === 'object' && !Array.isArray(incoming.roles)) {
|
|
406
|
-
const byId = new Map(incoming.profiles.map(p => [p.id, p]));
|
|
407
|
-
sanitizedRoles = {};
|
|
408
|
-
for (const k of PROXY_ROLE_KEYS) {
|
|
409
|
-
if (!(k in incoming.roles)) continue; // 未提交的 key 不进 patch → 合并时保留存储值
|
|
410
|
-
const v = incoming.roles[k];
|
|
411
|
-
// key 提交了但值非法(非字符串 / 悬空 id)→ 归 'follow'(显式纠正,不是保留)
|
|
412
|
-
sanitizedRoles[k] = (typeof v === 'string' && v && isValidRoleValue(v, byId)) ? v : 'follow';
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
473
|
// active/roles 走 workspace 级别存储(当前进程独占);合并语义:缺省字段保留文件现值
|
|
416
|
-
|
|
417
|
-
|
|
474
|
+
if (scope === 'session') {
|
|
475
|
+
// 会话级:写进程内映射(主代理 + 角色),不碰 workspace 文件 / 全局默认。
|
|
476
|
+
// roles 按 key 合并:未提交的角色保留会话现值(与 workspace mergeActivePayload 同语义)。
|
|
477
|
+
const existing = getSessionProxy(sessionKey);
|
|
478
|
+
setSessionProxyProfile(sessionKey, {
|
|
479
|
+
main: hasActive ? incoming.active : (existing?.main || getGlobalDefaultProfileId()),
|
|
480
|
+
roles: {
|
|
481
|
+
subagent: sanitizedRoles && 'subagent' in sanitizedRoles ? sanitizedRoles.subagent : (existing?.roles?.subagent || 'follow'),
|
|
482
|
+
teammate: sanitizedRoles && 'teammate' in sanitizedRoles ? sanitizedRoles.teammate : (existing?.roles?.teammate || 'follow'),
|
|
483
|
+
},
|
|
484
|
+
});
|
|
485
|
+
_loadProxyProfile(); // 列表可能同时变了
|
|
486
|
+
} else if (hasActive || sanitizedRoles) {
|
|
418
487
|
setActiveProfileForWorkspace(hasActive ? incoming.active : undefined, sanitizedRoles);
|
|
419
488
|
} else {
|
|
420
489
|
_loadProxyProfile(); // 仅列表变化时也刷新一次以反映删除 / 重命名
|
|
421
490
|
}
|
|
422
|
-
//
|
|
423
|
-
|
|
491
|
+
// 清理悬空会话映射:只针对"本次确实从列表中消失"的 profile id(而非整张提交列表),
|
|
492
|
+
// 避免陈旧 tab 的全量列表把别的会话仍有效的绑定清掉。与 scope 无关。
|
|
493
|
+
if (pruneSessionProxyProfiles) {
|
|
494
|
+
// incoming.profiles 已是落盘后的全量;任何不在这张表里的绑定 id 都是悬空。
|
|
495
|
+
// 注意:这是删 profile 的唯一入口,故以新列表为准清理是安全的。
|
|
496
|
+
pruneSessionProxyProfiles(new Set(incoming.profiles.map(p => p.id)));
|
|
497
|
+
}
|
|
498
|
+
// SSE:session 变更只发同实例客户端(别戳到其他会话的 tab);global/列表刷新全发。
|
|
499
|
+
// session 作用域下生效的 active 是该会话映射里的 main(roles-only 调用时回退到现值)。
|
|
500
|
+
const sessionNow = scope === 'session' ? getSessionProxy(sessionKey) : null;
|
|
501
|
+
const effectiveActive = scope === 'session' ? (sessionNow?.main || null) : getActiveProfileId();
|
|
424
502
|
const activeProfile = incoming.profiles?.find(p => p.id === effectiveActive) || null;
|
|
425
503
|
const maskedProfile = activeProfile?.apiKey ? { ...activeProfile, apiKey: deps.maskApiKey(activeProfile.apiKey) } : activeProfile;
|
|
426
|
-
|
|
504
|
+
const globalActive = getGlobalDefaultProfileId();
|
|
505
|
+
if (scope === 'session') {
|
|
506
|
+
const targets = filterClientsByInstance(deps.clients, sessionKey);
|
|
507
|
+
sendEventToClients(targets, 'proxy_profile', { active: effectiveActive, profile: maskedProfile, instanceKey: sessionKey, roles: sessionNow ? sessionBindingRoles(sessionNow) : undefined, globalActive });
|
|
508
|
+
} else {
|
|
509
|
+
sendEventToClients(deps.clients, 'proxy_profile', { active: effectiveActive, profile: maskedProfile, roles: getStoredRoles(), global: true, globalActive });
|
|
510
|
+
}
|
|
427
511
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
428
|
-
res.end(JSON.stringify({ ok: true }));
|
|
512
|
+
res.end(JSON.stringify({ ok: true, scope: scope || 'global', active: effectiveActive, globalActive }));
|
|
429
513
|
} catch {
|
|
430
514
|
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
431
515
|
res.end(JSON.stringify({ error: 'Invalid JSON' }));
|