@yahyahammad/venastine 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tui/themes.py CHANGED
@@ -1,366 +1,559 @@
1
- """
2
- tui/themes.py
3
-
4
- Fourteen themes: the eight-theme neutral grid (dark/light x
5
- plain/red/green/blue) plus six standalone tinted themes (matrix,
6
- nightmare, ember, midnight, glassy-lapis, paper) whose PANELS carry the
7
- identity -- background/surface/panel are theirs, not the grid's shared
8
- neutrals.
9
-
10
- Pure presentation -- no import of core/, no harness state. Two things
11
- outside this module carry a theme name: the persisted `tui.theme` setting,
12
- validated by core/config_loader.py's _KNOWN_TUI, and tui/preferences.py's
13
- remembered choice. The second deliberately does NOT validate against
14
- THEME_NAMES -- it stores an opaque string and lets the App decide whether
15
- it still resolves, because ctrl+p's command palette can select one of
16
- Textual's own built-in themes and a whitelist here would silently forget
17
- it.
18
-
19
- Built on textual.theme.Theme (verified against the pinned textual 1.0.0,
20
- per D22's rule about not assuming a dependency's API shape). Textual
21
- derives the full variable set from these anchors, so each theme only
22
- declares the colours that actually differ.
23
- """
24
-
25
- from textual.color import Color
26
- from textual.theme import Theme
27
-
28
- # Shared neutrals. The accent variants below change only the three hue
29
- # slots (primary/secondary/accent), so a colour tweak to the base surfaces
30
- # lands in all eight grid themes at once rather than eight near-copies
31
- # drifting.
32
- _DARK_BASE = {
33
- "background": "#0f1115",
34
- "surface": "#171a21",
35
- "panel": "#1e222b",
36
- "foreground": "#e4e6eb",
37
- "warning": "#d9a441",
38
- "error": "#cf5c4a",
39
- "success": "#5aa86f",
40
- "dark": True,
41
- }
42
-
43
- _LIGHT_BASE = {
44
- "background": "#f7f7f5",
45
- "surface": "#ffffff",
46
- "panel": "#eceae6",
47
- "foreground": "#1b1c1e",
48
- "warning": "#9a6d10",
49
- "error": "#a63a2a",
50
- "success": "#2f7343",
51
- "dark": False,
52
- }
53
-
54
- # (primary, secondary, accent) per variant. Dark and light get separate
55
- # values because a hue readable on #0f1115 is usually too pale on #f7f7f5.
56
- #
57
- # The four DARK secondaries were lifted in batch 29 (#14): the pass role
58
- # renders in `secondary`, and every original value sat below 3.5:1 against
59
- # the shared dark background -- plain at 3.37 was the filed defect, red
60
- # ~2.7 and blue ~3.0 were the same defect nobody had measured. The floor
61
- # is pinned in tests/test_themes.py; these are the minimal luminance moves
62
- # that clear it.
63
- _ACCENTS_DARK = {
64
- # dark-plain's ACCENT was lifted in batch 41 (X1), for batch 29's
65
- # reason applied to a different axis. #14 measured contrast against
66
- # the BACKGROUND; this is separation between two roles that sit on
67
- # adjacent lines. `tool` renders in accent and `thinking` in
68
- # secondary, and on a deliberately monochrome theme hue cannot
69
- # separate them -- only lightness can. #a9b2c3 was 98.5 redmean
70
- # units from #8792a2, the tightest secondary/accent pair of all
71
- # fourteen themes (the next is paper at 143.8). #b8c1d1 is 142.7,
72
- # which clears that floor while staying 111 units off the
73
- # foreground -- go lighter and the assistant label melts into the
74
- # body text it introduces, which is the same defect facing the
75
- # other way.
76
- "plain": ("#8a93a3", "#8792a2", "#b8c1d1"),
77
- "red": ("#d4674f", "#b0513c", "#e8917b"),
78
- "green": ("#5fa876", "#4d8f63", "#8ecba1"),
79
- "blue": ("#5b90cc", "#4a76b3", "#8bb6e6"),
80
- }
81
-
82
- _ACCENTS_LIGHT = {
83
- "plain": ("#5a6273", "#3c4252", "#7d8595"),
84
- "red": ("#b04a33", "#7d3423", "#c9705a"),
85
- "green": ("#3f7f57", "#2b5a3c", "#5d9c74"),
86
- "blue": ("#3f6fa8", "#2b4d76", "#6091c7"),
87
- }
88
-
89
- # Standalone tinted themes (batch 29). Each OVERRIDES the shared base
90
- # outright -- that is their identity: the panels themselves carry the
91
- # palette, not just borders and text. Severity slots default to the grid
92
- # trio and are overridden ONLY where contrast against the theme's own
93
- # tint demands it, keeping the semantic hue family (danger stays
94
- # red-ish); every override carries its reason, and the floors live in
95
- # tests/test_themes.py (foreground >= 7:1, severity >= 4:1, identity
96
- # >= 3.5:1, all against the theme's own background).
97
- _STANDALONE = [
98
- dict(
99
- name="matrix", dark=True,
100
- background="#0a120c", surface="#0f1a12", panel="#14231a",
101
- foreground="#c8e6d0",
102
- primary="#3dd968", secondary="#2f9e52", accent="#7dffb0",
103
- # success overridden: the shared #5aa86f dissolves into matrix's
104
- # own green-dark background.
105
- success="#4ee08a",
106
- ),
107
- dict(
108
- name="nightmare", dark=True,
109
- background="#140b0e", surface="#1c0f14", panel="#251318",
110
- foreground="#e8d5d8",
111
- primary="#c94f5f", secondary="#a8556a", accent="#e88a96",
112
- # error overridden: red-on-red -- the shared #cf5c4a loses the
113
- # alarm against nightmare's blood background.
114
- error="#ff7b6b",
115
- ),
116
- dict(
117
- name="ember", dark=True,
118
- background="#16100a", surface="#1f1610", panel="#291d13",
119
- foreground="#ecdfd0",
120
- primary="#e08a3c", secondary="#a86228", accent="#f2b06a",
121
- # warning overridden yellower: the shared amber sat on top of
122
- # ember's primary orange and read as emphasis, not as caution.
123
- warning="#d9b83f",
124
- ),
125
- dict(
126
- name="midnight", dark=True,
127
- background="#0a0f1e", surface="#101830", panel="#16203c",
128
- foreground="#d5dcea",
129
- primary="#6f9fe8", secondary="#4a6fb0", accent="#9dbdf2",
130
- ),
131
- dict(
132
- name="glassy-lapis", dark=True,
133
- background="#14243f", surface="#1c2f52", panel="#243a63",
134
- foreground="#e2ecf8",
135
- primary="#7fb4ff", secondary="#5a8ac9", accent="#a8ccff",
136
- # error overridden: lapis is the lightest dark background, and
137
- # the shared #cf5c4a fell just under the severity floor on it.
138
- error="#e06a58",
139
- ),
140
- dict(
141
- name="paper", dark=False,
142
- background="#f4efe6", surface="#fbf8f2", panel="#eae3d5",
143
- foreground="#2b2620",
144
- primary="#7a5c2e", secondary="#5c4a32", accent="#9c7b45",
145
- ),
146
- ]
147
-
148
-
149
- def _build(variant: str, dark: bool) -> Theme:
150
- base = _DARK_BASE if dark else _LIGHT_BASE
151
- primary, secondary, accent = (
152
- _ACCENTS_DARK if dark else _ACCENTS_LIGHT
153
- )[variant]
154
- return Theme(
155
- name=f"{'dark' if dark else 'light'}-{variant}",
156
- primary=primary,
157
- secondary=secondary,
158
- accent=accent,
159
- **base,
160
- )
161
-
162
-
163
- def _build_standalone(spec: dict) -> Theme:
164
- base = _DARK_BASE if spec["dark"] else _LIGHT_BASE
165
- merged = {**base, **{k: v for k, v in spec.items() if k != "name"}}
166
- return Theme(name=spec["name"], **merged)
167
-
168
-
169
- ALL_THEMES = (
170
- [
171
- _build(variant, dark)
172
- for dark in (True, False)
173
- for variant in ("plain", "red", "green", "blue")
174
- ]
175
- + [_build_standalone(spec) for spec in _STANDALONE]
176
- )
177
-
178
- THEME_NAMES = [t.name for t in ALL_THEMES]
179
- DEFAULT_THEME = "dark-plain"
180
-
181
-
182
- def register_all(app) -> None:
183
- """Register every theme on the app. Call before setting app.theme."""
184
- for theme in ALL_THEMES:
185
- app.register_theme(theme)
186
-
187
-
188
- # ---------------------------------------------------------------------------
189
- # ---- Role palette (ROADMAP_v2 §26) ----------------------------------------
190
- # ---------------------------------------------------------------------------
191
- #
192
- # The transcript was uniformly white: a user message, the model's answer, a
193
- # pipeline trace line and a tool call were the same colour, and the "you"
194
- # label read as the first word of the message it introduced.
195
- #
196
- # WHY THIS IS A FUNCTION OF A THEME rather than a table of colour names.
197
- # Everything else in the TUI styles itself through app.tcss, which uses
198
- # theme variables ($panel, $primary) and so restyles across all fourteen
199
- # themes without edits. A RichLog cannot do that -- it renders Rich Text
200
- # objects, and a Rich style needs a concrete colour, not a variable to
201
- # resolve later. So the resolution happens here, against the Theme
202
- # object, and the same property holds: no literal appears below, and a
203
- # new theme needs no change in this section.
204
- #
205
- # Severity colours. Across the eight GRID themes, warning/error/success
206
- # are shared by _DARK_BASE and _LIGHT_BASE and mean the same thing
207
- # everywhere; primary/secondary/accent are the per-variant hues. A
208
- # STANDALONE theme may override a severity slot when its own panel tint
209
- # would swallow the shared value (matrix's success, nightmare's error,
210
- # ember's warning, glassy-lapis's error -- each with its reason above),
211
- # keeping the semantic hue family. Either way severity uses the
212
- # theme-resolved trio and identity uses the hues, rather than the
213
- # reverse. Floors are pinned in tests/test_themes.py.
214
-
215
- #: How far a diff row's background is blended TOWARD the theme's own
216
- #: background (batch 41, X7). 0.8 leaves a band that stands off the
217
- #: page by 1.22-1.53 across the fourteen themes while the foreground
218
- #: still reads on it at 9.3:1 or better -- a highlight rather than a
219
- #: slab. Both floors are pinned in tests/test_themes.py.
220
- DIFF_TINT = 0.8
221
-
222
-
223
- def _tint(colour: str, background: str, factor: float = DIFF_TINT) -> str:
224
- """`colour` faded toward `background`, as a hex string.
225
-
226
- Derived from the theme's own slots rather than written down, for
227
- the reason the whole of this section exists (#116): a literal pair
228
- of green and red backgrounds would be designed against one of the
229
- fourteen palettes and wrong on the other thirteen -- and on the six
230
- standalone themes, whose panels carry the identity, visibly so.
231
- """
232
- return Color.parse(colour).blend(Color.parse(background), factor).hex
233
-
234
-
235
- def role_styles(theme: Theme) -> dict[str, str]:
236
- """Rich style strings keyed by transcript role, for one theme.
237
-
238
- Roles are what a line MEANS, not where it came from: `pass` covers a
239
- research pass boundary whether the CLI or the TUI produced it, and
240
- `tool_error` is a failed tool call rather than "amber".
241
- """
242
- return {
243
- # Who is speaking. The hues, because these distinguish identity.
244
- "user": f"bold {theme.primary}",
245
- "user_label": f"bold {theme.primary}",
246
- "assistant_label": f"bold {theme.accent}",
247
- # The answer itself stays plain foreground DELIBERATELY. It is the
248
- # longest text on screen and the thing most often actually read;
249
- # tinting it costs contrast to say something the label already said.
250
- "assistant": "",
251
- # The harness talking about itself.
252
- "system": "dim italic",
253
- # §38: the model's reasoning, when tui.show_thinking renders it
254
- # inline. `secondary` because thinking is the answer's quieter
255
- # sibling rather than a severity or an identity -- it already
256
- # clears the identity floor on every theme, so no theme constant
257
- # moves for this. Italic separates it from `pass`/`pass_done`,
258
- # which share the hue in the research view.
259
- "thinking": f"italic {theme.secondary}",
260
- "pass": f"bold {theme.secondary}",
261
- "pass_done": theme.secondary,
262
- # PLAIN accent, not `dim` (batch 41, X1). Two reasons, and the
263
- # second is the one that generalises. `dim {accent}` sat a
264
- # measured 98.5 redmean units from `thinking`'s
265
- # `italic {secondary}` on dark-plain -- the shipped default,
266
- # and the tightest pair of any theme (every other theme is
267
- # >= 143) -- so a tool call and a reasoning line were one
268
- # colour on the palette most people actually see. And `dim` is
269
- # a Rich ATTRIBUTE, not a colour: tests/test_themes.py's
270
- # contrast floors measure the undimmed hue and cannot see what
271
- # the terminal paints, so the style on EVERY tool call was the
272
- # one style whose real contrast nothing measured. Plain accent
273
- # moves it up, away from secondary, into a number the floors
274
- # can see.
275
- "tool": theme.accent,
276
- # How bad it is. The three shared colours.
277
- "tool_error": theme.warning,
278
- # BOLD, where tool_error is plain (X2). Both are non-fatal and
279
- # keep the hue family; the weight separates the harness raising
280
- # its voice from a tool that failed. They were the same string
281
- # outright until batch 41, which was survivable only because
282
- # nothing routed a WARNING here at all -- see
283
- # TranscriptLogHandler, where that was the actual defect.
284
- "warning": f"bold {theme.warning}",
285
- "error": f"bold {theme.error}",
286
- "success": theme.success,
287
- # Confidence tiers, ordered worst-to-best in meaning rather than in
288
- # this dict. UNVERIFIED_COVERAGE is a gap in what was asked, not a
289
- # claim that failed, so it reads as absent rather than as wrong.
290
- "HIGH": theme.success,
291
- "MEDIUM": theme.foreground,
292
- "LOW": theme.warning,
293
- "UNVERIFIED": theme.error,
294
- "UNVERIFIED_COVERAGE": f"dim {theme.error}",
295
- # §41's inline diff for `write` and `edit`. The only roles in
296
- # this table that set a BACKGROUND, because the whole point is
297
- # that a changed row is marked across its full width rather
298
- # than at the one character that carries the sign.
299
- "diff_add": f"{theme.foreground} on {_tint(theme.success, theme.background)}",
300
- "diff_del": f"{theme.foreground} on {_tint(theme.error, theme.background)}",
301
- # Unchanged context recedes: it is there to place the change,
302
- # not to be read. `secondary` rather than a dimmed foreground
303
- # for X1's reason -- `dim` is an attribute no floor can
304
- # measure.
305
- "diff_context": theme.secondary,
306
- # The file being changed. Bold foreground takes no hue at all,
307
- # which is what keeps it out of the identity roles the same
308
- # batch just separated -- a path is not a speaker.
309
- "diff_header": f"bold {theme.foreground}",
310
- }
311
-
312
-
313
- def styles_for(app) -> dict[str, str]:
314
- """The active theme's role styles, or unstyled when there is no app.
315
-
316
- A widget is constructed before it is mounted and tests build them bare
317
- (`ResearchProgress()` in test_pipeline_events.py), where `self.app`
318
- RAISES rather than returning None. Falling back to empty strings keeps
319
- a widget renderable in both cases -- Rich treats "" as no style -- so
320
- presentation degrades instead of a NoActiveAppError reaching a test
321
- that is not about theming at all.
322
- """
323
- try:
324
- theme = app.get_theme(app.theme)
325
- except Exception: # noqa: BLE001 -- no app, or a theme name we lost
326
- theme = None
327
- if theme is None:
328
- return {}
329
- return role_styles(theme)
330
-
331
-
332
- def syntax_theme_for(app) -> str:
333
- """Which Rich token theme code blocks highlight against (#116).
334
-
335
- Rich ships exactly two: ansi_dark for dark backgrounds, ansi_light for
336
- light ones. Half the shipped themes are light, and every one of them
337
- was rendering every code block in a palette designed against the
338
- opposite background -- on the one transcript element a reader is most
339
- likely to read character by character.
340
-
341
- Resolved here, against the Theme object's own `dark` flag, for the same
342
- reason role_styles is: a RichLog cannot reach app.tcss variables, so
343
- the lookup happens where the Theme object already is. No running app
344
- (bare-built test widgets) defaults to dark, which preserves what the
345
- unconditional version did.
346
- """
347
- try:
348
- theme = app.get_theme(app.theme)
349
- except Exception: # noqa: BLE001 -- no app, or a theme name we lost
350
- theme = None
351
- if theme is not None and not theme.dark:
352
- return "ansi_light"
353
- return "ansi_dark"
354
-
355
-
356
- def resolve(name: str | None) -> str:
357
- """Theme name to apply, falling back to the default.
358
-
359
- Returns the default rather than raising: config_loader already
360
- type-checks `tui.theme` as a string, but it cannot know the valid
361
- names without importing this module, and a stale name in a settings
362
- file should not stop the app from starting.
363
- """
364
- if name in THEME_NAMES:
365
- return name
366
- return DEFAULT_THEME
1
+ """
2
+ tui/themes.py
3
+
4
+ Fourteen themes: the eight-theme neutral grid (dark/light x
5
+ plain/red/green/blue) plus six standalone tinted themes (matrix,
6
+ nightmare, ember, midnight, glassy-lapis, paper) whose PANELS carry the
7
+ identity -- background/surface/panel are theirs, not the grid's shared
8
+ neutrals.
9
+
10
+ Pure presentation -- no import of core/, no harness state, with one
11
+ narrowing batch 64 wrote down rather than hid: `styles_for` keeps the
12
+ set of theme names it has already complained about, because it runs
13
+ once per rendered line and the complaint must not. Two things
14
+ outside this module carry a theme name: the persisted `tui.theme` setting,
15
+ validated by core/config_loader.py's _KNOWN_TUI, and tui/preferences.py's
16
+ remembered choice. The second deliberately does NOT validate against
17
+ THEME_NAMES -- it stores an opaque string and lets the App decide whether
18
+ it still resolves, because ctrl+p's command palette can select one of
19
+ Textual's own built-in themes and a whitelist here would silently forget
20
+ it.
21
+
22
+ Built on textual.theme.Theme (verified against the pinned textual 1.0.0,
23
+ per D22's rule about not assuming a dependency's API shape). Textual
24
+ derives the full variable set from these anchors, so each theme only
25
+ declares the colours that actually differ.
26
+ """
27
+
28
+ import logging
29
+
30
+ from textual.color import Color
31
+ from textual.theme import Theme
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ # Shared neutrals. The accent variants below change only the three hue
36
+ # slots (primary/secondary/accent), so a colour tweak to the base surfaces
37
+ # lands in all eight grid themes at once rather than eight near-copies
38
+ # drifting.
39
+ _DARK_BASE = {
40
+ "background": "#0f1115",
41
+ "surface": "#171a21",
42
+ "panel": "#1e222b",
43
+ "foreground": "#e4e6eb",
44
+ "warning": "#d9a441",
45
+ "error": "#cf5c4a",
46
+ "success": "#5aa86f",
47
+ "dark": True,
48
+ }
49
+
50
+ _LIGHT_BASE = {
51
+ "background": "#f7f7f5",
52
+ "surface": "#ffffff",
53
+ "panel": "#eceae6",
54
+ "foreground": "#1b1c1e",
55
+ "warning": "#9a6d10",
56
+ "error": "#a63a2a",
57
+ "success": "#2f7343",
58
+ "dark": False,
59
+ }
60
+
61
+ # (primary, secondary, accent) per variant. Dark and light get separate
62
+ # values because a hue readable on #0f1115 is usually too pale on #f7f7f5.
63
+ #
64
+ # The four DARK secondaries were lifted in batch 29 (#14): the pass role
65
+ # renders in `secondary`, and every original value sat below 3.5:1 against
66
+ # the shared dark background -- plain at 3.37 was the filed defect, red
67
+ # ~2.7 and blue ~3.0 were the same defect nobody had measured. The floor
68
+ # is pinned in tests/test_themes.py; these are the minimal luminance moves
69
+ # that clear it.
70
+ _ACCENTS_DARK = {
71
+ # dark-plain's ACCENT was lifted in batch 41 (X1), for batch 29's
72
+ # reason applied to a different axis. #14 measured contrast against
73
+ # the BACKGROUND; this is separation between two roles that sit on
74
+ # adjacent lines. `tool` renders in accent and `thinking` in
75
+ # secondary, and on a deliberately monochrome theme hue cannot
76
+ # separate them -- only lightness can. #a9b2c3 was 98.5 redmean
77
+ # units from #8792a2, the tightest secondary/accent pair of all
78
+ # fourteen themes (the next is paper at 143.8). #b8c1d1 is 142.7,
79
+ # which clears that floor while staying 111 units off the
80
+ # foreground -- go lighter and the assistant label melts into the
81
+ # body text it introduces, which is the same defect facing the
82
+ # other way.
83
+ "plain": ("#8a93a3", "#8792a2", "#b8c1d1"),
84
+ "red": ("#d4674f", "#b0513c", "#e8917b"),
85
+ "green": ("#5fa876", "#4d8f63", "#8ecba1"),
86
+ "blue": ("#5b90cc", "#4a76b3", "#8bb6e6"),
87
+ }
88
+
89
+ _ACCENTS_LIGHT = {
90
+ "plain": ("#5a6273", "#3c4252", "#7d8595"),
91
+ "red": ("#b04a33", "#7d3423", "#c9705a"),
92
+ "green": ("#3f7f57", "#2b5a3c", "#5d9c74"),
93
+ "blue": ("#3f6fa8", "#2b4d76", "#6091c7"),
94
+ }
95
+
96
+ # Standalone tinted themes (batch 29). Each OVERRIDES the shared base
97
+ # outright -- that is their identity: the panels themselves carry the
98
+ # palette, not just borders and text. Severity slots default to the grid
99
+ # trio and are overridden ONLY where contrast against the theme's own
100
+ # tint demands it, keeping the semantic hue family (danger stays
101
+ # red-ish); every override carries its reason, and the floors live in
102
+ # tests/test_themes.py (foreground >= 7:1, severity >= 4:1, identity
103
+ # >= 3.5:1, all against the theme's own background).
104
+ _STANDALONE = [
105
+ dict(
106
+ name="matrix", dark=True,
107
+ background="#0a120c", surface="#0f1a12", panel="#14231a",
108
+ foreground="#c8e6d0",
109
+ primary="#3dd968", secondary="#2f9e52", accent="#7dffb0",
110
+ # success overridden: the shared #5aa86f dissolves into matrix's
111
+ # own green-dark background.
112
+ success="#4ee08a",
113
+ ),
114
+ dict(
115
+ name="nightmare", dark=True,
116
+ background="#140b0e", surface="#1c0f14", panel="#251318",
117
+ foreground="#e8d5d8",
118
+ primary="#c94f5f", secondary="#a8556a", accent="#e88a96",
119
+ # error overridden: red-on-red -- the shared #cf5c4a loses the
120
+ # alarm against nightmare's blood background.
121
+ error="#ff7b6b",
122
+ ),
123
+ dict(
124
+ name="ember", dark=True,
125
+ background="#16100a", surface="#1f1610", panel="#291d13",
126
+ foreground="#ecdfd0",
127
+ primary="#e08a3c", secondary="#a86228", accent="#f2b06a",
128
+ # warning overridden yellower: the shared amber sat on top of
129
+ # ember's primary orange and read as emphasis, not as caution.
130
+ warning="#d9b83f",
131
+ ),
132
+ dict(
133
+ name="midnight", dark=True,
134
+ background="#0a0f1e", surface="#101830", panel="#16203c",
135
+ foreground="#d5dcea",
136
+ primary="#6f9fe8", secondary="#4a6fb0", accent="#9dbdf2",
137
+ ),
138
+ dict(
139
+ name="glassy-lapis", dark=True,
140
+ background="#14243f", surface="#1c2f52", panel="#243a63",
141
+ foreground="#e2ecf8",
142
+ primary="#7fb4ff", secondary="#5a8ac9", accent="#a8ccff",
143
+ # error overridden: lapis is the lightest dark background, and
144
+ # the shared #cf5c4a fell just under the severity floor on it.
145
+ error="#e06a58",
146
+ ),
147
+ dict(
148
+ name="paper", dark=False,
149
+ background="#f4efe6", surface="#fbf8f2", panel="#eae3d5",
150
+ foreground="#2b2620",
151
+ primary="#7a5c2e", secondary="#5c4a32", accent="#9c7b45",
152
+ ),
153
+ ]
154
+
155
+
156
+ def _build(variant: str, dark: bool) -> Theme:
157
+ base = _DARK_BASE if dark else _LIGHT_BASE
158
+ primary, secondary, accent = (
159
+ _ACCENTS_DARK if dark else _ACCENTS_LIGHT
160
+ )[variant]
161
+ return Theme(
162
+ name=f"{'dark' if dark else 'light'}-{variant}",
163
+ primary=primary,
164
+ secondary=secondary,
165
+ accent=accent,
166
+ **base,
167
+ )
168
+
169
+
170
+ def _build_standalone(spec: dict) -> Theme:
171
+ base = _DARK_BASE if spec["dark"] else _LIGHT_BASE
172
+ merged = {**base, **{k: v for k, v in spec.items() if k != "name"}}
173
+ return Theme(name=spec["name"], **merged)
174
+
175
+
176
+ ALL_THEMES = (
177
+ [
178
+ _build(variant, dark)
179
+ for dark in (True, False)
180
+ for variant in ("plain", "red", "green", "blue")
181
+ ]
182
+ + [_build_standalone(spec) for spec in _STANDALONE]
183
+ )
184
+
185
+ THEME_NAMES = [t.name for t in ALL_THEMES]
186
+ DEFAULT_THEME = "dark-plain"
187
+
188
+
189
+ def register_all(app) -> None:
190
+ """Register every theme on the app. Call before setting app.theme."""
191
+ for theme in ALL_THEMES:
192
+ app.register_theme(theme)
193
+
194
+
195
+ # ---------------------------------------------------------------------------
196
+ # ---- Role palette (ROADMAP_v2 §26) ----------------------------------------
197
+ # ---------------------------------------------------------------------------
198
+ #
199
+ # The transcript was uniformly white: a user message, the model's answer, a
200
+ # pipeline trace line and a tool call were the same colour, and the "you"
201
+ # label read as the first word of the message it introduced.
202
+ #
203
+ # WHY THIS IS A FUNCTION OF A THEME rather than a table of colour names.
204
+ # Everything else in the TUI styles itself through app.tcss, which uses
205
+ # theme variables ($panel, $primary) and so restyles across all fourteen
206
+ # themes without edits. A RichLog cannot do that -- it renders Rich Text
207
+ # objects, and a Rich style needs a concrete colour, not a variable to
208
+ # resolve later. So the resolution happens here, against the Theme
209
+ # object, and the same property holds: no literal appears below, and a
210
+ # new theme needs no change in this section.
211
+ #
212
+ # Severity colours. Across the eight GRID themes, warning/error/success
213
+ # are shared by _DARK_BASE and _LIGHT_BASE and mean the same thing
214
+ # everywhere; primary/secondary/accent are the per-variant hues. A
215
+ # STANDALONE theme may override a severity slot when its own panel tint
216
+ # would swallow the shared value (matrix's success, nightmare's error,
217
+ # ember's warning, glassy-lapis's error -- each with its reason above),
218
+ # keeping the semantic hue family. Either way severity uses the
219
+ # theme-resolved trio and identity uses the hues, rather than the
220
+ # reverse. Floors are pinned in tests/test_themes.py.
221
+
222
+ #: How far a diff row's background is blended TOWARD the theme's own
223
+ #: background (batch 41, X7). 0.8 leaves a band that stands off the
224
+ #: page by 1.22-1.53 across the fourteen themes while the foreground
225
+ #: still reads on it at 9.3:1 or better -- a highlight rather than a
226
+ #: slab. Both floors are pinned in tests/test_themes.py.
227
+ DIFF_TINT = 0.8
228
+
229
+
230
+ #: The eight Theme slots `role_styles` reads. Every one of them but
231
+ #: `primary` is Optional[str] on textual's own Theme, and three of the
232
+ #: twelve built-ins the command palette offers do leave one blank or
233
+ #: fill it with a vocabulary Rich cannot read: textual-dark has no
234
+ #: `background`, textual-light no `foreground`, textual-ansi nothing
235
+ #: but `ansi_*` names. Reading them raw is what made selecting
236
+ #: textual-dark kill the harness AT MOUNT -- and keep killing it,
237
+ #: since watch_theme had already remembered the name (batch 64).
238
+ _SLOTS = ("primary", "secondary", "accent", "warning", "error",
239
+ "success", "foreground", "background")
240
+
241
+ #: Filled palettes, keyed on the RAW SLOT VALUES rather than on
242
+ #: theme.name. Theme is a plain mutable dataclass and
243
+ #: App.register_theme overwrites by name, so a name key would hand a
244
+ #: re-registered theme the colours of the one it replaced; a value key
245
+ #: cannot. Memoisation of a pure function of its input, which is why
246
+ #: it costs this module nothing the docstring claims -- and it earns
247
+ #: its place because the fallback below is 0.194ms against
248
+ #: role_styles' own 0.004ms, on a function called once per drawn line.
249
+ _RESOLVED: dict[tuple, dict[str, str]] = {}
250
+
251
+
252
+ def _rich(colour: str) -> str:
253
+ """Textual's `ansi_*` colour names in Rich's vocabulary.
254
+
255
+ textual-ansi fills every slot with `ansi_blue`/`ansi_default` --
256
+ the terminal's own sixteen, which is the entire point of that
257
+ theme -- and Rich's Style.parse does not know the prefix. It knows
258
+ the names underneath it: textual.color.ANSI_COLORS is exactly the
259
+ ANSI subset of rich.color.ANSI_COLOR_NAMES (verified by set
260
+ difference against the pinned 1.0.0, per D22), and `ansi_default`
261
+ is Rich's `default`. A translation, then, rather than a guess.
262
+
263
+ Not doing it was never a crash, which is why it lasted: Rich's
264
+ Text.render resolves a style string with `default=Style.null()`,
265
+ so an unparseable one renders PLAIN and says nothing. Twenty-five
266
+ of the thirty-four roles were silently unstyled on textual-ansi --
267
+ the uniformly white transcript this section exists to fix, reached
268
+ by a different road.
269
+ """
270
+ return colour[5:] if colour.startswith("ansi_") else colour
271
+
272
+
273
+ def _palette(theme: Theme) -> dict[str, str]:
274
+ """`_SLOTS`, every one of them filled, in Rich's vocabulary.
275
+
276
+ A blank slot is filled from textual's OWN derivation --
277
+ to_color_system().generate() is what it builds app.tcss's
278
+ $background and $foreground out of -- rather than from a constant
279
+ invented here, which would be a second opinion about a colour the
280
+ rest of the screen already has.
281
+
282
+ A FALLBACK and never a replacement, for two measured reasons.
283
+ generate() is lossy: the base shade comes back as
284
+ `color.lighten(0).hex`, an HSL round trip, which moves #d9a441 to
285
+ #D8A441 and differs from the raw slot on 41 values across the
286
+ fourteen shipped themes. And it is 48x slower than role_styles
287
+ itself. Reaching for it only where a slot is actually None leaves
288
+ all fourteen byte-identical and costs the other twenty-four themes
289
+ eight getattrs.
290
+ """
291
+ raw = tuple(getattr(theme, slot) for slot in _SLOTS)
292
+ if all(raw):
293
+ return {slot: _rich(value) for slot, value in zip(_SLOTS, raw)}
294
+ key = raw + (theme.dark,)
295
+ if key not in _RESOLVED:
296
+ generated = theme.to_color_system().generate()
297
+ _RESOLVED[key] = {slot: _rich(value or generated[slot])
298
+ for slot, value in zip(_SLOTS, raw)}
299
+ return _RESOLVED[key]
300
+
301
+
302
+ def _tint(colour: str, background: str,
303
+ factor: float = DIFF_TINT) -> str | None:
304
+ """`colour` faded toward `background`, as a hex string -- or None.
305
+
306
+ Derived from the theme's own slots rather than written down, for
307
+ the reason the whole of this section exists (#116): a literal pair
308
+ of green and red backgrounds would be designed against one of the
309
+ fourteen palettes and wrong on the other thirteen -- and on the six
310
+ standalone themes, whose panels carry the identity, visibly so.
311
+
312
+ None when either end is one of the terminal's own sixteen, which
313
+ is textual-ansi and nothing else: there is no RGB there to blend,
314
+ so there is no band to draw. Not a hypothetical guard -- textual's
315
+ Color.parse raises on Rich's `default`, and blending two ANSI
316
+ colours in textual hands back one of them unchanged, so both
317
+ answers were wrong before this said so.
318
+ """
319
+ if not (colour.startswith("#") and background.startswith("#")):
320
+ return None
321
+ return Color.parse(colour).blend(Color.parse(background), factor).hex
322
+
323
+
324
+ def role_styles(theme: Theme) -> dict[str, str]:
325
+ """Rich style strings keyed by transcript role, for one theme.
326
+
327
+ Roles are what a line MEANS, not where it came from: `pass` covers a
328
+ research pass boundary whether the CLI or the TUI produced it, and
329
+ `tool_error` is a failed tool call rather than "amber".
330
+
331
+ Reads the RESOLVED palette rather than the Theme's own slots,
332
+ which is batch 64: three of the twenty-six themes ctrl+p offers
333
+ leave a slot at None or fill it with textual's `ansi_*` names,
334
+ and one of them took the whole app down at mount. `_palette`
335
+ fills and translates; nothing below can see the difference.
336
+ """
337
+ palette = _palette(theme)
338
+ add = _tint(palette["success"], palette["background"])
339
+ delete = _tint(palette["error"], palette["background"])
340
+ return {
341
+ # Who is speaking. The hues, because these distinguish identity.
342
+ "user": f"bold {palette['primary']}",
343
+ "user_label": f"bold {palette['primary']}",
344
+ "assistant_label": f"bold {palette['accent']}",
345
+ # The answer itself stays plain foreground DELIBERATELY. It is the
346
+ # longest text on screen and the thing most often actually read;
347
+ # tinting it costs contrast to say something the label already said.
348
+ "assistant": "",
349
+ # The harness talking about itself.
350
+ "system": "dim italic",
351
+ # §38: the model's reasoning, when tui.show_thinking renders it
352
+ # inline. `secondary` because thinking is the answer's quieter
353
+ # sibling rather than a severity or an identity -- it already
354
+ # clears the identity floor on every theme, so no theme constant
355
+ # moves for this. Italic separates it from `pass`/`pass_done`,
356
+ # which share the hue in the research view.
357
+ "thinking": f"italic {palette['secondary']}",
358
+ "pass": f"bold {palette['secondary']}",
359
+ "pass_done": palette["secondary"],
360
+ # PLAIN accent, not `dim` (batch 41, X1). Two reasons, and the
361
+ # second is the one that generalises. `dim {accent}` sat a
362
+ # measured 98.5 redmean units from `thinking`'s
363
+ # `italic {secondary}` on dark-plain -- the shipped default,
364
+ # and the tightest pair of any theme (every other theme is
365
+ # >= 143) -- so a tool call and a reasoning line were one
366
+ # colour on the palette most people actually see. And `dim` is
367
+ # a Rich ATTRIBUTE, not a colour: tests/test_themes.py's
368
+ # contrast floors measure the undimmed hue and cannot see what
369
+ # the terminal paints, so the style on EVERY tool call was the
370
+ # one style whose real contrast nothing measured. Plain accent
371
+ # moves it up, away from secondary, into a number the floors
372
+ # can see.
373
+ "tool": palette["accent"],
374
+ # How bad it is. The three shared colours.
375
+ "tool_error": palette["warning"],
376
+ # BOLD, where tool_error is plain (X2). Both are non-fatal and
377
+ # keep the hue family; the weight separates the harness raising
378
+ # its voice from a tool that failed. They were the same string
379
+ # outright until batch 41, which was survivable only because
380
+ # nothing routed a WARNING here at all -- see
381
+ # TranscriptLogHandler, where that was the actual defect.
382
+ "warning": f"bold {palette['warning']}",
383
+ "error": f"bold {palette['error']}",
384
+ "success": palette["success"],
385
+ # Confidence tiers, ordered worst-to-best in meaning rather than in
386
+ # this dict. UNVERIFIED_COVERAGE is a gap in what was asked, not a
387
+ # claim that failed, so it reads as absent rather than as wrong.
388
+ "HIGH": palette["success"],
389
+ "MEDIUM": palette["foreground"],
390
+ "LOW": palette["warning"],
391
+ "UNVERIFIED": palette["error"],
392
+ "UNVERIFIED_COVERAGE": f"dim {palette['error']}",
393
+ # §41's inline diff for `write` and `edit`. The only roles in
394
+ # this table that set a BACKGROUND, because the whole point is
395
+ # that a changed row is marked across its full width rather
396
+ # than at the one character that carries the sign.
397
+ #
398
+ # Unless there is no background to set. `_tint` answers None on
399
+ # a theme whose colours are the terminal's own sixteen --
400
+ # textual-ansi and nothing else -- and the row then takes the
401
+ # severity colour as its FOREGROUND, which is what git, diff
402
+ # and patch all do in a sixteen-colour terminal. A solid band
403
+ # was the alternative, and DIFF_TINT's comment above turns that
404
+ # down for every theme that CAN be measured; picking it for the
405
+ # one that cannot would be backwards.
406
+ "diff_add": (f"{palette['foreground']} on {add}" if add
407
+ else palette["success"]),
408
+ "diff_del": (f"{palette['foreground']} on {delete}" if delete
409
+ else palette["error"]),
410
+ # Unchanged context recedes: it is there to place the change,
411
+ # not to be read. `secondary` rather than a dimmed foreground
412
+ # for X1's reason -- `dim` is an attribute no floor can
413
+ # measure.
414
+ "diff_context": palette["secondary"],
415
+ # The file being changed. Bold foreground takes no hue at all,
416
+ # which is what keeps it out of the identity roles the same
417
+ # batch just separated -- a path is not a speaker.
418
+ "diff_header": f"bold {palette['foreground']}",
419
+ # Batch 53's markdown marks. These are marks INSIDE an entry rather
420
+ # than kinds of line, which is why they sit outside MESSAGE_ROLES
421
+ # exactly as the diff roles above do: the pairwise-distinctness and
422
+ # separation floors ask whether two LINES can be told apart, and a
423
+ # bold word never sits on the line below a tool call.
424
+ #
425
+ # This does narrow `assistant`'s "stays plain foreground
426
+ # DELIBERATELY" a few lines up, and the narrowing is the decision:
427
+ # that rule is about the BODY, whose length is the reason tinting it
428
+ # costs more contrast than it buys. A heading and a bold run are
429
+ # marks the model asked for, on a few cells at a time.
430
+ #
431
+ # A heading takes weight and no hue, `diff_header`'s reasoning --
432
+ # a section title is not a speaker either. Strong takes the
433
+ # attribute alone, because the one thing `**` means is emphasis
434
+ # within body text and a colour would make it a different KIND of
435
+ # line. Inline code borrows `secondary`, the transcript's quieter
436
+ # slot, so an identifier reads as set apart from the prose without
437
+ # competing with the accent a tool call uses.
438
+ "md_heading": f"bold {palette['foreground']}",
439
+ "md_strong": "bold",
440
+ "md_code": palette["secondary"],
441
+ # Batch 58's three additions, and the shape of the first two is
442
+ # `md_strong`'s: an inline mark says something about the WORDS it
443
+ # covers, so it takes the attribute and no hue -- a colour would
444
+ # make it a different kind of line rather than a stressed one.
445
+ "md_em": "italic",
446
+ "md_strike": "strike",
447
+ # A link takes UNDERLINE and no hue either, and here the reason is
448
+ # the palette rather than the principle: `accent` is already the
449
+ # assistant's own label and every tool call, and `secondary` is
450
+ # reasoning and inline code. Underline is the one link convention
451
+ # every terminal shares, and it costs no slot to say it.
452
+ "md_link": "underline",
453
+ # A list marker recedes for `diff_context`'s reason -- it is there
454
+ # to place the text, not to be read -- so the eye lands on the
455
+ # first word rather than on the hyphen the model happened to type.
456
+ "md_bullet": palette["secondary"],
457
+ # The table's own furniture. The border recedes for
458
+ # `diff_context`'s reason -- it is there to place the cells, not to
459
+ # be read -- and the header row is the heading rule applied inside
460
+ # the grid, so a table and a `##` above it agree about what a title
461
+ # looks like.
462
+ "table_border": palette["secondary"],
463
+ "table_header": f"bold {palette['foreground']}",
464
+ }
465
+
466
+
467
+ #: Theme names already complained about, so the warning below is said
468
+ #: once each rather than once per line drawn.
469
+ _UNSTYLABLE: set[str] = set()
470
+
471
+
472
+ def styles_for(app) -> dict[str, str]:
473
+ """The active theme's role styles, or unstyled when there is no app.
474
+
475
+ A widget is constructed before it is mounted and tests build them bare
476
+ (`ResearchProgress()` in test_pipeline_events.py), where `self.app`
477
+ RAISES rather than returning None. Falling back to empty strings keeps
478
+ a widget renderable in both cases -- Rich treats "" as no style -- so
479
+ presentation degrades instead of a NoActiveAppError reaching a test
480
+ that is not about theming at all.
481
+
482
+ The SECOND guard is batch 64's, and it is the one that had to be
483
+ learned. role_styles used to be able to RAISE -- a theme with a
484
+ slot at None reached Color.parse(None) -- and this function is on
485
+ the path of every transcript line, the session banner in on_mount
486
+ included. So a theme the command palette offered took the app down
487
+ at startup and kept taking it down, because watch_theme had
488
+ already written the name to a preference store that lives at the
489
+ USER tier, outside the install tree, where reinstalling cannot
490
+ reach it. _palette makes that particular fault impossible; this
491
+ makes the CLASS of it non-fatal, which is Section 27's rule that a
492
+ display failure is contained rather than fatal. An uncoloured
493
+ transcript is unhelpful; a harness that will not start is not a
494
+ harness.
495
+
496
+ It warns, ONCE per theme. That is the opposite of
497
+ preferences._remember's deliberate non-latching, and for the
498
+ reason that module states: a warning fires there on a human's own
499
+ action, and fires here on every line drawn. Silence is precisely
500
+ what let textual-light and textual-ansi render unstyled for as
501
+ long as they did -- Rich resolves an unparseable style with
502
+ `default=Style.null()` and says nothing -- so a contained failure
503
+ that reported nothing would be the same defect wearing a better
504
+ exception story.
505
+ """
506
+ try:
507
+ theme = app.get_theme(app.theme)
508
+ except Exception: # noqa: BLE001 -- no app, or a theme name we lost
509
+ theme = None
510
+ if theme is None:
511
+ return {}
512
+ try:
513
+ return role_styles(theme)
514
+ except Exception: # noqa: BLE001 -- a theme this build cannot resolve
515
+ name = getattr(theme, "name", "?")
516
+ if name not in _UNSTYLABLE:
517
+ _UNSTYLABLE.add(name)
518
+ logger.warning(
519
+ "Theme %r could not be resolved into transcript "
520
+ "colours, so the transcript will render unstyled. Pick "
521
+ "another with /theme or ctrl+p.", name)
522
+ return {}
523
+
524
+
525
+ def syntax_theme_for(app) -> str:
526
+ """Which Rich token theme code blocks highlight against (#116).
527
+
528
+ Rich ships exactly two: ansi_dark for dark backgrounds, ansi_light for
529
+ light ones. Half the shipped themes are light, and every one of them
530
+ was rendering every code block in a palette designed against the
531
+ opposite background -- on the one transcript element a reader is most
532
+ likely to read character by character.
533
+
534
+ Resolved here, against the Theme object's own `dark` flag, for the same
535
+ reason role_styles is: a RichLog cannot reach app.tcss variables, so
536
+ the lookup happens where the Theme object already is. No running app
537
+ (bare-built test widgets) defaults to dark, which preserves what the
538
+ unconditional version did.
539
+ """
540
+ try:
541
+ theme = app.get_theme(app.theme)
542
+ except Exception: # noqa: BLE001 -- no app, or a theme name we lost
543
+ theme = None
544
+ if theme is not None and not theme.dark:
545
+ return "ansi_light"
546
+ return "ansi_dark"
547
+
548
+
549
+ def resolve(name: str | None) -> str:
550
+ """Theme name to apply, falling back to the default.
551
+
552
+ Returns the default rather than raising: config_loader already
553
+ type-checks `tui.theme` as a string, but it cannot know the valid
554
+ names without importing this module, and a stale name in a settings
555
+ file should not stop the app from starting.
556
+ """
557
+ if name in THEME_NAMES:
558
+ return name
559
+ return DEFAULT_THEME