cc-viewer 1.9.39 → 1.9.40

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.
@@ -0,0 +1,99 @@
1
+ // Per-platform proxy-profile pin for IM SDK workers.
2
+ //
3
+ // An IM worker binds its interceptor workspace from process.cwd() (= IM_<id>) the moment
4
+ // server/proxy.js → server/interceptor.js is imported, and reads <LOG_DIR>/IM_<id>/
5
+ // active-profile.json at module top. So the pin must be written BEFORE that import — cli.js
6
+ // calls applyImProxyProfile() just before importing proxy.js.
7
+ //
8
+ // Source of truth: the platform's config (`preferences.json.<platform>.proxyProfileId`). The
9
+ // workspace file is a projection of that config, re-asserted on every boot. We deliberately do
10
+ // NOT reuse interceptor's _writeWorkspaceActive (private, returns bool, swallows) or
11
+ // mergeActivePayload for the clear path: mergeActivePayload coerces a non-string activeId to
12
+ // 'max' (an explicit Default pin), which cannot express "clear the override and follow global".
13
+ // Omitting the activeId key restores the global fallback (see _readWorkspaceActive, which only
14
+ // honors a string activeId). Reads/writes go through the shared json-store kernel (atomic, 0600).
15
+ //
16
+ // "Unset" vs "explicitly cleared": an empty config pin is ambiguous — it is both the factory
17
+ // state and the value after a user clears the selector. A marker file (.proxy-pin-bootstrapped)
18
+ // records that first-boot adoption has already run: before the marker, an existing workspace pin
19
+ // (set via the worker's own proxy UI) is ADOPTED into the config rather than discarded; after the
20
+ // marker, an empty config authoritatively clears the override.
21
+ import { join } from 'node:path';
22
+ import { existsSync, writeFileSync } from 'node:fs';
23
+ import { reportSwallowed } from '../error-report.js';
24
+ import { readJsonStrict, writeJsonAtomic } from '../json-store.js';
25
+ import { normalizeRoles } from '../interceptor-core.js';
26
+ import { loadConfig, saveConfig } from './im-config.js';
27
+ import { imDir } from './im-lock.js';
28
+ import { LOG_DIR } from '../../../findcc.js';
29
+
30
+ const BOOTSTRAP_MARK = '.proxy-pin-bootstrapped';
31
+
32
+ function profileIdsOrNull() {
33
+ // null = profile.json absent/unreadable (unknown, not "empty").
34
+ const file = join(LOG_DIR, 'profile.json');
35
+ const r = readJsonStrict(file);
36
+ if (r.state === 'corrupt') {
37
+ reportSwallowed('im-proxy-profile.read-profile-json', new Error(`profile.json unreadable: ${file}`));
38
+ return null;
39
+ }
40
+ if (r.state !== 'ok') return null;
41
+ return new Set((r.data?.profiles || []).filter((p) => p && typeof p.id === 'string').map((p) => p.id));
42
+ }
43
+
44
+ function markBootstrapped(id) {
45
+ try { writeFileSync(join(imDir(id), BOOTSTRAP_MARK), '', { mode: 0o600 }); }
46
+ catch (err) { reportSwallowed('im-proxy-profile.bootstrap-mark', err); } // best-effort
47
+ }
48
+
49
+ // Persist the platform's pinned proxy profile into the worker's workspace active-profile.json.
50
+ // Returns { applied: 'noop'|'pinned'|'cleared'|'adopted', file }. Throws only when the atomic
51
+ // write fails; the caller (worker boot) treats that as non-fatal and falls back to the
52
+ // existing/global profile.
53
+ export function applyImProxyProfile(id, profileId) {
54
+ const file = join(imDir(id), 'active-profile.json');
55
+ const pin = typeof profileId === 'string' ? profileId.trim() : '';
56
+
57
+ // Structured read: missing / ok / corrupt. A corrupt file is repaired below with a clean
58
+ // payload — data-loss class, must be reported (throttled).
59
+ const r = readJsonStrict(file);
60
+ if (r.state === 'corrupt') {
61
+ reportSwallowed('im-proxy-profile.read-workspace-active', new Error(`active-profile.json unreadable: ${file}`));
62
+ }
63
+ const existing = r.state === 'ok' ? r.data : null;
64
+ // Merge-preserve roles: the worker's own Web UI may own subagent/teammate assignments.
65
+ const roles = normalizeRoles(existing?.roles);
66
+ const existingPin = (typeof existing?.activeId === 'string' && existing.activeId) ? existing.activeId : '';
67
+ const bootstrapped = existsSync(join(imDir(id), BOOTSTRAP_MARK));
68
+
69
+ if (!pin) {
70
+ if (existingPin && r.state === 'ok' && !bootstrapped) {
71
+ // First boot with an empty config but a runtime-set workspace pin: adopt it into the config
72
+ // (so the upgrade never silently discards the user's choice), then config is authoritative.
73
+ try { saveConfig(id, { ...loadConfig(id), proxyProfileId: existingPin }); }
74
+ catch (err) { reportSwallowed('im-proxy-profile.adopt-pin', err); } // non-fatal: keep the runtime pin this boot
75
+ markBootstrapped(id);
76
+ return { applied: 'adopted', file };
77
+ }
78
+ markBootstrapped(id);
79
+ if (!existingPin && r.state !== 'corrupt') return { applied: 'noop', file }; // follow global, nothing to clear
80
+ // Empty config AFTER bootstrap (or a corrupt file) ⇒ authoritatively clear: omit activeId.
81
+ writeJsonAtomic(file, { roles }, { mode: 0o600 });
82
+ return { applied: 'cleared', file };
83
+ }
84
+
85
+ // A non-empty config pin is authoritative; it also settles the bootstrap state.
86
+ markBootstrapped(id);
87
+ if (pin !== 'max') {
88
+ const ids = profileIdsOrNull();
89
+ // Unknown id: the interceptor resolves a dangling workspace activeId to Default and the
90
+ // session seed degrades to legacy main (also Default). Keep the pin so it auto-resumes if
91
+ // the profile is re-created; record it for diagnosis. profile.json unreadable → skip.
92
+ if (ids && !ids.has(pin)) {
93
+ reportSwallowed('im-proxy-profile.unknown-profile',
94
+ new Error(`IM ${id} pinned proxy profile "${pin}" not in profile.json — worker will fall back to Default`));
95
+ }
96
+ }
97
+ writeJsonAtomic(file, { activeId: pin, roles }, { mode: 0o600 });
98
+ return { applied: 'pinned', file };
99
+ }
@@ -105,6 +105,10 @@ function dingtalkConfigPost(req, res, parsedUrl, isLocal, deps) {
105
105
  cardTemplateId: incoming.cardTemplateId,
106
106
  aiCardTemplateId: incoming.aiCardTemplateId,
107
107
  aiCardStreamKey: incoming.aiCardStreamKey,
108
+ // Pass through the proxy-profile pin; a client that predates the field omits it, which would
109
+ // let normalize() reset it to ''. Preserve the stored value in that case (mirrors the
110
+ // secret-field "empty = keep" convention) so a legacy full save cannot silently clear the pin.
111
+ proxyProfileId: 'proxyProfileId' in incoming ? incoming.proxyProfileId : loadDingTalkConfig().proxyProfileId,
108
112
  });
