Skip to content

Commit 6e076f3

Browse files
authored
Merge pull request #6 from phase3dev/md-copy-export
feat(md-copy): per-message + whole-conversation markdown copy/export
2 parents 90bdfad + e71e702 commit 6e076f3

19 files changed

Lines changed: 2486 additions & 71 deletions

‎.github/workflows/ci.yml‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,27 @@ jobs:
3232

3333
- name: Node syntax check (node --check)
3434
run: |
35-
for f in launcher/claudemax.win.js fixes/thinking-summaries/proxy.js; do
35+
for f in launcher/claudemax.win.js fixes/thinking-summaries/proxy.js fixes/markdown-copy-export/webview-inject.js; do
3636
node --check "$f"
3737
done
3838
3939
- name: Python compile
40-
run: python3 -m py_compile fixes/context-icon/fix-context-icon.py tests/test_regressions.py tests/test_reconcile.py
40+
run: >
41+
python3 -m py_compile
42+
fixes/context-icon/fix-context-icon.py
43+
fixes/markdown-copy-export/cc-export.py
44+
fixes/markdown-copy-export/add-md-copy.py
45+
tools/gen-embeds
46+
tests/test_regressions.py tests/test_reconcile.py
47+
tests/test_md_export.py tests/test_md_converter.py tests/test_md_inject.py
48+
tests/test_md_patcher.py tests/test_gen_embeds.py
49+
50+
- name: Embed drift check
51+
# The launcher + standalone patcher carry a generated copy of the md-copy
52+
# webview payload. --strict fails the build if any of the three consumers is
53+
# missing its embed region (so a vanished region can't pass silently); --check
54+
# fails if a present region drifts from the single source.
55+
run: python3 tools/gen-embeds --check --strict
4156

4257
- name: Regression tests
4358
run: python3 -m unittest discover -s tests -v

