@devries-cameron20 / t3code Mirror · read-only / commits / 524a53183d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 00:45 UTC

fix(mobile): tool call commands are highlighted and monospaced like on web (#33957)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 10, 2026 at 09:36 UTC 524a53183d81a8fe6417c20090cdb45cd6d133cc
12 files changed +244 -133
apps/mobile/global.css
+4
@@ -5,6 +5,10 @@
5 /* ─── Theme tokens ──────────────────────────────────────────────────── */
6 @layer theme {
7 :root {
8 + /* Native text takes one family name, not Tailwind's font stack. */
9 + @variant ios {
10 + --font-mono: "ui-monospace";
11 + }
12 @variant android {
13 --font-mono: "monospace";
14 }
apps/mobile/src/features/threads/thread-work-log.tsx
+42 -3
@@ -25,6 +25,7 @@ import {
25 useEffect,
26 useId,
27 useLayoutEffect,
28 + useMemo,
29 useRef,
30 useState,
31 type ComponentProps,
@@ -36,6 +37,7 @@ import {
37 Pressable,
38 ScrollView,
39 StyleSheet,
40 + Text as RNText,
41 useAnimatedValue,
42 View,
43 } from "react-native";
@@ -54,6 +56,11 @@ import { useAtomCommand } from "../../state/use-atom-command";
56 import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
57 import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity";
58 import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
59 +import { highlightCommand, type HighlightedLines } from "../../lib/highlights";
60 +import {
61 + commandHighlightLanguage,
62 + withVisibleControlCharacters,
63 +} from "@t3tools/client-runtime/work-log/command-label";
64
65 import { AppText as Text } from "../../components/ui/AppText";
66 import { T3Wordmark } from "../../components/T3Wordmark";
@@ -807,6 +814,31 @@ function ToolCodeText({
814 readonly theme: "light" | "dark";
815 }) {
816 const lines = useMarkdownCodeHighlight({ code, language, theme, enabled: true });
817 + return <HighlightedCodeText code={code} lines={lines} />;
818 +}
819 +
820 +function CommandCodeText({
821 + command,
822 + theme,
823 +}: {
824 + readonly command: string;
825 + readonly theme: "light" | "dark";
826 +}) {
827 + const code = withVisibleControlCharacters(command.trim());
828 + const lines = useMemo(
829 + () => highlightCommand(code, commandHighlightLanguage(code), theme),
830 + [code, theme],
831 + );
832 + return <HighlightedCodeText code={code} lines={lines} />;
833 +}
834 +
835 +function HighlightedCodeText({
836 + code,
837 + lines,
838 +}: {
839 + readonly code: string;
840 + readonly lines: HighlightedLines | null;
841 +}) {
842 let offset = 0;
843 const highlighted = lines?.flatMap((line, lineIndex) => {
844 const separator = lineIndex > 0 ? "\n" : "";
@@ -816,10 +848,11 @@ function ToolCodeText({
848 ...line.map((token) => {
849 const start = offset;
850 offset += token.content.length;
851 + // Plain RN Text inherits the mono font; AppText would reset it to sans.
852 return (
820 - <Text key={start} style={token.color ? { color: token.color } : undefined}>
853 + <RNText key={start} style={token.color ? { color: token.color } : undefined}>
854 {token.content}
822 - </Text>
855 + </RNText>
856 );
857 }),
858 ];
@@ -1179,7 +1212,13 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
1212 props.renderReasoning(reasoning.text)
1213 ) : call ? (
1214 [
1182 - call.command,
1215 + call.command ? (
1216 + <CommandCodeText
1217 + key="command"
1218 + command={call.command}
1219 + theme={props.themeAppearance}
1220 + />
1221 + ) : null,
1222 ...(call.args ?? []).map(([key, value]) => {
1223 const language =
1224 key === "html"
apps/mobile/src/lib/highlights.test.ts
+14 -1
@@ -3,7 +3,7 @@ import { pierreDark, pierreLight } from "@pierre/highlights/themes";
3 import { describe, expect, it, vi } from "vite-plus/test";
4
5 import { resolveHighlightLanguage } from "./highlightLanguage";
6 -import { highlightCode, tokenizeCode } from "./highlights";
6 +import { highlightCode, highlightCommand, tokenizeCode, type HighlightedLines } from "./highlights";
7
8 vi.mock("react-native-nitro-modules", async () => {
9 const { createWasmHighlightsModule } = await import("./highlights.testing");
@@ -37,6 +37,19 @@ describe("highlightCode", () => {
37 }
38 });
39
40 + it("colors a command's embedded script with that script's grammar", () => {
41 + const body = "import json\r\nprint(json.dumps({'ok': True}))";
42 + const code = `python3 - <<'PY'\r\n${body}\r\nPY`;
43 + const colors = (lines: HighlightedLines) =>
44 + lines.map((line) => line.map(({ content, color }) => [content, color]));
45 + const lines = highlightCommand(code, "shellscript", "dark");
46 +
47 + expect(lines.map((line) => line.map((token) => token.content).join(""))).toEqual(
48 + code.split("\r\n"),
49 + );
50 + expect(colors(lines.slice(1, 3))).toEqual(colors(highlightCode(body, "python", "dark")));
51 + });
52 +
53 it("keeps an over-long line as one plain token", () => {
54 const longLine = `const data = "${"x".repeat(1_000)}";`;
55 const [first, second] = highlightCode(`let a = 1;\n${longLine}`, "typescript", "dark");
apps/mobile/src/lib/highlights.ts
+45
@@ -1,3 +1,8 @@
1 +import {
2 + embeddedScripts,
3 + withEmbeddedScripts,
4 + type SyntaxToken,
5 +} from "@t3tools/client-runtime/work-log/embedded-scripts";
6 import type { T3Highlights } from "@t3tools/mobile-highlights-native";
7 import { NitroModules } from "react-native-nitro-modules";
8
@@ -82,6 +87,46 @@ export function tokenizeCode(code: string, language: string): TokenizedCode {
87 };
88 }
89
90 +/** Shell commands also color the scripts they embed, such as heredocs and `python -c`. */
91 +export function highlightCommand(
92 + code: string,
93 + language: "shellscript" | "powershell",
94 + scheme: HighlightScheme,
95 +): HighlightedLines {
96 + const tokenize = (text: string, lang: string) => {
97 + // A missing grammar keeps the shell colors, as on web.
98 + if (highlightLanguageId(lang) === 0) throw new Error(`No grammar for ${lang}`);
99 + return withOffsets(text, highlightCode(text, lang, scheme));
100 + };
101 + const embedded = language === "shellscript" ? embeddedScripts(code) : [];
102 + return withEmbeddedScripts(code, tokenize(code, language), embedded, tokenize).map((line) =>
103 + line.map((token) => ({
104 + content: token.content,
105 + color: token.color ?? null,
106 + fontStyle: token.fontStyle ?? null,
107 + })),
108 + );
109 +}
110 +
111 +function withOffsets(code: string, lines: HighlightedLines): SyntaxToken[][] {
112 + const endings = code.match(/\r?\n/gu) ?? [];
113 + let offset = 0;
114 + return lines.map((line, index) => {
115 + const tokens = line.map((token) => {
116 + const start = offset;
117 + offset += token.content.length;
118 + return {
119 + content: token.content,
120 + offset: start,
121 + ...(token.color ? { color: token.color } : {}),
122 + ...(token.fontStyle ? { fontStyle: token.fontStyle } : {}),
123 + };
124 + });
125 + offset += endings[index]?.length ?? 0;
126 + return tokens;
127 + });
128 +}
129 +
130 /** LF and CRLF split lines; a trailing line break yields a final empty line. */
131 export function highlightCode(
132 code: string,
apps/web/package.json
-1
@@ -86,7 +86,6 @@
86 "sql.js": "1.15.0",
87 "tailwind-merge": "^3.4.0",
88 "tiff": "7.1.3",
89 - "unbash": "^5.0.0",
89 "unified": "catalog:",
90 "use-sync-external-store": "^1.6.0",
91 "vfile": "^6.0.3",
apps/web/src/components/chat/HighlightedTokens.test.ts
+1 -50
@@ -1,7 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { embeddedScripts } from "../../lib/embeddedScripts";
4 -import { keyedLines, withEmbeddedScripts, wordsOf } from "./HighlightedTokens";
3 +import { keyedLines, wordsOf } from "./HighlightedTokens";
4
5 function tokensOf(...contents: string[]) {
6 let offset = 0;
@@ -34,51 +33,3 @@ describe("keyedLines", () => {
33 expect(rendered).toBe(code);
34 });
35 });
37 -
38 -describe("withEmbeddedScripts", () => {
39 - function tokenize(text: string, language: string) {
40 - if (language === "unknown") throw new Error("Language not found");
41 - let lineStart = 0;
42 - return text.split(/\r?\n/u).map((line) => {
43 - const tokens = [...line.matchAll(/\S+|\s+/gu)].map((match) => ({
44 - content: match[0],
45 - offset: lineStart + match.index,
46 - color: language,
47 - }));
48 - lineStart +=
49 - line.length + (text.slice(lineStart + line.length).match(/^\r?\n/u)?.[0].length ?? 0);
50 - return tokens;
51 - });
52 - }
53 -
54 - function colorsOf(code: string, scripts = embeddedScripts(code)) {
55 - const lines = withEmbeddedScripts(code, tokenize(code, "shellscript"), scripts, tokenize);
56 - expect(lines.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
57 - code.replaceAll("\r\n", "\n"),
58 - );
59 - return lines.flat().map((token) => [token.content, token.color]);
60 - }
61 -
62 - it("colors each nested script with its own grammar, keeping the text", () => {
63 - expect(colorsOf(`bash -lc "python3 -c 'print(1)'"`)).toEqual([
64 - [`bash -lc "python3 -c '`, "shellscript"],
65 - ["print(1)", "python"],
66 - [`'"`, "shellscript"],
67 - ]);
68 - });
69 -
70 - it("colors an escape sequence like the character it spells", () => {
71 - expect(colorsOf(`bash -c "python3 -c 'print(\\"x\\")'"`)).toContainEqual([
72 - `print(\\"x\\")`,
73 - "python",
74 - ]);
75 - });
76 -
77 - it("keeps the surrounding colors where a grammar is missing", () => {
78 - const code = "cat > x.ts <<'EOF'\r\nbody\r\nEOF";
79 - const [script] = embeddedScripts(code);
80 - const characterColors = (scripts: ReturnType<typeof embeddedScripts>) =>
81 - colorsOf(code, scripts).flatMap(([content, color]) => [...content!].map(() => color));
82 - expect(characterColors([{ ...script!, language: "unknown" }])).toEqual(characterColors([]));
83 - });
84 -});
apps/web/src/components/chat/HighlightedTokens.tsx
+6 -70
@@ -1,18 +1,14 @@
1 import { use, type CSSProperties } from "react";
2
3 +import {
4 + withEmbeddedScripts,
5 + type EmbeddedScript,
6 + type SyntaxToken,
7 +} from "@t3tools/client-runtime/work-log/embedded-scripts";
8 +
9 import { resolveDiffThemeName } from "../../lib/diffRendering";
4 -import type { EmbeddedScript } from "../../lib/embeddedScripts";
10 import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
11
7 -interface SyntaxToken {
8 - readonly content: string;
9 - readonly offset: number;
10 - readonly color?: string;
11 - readonly fontStyle?: number;
12 -}
13 -
14 -type TokenLines = ReadonlyArray<ReadonlyArray<SyntaxToken>>;
15 -
12 const NO_EMBEDDED_SCRIPTS: ReadonlyArray<EmbeddedScript> = [];
13
14 function syntaxTokenStyle(token: SyntaxToken): CSSProperties {
@@ -80,66 +76,6 @@ export function HighlightedTokens({
76 );
77 }
78
83 -export function withEmbeddedScripts(
84 - code: string,
85 - lines: TokenLines,
86 - embedded: ReadonlyArray<EmbeddedScript>,
87 - tokenize: (text: string, language: string) => TokenLines,
88 -): TokenLines {
89 - if (embedded.length === 0) return lines;
90 - const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
91 - for (const token of lines.flat()) {
92 - styles.fill(token, token.offset, token.offset + token.content.length);
93 - }
94 - for (const script of embedded) {
95 - let scriptLines: TokenLines;
96 - try {
97 - scriptLines = tokenize(script.text, script.language);
98 - } catch {
99 - continue;
100 - }
101 - for (const token of scriptLines.flat()) {
102 - if (token.content === "") continue;
103 - const last = token.offset + token.content.length - 1;
104 - styles.fill(token, script.starts[token.offset], script.ends[last]);
105 - }
106 - }
107 - return restyledLines(code, styles);
108 -}
109 -
110 -function restyledLines(
111 - code: string,
112 - styles: ReadonlyArray<SyntaxToken | undefined>,
113 -): SyntaxToken[][] {
114 - const lines: SyntaxToken[][] = [];
115 - let start = 0;
116 - for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
117 - const end = lineBreak?.index ?? code.length;
118 - const tokens: SyntaxToken[] = [];
119 - for (let index = start; index < end;) {
120 - const style = styles[index];
121 - let next = index + 1;
122 - while (
123 - next < end &&
124 - styles[next]?.color === style?.color &&
125 - styles[next]?.fontStyle === style?.fontStyle
126 - ) {
127 - next += 1;
128 - }
129 - tokens.push({
130 - content: code.slice(index, next),
131 - offset: index,
132 - ...(style?.color ? { color: style.color } : {}),
133 - ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
134 - });
135 - index = next;
136 - }
137 - lines.push(tokens);
138 - if (lineBreak) start = lineBreak.index + lineBreak[0].length;
139 - }
140 - return lines;
141 -}
142 -
79 /** Restore CRLF from source; Shiki strips both line-ending forms. */
80 export function keyedLines<Token extends SyntaxToken>(
81 code: string,
apps/web/src/components/chat/ShellCommandBlock.tsx
+4 -2
@@ -10,9 +10,11 @@ import { HighlightedTokens } from "./HighlightedTokens";
10
11 const WORD_CLASS_NAME = "inline-block max-w-full [overflow-wrap:anywhere]";
12
13 -let embeddedScriptsModule: Promise<typeof import("../../lib/embeddedScripts")> | undefined;
13 +let embeddedScriptsModule:
14 + | Promise<typeof import("@t3tools/client-runtime/work-log/embedded-scripts")>
15 + | undefined;
16 function loadEmbeddedScripts() {
15 - embeddedScriptsModule ??= import("../../lib/embeddedScripts");
17 + embeddedScriptsModule ??= import("@t3tools/client-runtime/work-log/embedded-scripts");
18 return embeddedScriptsModule;
19 }
20
packages/client-runtime/package.json
+6 -1
@@ -423,6 +423,10 @@
423 "types": "./src/work-log/commandLabel.ts",
424 "default": "./src/work-log/commandLabel.ts"
425 },
426 + "./work-log/embedded-scripts": {
427 + "types": "./src/work-log/embeddedScripts.ts",
428 + "default": "./src/work-log/embeddedScripts.ts"
429 + },
430 "./work-log/scroll-anchor": {
431 "types": "./src/work-log/scrollAnchor.ts",
432 "default": "./src/work-log/scrollAnchor.ts"
@@ -574,7 +578,8 @@
578 "@t3tools/source-control-definitions": "workspace:*",
579 "effect": "catalog:",
580 "jszip": "3.10.1",
577 - "three": "0.180.0"
581 + "three": "0.180.0",
582 + "unbash": "^5.0.0"
583 },
584 "devDependencies": {
585 "@effect/vitest": "catalog:",
packages/client-runtime/src/work-log/embeddedScripts.test.ts renamed
+49 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { embeddedScripts } from "./embeddedScripts";
3 +import { embeddedScripts, withEmbeddedScripts } from "./embeddedScripts.ts";
4
5 function scriptsOf(command: string) {
6 return embeddedScripts(command).map((script) => {
@@ -112,3 +112,51 @@ describe("embeddedScripts", () => {
112 expect(scriptsOf(command)).toEqual([]);
113 });
114 });
115 +
116 +describe("withEmbeddedScripts", () => {
117 + function tokenize(text: string, language: string) {
118 + if (language === "unknown") throw new Error("Language not found");
119 + let lineStart = 0;
120 + return text.split(/\r?\n/u).map((line) => {
121 + const tokens = [...line.matchAll(/\S+|\s+/gu)].map((match) => ({
122 + content: match[0],
123 + offset: lineStart + match.index,
124 + color: language,
125 + }));
126 + lineStart +=
127 + line.length + (text.slice(lineStart + line.length).match(/^\r?\n/u)?.[0].length ?? 0);
128 + return tokens;
129 + });
130 + }
131 +
132 + function colorsOf(code: string, scripts = embeddedScripts(code)) {
133 + const lines = withEmbeddedScripts(code, tokenize(code, "shellscript"), scripts, tokenize);
134 + expect(lines.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
135 + code.replaceAll("\r\n", "\n"),
136 + );
137 + return lines.flat().map((token) => [token.content, token.color]);
138 + }
139 +
140 + it("colors each nested script with its own grammar, keeping the text", () => {
141 + expect(colorsOf(`bash -lc "python3 -c 'print(1)'"`)).toEqual([
142 + [`bash -lc "python3 -c '`, "shellscript"],
143 + ["print(1)", "python"],
144 + [`'"`, "shellscript"],
145 + ]);
146 + });
147 +
148 + it("colors an escape sequence like the character it spells", () => {
149 + expect(colorsOf(`bash -c "python3 -c 'print(\\"x\\")'"`)).toContainEqual([
150 + `print(\\"x\\")`,
151 + "python",
152 + ]);
153 + });
154 +
155 + it("keeps the surrounding colors where a grammar is missing", () => {
156 + const code = "cat > x.ts <<'EOF'\r\nbody\r\nEOF";
157 + const [script] = embeddedScripts(code);
158 + const characterColors = (scripts: ReturnType<typeof embeddedScripts>) =>
159 + colorsOf(code, scripts).flatMap(([content, color]) => [...content!].map(() => color));
160 + expect(characterColors([{ ...script!, language: "unknown" }])).toEqual(characterColors([]));
161 + });
162 +});
packages/client-runtime/src/work-log/embeddedScripts.ts renamed
+70 -1
@@ -1,4 +1,4 @@
1 -import { getFiletypeFromFileName } from "@pierre/diffs";
1 +import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
2 import {
3 parse,
4 type Command,
@@ -16,6 +16,15 @@ export interface EmbeddedScript {
16 readonly ends: ReadonlyArray<number>;
17 }
18
19 +export interface SyntaxToken {
20 + readonly content: string;
21 + readonly offset: number;
22 + readonly color?: string;
23 + readonly fontStyle?: number;
24 +}
25 +
26 +type TokenLines = ReadonlyArray<ReadonlyArray<SyntaxToken>>;
27 +
28 interface MappedText {
29 readonly text: string;
30 readonly starts: ReadonlyArray<number>;
@@ -506,3 +515,63 @@ class MappedTextBuilder {
515 this.ends.push(start + length);
516 }
517 }
518 +
519 +export function withEmbeddedScripts(
520 + code: string,
521 + lines: TokenLines,
522 + embedded: ReadonlyArray<EmbeddedScript>,
523 + tokenize: (text: string, language: string) => TokenLines,
524 +): TokenLines {
525 + if (embedded.length === 0) return lines;
526 + const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
527 + for (const token of lines.flat()) {
528 + styles.fill(token, token.offset, token.offset + token.content.length);
529 + }
530 + for (const script of embedded) {
531 + let scriptLines: TokenLines;
532 + try {
533 + scriptLines = tokenize(script.text, script.language);
534 + } catch {
535 + continue;
536 + }
537 + for (const token of scriptLines.flat()) {
538 + if (token.content === "") continue;
539 + const last = token.offset + token.content.length - 1;
540 + styles.fill(token, script.starts[token.offset], script.ends[last]);
541 + }
542 + }
543 + return restyledLines(code, styles);
544 +}
545 +
546 +function restyledLines(
547 + code: string,
548 + styles: ReadonlyArray<SyntaxToken | undefined>,
549 +): SyntaxToken[][] {
550 + const lines: SyntaxToken[][] = [];
551 + let start = 0;
552 + for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
553 + const end = lineBreak?.index ?? code.length;
554 + const tokens: SyntaxToken[] = [];
555 + for (let index = start; index < end;) {
556 + const style = styles[index];
557 + let next = index + 1;
558 + while (
559 + next < end &&
560 + styles[next]?.color === style?.color &&
561 + styles[next]?.fontStyle === style?.fontStyle
562 + ) {
563 + next += 1;
564 + }
565 + tokens.push({
566 + content: code.slice(index, next),
567 + offset: index,
568 + ...(style?.color ? { color: style.color } : {}),
569 + ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
570 + });
571 + index = next;
572 + }
573 + lines.push(tokens);
574 + if (lineBreak) start = lineBreak.index + lineBreak[0].length;
575 + }
576 + return lines;
577 +}
pnpm-lock.yaml
+3 -3
@@ -1230,9 +1230,6 @@ importers:
1230 tiff:
1231 specifier: 7.1.3
1232 version: 7.1.3
1233 - unbash:
1234 - specifier: ^5.0.0
1235 - version: 5.0.0
1233 unified:
1234 specifier: 'catalog:'
1235 version: 11.0.5
@@ -1532,6 +1529,9 @@ importers:
1529 three:
1530 specifier: 0.180.0
1531 version: 0.180.0
1532 + unbash:
1533 + specifier: ^5.0.0
1534 + version: 5.0.0
1535 devDependencies:
1536 '@effect/vitest':
1537 specifier: 4.1.2