Repository navigation
Expand file tree
/
Copy pathpatch-extension.py
More file actions
2604 lines (2298 loc) · 117 KB
/
Copy pathpatch-extension.py
File metadata and controls
2604 lines (2298 loc) · 117 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
#!/usr/bin/env python3
"""
Patch the bundled webview of the Claude Code VS Code extension.
Three changes, all idempotent:
1. CSS — enlarge the attachment pill ONLY when it contains an image
thumbnail. Text/document context pills (build.txt, settings.json, etc)
stay at the stock 24px height. Achieved with a :has(.thumbIcon) selector
so the geometry only applies when the pill has a thumbnail child. The
thumbnail image itself is also enlarged via the .thumbIcon rule.
2. CSS — make the pill remove (X) button always visible, not only on hover.
The button and its onRemove handler already exist in the bundle; the
stock CSS hides it behind opacity:0 until you hover the pill.
3. JS — gate the click-to-open behavior on tool body rows (the IN and OUT
blocks in the chat). Plain clicks no longer open the tool output as an
editor tab. Cmd+click (or Ctrl+click) still opens it. The cursor pointer
affordance is removed so the row looks like plain text.
Migration: an earlier shape of this script (utils Build 1-4, this repo
Builds 1-2) replaced the .pill_lcdCYQ rule directly, which made every pill
80px tall — including text-context pills. On bundles where that old form
is detected, the patcher reverts the over-broad rules to original before
applying the new scoped rule.
Searches for installed extension folders in:
~/.vscode-server/extensions/anthropic.claude-code-* (Remote-SSH server)
~/.vscode/extensions/anthropic.claude-code-* (local install)
Backs up modified files to <name>.bak.<timestamp> before editing.
"""
from __future__ import annotations
import glob
import json
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
# --- Tunable image-pill sizes (only applied to pills with a thumbnail image) -
PILL_HEIGHT = 80 # original 24 (stock pill height, kept for non-image)
THUMB_SIZE = 72 # original 12
PILL_MAX_WIDTH = 300 # original 180
PILL_GAP = 7 # original 4
# --- Internal --------------------------------------------------------------
EXTENSION_GLOBS = [
"~/.vscode-server/extensions/anthropic.claude-code-*",
"~/.vscode/extensions/anthropic.claude-code-*",
]
# Original CSS rules — must match the bundle byte-for-byte.
ORIGINAL_PILL_TAIL = (
"gap:4px;min-width:0;max-width:180px;height:24px;"
"transition:border-color .15s}"
)
ORIGINAL_THUMB_RULE = (
".thumbIcon_lcdCYQ{object-fit:cover;border-radius:max(1px,"
"calc(var(--pill-radius) - var(--pill-padding)));flex-shrink:0;"
"width:12px;height:12px}"
)
ORIGINAL_LABEL_RULE = (
".label_lcdCYQ{color:var(--app-primary-foreground);white-space:nowrap;"
"overflow:hidden;text-overflow:ellipsis;min-width:0;font-size:11px;"
"font-weight:500}"
)
ORIGINAL_REMOVE_BUTTON_RULE = (
".removeButton_lcdCYQ{position:absolute;display:flex;"
"border-radius:0 var(--pill-radius)var(--pill-radius)0;"
"cursor:pointer;opacity:0;background:linear-gradient(to right,"
"transparent 0%,var(--pill-bg)50%,var(--pill-bg)100%);border:none;"
"justify-content:flex-end;align-items: center;width:32px;"
"padding:0 6px 0 0;transition:opacity .15s;top:0;bottom:0;right:0}"
)
# Old over-broad shapes the patcher used to write (utils Build 1-4, this
# repo Build 1-2). When detected, the new patcher reverts them so text-context
# pills stop rendering at image-pill size.
OLD_PATCHED_PILL_TAIL = (
"gap:7px !important;min-width:0;max-width:300px !important;"
"height:80px !important;min-height:80px !important;"
"transition:border-color .15s}"
)
OLD_PATCHED_LABEL_RULE = (
".label_lcdCYQ{color:var(--app-primary-foreground);white-space:nowrap;"
"overflow:hidden;text-overflow:ellipsis;min-width:0;"
"font-size:13px !important;font-weight:500}"
)
# New scoped image-pill rule. Appended to the CSS so the cascade picks it
# only when a .pill has a .thumbIcon child (image kind).
IMAGE_PILL_RULE_MARKER = ".pill_lcdCYQ:has(.thumbIcon_lcdCYQ){"
REMOVE_BUTTON_PATCHED_MARKER = (
"cursor:pointer;opacity:1 !important;background:linear-gradient(to right,"
)
# JS patterns: only tool body rows (className:J0.toolBodyRowContent) get the
# click-gating. The unrelated "secondaryLine" match is skipped.
#
# Two render-path variants exist in the bundle:
# 1. Conditional cursor — `style:VAR?{cursor:"pointer"}:void 0`. Used when
# the row may or may not have a click handler (e.g. tool input/output
# where the openable-as-tab decision is dynamic).
# 2. Unconditional cursor — `style:{cursor:"pointer"}`. Used by the slash
# command / prompt input row, which is always clickable.
#
# Both have to be patched or you can still trigger an unwanted open by
# clicking on the slash command IN row.
JS_TOOL_ROW_COND_PATTERN = re.compile(
r'(className:J0\.toolBodyRowContent,)'
r'onClick:([A-Za-z_$][A-Za-z0-9_$]*),'
r'style:\2\?\{cursor:"pointer"\}:void 0'
)
JS_TOOL_ROW_UNCOND_PATTERN = re.compile(
r'(className:J0\.toolBodyRowContent,)'
r'onClick:([A-Za-z_$][A-Za-z0-9_$]*),'
r'style:\{cursor:"pointer"\}(?!:)'
)
# Bare ()=>{...openContent(...)} arrow functions — used by Glob/Grep summary
# rows, the Agent input, and a few other tools. Catches the click handler
# wherever it appears, including inside inline ternaries.
JS_ARROW_VOID_OPENCONTENT_PATTERN = re.compile(
r'\(\)=>\{(\$\.fileOpener\.openContent\([^)]+\))\}'
)
# REPL header click — already takes the event arg as Q, just adds the gate.
JS_REPL_PATTERN = re.compile(
r'\(Q\)=>\{Q\.stopPropagation\(\),Q\.preventDefault\(\),'
r'(\$\.fileOpener\.openContent\([^)]+\))\}'
)
# Diagnostics J() function — declared without args, called from {onClick:J}.
# Replace the function declaration to take an event arg and gate.
JS_DIAGNOSTICS_PATTERN = re.compile(
r'function J\(\)\{let Y=RN0\(\$\);'
r'Z\.fileOpener\.openContent\(Y,"Diagnostics: VSCode Problems",!1\)\}'
)
JS_PATCHED_MARKER = "if(e.metaKey||e.ctrlKey)"
# --- Dynamic nav-tab label width ------------------------------------------
# The stock navTabLabel is hard-capped at max-width:120px regardless of how
# many tabs are open or how wide the sidebar is. On an ultrawide monitor with
# three sessions open, every label gets a "Investigate Session Reap…" ellipsis
# even though there is hundreds of pixels of unused header room.
#
# Earlier builds tiered the cap by tab count (1-2 → 400px, 3-4 → 75px, etc.).
# That was still hardcoded — same 75px on a 14" MBP and a 5K ultrawide.
#
# Build 37+ — fully dynamic via flex layout. Tabs share whatever container
# width is available; ellipsis kicks in only when content actually overflows.
# - .navTab_hONcXw becomes a flex container with `flex:1 1 0` so siblings
# split the available room equally and `min-width:0` so flex-shrink can
# clamp them below content size.
# - .navTabLabel_hONcXw drops the fixed max-width (set to none) and uses
# `flex:1 1 0; min-width:0` so the label fills its pill but truncates
# with the existing overflow:hidden + text-overflow:ellipsis when the
# pill is squeezed.
# - 5+/7+ tab font-size shrinks are kept — they pack more characters per
# pixel when the sidebar is dense, independent of any width cap.
ORIGINAL_NAV_TAB_LABEL_RULE = (
".navTabLabel_hONcXw{white-space:nowrap;overflow:hidden;"
"text-overflow:ellipsis;max-width:120px}"
)
DYNAMIC_TAB_WIDTH_MARKER = ".navTab_hONcXw{display:flex;align-items:center;flex:1 1 0"
# Old form Build 7-15 — no 1-2 tab base override, only 3+/5+/7+ shrinks.
OLD_DYNAMIC_TAB_WIDTH_RULES_V1 = (
"*:has(>.navTab_hONcXw:nth-child(3)) .navTabLabel_hONcXw{max-width:75px}"
"*:has(>.navTab_hONcXw:nth-child(5)) .navTabLabel_hONcXw{max-width:50px}"
"*:has(>.navTab_hONcXw:nth-child(7)) .navTabLabel_hONcXw{max-width:35px}"
)
# Old form Build 16 — added 1-2 tab base override but still single-line at 5+/7+.
OLD_DYNAMIC_TAB_WIDTH_RULES_V2 = (
".navTabLabel_hONcXw{max-width:400px}"
"*:has(>.navTab_hONcXw:nth-child(3)) .navTabLabel_hONcXw{max-width:75px}"
"*:has(>.navTab_hONcXw:nth-child(5)) .navTabLabel_hONcXw{max-width:50px}"
"*:has(>.navTab_hONcXw:nth-child(7)) .navTabLabel_hONcXw{max-width:35px}"
)
# Old form Build 17 — 2-line 5+/7+ with hardcoded 75px at 3-4 tabs.
OLD_DYNAMIC_TAB_WIDTH_RULES_V3 = (
".navTabLabel_hONcXw{max-width:400px}"
"*:has(>.navTab_hONcXw:nth-child(3)) .navTabLabel_hONcXw{max-width:75px}"
"*:has(>.navTab_hONcXw:nth-child(5)) .navTab_hONcXw{font-size:.7em}"
"*:has(>.navTab_hONcXw:nth-child(5)) .navTabLabel_hONcXw"
"{max-width:90px;white-space:normal;display:-webkit-box;"
"-webkit-box-orient:vertical;-webkit-line-clamp:2;line-height:1.15}"
"*:has(>.navTab_hONcXw:nth-child(7)) .navTab_hONcXw{font-size:.65em}"
"*:has(>.navTab_hONcXw:nth-child(7)) .navTabLabel_hONcXw{max-width:70px}"
)
DYNAMIC_TAB_WIDTH_RULES = (
".navTab_hONcXw{display:flex;align-items:center;flex:1 1 0;min-width:0}"
".navTabLabel_hONcXw{flex:1 1 0;min-width:0;max-width:none}"
"*:has(>.navTab_hONcXw:nth-child(5)) .navTab_hONcXw{font-size:.7em}"
"*:has(>.navTab_hONcXw:nth-child(7)) .navTab_hONcXw{font-size:.65em}"
)
# --- Active-session title bar — uncap width --------------------------------
# Stock: titleGroup is capped at max-width:300px so even short auto-generated
# titles like "Extend title length for repository descriptions" truncate with
# ellipsis when there is plenty of horizontal room in the header.
# Patch: drop just the max-width so the title bar grows to fit its content
# up to the available header width. The headerSpacer (flex:1) still keeps
# any right-side buttons pinned right. Single-line ellipsis behavior in
# titleTextInner is left intact for the rare title that exceeds the header
# width — better than wrapping the header onto two rows.
ORIGINAL_TITLE_GROUP_RULE = (
".titleGroup_aqhumA{display:flex;overflow:hidden;"
"font-size:var(--vscode-chat-font-size,13px);"
"font-family:var(--vscode-chat-font-family);"
"border-radius:6px;align-items:stretch;min-width:0;max-width:300px}"
)
PATCHED_TITLE_GROUP_RULE = (
".titleGroup_aqhumA{display:flex;overflow:hidden;"
"font-size:var(--vscode-chat-font-size,13px);"
"font-family:var(--vscode-chat-font-family);"
"border-radius:6px;align-items:stretch;min-width:0}"
)
TITLE_UNLOCK_PATCHED_MARKER = (
"border-radius:6px;align-items:stretch;min-width:0}"
)
# --- Image-only submit ----------------------------------------------------
# The chat input has TWO gates that block submission when the trimmed text
# content is empty. To allow submitting a paste-only image, patch both:
#
# 1. The Enter key handler: `if(z8(),t.current?.textContent?.trim()||"")k1()`
# currently only calls the submit (k1) when the trimmed text is truthy.
# Patched form: always call k1.
#
# 2. The submit function k1 itself: `let I1=t.current?.textContent?.trim()||
# "";if(!I1)return;` — bails if I1 is empty.
# Patched form: bail when text is empty AND no attachment chip is in the
# DOM. The .thumbIcon_lcdCYQ class on the attachment pill is the DOM
# signal that an image is attached and pending send. Also, if I1 is empty
# AFTER the gate (image-only path), substitute U+200B (ZERO WIDTH SPACE)
# so the message body is never an empty string. Without this substitution,
# the CLI agent builds an empty text content block with cache_control set
# on it, and the Anthropic API rejects with "cache_control cannot be set
# for empty text blocks". ZWS is non-empty to the API but renders as
# nothing in the chat UI, so no visible placeholder character appears in
# the conversation. JS String.prototype.trim() does not strip ZWS, so it
# survives any downstream re-trim. Build 14 used "." instead, which
# worked but was visible in the chat. ZWS landed in Build 17. Diagnosed
# 2026-05-03.
#
# DOM-based attachment check is hacky but avoids reverse-engineering the
# component's internal React state names, which change on every minified
# rebuild.
ORIGINAL_ENTER_GATE = (
'if(U6(),t.current?.textContent?.trim()||"")q1()'
)
PATCHED_ENTER_GATE = (
'if(U6(),1)q1()'
)
# Regex forms — capture the two rotating function names so the patch survives
# minifier renames between Anthropic releases.
# Examples: z8/k1 in 2.1.152, U6/q1 in 2.1.158.
ENTER_GATE_RE = re.compile(
r'if\((\w+)\(\),\w+\.current\?\.textContent\?\.trim\(\)\|\|""\)(\w+)\(\)'
)
ENTER_GATE_PATCHED_RE = re.compile(r'if\(\w+\(\),1\)\w+\(\)')
# --- image-only submit: rename-proof gate detection -------------------------
# Anthropic rotates minified locals every release (L1 -> je in 2.1.219, I1
# before that). Build 10 hardcoded them, so on a fresh bundle the patch silently
# no-ops and reports "k1-gate not found" — indistinguishable from real breakage.
# Build 11 captures the names instead, and detects the patched form structurally
# plus a stable comment marker, so neither check depends on the mangler.
K1_GATE_RE = re.compile(
r'let (\w+)=(\w+)\.current\?\.textContent\?\.trim\(\)\|\|"";if\(!\1\)return;'
)
# Any patched variant, Build 4 through today, regardless of local names.
K1_GATE_PATCHED_RE = re.compile(
r'let (\w+)=\w+\.current\?\.textContent\?\.trim\(\)\|\|"";'
r'if\(!\1&&!document\.querySelector\('
)
# Stable marker — a comment the mangler cannot rename.
IMAGE_ONLY_PATCHED_MARKER = "/*__cce_ios*/"
# Full patched statement, including whatever placeholder an older build wrote
# ("" in Build 4-13, "." in Build 14-16, ZWS today). Used to normalize an old
# patched bundle up to the current form instead of skipping it.
K1_GATE_PATCHED_FULL_RE = re.compile(
r'let (\w+)=(\w+)\.current\?\.textContent\?\.trim\(\)\|\|"";'
r'if\(!\1&&!document\.querySelector\([^)]*\)\)return;'
r'(?:if\(!\1\)\1="[^"]*";)?'
r'(?:/\*__cce_ios\*/)?'
)
# What counts as "an attachment is pending send".
#
# This was `[class*="thumbIcon_"]` — the <img> inside the attachment pill —
# through Build 11, and it is subtly wrong twice over. The pill renders the
# instant the file joins the attachment list, but the thumbnail is
# `thumbnailUrl ? <img class=thumbIcon> : <GenericIcon>` and thumbnailUrl only
# arrives once the FileReader has resolved a dataUrl. Paste a large screenshot
# and hit Enter immediately and you lose that race, silently. Worse, the pill
# is only handed a thumbnailUrl when `file.type.startsWith("image/")`, so an
# image with an empty or non-image MIME type never grows a thumb at all.
#
# The attachment row is rendered behind `attachments.length > 0` and nothing
# else, which is exactly the condition we mean. Substring-matched so the
# per-release CSS-module hash bump cannot break it; the thumb arm is kept as a
# fallback.
THUMB_SELECTOR = '[class*="attachedFilesContainer"],[class*="thumbIcon_"]'
def build_patched_k1_gate(var: str, ref: str) -> str:
"""Render the image-only gate using the bundle's own local names."""
return (
f'let {var}={ref}.current?.textContent?.trim()||"";'
f'if(!{var}&&!document.querySelector(\'{THUMB_SELECTOR}\'))return;'
f'if(!{var}){var}="\u200b";{IMAGE_ONLY_PATCHED_MARKER}'
)
# --- Live override-aware title in the in-session title bar ------------------
# Stock: the title-bar JSX renders `$.activeSession.value?.summary.value`
# directly. session.summary is a Signal that gets set ONCE when the session
# loads from the JSONL transcript. So when an external writer (the namer
# system in vscode-session-namer) appends a custom-title event to the
# transcript or pushes an entry into ~/.claude/session-overrides.json, the
# in-webview title bar stays stale until the next session-resume.
#
# The bundle already has an override-aware reader: `Wk(session)` checks
# `globalThis.__cceOverridesSig` (which extension.js polls from
# session-overrides.json every 1 second and posts to the webview) before
# falling back to `session.summary.value`. The OS-level editor tab title
# uses Wk and updates live; the in-webview title bar does not.
#
# Patch: replace every `$.activeSession.value?.summary.value||"Untitled"`
# in the title-bar JSX (4 sites — rename-mode capture, input defaultValue,
# button tooltip, visible span) with a Wk-aware ternary that handles the
# null-active-session case Wk itself does not guard.
ORIGINAL_TITLE_SUMMARY_READ = (
'$.activeSession.value?.summary.value||"Untitled"'
)
# The title-func identifier (Wk/Kk/etc.) drifts with every Anthropic bundle
# re-minify. Both the live-title ternary and the wk-override body need to
# refer to whatever the current name is, and we need to *rewrite* old
# patched ternaries when the name changes underneath us — otherwise the
# ternary ends up calling a stale identifier that the new bundle assigned
# to something else entirely (e.g. the React import alias).
RE_TITLE_FUNC = re.compile(
r'function ([A-Za-z_$][A-Za-z_$0-9]*)\(\$\)\{return \$\.summary\.value\|\|"Untitled"\}'
)
RE_PATCHED_TITLE_TERNARY = re.compile(
r'\(\$\.activeSession\.value\?([A-Za-z_$][A-Za-z_$0-9]*)\(\$\.activeSession\.value\):"Untitled"\)'
)
WK_OVERRIDE_PATCHED_MARKER = '_sig=_g.__cceOverridesSig'
# --- Restore the override pipeline (regression in 2.1.128) ------------------
# 2.1.126 had three pieces working together:
# 1. extension.js polled ~/.claude/session-overrides.json every second and
# posted {type:"cce_override_update",overrides:_o} into each webview.
# 2. webview/index.js had a one-shot listener that wrote those overrides
# onto globalThis.__cceOverridesSig.value.
# 3. webview/index.js had Wk(session) check that signal before falling back
# to session.summary.value.
# 2.1.128 stripped all three. Wk became `function Wk($){return $.summary.value||"Untitled"}`,
# the listener and the polling loop are gone. Our existing live-title and
# force-title-bar patches still apply (they call Wk), but Wk is now a stub —
# which is why the namer system writes new titles to disk and the in-webview
# bar never updates. These three patches restore the pipeline by lifting the
# 2.1.126 source verbatim, with one tweak: __cceOverridesSig is initialized
# as a plain {value:null} object instead of a preact-signal so the patch does
# not depend on a minified Signal constructor name.
# Signal factory regex — matches `activeSession=O0(void 0)` to capture the
# minified signal-factory name. Falling back to a plain {value:null} object
# leaves __cceOverridesSig non-reactive, so Wk re-reads its value but Preact
# never re-renders the title-bar JSX. With a real signal, the listener's
# `_sig.value=d.overrides` write triggers reactivity across all three displays
# (editor tab, sidebar, in-webview title bar) on the same 1s polling tick.
RE_SIGNAL_FACTORY = re.compile(r'\bactiveSession=([A-Za-z_$][A-Za-z_$0-9]*)\(void 0\)')
OVERRIDES_CONSUMER_PATCHED_MARKER = '__cceListenerInstalled'
# Build 25-37 form: postMessage only — updated only the in-webview title bar.
# The editor tab (panel.title) was set ONCE at session-load by stock parsing
# of JSONL custom-title events and never refreshed at runtime. Long sessions
# would drift: the namer rewrote session-overrides.json on every drift-check,
# the in-webview bar tracked it live, but the editor tab stayed pinned to
# whatever title was active when the panel first opened. Documented in the
# CLAUDE.md "four display contexts" table as if it worked, but it didn't.
OLD_OVERRIDES_PRODUCER_IIFE_V1 = (
'(function(){try{'
'var _fs=require("fs"),_pa=require("path"),'
'_op=_pa.join(require("os").homedir(),".claude","session-overrides.json");'
'var _send=function(){try{'
'var _o={};'
'try{_o=JSON.parse(_fs.readFileSync(_op,"utf8"))}catch(e){}'
'V.webview.postMessage({type:"cce_override_update",overrides:_o})'
'}catch(e){}};'
'setInterval(_send,1000);_send()'
'}catch(e){}})()'
)
# Build 38+ form: also writes V.title=_o[K] so the editor tab actually
# tracks the override.
#
# Why K is the sessionId here:
# The IIFE is injected after `this.webviews.add(<name>)`. There are 3
# call sites in the bundle:
# - resolveWebviewView(V, K, B) — sidebar webview
# - setupPanel(V, K, B, x) — session panel ← K = sessionId
# - resolveSessionListView(V, K, B) — session list view
#
# Confirmed by tracing the only setupPanel caller in the bundle:
# `if(this.setupPanel(U, V, K, q), V) this.sessionPanels.set(V, U)`
# The outer V is the sessionId stored as the Map key. Inside setupPanel
# it is renamed to K (param 2). For the other two sites, K is not a
# sessionId, so `_o[K]` is undefined and the V.title= write no-ops safely.
#
# Why all three try/catches:
# resolveSessionListView's V is a WebviewView, not a WebviewPanel.
# WebviewView.title is settable per VS Code API but defensive try/catch
# protects against any host where it isn't.
#
# What will break this patch in a future Anthropic release:
# - Renaming the K parameter in setupPanel (e.g. K → N). The patcher's
# re-anchor logic is the same as folder-search/session-open-column —
# update OVERRIDES_PRODUCER_IIFE to reference the new param name.
# - Removing this.sessionPanels.set(V, U) — would break sessionId capture
# entirely. Check archive/<version>-darwin-arm64.tar.gz to diff.
# 2.1.140 form: setupPanel/resolveWebviewView/resolveSessionListView were
# refactored — the panel is now the FIRST param `z`, and `V` is something
# else (a column number / token / boolean). Writing `V.title=_o[K]` from
# inside these functions targeted the wrong identifier and silently no-op'd
# inside the try/catch. The editor tab stayed pinned to the load-time
# aiTitle. Fix: reference `z` (the panel) instead. Kept as
# BROKEN_V_OVERRIDES_PRODUCER_IIFE so installs still carrying the dead form
# get migrated to the working z-form.
BROKEN_V_OVERRIDES_PRODUCER_IIFE = (
'(function(){try{'
'var _fs=require("fs"),_pa=require("path"),'
'_op=_pa.join(require("os").homedir(),".claude","session-overrides.json");'
'var _send=function(){try{'
'var _o={};'
'try{_o=JSON.parse(_fs.readFileSync(_op,"utf8"))}catch(e){}'
'try{V.webview.postMessage({type:"cce_override_update",overrides:_o})}catch(e){}'
'try{if(typeof K==="string"&&_o[K]&&V.title!==_o[K])V.title=_o[K]}catch(e){}'
'}catch(e){}};'
'setInterval(_send,1000);_send()'
'}catch(e){}})()'
)
# Build 55 form: writes z.title=_o[K] only when the function parameter K is a
# string sessionId. That assumption holds for the `createPanel` call site
# (this.setupPanel(B, z, K, Z) → formal K = the sessionId) but FAILS for the
# `registerWebviewPanelSerializer.deserializeWebviewPanel` call site:
# D.setupPanel(w, void 0, void 0, I)
# When VS Code restores a previously-opened tab on window reload, this is the
# path it uses. K is undefined, the override-write no-ops forever, and the
# editor tab stays stuck at the load-time aiTitle even though the in-session
# title bar (which gets the full overrides object via postMessage) updates
# correctly. Diagnosed 2026-05-18 on session 3d0750d5 in 2.1.143.
# Kept as BUILD_55_OVERRIDES_PRODUCER_IIFE so installs carrying it migrate.
BUILD_55_OVERRIDES_PRODUCER_IIFE = (
'(function(){try{'
'var _fs=require("fs"),_pa=require("path"),'
'_op=_pa.join(require("os").homedir(),".claude","session-overrides.json");'
'var _send=function(){try{'
'var _o={};'
'try{_o=JSON.parse(_fs.readFileSync(_op,"utf8"))}catch(e){}'
'try{z.webview.postMessage({type:"cce_override_update",overrides:_o})}catch(e){}'
'try{if(typeof K==="string"&&_o[K]&&z.title!==_o[K])z.title=_o[K]}catch(e){}'
'}catch(e){}};'
'setInterval(_send,1000);_send()'
'}catch(e){}})()'
)
# Build 56 form: captures the enclosing class instance via .call(this) and,
# when K is not a string sessionId, reverse-looks-up the sessionId by
# scanning this.sessionPanels for the panel reference. Handles the
# deserializeWebviewPanel(w, void 0, void 0, I) path correctly: once the
# session attaches (and sessionPanels.set(D, z) fires), the next 1-second
# tick resolves the sessionId and writes the title override.
OVERRIDES_PRODUCER_IIFE = (
'(function(){try{'
'var _self=this;'
'var _fs=require("fs"),_pa=require("path"),'
'_op=_pa.join(require("os").homedir(),".claude","session-overrides.json");'
'var _send=function(){try{'
'var _o={};'
'try{_o=JSON.parse(_fs.readFileSync(_op,"utf8"))}catch(e){}'
'try{z.webview.postMessage({type:"cce_override_update",overrides:_o})}catch(e){}'
'try{'
'var _sid=(typeof K==="string")?K:null;'
'if(!_sid&&_self&&_self.sessionPanels&&_self.sessionPanels.forEach)'
'_self.sessionPanels.forEach(function(_v,_k){if(_v===z)_sid=_k});'
'if(_sid&&_o[_sid]&&z.title!==_o[_sid])z.title=_o[_sid];'
'}catch(e){}'
'}catch(e){}};'
'setInterval(_send,1000);_send()'
'}catch(e){}}).call(this)'
)
# Marker is a substring unique to the Build 56 form (reverse-lookup branch).
# Bundles carrying the Build 55 z-form will NOT match this marker and will be
# migrated.
OVERRIDES_PRODUCER_PATCHED_MARKER = '_self.sessionPanels.forEach'
RE_WEBVIEWS_ADD = re.compile(r'(this\.webviews\.add\([A-Za-z0-9_\$]+\))([,;])')
# --- Force in-session title bar in full-editor mode -------------------------
# Stock: the title bar (titleGroup + rename pencil + headerSpacer) is wrapped
# in `!window.IS_FULL_EDITOR && createElement(Fragment, ...)`. Sessions opened
# via claude-vscode.primaryEditor.open pass ViewColumn.Active, which the host
# detects (N=B===ViewColumn.Active) and forwards to the webview as
# IS_FULL_EDITOR=true — so those sessions never get the in-webview title bar.
# The VS Code editor tab title above is then the only place to see or rename
# the session, and it truncates aggressively when many tabs are open.
#
# Patch: remove just the first IS_FULL_EDITOR guard so the title bar always
# renders, regardless of how the panel was opened. The second
# !window.IS_FULL_EDITOR guard later in the same JSX wraps an onboarding
# fragment and is left alone.
#
# Anchored on `{className:h6.header},` so the patch only matches the header
# children list, not any other IS_FULL_EDITOR check elsewhere in the bundle.
ORIGINAL_TITLE_GUARD = (
'{className:h6.header},'
'!window.IS_FULL_EDITOR&&'
'p0.default.createElement(p0.default.Fragment,null,'
'p0.default.createElement("div",{ref:J,className:`${h6.titleGroup}'
)
PATCHED_TITLE_GUARD = (
'{className:h6.header},'
'p0.default.createElement(p0.default.Fragment,null,'
'p0.default.createElement("div",{ref:J,className:`${h6.titleGroup}'
)
TITLE_GUARD_PATCHED_MARKER = PATCHED_TITLE_GUARD
# --- Folder @mention selection -----------------------------------------------
# When you click a directory in the @ mention dropdown the extension currently
# just populates the text input with the folder path so you can keep typing to
# drill into it — it does NOT add a context chip. Patching `m1` to always be
# true makes directories behave identically to files: a chip is created and the
# cursor moves past a trailing space so the mention is closed.
# Regex form — captures the minified helper-function name (`Gq1` in early
# bundles, `Qq1` as of 2.1.136) so a single-character rename does not break
# the anchor. The rest of the literal string is stable across recent builds.
DIR_MENTION_RE = re.compile(
r'let m1=!\((?P<tvar>[A-Za-z_$][\w$]*)&&d\.type==="directory"\),_0=m1\?d\.path\+" ":d\.path,'
r'k0=(?P<helper>[A-Za-z_$][\w$]*)\(D,(?P<l2var>[A-Za-z_$][\w$]*),_0,!0\);'
r'if\(t\.current\.textContent=k0,A\(k0\),m1\)'
r'(?P<setfn>[A-Za-z_$][\w$]*)\(\(O5\)=>new Set\(O5\)\.add\(`@\$\{d\.path\}`\)\);'
r'let l0=t\.current\.firstChild\|\|t\.current;if\(l0\)\{'
r'let O5=document\.createRange\(\),(?P<s2var>[A-Za-z_$][\w$]*)=m1\?1:0,'
)
DIR_MENTION_PATCHED_MARKER = 'let m1=!0,_0=d.path+" "'
# --- User message arrival timestamp ----------------------------------------
# Stamp each new user message bubble with arrival time, James's local time.
# The chat UI does not display user message timestamps natively. Replaces the
# prior approach where Claude echoed `[Your msg: ...]` in its response.
#
# Only NEW user messages get stamped. Existing ones loaded from session history
# at webview start are left blank — their original send time is not knowable
# from the DOM.
#
# V4/V5 (Build 34): move the stamp from a block under the bubble to an
# inline chip prefixing the message text. James asked for this on
# 2026-05-07 ("inject the date with some formatting inline with my text
# just before it"). Two changes:
# 1. The JS IIFE now stamps the inner `userMessage_HASH` element (the
# bubble itself) instead of the outer `userMessageContainer_HASH`. This
# lets ::before sit inline with the bubble text rather than as a block
# child of the wrapper.
# 2. The CSS selector switches to `[data-arrived]::before` (inline).
# V5 (same-session follow-up): keep seconds in the format string. James
# asked for them back right after seeing V4 without them. Format is now
# "May 6, 2026 3:12:47 PM" — same precision as V3, just inline now.
# Stamping the inner bubble also naturally avoids the duplicate-stamp bug
# that V2/V3 dodged with a previous-sibling check: only the main container
# has a `userMessage_` child; the attachments-wrapper container does not.
USER_MSG_TIME_CSS_RULE = (
'[data-arrived]::before{'
'content:attr(data-arrived) " ";'
'font-size:10px;'
'font-family:var(--vscode-editor-font-family,monospace);'
'color:var(--app-secondary-foreground);'
'opacity:.55;'
'margin-right:6px;'
'letter-spacing:.02em;'
'user-select:none;'
'white-space:pre'
'}'
)
USER_MSG_TIME_CSS_MARKER = '[data-arrived]::before'
# Old V1–V3 CSS form — block ::after under the container. Cleanup pass
# strips this from any live bundle that still has it, so machines pick up
# the inline V4 form without waiting for the next Anthropic release.
USER_MSG_TIME_CSS_OLD_MARKER = '[class*="userMessageContainer_"]::after'
USER_MSG_TIME_JS_IIFE = (
"\n;(function(){"
"if(globalThis.__cceUserMsgStampInstalledV5)return;"
"globalThis.__cceUserMsgStampInstalledV5=true;"
"function _f(d){"
"var mo=['January','February','March','April','May','June','July','August','September','October','November','December'],"
"h=d.getHours(),m=d.getMinutes(),s=d.getSeconds(),"
"ap=h>=12?'PM':'AM',h12=h%12||12;"
"return mo[d.getMonth()]+' '+d.getDate()+', '+d.getFullYear()+' '+h12+':'+('0'+m).slice(-2)+':'+('0'+s).slice(-2)+' '+ap"
"}"
"function _stamp(c){"
"if(c.hasAttribute('data-cce-stamped'))return;"
"c.setAttribute('data-cce-stamped','1');"
"var inner=c.querySelector('[class*=\"userMessage_\"]');"
"if(!inner)return;"
"if(inner.hasAttribute('data-arrived'))return;"
"inner.setAttribute('data-arrived',_f(new Date()))"
"}"
"new MutationObserver(function(mu){"
"for(var i=0;i<mu.length;i++){"
"var an=mu[i].addedNodes;"
"for(var j=0;j<an.length;j++){"
"var n=an[j];"
"if(n.nodeType!==1)continue;"
"if(n.matches&&n.matches('[class*=\"userMessageContainer_\"]'))_stamp(n);"
"if(n.querySelectorAll){"
"var ds=n.querySelectorAll('[class*=\"userMessageContainer_\"]');"
"for(var k=0;k<ds.length;k++)_stamp(ds[k])"
"}}}"
"}).observe(document.body,{childList:true,subtree:true})"
"})();\n"
)
USER_MSG_TIME_JS_MARKER = "__cceUserMsgStampInstalledV5"
# Old markers — the cleanup pass strips V1 (raw milliseconds, double-
# stamping), V2 (raw milliseconds, no double-stamping), V3 (block ::after
# with seconds), and V4 (inline, no seconds). V5 is inline with seconds.
USER_MSG_TIME_JS_MARKERS_OLD = (
"__cceUserMsgStampInstalled=true",
"__cceUserMsgStampInstalledV2=true",
"__cceUserMsgStampInstalledV3=true",
"__cceUserMsgStampInstalledV4=true",
# V5 joined the strip list when the stamps were retired (2026-10-03).
"__cceUserMsgStampInstalledV5=true",
)
# --- Auto-scroll to bottom: REMOVED (Build 10, 2026-08-25) ------------------
# Builds 8 and 9 injected an IIFE that pinned the messages container to the
# bottom on every DOM mutation. Build 8 had no gate and fought every scroll-up.
# Build 9 added the standard within-64px stick-to-bottom gate, which still left
# a hesitation: any scroll-up that stayed inside that 64px band re-armed the pin
# and snapped James back down, and the rAF pin could land between his wheel
# input and the scroll event. James asked for zero hesitation when scrolling up,
# so the whole patch is gone and the panel uses Anthropic's stock scroll
# behavior. Do NOT reintroduce a MutationObserver-driven scroll pin here.
# --- Gold star on the active Local/Web tab ----------------------------------
# Build 28 originally placed this star on `.sessionItem_OOQiHg.active_OOQiHg`
# (the selected session row). Build 31 moved it to the active tab in the
# Local/Web segmented control above the session list, which is the actual
# "where am I" indicator James wants.
#
# Historical context: this was first wired up by editing the live JSX on
# 2026-05-05 ("Local ★" / "Web ★" via inline span), but never made it into the
# patcher, so it got lost on the next Anthropic release when the watcher
# re-patched. Build 31 makes it permanent here as a CSS-only patch — no JSX
# substitution to chase across minifier renames.
#
# JSX shape (from 2.1.132 webview/index.js):
# <div class="segmented_HASH">
# <button class="tab_HASH tabActive_HASH"><Pe1/>Local</button>
# <button class="tab_HASH"> <Bs/>Web</button>
# </div>
#
# Class-prefix selector ([class*="segmented_"] etc.) survives the per-release
# hash bump. ::after places the star at the end of the active tab — after the
# "Local" or "Web" label — matching the historical "Local ★" placement.
ACTIVE_TAB_STAR_CSS = (
'[class*="segmented_"] [class*="tab_"][class*="tabActive_"]::after{'
'content:" \\2605";'
'color:#FFD700;'
'font-size:13px;'
'flex-shrink:0;'
'line-height:1;'
'margin-left:4px;'
'text-shadow:0 0 3px rgba(255,215,0,.5)'
'}'
)
ACTIVE_TAB_STAR_MARKER = '[class*="segmented_"] [class*="tab_"][class*="tabActive_"]::after'
# Old Build 28 selector — used by the cleanup pass to strip the session-row
# star CSS rule left behind in the live bundle on machines that ran Build 28.
OLD_ACTIVE_SESSION_STAR_PREFIX = ".sessionItem_OOQiHg.active_OOQiHg::before"
# --- Show parent folders in tool-call rows ----------------------------------
# Anthropic's webview renders Read / Edit / Write / MultiEdit tool-call rows
# by displaying ONLY the basename of the touched file: every callsite calls
# `Z.file_path.split("/").pop()` and uses the result as the link text. With
# many parallel sessions across multiple repos, "patch-extension.py" alone is
# ambiguous — James needs to see which repo owns the file at a glance, per
# his fully-qualified-paths memory.
#
# Historical context: this was patched into the live bundle on 2026-05-03
# (see /tmp/patch_studio_server_extension.py + patch_mbp_extension_v2.py in
# the JSONLs from that session) but never made it into patch-extension.py.
# Every Anthropic re-emit + watcher re-patch since then has reverted it.
# Build 33 makes it permanent.
#
# Format: `.slice(-3).join("/")` — last 3 segments, e.g.
# `vscode-extension/patch-extension.py` or
# `cc/memory/feedback_fully_qualified_paths.md`. Enough to ID the repo,
# without the noise of `/Users/ojhurst/apps/`.
#
# Seven sites across the 2.1.132 webview bundle. Click handlers untouched —
# they always open the full path stored on the tool input object.
# Build 11: anchored on the API property names (file_path, planFilePath,
# notebook_path) and the method name fileToolHeader, none of which the mangler
# touches — they are schema/interface identifiers, not locals. Build 10 pinned
# the surrounding locals ($, Z, J, Y) instead, so 2.1.219's rename made all
# seven anchors miss and the patch reported "no anchors matched" while the
# feature was in fact still live from a hand-patch. Property-name anchoring
# survives re-minification.
FULL_PATH_TOOL_HEADER_RES = (
# Edit / Write / MultiEdit share this method; its arg is a bare local.
re.compile(r'(fileToolHeader\(\w+,\w+,\w+\)\{let \w+=\w+\?)\.split\("/"\)\.pop\(\)'),
# Read header, batched fileReads, both permissionRequest dialogs, the Write
# body label, ExitPlanMode, and NotebookEdit — all keyed on the property.
re.compile(
r'((?:\(\w+\.file_path\|\|""\)|\w+\.file_path\??'
r'|\w+\.planFilePath|\w+\.notebook_path\??))\.split\("/"\)\.pop\(\)'
),
)
FULL_PATH_TOOL_HEADER_SUB = r'\1.split("/").slice(-3).join("/")'
# Already-patched detection, also property-anchored.
FULL_PATH_TOOL_HEADER_MARKER_RE = re.compile(
r'(?:fileToolHeader\(\w+,\w+,\w+\)\{let \w+=\w+\?|\w+\.file_path\??)'
r'\.split\("/"\)\.slice\(-3\)\.join\("/"\)'
)
# --- Folder search by name in @ mention dropdown -----------------------------
# The IW() function in extension.js builds its folder list solely from parent
# paths of files whose FILENAME matches the query. Typing "@vscode-exten"
# finds screenshot PNGs (which have that string in their name) but never
# surfaces the vscode-extension/ folder because its children (build.txt, etc.)
# do not contain that string in their filename.
#
# Fix: after the existing file-derived directory pass, run a second findFiles
# with "**/*<query>*/**" to find any file inside a folder whose name matches.
# Extract the matching folder segments and add them as directory results.
#
# Anthropic re-minifies every release and identifiers rotate constantly. The
# previous approach maintained one literal-string ORIGINAL/PATCHED pair per
# rotation (V1 through V5) which broke on every minor release. The current
# approach matches the dir-sort fragment with a single regex that uses named
# backreferences, so the seven rotating single-letter idents (lowercased
# query, raw query, outer iterator, folder Set, result array, sort param a,
# sort param b) self-heal. The vscode module name and exclusion options var
# are pulled from the surrounding function with a separate lookback regex.
# Structural changes (e.g. the 2.1.138 regression from type-priority sort to
# pure-alphabetical) still need a human; identifier rotations do not.
IW_DIR_SORT_RE = re.compile(
r'let\s+(?P<lc>\w{1,3})=(?P<q>\w{1,3})\?\.toLowerCase\(\);'
r'for\(let\s+(?P<it>\w{1,3})\s+of\s+(?P<folder>\w{1,3})\)'
r'if\(!(?P=lc)\|\|(?P=it)\.toLowerCase\(\)\.includes\((?P=lc)\)\)'
r'(?P<result>\w{1,3})\.push\(\{path:(?P=it)\+"/",'
r'name:(?P=it)\.split\("/"\)\.pop\(\)\|\|"",type:"directory"\}\);'
r'(?P=result)\.sort\(\((?P<sa>\w{1,3}),(?P<sb>\w{1,3})\)=>'
r'(?:'
r'(?P=sa)\.type===(?P=sb)\.type\?'
r'(?P=sa)\.path\.localeCompare\((?P=sb)\.path\):'
r'(?P=sa)\.type==="directory"\?-1:1'
r'|'
r'(?P=sa)\.path\.localeCompare\((?P=sb)\.path\)'
r'\)'
r')'
)
# Captures the vscode module name and the exclusion options var from the
# nearest preceding `await <m>.workspace.findFiles(<glob>, <opts>, 100)` —
# both live in the same function as the dir-sort fragment.
IW_VSCODE_OPTS_RE = re.compile(
r'\bawait\s+(\w{1,3})\.workspace\.findFiles\(\w{1,3},(\w{1,3}),100\)'
)
IW_DIR_SORT_PATCHED_MARKER = 'workspace.findFiles("**/*"+'
# --- Fix Dp4 basename for directory paths ------------------------------------
# Dp4() maps each candidate path to {path, filename, testPenalty}. For directory
# paths derived from Op4() they always end in "/" (e.g. "fb-email-slurper-3000/").
# path.basename("fb-email-slurper-3000/") returns "" (empty string) because Node
# path.basename strips a trailing slash first and then finds nothing.
#
# Fuse.js weights filename at 2x and path at 1x. With filename="" the score is:
# (path_score*1 + 1.0*2) / 3 ≈ 0.7 → above threshold=0.5 → REJECTED.
#
# Fix: strip the trailing "/" before calling basename so directories get their
# correct short name ("fb-email-slurper-3000" instead of "").
#
# 2026-05-07: converted from literal string match to regex with backrefs so
# it survives the per-release minifier rename. Originally hardcoded `pT` for
# the path module; 2.1.132 renamed it to `lT`. The pattern now captures
# whichever 1–3 char identifier the minifier picked and reuses it in the
# replacement.
DP4_BASENAME_RE = re.compile(
r'(\w{1,3})=(\w{1,3})\.map\(\((\w{1,3})\)=>'
r'\(\{path:\3,filename:(\w{1,3})\.basename\(\3\),'
r'testPenalty:\3\.includes\("test"\)\?1:0\}\)\)'
)
# Patched-form detector: the strip-trailing-slash dance is unique to our
# patch. Identifiers are wildcarded so this matches regardless of which
# letters the next minifier picks.
DP4_BASENAME_PATCHED_RE = re.compile(
r'filename:\w{1,3}\.basename\('
r'\w{1,3}\.endsWith\("/"\)\?\w{1,3}\.slice\(0,-1\):\w{1,3}\),'
)
# --- Folder-first sort in @ mention dropdown ---------------------------------
# After the folder-search patch, results are sorted purely alphabetically.
# Patch changes the final sort so directories come before files, and within
# each group results sort by BASENAME (last path segment) rather than full
# path. The basename change matters: typing @freeflow-d should surface
# freeflow-dev/ at the top, not a deeper folder like
# image-create/doodle/freeflow-dev-icon/ whose path prefix sorts earlier.
# With basename sort, "freeflow-dev" wins over "freeflow-dev-icon"
# alphabetically — the shorter exact-prefix folder rises to #1.
#
# The match accepts either the upstream original (pure-alphabetical sort) or
# the type-priority intermediate form left behind by folder-search v1+, and
# captures the three rotating identifiers (sort param a, sort param b, result
# array). Same self-healing approach as IW_DIR_SORT_RE — identifier rotations
# do not require code changes.
IW_SORT_RE = re.compile(
r'(?P<result>\w{1,3})\.sort\(\((?P<sa>\w{1,3}),(?P<sb>\w{1,3})\)=>'
r'(?:'
# upstream type-priority form
r'(?P=sa)\.type===(?P=sb)\.type\?'
r'(?P=sa)\.path\.localeCompare\((?P=sb)\.path\):'
r'(?P=sa)\.type==="directory"\?-1:1'
r'|'
# upstream pure-alphabetical form
r'(?P=sa)\.path\.localeCompare\((?P=sb)\.path\)'
r'|'
# this patcher's earlier basename-only form — matched so the relevance
# upgrade can replace it in place, no backup restore needed
r'\{if\((?P=sa)\.type!==(?P=sb)\.type\)return (?P=sa)\.type==="directory"\?-1:1;'
r'let _bn=p=>\{let t=p\.endsWith\("/"\)\?p\.slice\(0,-1\):p;return t\.split\("/"\)\.pop\(\)\};'
r'return _bn\((?P=sa)\.path\)\.localeCompare\(_bn\((?P=sb)\.path\)\)\}'
r')'
r'\)\}catch\{\}return\s+(?P=result)\}'
)
# Marker proving the current ranked-and-filtered sort is present. A bundle
# carrying any older sort form will NOT contain it. Bumped to v3 when the
# dropdown started dropping directories that do not match the query.
IW_SORT_PRIORITY_MARKER = '/*__cce_relrank3__*/'
# The lowercased-query var, declared `let <x>=<y>?.toLowerCase();` at the head
# of the IW dir block. folder-sort-priority closes its comparator over this so
# it can rank each folder by how well its name matches what the user typed.
IW_LC_LOOKBACK_RE = re.compile(r'let\s+(\w{1,3})=\w{1,3}\?\.toLowerCase\(\);')
# --- Open session as next tab at far right (not split pane) -------------------
# When opening a session from the sessions list and no existing Claude tab group
# is found, the stock code calls findUnusedColumn() which creates a new split
# pane. Instead, find the rightmost non-empty tab group and open there so the
# session lands to the right of everything else rather than wherever focus is.
# Falls back to ViewColumn.Beside (new split to the right) only if no tab
# groups exist at all (e.g. fresh empty VS Code window).
#
# Two originals are handled: the stock bundle form and the v1 patched form
# (ViewColumn.Active) so re-patching after a version bump works either way.
# NOTE: as of 2.1.128 the vscode module reference in this region is `C0` and
# the createPanel-local "started in new column" flag is `N`. Older bundles used
# `b0` and `x` respectively. If a future release renames the module again,
# refresh PATCHED_SESSION_SPLIT (two `C0` references) and ORIGINAL_SESSION_SPLIT
# (the trailing flag char) together. The V1 fallback string only catches a
# stale already-patched form on disk; harmless to leave even when its module
# name no longer matches the surrounding scope.
ORIGINAL_SESSION_SPLIT_V1 = 'else G=b0.ViewColumn.Active'
# Generic regex form — anchors on `findUnusedColumn()` and captures both the
# column variable (group 'colvar') and the flag variable (group 'flagvar').
# Survives the build-to-build minified rename churn (G/x/N swap pattern seen
# across 2.1.126 → 2.1.138). The vscode module identifier is captured separately
# below from the adjacent `.window.createWebviewPanel("claudeVSCodePanel"...)`
# call so we can rewrite ViewColumn.Beside against the right import alias.
SESSION_SPLIT_RE = re.compile(
r'else\s+(?P<colvar>[A-Za-z_$][\w$]*)\s*=\s*this\.findUnusedColumn\(\)\s*,\s*'
r'(?P<flagvar>[A-Za-z_$][\w$]*)\s*=\s*!0'
)
SESSION_SPLIT_MODULE_RE = re.compile(
r'([A-Za-z_$][\w$]*)\.window\.createWebviewPanel\("claudeVSCodePanel"'
)
SESSION_SPLIT_PATCHED_MARKER = '_tg.reduce((a,c)=>a.viewColumn>c.viewColumn'
# --- Strip broken moveEditorToEndOfGroup call -------------------------------
# The Remote-SSH bundle of 2.1.126 (and possibly later builds) registers the
# claude-vscode.editor.open command with a trailing call to
# workbench.action.moveEditorToEndOfGroup
# That command does not exist in VS Code, so every "Open in New Tab" invocation
# pops an error dialog. The local-install bundle for the SAME version label
# does NOT contain this call — Anthropic ships two different artifacts under
# 2.1.126 depending on Remote-SSH vs local install.
#
# Match on the broken command name so the patch survives minified identifier
# changes (the vscode import alias is currently I4 but renames build-to-build).
# Drop the leading semicolon too so the surrounding statement still terminates
# cleanly.
BROKEN_MOVE_EDITOR_PATTERN = re.compile(
r';await [A-Za-z_$][A-Za-z0-9_$]*\.commands\.executeCommand'
r'\("workbench\.action\.moveEditorToEndOfGroup"\)'
)
def patch_strip_broken_move_editor(text: str) -> tuple[str, list[str], list[str]]:
"""Remove the bogus workbench.action.moveEditorToEndOfGroup call."""
applied: list[str] = []
skipped: list[str] = []
matches = list(BROKEN_MOVE_EDITOR_PATTERN.finditer(text))
if not matches:
skipped.append("strip-broken-move-editor (not present)")
return text, applied, skipped
new_text = BROKEN_MOVE_EDITOR_PATTERN.sub("", text)
applied.append(f"strip-broken-move-editor ({len(matches)} site)")
return new_text, applied, skipped
def patch_title_unlock(text: str) -> tuple[str, list[str], list[str]]:
"""Drop the 300px cap on the active-session title bar.
The header is `display:flex` with a sibling `headerSpacer` set to flex:1,
so removing just the cap on titleGroup lets the title use as much
horizontal room as is free without disturbing the right-side buttons.
Single-line ellipsis behavior in titleTextInner is left intact so the
rare title that exceeds the full header width still clips cleanly
instead of wrapping the header onto two rows.
Returns (new_text, applied_messages, skipped_messages).
"""
applied: list[str] = []
skipped: list[str] = []
new_text = text
if TITLE_UNLOCK_PATCHED_MARKER in new_text:
skipped.append("title-unlock (already)")
return new_text, applied, skipped
if ORIGINAL_TITLE_GROUP_RULE not in new_text:
skipped.append("title-unlock (titleGroup rule not found)")
return new_text, applied, skipped
new_text = new_text.replace(
ORIGINAL_TITLE_GROUP_RULE, PATCHED_TITLE_GROUP_RULE, 1
)
applied.append("title-unlock (300px cap dropped)")
return new_text, applied, skipped
def patch_dynamic_tab_widths(text: str) -> tuple[str, list[str], list[str]]:
"""Append responsive navTabLabel max-width rules keyed on tab count.
Uses CSS :has() so no JS is needed — the browser recalculates on every
DOM change. Rules cascade in declaration order so the highest tab-count
match wins.
Returns (new_text, applied_messages, skipped_messages).
"""
applied: list[str] = []
skipped: list[str] = []
if DYNAMIC_TAB_WIDTH_MARKER in text:
skipped.append("dynamic-tab-widths (already)")
return text, applied, skipped
if ORIGINAL_NAV_TAB_LABEL_RULE not in text:
skipped.append("dynamic-tab-widths (navTabLabel rule not found)")
return text, applied, skipped
new_text = text
# Strip prior forms in newest-first order so superset rules don't survive.
if OLD_DYNAMIC_TAB_WIDTH_RULES_V3 in new_text:
new_text = new_text.replace(OLD_DYNAMIC_TAB_WIDTH_RULES_V3, "", 1)
applied.append("dynamic-tab-widths (stripped Build 17 tier-by-count form)")
elif OLD_DYNAMIC_TAB_WIDTH_RULES_V2 in new_text:
new_text = new_text.replace(OLD_DYNAMIC_TAB_WIDTH_RULES_V2, "", 1)
applied.append("dynamic-tab-widths (stripped Build 16 single-line form)")
elif OLD_DYNAMIC_TAB_WIDTH_RULES_V1 in new_text:
new_text = new_text.replace(OLD_DYNAMIC_TAB_WIDTH_RULES_V1, "", 1)
applied.append("dynamic-tab-widths (stripped Build 7-15 form)")
new_text = new_text.rstrip() + "\n" + DYNAMIC_TAB_WIDTH_RULES + "\n"
applied.append(
"dynamic-tab-widths (flex 1 1 0 — labels fill pills, share container)"
)
return new_text, applied, skipped
def image_pill_rule() -> str:
"""Scoped rule appended to the CSS — applies only when a pill has a
.thumbIcon child (image kind). Text/document context pills never match
this selector, so they keep the stock 24px height."""
return (
".pill_lcdCYQ:has(.thumbIcon_lcdCYQ){"
f"gap:{PILL_GAP}px !important;"
f"max-width:{PILL_MAX_WIDTH}px !important;"
f"height:{PILL_HEIGHT}px !important;"
f"min-height:{PILL_HEIGHT}px !important;}}"