‎README.md‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ Not affiliated with or endorsed by Anthropic. A future Claude Code update could
1414
The context-usage pie in the chat input is hidden until you have used more than 50% of the context window. With the 1M window that is about 500,000 tokens, so it is effectively never shown. Fix via the launcher (re-patches the webview on each launch), or a standalone patcher script.
1515
-> [details](#workaround-2-context-usage-icon)
1616

17+
3. **No markdown copy / export of chat** [added 2026-06-09].
18+
The chat cannot copy a whole message or the whole conversation as Markdown, and
19+
has no transcript export. Fix via the launcher (adds copy controls, re-applied
20+
each launch), a standalone patcher, or a standalone session exporter CLI.
21+
-> [details](fixes/markdown-copy-export/README.md)
22+
1723
## The launcher
1824

1925
The recommended fix for everything is one small launcher that wraps the real `claude` binary. It is a drop-in process wrapper carrying every fix in this repo; each fix is on by default and independently switchable with an environment variable, so the same artifact serves "I want everything" and "I want only X" without editing code and without recompiling.
@@ -29,6 +35,7 @@ Toggles (set in the environment where Claude Code launches, then reload):
2935
| `CC_RECONCILE` | `1` | `0` = do not read or write the webview bundle this launch (emergency bypass). Argument injection still runs. |
3036
| `CC_THINKING_DISPLAY` | `summarized` | `summarized` shows extended-thinking summaries; `omitted` hides them (no injection). |
3137
| `CC_PATCH_CONTEXT_ICON` | `1` | `0` leaves the context-usage icon unpatched (and reverts ours on the next launch). |
38+
| `CC_PATCH_MD_COPY` | `1` | `0` leaves the webview without the markdown copy/export controls (and reverts ours on the next launch). |
3239

3340
See [`launcher/README.md`](launcher/README.md) for wiring details, the VS Code env-setting how-to, and the build command.
3441

@@ -45,10 +52,15 @@ The three bash launchers and three Windows launchers are gone. There is now one
4552
| Old launcher | New equivalent |
4653
| --- | --- |
4754
| `claudemax` (both fixes) | `launcher/claudemax` - all fixes on (same behavior) |
48-
| `claude-think` (thinking only) | `launcher/claudemax` with `CC_PATCH_CONTEXT_ICON=0` |
49-
| `claude-context` (context icon only) | `launcher/claudemax` with `CC_THINKING_DISPLAY=omitted` |
55+
| `claude-think` (thinking only) | `launcher/claudemax` with `CC_PATCH_CONTEXT_ICON=0` (and `CC_PATCH_MD_COPY=0` if you do not want the copy UI) |
56+
| `claude-context` (context icon only) | `launcher/claudemax` with `CC_THINKING_DISPLAY=omitted` (and `CC_PATCH_MD_COPY=0` if you do not want the copy UI) |
5057
| any `.exe` | the single `claudemax.exe`; scope features via `CC_*` (VS Code `claudeCode.environmentVariables`) |
5158

59+
> The unified launcher enables **every** fix by default, including the new
60+
> markdown copy/export controls in the chat UI. If you do not want those controls,
61+
> set `CC_PATCH_MD_COPY=0` (the webview is left untouched and any prior install is
62+
> reverted on the next launch).
63+
5264
Old release assets remain available for anyone pinned to a previous version.
5365

5466
---
@@ -309,6 +321,10 @@ Setup is otherwise identical to Option 1. This is unrelated to the fixes above.
309321
| [`fixes/thinking-summaries/proxy.js`](fixes/thinking-summaries/proxy.js) | thinking | Option 3 localhost proxy. Advanced and untested. |
310322
| [`fixes/thinking-summaries/test-thinking-display.sh`](fixes/thinking-summaries/test-thinking-display.sh) | thinking | Live A/B test showing that the flag is the relevant lever. |
311323
| [`fixes/context-icon/fix-context-icon.py`](fixes/context-icon/fix-context-icon.py) | context icon | Option 2 standalone webview patcher with `--revert`. |
324+
| [`fixes/markdown-copy-export/add-md-copy.py`](fixes/markdown-copy-export/add-md-copy.py) | markdown copy | Standalone webview patcher (sentinel block, reverse-transform `--revert`). |
325+
| [`fixes/markdown-copy-export/cc-export.py`](fixes/markdown-copy-export/cc-export.py) | markdown copy | Standalone session exporter (markdown/text, `--open`). |
326+
| [`fixes/markdown-copy-export/webview-inject.js`](fixes/markdown-copy-export/webview-inject.js) | markdown copy | Single source of the appended copy-controls IIFE. |
327+
| [`tools/gen-embeds`](tools/gen-embeds) | markdown copy | Generates the embedded payload into the launcher + patcher; `--check` drift gate. |
312328
| [`TECHNICAL.md`](TECHNICAL.md) | both | Full root-cause analysis, the reconcile model, and design notes. |
313329

314330
## Releases

‎TECHNICAL.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,25 @@ Every launch, for each webview file a bundle-patch feature targets, the launcher
217217

218218
Timing note: the wrapper patches `index.js` on disk when the CLI is spawned, which can be *after* the webview already loaded the old bundle. So the first time you enable it you may need two reloads (the spawn patches the file, then the webview loads the patched bundle). Later windows and post-update launches are already patched on disk.
219219

220+
**Append features and multiple files.** A feature is either an *in-place* edit
221+
(context-icon: a marked swap deep in `index.js`) or an *append* (md-copy: a
222+
sentinel-delimited block at end-of-file). Each append feature's `undo` is
223+
marker-scoped block removal (it deletes exactly its own OPEN..CLOSE block and
224+
keeps any bytes after CLOSE), so append features compose with in-place features
225+
and with each other without overlap, regardless of registration order. The reconcile runs per
226+
file with that file's own feature list: `index.js` carries `[context-icon,
227+
md-copy]`; `index.css` carries `[md-copy]`. md-copy's block is byte-identical
228+
across the bash launcher (quoted heredocs), the node launcher (JSON string
229+
literals), and the standalone `add-md-copy.py` (base64): `"\n" + OPEN + "\n" +
230+
PAYLOAD + "\n" + CLOSE + "\n"`, where `OPEN`/`CLOSE` are `/* cc-md-copy v1 */`
231+
and `/* /cc-md-copy v1 */` and `PAYLOAD` is the source with trailing newlines
232+
stripped. The payload's single source is `fixes/markdown-copy-export/webview-inject.{js,css}`;
233+
`tools/gen-embeds` writes the embedded copies and `tools/gen-embeds --check`
234+
fails the build on drift. The standalone `add-md-copy.py` keeps its own
235+
`.bak-md-copy` emergency snapshot; its `--revert` is the same reverse transform
236+
(not a backup restore), so removing md-copy never disturbs a co-applied
237+
context-icon.
238+
220239
## How the icon works (context for future changes)
221240

222241
### Data source resets on reload
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# markdown-copy-export
2+
3+
## What it fixes
4+
5+
The Claude Code VS Code chat has no way to copy a whole message or the whole
6+
conversation as Markdown (only code blocks have a copy button). This adds a
7+
per-message copy control (Markdown primary, plain text secondary) on every user
8+
and assistant message, a "copy entire conversation" control, and a standalone
9+
CLI that exports a session transcript to Markdown/plain text or opens the raw
10+
`.jsonl`. Affects the VS Code extension webview; the CLI is independent of it.
11+
12+
## Standalone usage
13+
14+
Webview controls (one-shot patch, re-applied automatically by the launcher):
15+
16+
python3 fixes/markdown-copy-export/add-md-copy.py # patch all installs
17+
python3 fixes/markdown-copy-export/add-md-copy.py --revert # remove (reverse transform)
18+
python3 fixes/markdown-copy-export/add-md-copy.py /path/to/webview/index.js
19+
20+
Reload the window after patching (first enable may need two reloads, like
21+
context-icon). `--revert` removes only our sentinel block, so it composes with
22+
the context-icon patcher on the same file.
23+
24+
Session exporter (independent of the webview):
25+
26+
python3 fixes/markdown-copy-export/cc-export.py # latest session -> markdown
27+
python3 fixes/markdown-copy-export/cc-export.py --format text
28+
python3 fixes/markdown-copy-export/cc-export.py --include-thinking --include-tools
29+
python3 fixes/markdown-copy-export/cc-export.py --session ID -o out.md
30+
python3 fixes/markdown-copy-export/cc-export.py --open # open raw .jsonl in VS Code
31+
32+
## Launcher toggle
33+
34+
`CC_PATCH_MD_COPY` (default `1`). `0` leaves the webview without the copy
35+
controls and reverts ours on the next launch. `CC_WORKAROUNDS=0` reverts it too.
36+
37+
## Maintenance Contract
38+
39+
- Anchors / selectors: user bubble `[class*="userMessageContainer_"]`; assistant
40+
bubble `[data-testid="assistant-message"]` (NOT `[data-message-rating]` — that is
41+
the nested, experiment+analytics-gated rating widget, which the sanitizer strips);
42+
chrome strip-prefixes `toolUse_`/`toolResult_`/`toolReference_`/`thinking_`/
43+
`unknownContent_` plus `[data-message-rating]` and `button`;
44+
`navigator.clipboard.writeText` (proven to work via the built-in copy-code
45+
button). Optional refinements pinned at install: the messages container and the
46+
single all-content wrapper, if any (see the inject source constants
47+
`MESSAGES_CONTAINER` / `ASSISTANT_CONTENT`). When a bundle update renames the
48+
bubble anchor or a chrome hook, the Phase-9 selector guard fails loudly; re-pin
49+
the constant and the Phase-2 fixtures together.
50+
- Ownership marker: the sentinel block `/* cc-md-copy v1 */ ... /* /cc-md-copy v1 */`
51+
appended to `webview/index.js` (the IIFE) and `webview/index.css` (its styles).
52+
- Failure mode if an anchor moves: fails safe - the controls simply do not appear
53+
(the IIFE no-ops; `boot()` is fully guarded). The conversation walk degrades to
54+
"no bubbles matched", never wrong output. The launcher patch still installs.
55+
- Launcher registry entry: feature id `md-copy`, files `webview/index.js` +
56+
`webview/index.css`, apply = append the sentinel block (registered LAST, after
57+
context-icon), undo = marker-scoped block removal (deletes exactly its own
58+
OPEN..CLOSE block, keeps any bytes after CLOSE; composes regardless of ordering).
59+
The payload is the single source `webview-inject.{js,css}`,
60+
embedded into the launcher and `add-md-copy.py` by `tools/gen-embeds` (CI drift
61+
check: `tools/gen-embeds --check`).
62+
- Test fixture: `tests/test_md_converter.py`, `tests/test_md_inject.py`,
63+
`tests/test_md_patcher.py`, `tests/test_md_export.py`, `tests/test_gen_embeds.py`,
64+
and the `md-copy` cases in `tests/test_reconcile.py`.

‎fixes/markdown-copy-export/add-md-copy.py‎

Lines changed: 165 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
#!/usr/bin/env python3
2+
"""cc-export - export a Claude Code session transcript to Markdown or plain text.
3+
4+
Reads the session JSONL directly (the high-fidelity source: exact text, no
5+
re-conversion), so it is independent of the VS Code webview. Default output is
6+
the readable conversation only (user text + assistant text); thinking and tool
7+
calls are opt-in. `--open` opens the raw .jsonl in the editor instead.
8+
9+
python3 cc-export.py # latest session in this cwd -> stdout (markdown)
10+
python3 cc-export.py --session ID # a specific session id
11+
python3 cc-export.py --format text # plain text
12+
python3 cc-export.py --include-thinking --include-tools
13+
python3 cc-export.py -o out.md # write to a file
14+
python3 cc-export.py --open # open the raw transcript in VS Code
15+
python3 cc-export.py --cwd /path/to/proj # resolve as if launched from there
16+
17+
The JSONL is an internal format that can change, so each row's shape is validated
18+
and unknown shapes are skipped rather than assuming a fixed schema.
19+
"""
20+
import argparse
21+
import glob
22+
import json
23+
import os
24+
import subprocess
25+
import sys
26+
import unicodedata
27+
28+
29+
def config_dir(env=None):
30+
env = env if env is not None else os.environ
31+
return env.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude")
32+
33+
34+
def project_key_for_cwd(cwd):
35+
"""The on-disk project dir name: realpath, NFC-normalized, slashes -> dashes."""
36+
real = os.path.realpath(cwd)
37+
norm = unicodedata.normalize("NFC", real)
38+
return norm.replace(os.sep, "-").replace("/", "-")
39+
40+
41+
def resolve_session(config, cwd, session_id):
42+
"""Return the path to the session JSONL, or None.
43+
44+
With an explicit id: look in this cwd's project dir, then scan all project
45+
dirs. With no id: the most recently modified .jsonl in this cwd's project dir.
46+
"""
47+
projects = os.path.join(config, "projects")
48+
key = project_key_for_cwd(cwd)
49+
proj_dir = os.path.join(projects, key)
50+
if session_id:
51+
local = os.path.join(proj_dir, f"{session_id}.jsonl")
52+
if os.path.isfile(local):
53+
return local
54+
for hit in glob.glob(os.path.join(projects, "*", f"{session_id}.jsonl")):
55+
if os.path.isfile(hit):
56+
return hit
57+
return None
58+
candidates = glob.glob(os.path.join(proj_dir, "*.jsonl"))
59+
if not candidates:
60+
return None
61+
return max(candidates, key=lambda p: os.path.getmtime(p))
62+
63+
64+
def read_rows(path):
65+
rows = []
66+
with open(path, "r", encoding="utf-8") as f:
67+
for line in f:
68+
line = line.strip()
69+
if not line:
70+
continue
71+
try:
72+
rows.append(json.loads(line))
73+
except json.JSONDecodeError:
74+
continue # skip a corrupt line rather than abort
75+
return rows
76+
77+
78+
def _blocks(content):
79+
"""Normalize a message's content to a list of block dicts.
80+
81+
Content may be a plain string (treated as one text block) or a list.
82+
"""
83+
if isinstance(content, str):
84+
return [{"type": "text", "text": content}]
85+
if isinstance(content, list):
86+
return [b for b in content if isinstance(b, dict)]
87+
return []
88+
89+
90+
def render(rows, fmt="markdown", include_thinking=False, include_tools=False):
91+
"""Render rows to markdown (with role headers) or plain text."""
92+
md = fmt != "text"
93+
parts = []
94+
for row in rows:
95+
if not isinstance(row, dict):
96+
continue
97+
rtype = row.get("type")
98+
if rtype not in ("user", "assistant"):
99+
continue # skip summary / file-history-snapshot / etc.
100+
message = row.get("message")
101+
if not isinstance(message, dict):
102+
continue
103+
blocks = _blocks(message.get("content"))
104+
chunks = []
105+
for b in blocks:
106+
bt = b.get("type")
107+
if bt == "text":
108+
t = b.get("text")
109+
if isinstance(t, str) and t.strip():
110+
chunks.append(t.rstrip())
111+
elif bt == "thinking" and include_thinking:
112+
t = b.get("thinking")
113+
if isinstance(t, str) and t.strip():
114+
chunks.append(_fence("thinking", t) if md else t.rstrip())
115+
elif bt == "tool_use" and include_tools:
116+
name = b.get("name", "tool")
117+
payload = json.dumps(b.get("input", {}), indent=2, ensure_ascii=False)
118+
chunks.append(_fence(f"tool_use {name}", payload) if md else f"[tool_use {name}] {payload}")
119+
elif bt == "tool_result" and include_tools:
120+
payload = b.get("content")
121+
if isinstance(payload, (dict, list)):
122+
payload = json.dumps(payload, indent=2, ensure_ascii=False)
123+
payload = "" if payload is None else str(payload)
124+
chunks.append(_fence("tool_result", payload) if md else f"[tool_result] {payload}")
125+
if not chunks:
126+
continue
127+
body = "\n\n".join(chunks)
128+
if md:
129+
header = "## User" if rtype == "user" else "## Assistant"
130+
parts.append(f"{header}\n\n{body}")
131+
else:
132+
parts.append(body)
133+
return ("\n\n".join(parts) + "\n") if parts else ""
134+
135+
136+
def _fence(label, text):
137+
# Pick a fence longer than the longest backtick run in the body, so content
138+
# that itself contains ``` cannot close the fence early.
139+
text = text.rstrip()
140+
longest = run = 0
141+
for ch in text:
142+
if ch == "`":
143+
run += 1
144+
longest = max(longest, run)
145+
else:
146+
run = 0
147+
fence = "`" * max(3, longest + 1)
148+
return f"{fence}{label}\n{text}\n{fence}"
149+
150+
151+
def main(argv=None, config=None, env=None):
152+
env = env if env is not None else os.environ
153+
argv = list(sys.argv[1:] if argv is None else argv)
154+
ap = argparse.ArgumentParser(prog="cc-export", description="Export a Claude Code session.")
155+
ap.add_argument("--session", default=None, help="session id (default: latest in cwd)")
156+
ap.add_argument("--cwd", default=None, help="resolve as if launched from this dir")
157+
ap.add_argument("--format", choices=("markdown", "text"), default="markdown")
158+
ap.add_argument("--include-thinking", action="store_true")
159+
ap.add_argument("--include-tools", action="store_true")
160+
ap.add_argument("--open", action="store_true", help="open the raw .jsonl in VS Code")
161+
ap.add_argument("-o", "--output", default=None, help="write to FILE (default: stdout)")
162+
args = ap.parse_args(argv)
163+
164+
conf = config if config is not None else config_dir(env)
165+
cwd = args.cwd or os.getcwd()
166+
path = resolve_session(conf, cwd, args.session)
167+
if not path:
168+
sys.stderr.write("cc-export: no matching session transcript found\n")
169+
return 1
170+
171+
if args.open:
172+
editor = env.get("CC_EDITOR", "code")
173+
try:
174+
subprocess.run([editor, path], check=False, env=env)
175+
except FileNotFoundError:
176+
sys.stderr.write(f"cc-export: editor '{editor}' not found on PATH\n")
177+
return 1
178+
return 0
179+
180+
out = render(
181+
read_rows(path),
182+
fmt=args.format,
183+
include_thinking=args.include_thinking,
184+
include_tools=args.include_tools,
185+
)
186+
if args.output:
187+
with open(args.output, "w", encoding="utf-8") as f:
188+
f.write(out)
189+
else:
190+
sys.stdout.write(out)
191+
return 0
192+
193+
194+
if __name__ == "__main__":
195+
sys.exit(main())

0 commit comments

Comments
 (0)