Repository navigation
Expand file tree
/
Copy pathextension.js
More file actions
2592 lines (2554 loc) · 160 KB
/
Copy pathextension.js
File metadata and controls
2592 lines (2554 loc) · 160 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// BSD 3-Clause License
// Copyright (c) 2026, Xnerv Wang
// All rights reserved.
'use strict';
/*
* Claude Code Plus - user interface additions for the Claude Code panel in VS Code.
*
* This extension owns no user interface of its own. It patches the Claude Code extension's own files at rest, one
* adapter per target file (see src/adapters.js), and every write is guarded the same way: match the expected code
* shape exactly once or write nothing, keep the untouched original beside the file, replace atomically, and put the
* original back on Remove or uninstall. A Claude Code build whose shape does not match is reported and left alone.
*
* Because the patch lives in files the editor has already loaded, installing or upgrading it asks for one reload.
* After that, turning the marks off and changing the message color take effect live, through the stylesheet written
* next to the panel (see src/live.js).
*/
const vscode = require('vscode');
const cp = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const webview = require('./src/webview');
const host = require('./src/host');
const { safeColor } = webview;
const { readTasks, taskDirs } = require('./src/tasks');
const background = require('./src/background');
const { createMapStop } = require('./src/map-stop');
const planNames = require('./src/plan-names');
const stewardView = require('./src/steward-view');
const relay = require('./src/relay');
const stewardMarks = require('./src/steward-marks');
const titleMarks = require('./src/title-marks');
const envelope = require('./src/envelope');
const stewards = require('./src/stewards');
const stewardLeads = require('./src/steward-leads');
const stewardKeys = require('./src/steward-keys');
const detachedEnds = require('./src/detachedends');
const bgEnds = require('./src/bgends');
const stoppedWork = require('./src/stoppedwork');
const replyImages = require('./src/reply-images');
const conversationLinks = require('./src/conversation-links');
const supervisorBadge = require('./src/supervisor-badge');
const planBars = require('./src/plan-bar');
const replyFigures = require('./src/reply-figures');
const modelMemory = require('./src/model-memory');
const efforts = require('./src/efforts');
const { sweepOrphans, planDir, readPlan } = require('./src/workplan');
const { transcriptOf, projectsDir, projectFolders, claudeDir, writeAtomic } = require('./src/claude-files');
const planInjections = require('./src/plan-injections');
const tokenMode = require('./src/token-mode');
const noticeTime = require('./src/notice-time');
const waiting = require('./src/waiting');
const waitingFor = require('./src/waiting-for');
const { createClaudeSource, isPanelTab, ANSWER_GO_WAIT_MS, ANSWER_SEND_MS, ID: CLAUDE_SOURCE_ID } = require('./src/claude-source');
const temporaryConversations = require('./src/temporary');
const { agentOfTab } = require('./src/other-agents');
const coreLink = require('./src/core-link');
const hookSettings = require('./src/hook-settings');
const pluginInstall = require('./src/plugin-install');
const pythonRuntime = require('./src/python-runtime');
const pythonOffer = require('./src/python-offer');
const latency = require('./src/openlatency');
const tabdot = require('./src/tabdot');
const activity = require('./src/activity');
const { goneStates } = require('./src/gone-states');
const sessionPins = require('./src/sessionpins');
const sessionColors = require('./src/sessioncolors');
const bgSessions = require('./src/bgsessions');
const droppedTabs = require('./src/droppedtabs');
const loadTabs = require('./src/load-tabs');
const panelRebuild = require('./src/panel-rebuild');
const retitleHost = require('./src/retitle');
/* The fifth argument of claude-vscode.editor.open. Claude Code's own session list opens conversations as full editor
tabs, without a title row of their own. */
const AS_FULL_EDITOR = true;
const loadMarks = require('./src/load-marks');
const duplicates = require('./src/duplicates');
const deleteSession = require('./src/deletesession');
const ADAPTERS = require('./src/adapters');
const removal = require('./src/removal');
const buildDigest = require('./src/build-digest');
const carryover = require('./src/carryover');
const unsupported = require('./src/unsupported');
const sentCheck = require('./src/sent-check');
const officialList = require('./src/official-list');
const claudeSessionList = require('./src/claude-session-list');
const titleRecord = require('./src/title-record');
const claudeLogin = require('./src/claude-login');
const claudeElsewhere = require('./src/claude-elsewhere');
const catchUp = require('./src/catch-up');
const sessionTotalsOf = require('./src/session-totals');
const PACKAGE = require('./package.json');
/* <publisher>.<name>, which is also how the editor names this extension's folders. Read from the manifest rather than
from the editor's API because deactivate needs it, and by then that API is gone. */
const ID = PACKAGE.publisher + '.' + PACKAGE.name;
/* Where this copy is installed, kept for deactivate for the same reason. */
let selfPath = '';
/* Settings and commands are named under this prefix. The keys this extension keeps in its own state are not settings,
are not seen by anyone, and keep the names they were first stored under. */
const PREFIX = 'claudeCodePlus.';
/* Earlier prefixes of settings and commands, newest first. */
const LEGACY_PREFIXES = ['claudeCodeWorkPlan.', 'claudeCodeExtras.'];
const SETTING = PREFIX + 'enabled';
const COLOR_SETTING = PREFIX + 'userMessageColor';
const EDGE_SETTING = PREFIX + 'userMessageEdge';
const REMOVED_KEY = 'claudeCodeExtras.removed';
const PLUGIN_KEY = 'claudeCodeExtras.workPlanPlugin';
const SWEEP_KEY = 'claudeCodeExtras.lastOrphanSweep';
const LATENCY_KEY = 'claudeCodeExtras.latencyOffset';
const THRESHOLD_SETTING = PREFIX + 'latencyThresholdSeconds';
const LATENCY_ON_SETTING = PREFIX + 'recordOpenLatency';
const PIN_MARGIN_SETTING = PREFIX + 'sessionPinsMarginDays';
const REOPEN_SETTING = PREFIX + 'reopenDroppedTabs';
const LOAD_TABS_SETTING = PREFIX + 'loadRestoredTabs';
const MODEL_SETTING = PREFIX + 'rememberModelPerConversation';
const HIDE_BG_SETTING = PREFIX + 'hideBackgroundSessions';
const HIDE_OFFICIAL_LIST_SETTING = PREFIX + officialList.SETTING;
/* The command the Hide It and Keep It buttons above Agent Plus's session list run; it is not in the Command Palette. */
const OFFICIAL_LIST_ANSWER = 'answerOfficialListQuestion';
const WORK_PLAN_SETTING = PREFIX + 'workPlan';
const BRIEF_SETTING = PREFIX + 'conversationBrief';
const TIME_ZONE_SETTING = PREFIX + 'tellClaudeYourTimeZone';
/* The four settings that agentPlus.tokenMode overrides outside Custom (src/token-mode.js); each is read through runs(). */
const MODE_SWITCHES = tokenMode.SWITCHES.filter((s) => s.key.startsWith(PREFIX)).map((s) => s.key);
const runs = (key) => tokenMode.effective(vscode, key);
/* Read by the plugin's hooks, which are separate processes and cannot see editor settings. Keys match plan_path.py.
package.json makes them application settings, since they go into one file that every conversation on the machine
reads. */
const HOOK_SETTINGS = {
enabled: WORK_PLAN_SETTING,
offerMinTurns: PREFIX + 'workPlanOfferMinTurns',
offerMinToolCalls: PREFIX + 'workPlanOfferMinToolCalls',
quietWhenReplyMatches: PREFIX + 'workPlanQuietWhenReplyMatches',
tellTimeZone: TIME_ZONE_SETTING,
brief: BRIEF_SETTING,
};
/*
* Memoize `read()` for the current turn of the event loop. A timer or event handler asks for the same value several
* times while it runs, and it is computed once per turn.
*/
function perTick(read) {
let value, have = false;
return () => {
if (!have) { value = read(); have = true; setImmediate(() => { have = false; }); }
return value;
};
}
/* Which folders of an extensions directory the editor has marked for deletion, read once per turn of the event loop. */
const marks = new Map();
function markedIn(root) {
if (!marks.size) setImmediate(() => marks.clear());
if (!marks.has(root)) marks.set(root, removal.obsolete(root));
return marks.get(root);
}
/*
* Every install of Claude Code this adapter can see: the one this window runs plus sibling versions in the same folder,
* less the siblings the editor has marked for deletion, which nobody will run again. `all` keeps those too, for taking
* our changes back out: a marked folder can still carry them until the editor deletes it.
*/
function installs(adapter, all = false) {
const ext = vscode.extensions.getExtension(adapter.id);
if (!ext) return [];
const root = path.dirname(ext.extensionPath);
const found = Array.from(new Set([ext.extensionPath, ...adapter.findInstalls(root)]));
return all ? found : removal.unmarked(found, ext.extensionPath, markedIn(root));
}
/* The editor's settings as last read. Reading them builds a merged copy of every scope, and a tick asks for a couple of
dozen values, so the copy is kept until the editor reports a change, when start() drops it. */
let settings = null;
const cfg = () => settings || (settings = vscode.workspace.getConfiguration());
function enabled() { return cfg().get(SETTING, true); }
/* "A", "A and B", "A, B and C". */
const listed = (xs) => (xs.length < 3 ? xs.join(' and ') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);
async function offerReload(text) {
const pick = await noticeTime.info(vscode, text, 'Reload Window');
if (pick === 'Reload Window') vscode.commands.executeCommand('workbench.action.reloadWindow');
}
/* A keybinding made before a rename names a command under an old prefix, so the old names stay registered, unlisted.
The editor refuses a name that another extension in this host holds already, as the old extension does until the host
restarts after it was updated, and that name is left to it. */
function registerCommand(name, fn) {
const all = [vscode.commands.registerCommand(PREFIX + name, fn)];
for (const p of LEGACY_PREFIXES) {
try { all.push(vscode.commands.registerCommand(p + name, fn)); } catch (_) { /* held by another extension */ }
}
return { dispose() { for (const d of all) d.dispose(); } };
}
/*
* Settings were once named under the old prefixes. A value set under an old name is copied to its new name, in the same
* scope, from the more recent prefix when both have one. The old ones are then cleared where the editor allows that;
* it may refuse to write a name no extension declares any more, and then the old line is left in place.
*
* A copy is made only where the new name has no value of its own, so nothing set under the new name is overwritten; and
* each scope is done once, so putting a new name back to its default later does not bring the old value back.
*/
const RENAMED_KEY = PREFIX + 'settingsRenamed';
async function renameSettings(context) {
const contrib = (context.extension.packageJSON.contributes || {}).configuration || {};
const names = [].concat(contrib).flatMap((c) => Object.keys((c && c.properties) || {}))
.filter((k) => k.startsWith(PREFIX)).map((k) => k.slice(PREFIX.length));
/* An application setting cannot be written to a workspace or folder, so those scopes skip it. An old name's value
there is left alone and does nothing. */
const userOnly = new Set([].concat(contrib).flatMap((c) => Object.entries((c && c.properties) || {}))
.filter(([, v]) => v && v.scope === 'application').map(([k]) => k.slice(PREFIX.length)));
const T = vscode.ConfigurationTarget;
const groups = [];
const all = () => vscode.workspace.getConfiguration();
if (!context.globalState.get(RENAMED_KEY)) {
groups.push({ state: context.globalState,
scopes: [{ where: 'user', target: T.Global, field: 'globalValue', conf: all }] });
}
const folders = vscode.workspace.workspaceFolders || [];
if (folders.length && !context.workspaceState.get(RENAMED_KEY)) {
const inFolder = (f) => ({ where: 'folder ' + f.name, target: T.WorkspaceFolder, field: 'workspaceFolderValue',
conf: () => vscode.workspace.getConfiguration(undefined, f.uri) });
groups.push({ state: context.workspaceState,
scopes: [{ where: 'workspace', target: T.Workspace, field: 'workspaceValue', conf: all }].concat(folders.map(inFolder)) });
}
const done = [];
for (const g of groups) {
let complete = true;
for (const sc of g.scopes) {
const conf = sc.conf();
let moved = 0, left = 0;
for (const name of names) {
if (sc.target !== T.Global && userOnly.has(name)) continue;
const found = LEGACY_PREFIXES.map((p) => {
const old = conf.inspect(p + name);
return { key: p + name, value: old ? old[sc.field] : undefined };
}).filter((o) => o.value !== undefined);
if (!found.length) continue;
const now = conf.inspect(PREFIX + name);
try {
if (!now || now[sc.field] === undefined) await conf.update(PREFIX + name, found[0].value, sc.target);
moved++;
} catch (_) { complete = false; continue; }
for (const o of found) { try { await conf.update(o.key, undefined, sc.target); } catch (_) { left++; } }
}
if (moved) done.push(`${moved} in ${sc.where}` + (left ? ` (${left} old line${left > 1 ? 's' : ''} left in place)` : ''));
}
if (complete) await g.state.update(RENAMED_KEY, true);
}
return done.join(', ');
}
/* The pins and colors chosen under the old id (src/carryover.js), copied before anything here reads its own. */
function carryOver(context, log) {
try {
const r = carryover.copyFiles(context.globalStorageUri.fsPath, [sessionPins.FILE, sessionColors.FILE]);
if (r.copied.length) log.appendLine(`copied from ${carryover.LEGACY_ID}: ${r.copied.join(', ')}`);
if (r.failed.length) log.appendLine(`could not copy from ${carryover.LEGACY_ID}: ${r.failed.join(', ')}`);
} catch (e) { log.appendLine('copying from ' + carryover.LEGACY_ID + ': ' + e.message); }
}
/*
* An earlier version of the old extension (src/carryover.js) patches Claude Code with its own build, and two extensions
* doing that take turns rewriting the same files. Until it is updated or uninstalled nothing here starts, since the old
* one still owns the patch, the plugin and the settings. Its commands share names with ours, and are left to it. The
* first start after it is gone runs as usual.
*/
const TOLD_KEY = PREFIX + 'toldEarlierBuild';
/* How long the first start waits for export.json from the old id's last version. */
const EXPORT_WAIT_MS = 20000;
/* How often the supervisors' titles and leads are looked at for Agent Plus (stewardsOfKey). */
const STEWARD_ORDER_MS = 5000;
function standAside(context, log, version) {
log.appendLine(`Work Plan for Claude Code ${version} (${carryover.LEGACY_ID}) is still installed and patches Claude Code itself; `
+ 'this extension does nothing until it is updated or uninstalled');
const tell = () => noticeTime.warning(vscode,
'An earlier version of Work Plan for Claude Code is installed. Update or uninstall it to use Claude Code Plus; your work plans come back after uninstall.',
'Show It',
).then((pick) => { if (pick === 'Show It') showOldExtension(); }, () => {});
for (const c of (context.extension.packageJSON.contributes || {}).commands || []) {
context.subscriptions.push(vscode.commands.registerCommand(c.command, tell));
}
if (context.globalState.get(TOLD_KEY) === version) return;
Promise.resolve(context.globalState.update(TOLD_KEY, version)).catch(() => {});
tell();
}
/* The old extension's page in the Extensions view, where it can be updated or uninstalled; a search for its id when the
editor cannot open the page. */
function showOldExtension() {
return Promise.resolve(vscode.commands.executeCommand('extension.open', carryover.LEGACY_ID))
.catch(() => vscode.commands.executeCommand('workbench.extensions.search', '@id:' + carryover.LEGACY_ID))
.then(undefined, () => {});
}
/*
* The old id's last version does nothing, and once this extension runs in its place it can be uninstalled. The question
* is not asked at a start that asks for a reload, so that reload comes first. It is asked again at later starts until
* its button is used.
*/
const TOLD_OLD_KEY = PREFIX + 'toldUninstallOld';
function offerUninstallOld(context) {
if (context.globalState.get(TOLD_OLD_KEY) === true) return;
noticeTime.info(vscode,
'Claude Code Plus is now running. Work Plan for Claude Code is still installed but no longer does anything; you can uninstall it from its Extensions page.',
'Show Extension',
).then((pick) => {
if (pick !== 'Show Extension') return;
Promise.resolve(context.globalState.update(TOLD_OLD_KEY, true)).catch(() => {});
showOldExtension();
}, () => {});
}
/*
* In Restricted Mode nothing starts until the workspace is trusted: everything this extension does writes files or runs
* Claude Code's command line. deactivate() still restores Claude Code's files on an uninstall, in Restricted Mode too.
*/
async function activate(context) {
selfPath = context.extensionPath;
const log = vscode.window.createOutputChannel('Claude Code Plus');
context.subscriptions.push(log);
let earlier = '', handing = false;
try {
const old = vscode.extensions.getExtension(carryover.LEGACY_ID);
earlier = carryover.earlierBuild(old);
handing = !!old && !earlier;
} catch (_) { /* not there */ }
if (earlier) { standAside(context, log, earlier); return; }
/* The title of a tab Claude Code creates without one of its own (src/host.js). The log line tells, after a tab came
back empty, whether it was opened with its conversation's title. */
globalThis.__cceTitleOf = (sessionId) => {
let title = '';
try { title = claudeSessionList.titleOf(sessionId); } catch (_) { title = ''; }
log.appendLine(`new tab for ${String(sessionId).slice(0, 8)}: ${title ? "its conversation's title" : "no title found, so Claude Code's default"}`);
return title;
};
context.subscriptions.push({ dispose: () => { delete globalThis.__cceTitleOf; } });
/* The old id's last version writes export.json when it activates, and the editor activates it only after this
activation has returned, since it depends on this extension. So the start waits for the file, and activation does
not wait for the start. */
const storage = context.globalStorageUri.fsPath;
const exported = path.join(carryover.legacyStorage(storage), carryover.EXPORT_FILE);
const waiting = handing && !fs.existsSync(exported);
const go = async () => {
if (waiting && !(await carryover.waitFor(exported, EXPORT_WAIT_MS))) {
log.appendLine(`${carryover.LEGACY_ID} wrote no ${carryover.EXPORT_FILE} within ${EXPORT_WAIT_MS / 1000}s; starting without it`);
}
try {
const taken = await carryover.importState(context.globalState, storage);
if (taken.length) log.appendLine(`taken from ${carryover.LEGACY_ID}: ${taken.join(', ')}`);
} catch (e) { log.appendLine(`reading ${exported}: ${e && e.message}`); }
carryOver(context, log);
let renamed = '';
try { renamed = await renameSettings(context); } catch (e) { renamed = 'failed: ' + (e && e.message); }
await start(context, log, renamed, handing);
};
if (vscode.workspace.isTrusted !== false) {
const started = go();
if (waiting) started.catch((e) => log.appendLine('starting: ' + ((e && e.stack) || e)));
else await started;
return;
}
log.appendLine('Restricted Mode: nothing starts until this workspace is trusted');
let started = false;
const trusted = vscode.workspace.onDidGrantWorkspaceTrust(() => {
if (started) return;
started = true;
go().catch((e) => log.appendLine('starting once trusted: ' + ((e && e.stack) || e)));
});
context.subscriptions.push(trusted);
}
function start(context, log, renamed, handing = false) {
if (renamed) log.appendLine(`settings moved from ${LEGACY_PREFIXES.map((p) => p + '*').join(' and ')} to ${PREFIX}*: ${renamed}`);
const removed = () => context.globalState.get(REMOVED_KEY, false) === true;
/*
* Install state of the copy this window runs (src/removal.js), memoized per turn of the event loop.
*
* Uninstalling: the editor has marked it for deletion with no other version staying, and waits for this window to
* restart its extensions. Until then it must not re-patch files another window has just restored.
*
* Replaced: another build of this extension is installed now (another version beside it, or the same version again
* over it) while this window keeps running this one. It then leaves every shared file alone; the windows that reload
* run the installed build and keep those files current. If the same package is installed again over this copy and no
* file differs from what this window loaded, the window adopts the new install stamp and carries on.
*/
let loadedStamp = removal.installStamp(context.extensionPath);
const loadedCode = buildDigest.digest(context.extensionPath);
let comparedStamp = 0;
const standing = perTick(() => {
const root = path.dirname(context.extensionPath), marked = markedIn(root);
const s = removal.standing(context.extensionPath, ID, loadedStamp, marked);
if (s !== 'replaced' || marked[path.basename(context.extensionPath)] === true || !loadedCode) return s;
const now = removal.installStamp(context.extensionPath);
if (!now || now === comparedStamp) return s;
comparedStamp = now;
if (buildDigest.digest(context.extensionPath) !== loadedCode) return s;
log.appendLine('the same package was installed again over this copy; this window keeps its part');
loadedStamp = now;
return '';
});
const uninstalling = () => standing() === 'uninstalling';
const replaced = () => standing() === 'replaced';
/* Whether this window keeps the state all windows share about running work: which conversation started which
background session, what runs now, and the ends of detached commands and background sessions with their notices. A
window running the installed build keeps it. So does a window whose build an install has replaced, as long as no
window runs the installed build; the supervisors table follows the same rule (src/steward-view.js writesTable).
Otherwise, while every window runs an earlier build, a conversation is told that its work ended only once a window
is reloaded, which can be hours later. */
let keepsShared = () => false;
const keepsWork = () => !uninstalling() && !removed() && (!replaced() || keepsShared());
const knownDirs = perTick(() => taskDirs(background.liveRecords()));
/* One setting per switchable addition, named after it. Reading them here rather than in src/webview.js keeps that
file free of the editor's API, which is what lets the tests run it. */
const switchedOff = () => webview.SWITCHES.filter((k) => cfg().get(PREFIX + 'show.' + k, true) === false);
/* The conversations pinned in the session list (src/sessionpins.js). The file is in this extension's storage on the
machine that holds the transcripts, and every window reads and writes the same one. */
const pinsFile = () => path.join(context.globalStorageUri.fsPath, sessionPins.FILE);
const pinsOn = () => !removed();
const pinMargin = () => cfg().get(PIN_MARGIN_SETTING, sessionPins.MARGIN_DAYS);
const colorsFile = () => path.join(context.globalStorageUri.fsPath, sessionColors.FILE);
/* Conversations run by several editor processes (src/duplicates.js), refreshed with the background work, and the
time of the last heartbeat from a page of this window's panels (src/page/99-sweep.js). */
let dupGroups = new Map(), pageAt = 0;
/* The test src/duplicates.js makes of this host's window entry, so that this host stops claiming its conversations
when other windows start treating it as having no window. */
const windowless = () => pageAt > 0 && Date.now() - pageAt > duplicates.NO_PAGE_MS;
const options = () => {
const off = switchedOff();
return {
enabled: enabled(), userColor: cfg().get(COLOR_SETTING, ''), userEdge: cfg().get(EDGE_SETTING, true) !== false,
off,
tasks: readTasks(knownDirs()),
background: off.includes('backgroundSessions') ? [] : background.collect(),
workers: off.includes('backgroundSessions') ? [] : background.workersNow() || [],
detached: off.includes('detachedCommands') ? [] : background.jobRows({ jobs: background.jobsNow() || [] }),
supervisor: supervisorBadge.live(cfg().get(PREFIX + supervisorBadge.SETTING, 'auto'), vscode.env.language),
foldLines: cfg().get(PREFIX + webview.FOLD_LINES_SETTING, webview.FOLD_LINES),
};
};
/* Never after Remove, which has just taken these files out of Claude Code's folder: a scan finishing afterwards would
put them back. */
/* A failed write is tried again a second later, up to five times, rather than waiting for the next change; a counter
the failed write could not move is moved by the next try (src/webview.js). */
let liveAgain = 0, liveFails = 0;
let liveAfterScan = false;
/* Tells this window's panels when any window rewrites the files beside Claude Code's panel (src/rev-watch.js): all of
them when the settings change, and a conversation's own panels when its work or efforts change. It watches the
folders this window writes the live files into. */
/* The message carries the two revisions, read from the revision image of the Claude Code install this window's panels
load from, so that a panel learns them without loading anything (src/page/05-page-setup.js says why it cannot). */
const styleRev = () => {
const dir = installs(webview)[0];
const r = dir ? webview.readRev(webview.liveFiles(dir).rev) : { w: 0, h: 0 };
return { type: 'cce_style_rev', w: r.w, h: r.h };
};
const tellAllRevs = () => { if (typeof globalThis.__cceToAllPanels === 'function') globalThis.__cceToAllPanels(styleRev()); };
const revWatch = require('./src/rev-watch').create({
name: webview.LIVE_REV, css: webview.LIVE_CSS,
tellAll: tellAllRevs,
tellSession: (id) => { if (typeof globalThis.__cceToPanel === 'function') globalThis.__cceToPanel(id, styleRev()); },
log: (m) => log.appendLine(m),
});
/* A panel asks when it starts or gets the focus. The answer goes to the panels of the conversation it names, or to
every panel of the window when it names none yet; a panel that missed the latest change loads the stylesheet again
when the answer reaches it. */
globalThis.__cceStyleRevAskHook = (sessionId) => {
try {
const sent = sessionId && typeof globalThis.__cceToPanel === 'function' && globalThis.__cceToPanel(sessionId, styleRev()) === true;
if (!sent) tellAllRevs();
} catch (e) { log.appendLine('revision answer: ' + e.message); }
};
context.subscriptions.push({ dispose: () => { revWatch.dispose(); delete globalThis.__cceStyleRevAskHook; } });
/* Panels restored with the window can start, and ask, before this extension is running to answer; they are told once
the first write is done. */
let revsToldOnce = false;
/* Written by a replaced window too: until a window runs the installed build, nobody else writes it, and the agent map
would keep the background sessions, scheduled prompts and detached commands as they were at the install. A window
of the installed build that writes it first is not overwritten (writeLive). */
const writeLiveNow = () => {
if (!keepsWork()) { revWatch.watch([]); return; }
liveAfterScan = false;
try {
const opts = options();
const dirs = installs(webview);
revWatch.watch(dirs.map((dir) => path.dirname(webview.liveFiles(dir).rev)).filter((d) => fs.existsSync(d)));
for (const dir of dirs) webview.writeLive(dir, opts);
liveFails = 0;
if (!revsToldOnce) { revsToldOnce = true; tellAllRevs(); }
} catch (e) {
log.appendLine('live refresh failed: ' + e.message);
if (!liveAgain && ++liveFails <= 5) liveAgain = setTimeout(() => { liveAgain = 0; writeLiveNow(); }, 1000);
}
};
/* Reads what the conversation in front of the reader has added to its transcript since last time - the only one, since
that is the one being looked at; the others were read when they were. A new session is written out at once rather
than at the next refresh, so it appears in the agent map while the launch is still on screen. */
/* Where each reply's effort changed, for the conversation in front of the reader, written beside the panel for it to
read (src/efforts.js). Not read at all when the model is switched off, since the effort is shown with it. */
const scanEffort = (opts) => {
if (!enabled() || !keepsWork() || switchedOff().includes('modelName')) return;
const id = activeChat();
if (!id) return;
efforts.scan(id, opts || {})
.then((r) => {
// Asked again: the scan may have finished after Remove, or once a window runs the installed build.
if (!r || !r.css || !keepsWork()) return;
for (const dir of installs(webview)) webview.writeEffort(dir, id, r.css);
})
.catch((e) => log.appendLine('reply efforts: ' + e.message));
};
/* Where Claude Code's own command line can be found: its binary ships inside each install. */
const claudeFolders = () => Array.from(new Set(ADAPTERS.flatMap((adapter) => installs(adapter))));
/* A replaced window (running an older build than the installed one) still scans so its own tabs keep their green
dots, and writes what it found only when keepsWork allows. */
const scanBackground = () => {
if (removed() || !enabled() || uninstalling() || switchedOff().includes('backgroundSessions')) return;
const id = activeChat();
if (!id) return;
const write = keepsWork();
background.scan(id, { write })
.then((r) => { if (r && r.added && write) writeLiveNow(); })
.catch((e) => log.appendLine('background sessions: ' + e.message));
};
/* Set when a sync here has patched or restored Claude Code's files; either asks for a reload. */
let reloadOffered = false;
/* Bring every install in line with the current settings. Only installing, upgrading or removing the patch itself
asks for a reload; on and off and the color are picked up by an open panel within a couple of seconds. */
/* Set by each sync: true when every installed Claude Code panel has this build's patch, which draws images in
replies. */
let panelShowsImages = false;
async function sync({ interactive = false } = {}) {
if (replaced()) {
log.appendLine('sync: this window runs a build that has since been installed again; leaving the patch to the windows running it');
if (interactive) offerReload('This window is running an earlier build of Claude Code Plus than the one now installed. Reload the window to run it.');
writeLiveNow();
return;
}
const patched = [], restored = [], problems = [], notSupported = new Set();
let panels = 0, panelsPatched = 0;
const leaving = uninstalling();
const restoring = removed() || leaving;
/* The live stylesheet's options, computed once and only for the panel's bundle (the host bundle ignores them),
since computing them reads the background sessions, the scheduled prompts and the pins. */
let opts = null;
let found = 0;
for (const adapter of ADAPTERS) {
for (const dir of installs(adapter, restoring)) {
found++;
const label = `${adapter.name} (${path.basename(dir)})`;
try {
if (restoring) {
const r = adapter.restore(dir);
log.appendLine(`${label}: ${r.message}`);
if (r.changed && !restored.includes(adapter.name)) restored.push(adapter.name);
} else {
const r = adapter.apply(dir, adapter === webview ? (opts || (opts = options())) : undefined);
log.appendLine(`${label}: ${r.message}${r.liveChanged ? ' (live settings updated)' : ''}`);
if (adapter === webview) { panels++; if (r.changed || r.current) panelsPatched++; }
if (r.changed && !patched.includes(adapter.name)) patched.push(adapter.name);
else if (!r.changed && !r.current) {
if (unsupported.isUnsupported(r.message)) notSupported.add(unsupported.versionOf(dir));
else problems.push(`${label}: ${r.message}`);
}
}
} catch (e) {
problems.push(`${label}: ${e.message}`);
log.appendLine(`${label}: error ${e.stack || e.message}`);
}
}
}
if (!found && interactive) noticeTime.warning(vscode, 'Claude Code Plus: the Claude Code extension is not installed, so there is nothing to patch.');
const showing = !restoring && panels > 0 && panelsPatched === panels;
if (showing !== panelShowsImages) { panelShowsImages = showing; writeHookSettings(); }
// Shown in the editor's display language; which rule failed is only in the output channel. Not awaited: a message
// with a button stays open.
if (notSupported.size) {
const details = vscode.l10n.t(unsupported.DETAILS);
noticeTime.warning(vscode, vscode.l10n.t(unsupported.MESSAGE, [...notSupported].join(', ')), details)
.then((pick) => { if (pick === details) log.show(true); }, () => {});
}
if (problems.length) noticeTime.warning(vscode, 'Claude Code Plus: ' + problems.join(' | '));
if (patched.length) offerReload(`Claude Code Plus is installed in ${listed(patched)}. Reload the window once to start; after that, On/Off and colors change live.`);
if (patched.length || restored.length) reloadOffered = true;
// An uninstall already has the editor asking for a restart of its extensions; a second prompt would only compete.
if (restored.length && !leaving) offerReload(`Claude Code Plus was removed from ${listed(restored)}. Reload the window to finish.`);
}
/* No status bar item for on and off.
*
* There was one, reading "Extras: On". It promised more than the setting behind it does: off stops the additions being
* drawn, while the patch, the injected script, its poll and the hooks all stay - so a reader took it for a switch that
* turns this extension off, which is the Remove command. It also sat one click away in the left status bar, where
* hitting it by accident silently changed a global setting. The three commands remain for anyone who wants it.
*/
const setEnabled = async (value) => {
const unremoving = value && removed();
if (unremoving) await context.globalState.update(REMOVED_KEY, false);
if (enabled() === value) { await sync({ interactive: true }); return; }
await cfg().update(SETTING, value, vscode.ConfigurationTarget.Global);
// The setting reaches the live stylesheet only; coming back from Remove needs the patch put back in as well.
if (unremoving) await sync({ interactive: true });
};
context.subscriptions.push(
registerCommand('enable', () => setEnabled(true)),
registerCommand('disable', () => setEnabled(false)),
registerCommand('toggle', () => setEnabled(!(enabled() && !removed()))),
registerCommand('remove', async () => {
await context.globalState.update(REMOVED_KEY, true);
await sync({ interactive: true });
}),
registerCommand('status', () => {
const lines = [];
for (const adapter of ADAPTERS) for (const d of installs(adapter, true)) lines.push(`${adapter.name} ${path.basename(d)}: ${adapter.status(d)}`);
noticeTime.info(vscode, 'Claude Code Plus — ' + (lines.join(' | ') || 'Claude Code is not installed') + (removed() ? ' (removed)' : '')
+ ' | ' + tokenModeLine());
}),
/* Every setting this extension has, in the editor's own settings UI: search, per-workspace values, sync and a JSON
view come with it, and none of it is ours to maintain. */
/*
* Take the plugin out of Claude Code's own settings, which is the only way to stop its skill description being
* loaded - about a hundred tokens a session that the switch above cannot reach, because the switch only tells the
* plugin's hooks to do nothing while the plugin itself stays registered.
*
* A command rather than something the switch does, because this writes Claude Code's configuration rather than ours,
* and an extension that quietly edits another tool's settings is the behaviour nobody wants to discover later.
* `disable` and not `uninstall`: uninstalling takes the plugin's data directory with it, and that is where every
* conversation's plan lives.
*/
registerCommand('disableWorkPlanPlugin', async () => {
const yes = await noticeTime.warning(vscode,
'Stop Claude Code loading the work plan plugin? This edits Claude Code\'s own settings, and saves the skill '
+ 'description it loads every session. Your existing plans are left alone.',
{ modal: true }, 'Stop loading it');
if (yes !== 'Stop loading it') return;
const r = await pluginInstall.disable(claudeFolders());
log.appendLine('work plan plugin: ' + r.said);
log.show(true);
if (r.ok) await offerReload('The work plan plugin will stop loading in conversations started after a reload.');
}),
registerCommand('openSettings',
// Our own id, so a change of publisher or name cannot leave this pointing at an extension that is not here.
() => vscode.commands.executeCommand('workbench.action.openSettings', '@ext:' + context.extension.id)),
/* Reads the records rather than measuring anything, so it is also the way to see them after a window restart. */
registerCommand('showOpenLatency', () => {
sampleLatency();
/* Every window's records, not just this one's - a regression shows up across windows, and the window you happen to
run this from is rarely the one that was slow. */
const records = latency.readAll(latencyDir());
log.appendLine('');
for (const line of latency.report(records, thresholdMs())) log.appendLine(line);
log.appendLine(` records: ${path.join(latencyDir(), 'open-latency-<pid>.jsonl')}, one per window`);
log.show(true);
}),
// A Claude Code update arrives as a new folder, so patch it as soon as that folder appears.
vscode.extensions.onDidChange(() => sync()),
);
const REFRESH_MS = 30000;
/*
* How long this window makes you wait, taken from the official extension's log rather than measured here - see
* src/openlatency.js for what is paired with what. It rides the half-minute timer because it costs one stat of one
* file when nothing has been written, and reads only the bytes appended since the last pass.
*
* It is deliberately not in the injected script. A readout added there once made reloading the window crash, and the
* mechanism was never established; the panel is also the wrong side to measure from, since what is being timed is a
* panel that has not started yet.
*/
/* A directory rather than a file: each window writes only its own, since several of them share this folder and
nothing locks it. src/openlatency.js says what goes wrong when they share one. */
const latencyDir = () => context.globalStorageUri.fsPath;
const stamp = () => {
const ours = context.extension && context.extension.packageJSON && context.extension.packageJSON.version;
const ext = vscode.extensions.getExtension(webview.id);
const theirs = ext && ext.packageJSON && ext.packageJSON.version;
return `${ours || '?'}/${theirs || '?'}`;
};
const thresholdMs = () => Math.max(1, cfg().get(THRESHOLD_SETTING, 10)) * 1000;
/* Read offset, open pairings and the fast-open count for this window's log, kept in memory only: each window has its
own log and a reload starts a new one, so shared storage would carry this state into the wrong log. */
let latencyState = {};
if (context.globalState.get(LATENCY_KEY) !== undefined) context.globalState.update(LATENCY_KEY, undefined);
function sampleLatency() {
/* Off means nothing is read either. Stopping only the writing would leave the log being opened and parsed every
thirty seconds, which is most of what this costs. */
if (!cfg().get(LATENCY_ON_SETTING, true)) return;
try {
const r = latency.sample({
log: latency.logFile(context.logUri.fsPath),
dir: latencyDir(),
state: latencyState,
version: stamp(),
thresholdMs: thresholdMs(),
});
if (r.state) latencyState = r.state;
/* Anything recorded is already past the threshold, so it is worth saying without being asked. */
for (const w of r.added) {
log.appendLine(`waited ${(w.waited / 1000).toFixed(1)}s for ${w.what} (${w.trigger}) at ${w.at}`);
}
} catch (e) {
log.appendLine('open latency: ' + e.message);
}
}
sampleLatency();
/* The other half of the same recording runs in the panel itself (src/panel-load-watch.js), put there by the patched
host bundle as each panel's HTML is built. That bundle runs in this process and reads this flag at that moment, so
the setting reaches the next panel opened without a reload. */
const loadWatchOff = () => { globalThis[host.LOAD_WATCH_OFF] = !cfg().get(LATENCY_ON_SETTING, true); };
loadWatchOff();
context.subscriptions.push({ dispose: () => { delete globalThis[host.LOAD_WATCH_OFF]; } });
/*
* Hand the hooks their thresholds.
*
* They run as their own processes, so the editor's settings cannot reach them directly; this is the one file they read
* instead, which keeps the settings UI as the only place a person edits these. Written on activation and whenever one
* of them changes, and never required to exist - the plugin ships its own defaults so it works without this extension.
*/
function writeHookSettings() {
const values = {};
for (const [key, setting] of Object.entries(HOOK_SETTINGS)) {
const v = MODE_SWITCHES.includes(setting) ? runs(setting) : cfg().get(setting);
if (typeof v === 'boolean') values[key] = v;
else if (typeof v === 'number' && v >= 1) values[key] = Math.floor(v);
else if (typeof v === 'string' && v) values[key] = v;
}
/* claudeCodePlus.show.replyImages controls both the panel drawing images and the hook that tells the model how to
add one. The hook stays off until panelShowsImages is true, so the model is never told about images no panel
can draw. */
values.replyImages = panelShowsImages && enabled() && !removed() && !uninstalling() && !switchedOff().includes('replyImages');
/* planDir(), not PLAN_DIR: that one is only the directory's name, and joined on its own it resolves against the
extension host's working directory - a config.json the hooks never read. Written only when it changes, and
replaced whole (src/hook-settings.js). */
try { hookSettings.writeHookSettings(planDir(), values); } catch (e) {
log.appendLine('work plan hook settings: ' + e.message);
}
}
writeHookSettings();
/* The day's count is written out when the window closes, which is the other moment it is known to be complete. */
context.subscriptions.push({
dispose: () => {
try { latency.flush({ dir: latencyDir(), state: latencyState }); } catch (_) { /* closing anyway */ }
},
});
/* The id of the conversation in front of the reader, or empty. The patched field writes it on every change; before
anything has, or when the panel has no conversation open, it is not a string and reads as empty, which Agent Plus
shows as no plan rather than another conversation's. */
const activeChat = () => {
const v = globalThis.__cceActiveChat;
return typeof v === 'string' ? v : '';
};
/*
* Delete the plans of conversations that no longer exist, at most once a calendar day.
*
* There is no timer for this, deliberately. It is reached from activation and from the periodic refresh below noticing
* that the day has changed - so opening a window is what triggers it, and a window left open for weeks still gets a
* turn. On every other call the whole cost is one string compare.
*
* The day is recorded before the work, not after: several windows are separate extension hosts sharing one unlocked
* directory, and a reading that keeps failing should not be retried twice a minute until midnight.
*/
const sweepPlans = async () => {
if (removed()) return;
const day = new Date().toISOString().slice(0, 10);
if (context.globalState.get(SWEEP_KEY, '') === day) return;
await context.globalState.update(SWEEP_KEY, day);
const r = sweepOrphans();
if (r.why) log.appendLine('orphan work plans: ' + r.why);
else if (r.deleted) log.appendLine(`orphan work plans: deleted ${r.deleted}, kept ${r.kept}`);
/* Efforts files beside the panel are pruned with the live-session list from the sweep just made; when that list is
unknown, nothing is removed. */
if (r.live) for (const dir of installs(webview, true)) webview.pruneEfforts(dir, r.live);
try { if (r.live) sessionColors.prune(colorsFile(), r.live); } catch (_) { /* tried again tomorrow */ }
};
/* The reader's time zone as a panel of this window last reported it (src/panel-tz.js), or empty until one has. */
const clientZone = () => {
const v = globalThis.__cceClientTimeZone;
return typeof v === 'string' ? v : '';
};
/* Notifications are timed in that zone once a panel has said it, and until then in this machine's zone, with its
name. */
noticeTime.setReaderZone(() => clientZone() || '');
/* The plugin's hooks tell the model this zone (tell-time-zone.py), and they run beside Claude Code with no way to ask
a panel, so it is left for them in a file. The last panel to report wins: one person behind several windows reads
them all in one zone. A window that has not heard from a panel yet writes nothing rather than an empty zone. */
const writeClientZone = () => {
try { hookSettings.writeClientZone(planDir(), clientZone()); } catch (e) {
log.appendLine('client time zone: ' + e.message);
}
};
/* Set as the window closes. The output channel was registered first, so it is closed by then and writing a line to it
throws. A command sent to Claude Code is cancelled, as the extension host is shutting down. */
let closing = false;
context.subscriptions.push({ dispose: () => { closing = true; } });
let liveStates = new Map(), unreadKeys = new Set(), statesTimer = 0;
/* The host's last state of each conversation whose panel here went away (src/gone-states.js, hostStates). */
const gone = goneStates({ agentsNow: () => claude.agentsNow(), pidsOf: waiting.pidsOf, trustMs: () => AGENTS_TRUST_MS });
const readTitles = waiting.reader();
/* Conversations renamed from the session list or by a supervisor, whose new conversation is then not named after its
first message (nameOpened). */
const renamedByOthers = new Set();
const titles = titleRecord.create({ dir: () => planDir() });
const recorded = async (id, title, how, rename) => {
const before = titles.set(id, title, how.by, how.steward);
let r;
try { r = await rename(); } catch (e) { titles.restore(id, before); throw e; }
if (!r || !['done', 'submitted', 'uncertain'].includes(r.outcome)) titles.restore(id, before);
return r;
};
/* Account & usage is asked again when the conversation in front or the ones running here change, not only when the
figures do: one that stopped before it had any would otherwise keep its "No figures yet" line. */
let accountKey = '';
const noteAccount = () => {
const key = `${activeChat()}|${[...liveStates.keys()].sort().join(',')}`;
if (key === accountKey) return;
accountKey = key;
try { sessionList.accountChanged(); } catch (_) { /* the list is not set up yet */ }
};
/* A panel reports 'waiting_input'; the rest of this extension calls it 'waiting'. */
globalThis.__cceStatesHook = (states, active, open, unread) => {
try {
const next = new Map((Array.isArray(states) ? states : [])
.filter((s) => s && typeof s.sessionId === 'string').map((s) => [s.sessionId, s.state === 'waiting_input' ? 'waiting' : s.state]));
/* A wait that begins or ends changes Agent Plus's count of the conversations that need the user. That count follows
the session list's rows, so Agent Plus hears of this change from the list now, without the usual settling delay. */
const waitMoved = [...new Set([...liveStates.keys(), ...next.keys()])].some((id) => (liveStates.get(id) === 'waiting') !== (next.get(id) === 'waiting'));
gone.note(liveStates, next);
liveStates = next;
unreadKeys = new Set((Array.isArray(unread) ? unread : []).filter((k) => typeof k === 'string'));
if (waitMoved) {
if (statesTimer) { clearTimeout(statesTimer); statesTimer = 0; }
claude.changed(true);
noteAccount();
} else if (!statesTimer) statesTimer = setTimeout(() => { statesTimer = 0; claude.changed(); noteAccount(); }, 300);
} catch (_) { /* the next update */ }
};
/* The info box asks for its conversation's process id, and the context meter's hover asks the same to get the work
plan's figures. `claude agents` is run for the process id unless the last run is under half a minute old. The work
plan's figures and the token mode are sent separately, without waiting for it. */
const sendPlan = (sessionId) => {
const transcript = runs(WORK_PLAN_SETTING) ? transcriptOf(sessionId) : '';
const mode = tokenMode.labelOf(tokenMode.modeNow(vscode));
(transcript ? planInjections.measure(transcript) : Promise.resolve(null)).then((m) => {
const reply = { type: 'cce_plan', sessionId, text: planInjections.describe(m), plan: planInjections.figures(m), mode };
if (typeof globalThis.__cceToPanel === 'function') globalThis.__cceToPanel(sessionId, reply);
}).catch((e) => log.appendLine('work plan figures: ' + (e && e.message)));
};
globalThis.__cceProcessHook = (sessionId) => {
if (removed() || !enabled()) return;
sendPlan(sessionId);
if (switchedOff().includes('footerInfo')) return;
claude.freshAgents().then((r) => {
const reply = { type: 'cce_process', sessionId, pids: r.records ? waiting.pidsOf(r.records, sessionId) : null };
if (typeof globalThis.__cceToPanel === 'function') globalThis.__cceToPanel(sessionId, reply);
}).catch((e) => log.appendLine('process for the info box: ' + (e && e.message)));
};
/*
* What each panel of this window last reported for its conversation besides its state: whether a turn runs and whether
* background tasks run (src/activity.js). A turn that ends while background work still runs leaves Claude Code's
* panel marking nothing unread until the work ends too, so a reply nobody saw is marked here, through the host, while
* no tab or sidebar shows the conversation on screen.
*/
const turns = activity.turnTracker();
let marksTimer = 0;
/* What each panel of this window last reported in front of it, { tool } or { dialog }, for Agent Plus's notices
(src/waiting-for.js). */
const waits = new Map();
const noteWait = (sessionId, wait, farewell) => {
const next = !farewell && wait && typeof wait === 'object' ? JSON.stringify(wait) : '';
if ((waits.get(sessionId) || '') === next) return;
if (next) waits.set(sessionId, next); else waits.delete(sessionId);
if (!statesTimer) statesTimer = setTimeout(() => { statesTimer = 0; claude.changed(); }, 300);
};
globalThis.__cceTurnHook = (sessionId, busy, bg, farewell, wait, quiet) => {
try {
noteWait(sessionId, wait, farewell);
const r = turns.report(sessionId, busy, bg, farewell);
if (!r.changed) return;
if (r.ended && enabled() && !removed()) {
const shown = typeof globalThis.__cceShownVisibly === 'function' ? globalThis.__cceShownVisibly(sessionId) === true : true;
if (activity.marksUnread(true, r.bg || bgWorking.has(sessionId), shown, quiet === true)
&& typeof globalThis.__cceSetUnread === 'function' && globalThis.__cceSetUnread(sessionId, true)) {
log.appendLine(`marked ${sessionId} unread: its turn ended out of sight while background work runs`);
}
}
// After the host has taken the same report in, which can leave its own state as it was.
if (!marksTimer) marksTimer = setTimeout(() => { marksTimer = 0; try { refreshMarks(); } catch (_) { /* not set up yet */ } }, 0);
} catch (e) { log.appendLine('turn report: ' + ((e && e.message) || e)); }
};
context.subscriptions.push({ dispose: () => {
if (statesTimer) clearTimeout(statesTimer);
if (marksTimer) clearTimeout(marksTimer);
if (globalThis.__cceStatesHook) delete globalThis.__cceStatesHook;
if (globalThis.__cceProcessHook) delete globalThis.__cceProcessHook;
if (globalThis.__cceTurnHook) delete globalThis.__cceTurnHook;
} });
/* Conversations with a panel or tab in this window, except those the host sees running in another window. */
const panelList = (name) => { try { const f = globalThis[name]; return typeof f === 'function' ? f() || [] : []; } catch (_) { return []; } };
const shownList = () => { const elsewhere = panelList('__cceSessionsElsewhere'); return panelList('__cceSessionsShown').filter((id) => !elsewhere.includes(id)); };
/* Assigned after the Supervisor panel is created below, which itself needs the source. */
let openAnywhere = null;
/* The list of running conversations, shared between windows (listAgents in src/waiting.js). A shared list is at most
20 seconds old when a window takes it, and src/claude-source.js caches it for that window like any other. */
const AGENTS_FILE = 'agents.json', AGENTS_SHARE_MS = 20000;
/* Session ids of the conversations whose page types an answer only after the host says go (src/page/91-answer.js). */
const confirming = new Set();
/*
* Agent Plus's session list (its protocol, Session list): the conversations of this window's first folder, read from
* their transcripts (src/claude-session-list.js), the places where each is open outside the VS Code windows the list
* knows of (src/claude-elsewhere.js), and the figures of the conversation in front, which the patched host passes on
* each time the CLI reports them (src/session-totals.js). Watching the transcripts starts once the list first asks for
* them.
*/
let claimed = new Map();
const places = claudeElsewhere.create({ ownPid: process.pid, claimed: (id) => claimed.has(id),
windowless: (pid) => duplicates.hostWindowless(pid, { dir: planDir() }) });
const sessionTotals = sessionTotalsOf.create({ changed: () => { sessionList.accountChanged(); } });
globalThis.__cceSessionTotalsHook = (id, totals) => { try { sessionTotals.note(id, totals); } catch (_) { /* the next report */ } };
const effortFiles = (id) => installs(webview, true).map((d) => path.join(d, 'webview', webview.EFFORT_PREFIX + id + '.css'));
/* Temporary conversations (src/temporary.js). Agent Plus's exports arrive once it registers this extension's source. */
const temporary = temporaryConversations.create({ core: () => agentCore, sourceId: CLAUDE_SOURCE_ID, log: (line) => log.appendLine(line) });
const scratchOf = (id) => {
let names = [];
try { names = fs.readdirSync(path.join(claudeDir(), 'scratch')); } catch (_) { names = []; }
return temporaryConversations.scratchDirs(claudeDir(), names, id);
};
/* Through the panel showing it, so its CLI hears of it too; otherwise in its transcript, which no process has open. */
const renameAnywhere = (id, title, how = {}) => recorded(id, title, { by: how.by || 'user', steward: how.steward || '' }, () => renameHere(id, title));
const renameHere = async (id, title) => {
if (claude.source.shows(id)) {
renamedByOthers.add(id);
const r = await renameConversation(id, title);
return r.outcome === 'submitted' ? { outcome: 'done' } : { outcome: r.outcome === 'refused' ? 'refused' : 'failed', reason: r.reason };
}
if (deleteSession.runningSessions().has(id)) return { outcome: 'refused', reason: 'a Claude Code process has it open and would write its old title back' };
const file = transcriptOf(id);
if (!file) return { outcome: 'refused', reason: 'Claude Code has no transcript of it on this machine' };
if (!claudeSessionList.appendTitle(file, id, title)) return { outcome: 'failed', reason: 'its transcript could not be written' };
try { if (typeof globalThis.__cceSessionsChanged === 'function') globalThis.__cceSessionsChanged(); } catch (_) { /* the panels catch up */ }
sessionList.changed();
return { outcome: 'done' };
};
const sessionList = claudeSessionList.create({
projects: () => projectsDir(),
started: () => { watchList(); },
ready: () => claude.freshAgents(),
state: (id) => claude.stateOf(id),
here: (id) => shownList().includes(id),
lastUserAt: (file) => lastUser.at(file),
elsewhere: () => {
try { claimed = deleteSession.shownElsewhere(planDir()); } catch (_) { claimed = new Map(); }
return places.scan();
},
isSteward: (id) => enabled() && !removed() && stewardMarks.stewardIds(stewardTable()).includes(String(id).toLowerCase()),
open: (id, where) => vscode.commands.executeCommand('claude-vscode.editor.open', id, undefined, undefined, undefined, AS_FULL_EDITOR,
{ programmatic: where === 'sidebar' ? 'cce-pin-to-sidebar' : 'pin-to-panel' }),
/* A new conversation has no id until its first message is sent, so the core is answered without one. A temporary
one is registered once its panel has that id (src/temporary.js). The sidebar shows one conversation after
another in the same view, where a new one cannot be told apart, so a temporary one is refused there. */
create: async (where, { temporary: temp = false } = {}) => {
if (temp && where === 'sidebar') return { refused: 'Claude Code Plus starts a temporary conversation only in a tab' };
if (temp && !temporary.available()) return { refused: 'Agent Plus has no temporary conversations' };
if (temp) temporary.arm();
try {
await vscode.commands.executeCommand('claude-vscode.editor.open', undefined, undefined, undefined, undefined, AS_FULL_EDITOR,
{ programmatic: where === 'sidebar' ? 'cce-pin-to-sidebar' : 'pin-to-panel' });
} finally {
if (temp) setTimeout(() => temporary.disarm(), 1000);
}
return '';
},
rename: (id, title, how) => renameAnywhere(id, title, how),
sawTitle: (id, sum) => titles.saw(id, sum),
remove: async (ids, { temporary: temp = false } = {}) => {
/* With `temporary`, Agent Plus is deleting temporary conversations whose grace period is over, and only the ones
it holds as temporary are deleted. Every delete also removes the conversation's scratch session folder. */
const refusedNow = temp ? ids.filter((id) => !temporary.isTemporary(id)) : [];
if (temp) ids = ids.filter((id) => temporary.isTemporary(id));
let shown;
try { shown = typeof globalThis.__cceSessionsShown === 'function' ? globalThis.__cceSessionsShown() : null; } catch (_) { shown = null; }
const results = claudeSessionList.deleteChecked(ids, {
shown, running: deleteSession.runningSessions(), elsewhere: deleteSession.shownElsewhere(planDir()),
findAll: (want) => deleteSession.findAll(want, { planDir: planDir(), extra: effortFiles, scratch: scratchOf }),
remove: (found) => deleteSession.remove(found),
forget: (id) => {
try { sessionPins.setPinned(pinsFile(), id, false); } catch (_) { /* not pinned */ }
try { sessionColors.setColor(colorsFile(), [id], null); } catch (_) { /* not coloured */ }