109
113
  // 驱动进程管理器(替代旧的在进程 reloadBridge):启用→重启 worker,停用→停 worker。
110
114
  try {
@@ -186,6 +186,10 @@ function imConfigPost(req, res, parsedUrl, isLocal, deps) {
186
186
  const incomingObj = (incoming && typeof incoming === 'object' && !Array.isArray(incoming)) ? incoming : {};
187
187
  const touchesOthers = desc.fields.some((f) => f.key !== 'enabled' && f.key in incomingObj);
188
188
  const effective = touchesOthers ? incomingObj : { ...loadConfig(id), enabled: !!incomingObj.enabled };
189
+ // Preserve the proxy-profile pin across full saves from a client that predates the field (a
190
+ // stale browser bundle / older API caller): absent from the body must not reset it to ''.
191
+ // Mirrors the secret-field "empty = keep" convention so the pin survives version skew.
192
+ if (!('proxyProfileId' in effective)) effective.proxyProfileId = loadConfig(id).proxyProfileId;
189
193
  if (effective.enabled) warnIfEmptyAllowlist(id, effective);
190
194
  const saved = saveConfig(id, effective);
191
195
  // applyProcess(默认 true,保持旧调用方语义):前端 onBlur 自动保存传 false → 仅存盘、不驱动进程,