Repository navigation
Expand file tree
/
Copy pathrenderer.py
More file actions
2134 lines (1884 loc) · 90.2 KB
/
Copy pathrenderer.py
File metadata and controls
2134 lines (1884 loc) · 90.2 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
"""HTML renderer implementation for Claude Code transcripts."""
from __future__ import annotations
from pathlib import Path
import re
from typing import TYPE_CHECKING, Any, Optional, Tuple, cast
if TYPE_CHECKING:
from ..dag import SessionTree
from ..cache import get_library_version
from ..models import (
AssistantTextMessage,
AwaySummaryMessage,
BashInputMessage,
BashOutputMessage,
CommandOutputMessage,
CompactedSummaryMessage,
RenderingDepth,
HookAttachmentMessage,
HookSummaryMessage,
ImageContent,
SessionHeaderMessage,
SlashCommandMessage,
SystemMessage,
TaskNotificationMessage,
TeammateMessage,
ThinkingMessage,
ToolResultMessage,
ToolUseMessage,
TranscriptEntry,
UnknownMessage,
UserMemoryMessage,
UserSlashCommandMessage,
UserTextMessage,
WorkflowAgentMessage,
WorkflowPhaseMessage,
# Tool input types
AskUserQuestionInput,
AskUserQuestionItem,
BashInput,
DeleteInput,
EditInput,
ExitPlanModeInput,
GlobInput,
GrepInput,
MultiEditInput,
ReadInput,
SendMessageInput,
TaskCreateInput,
TaskInput,
TaskListInput,
TaskOutputInput,
TaskStopInput,
TaskUpdateInput,
TeamCreateInput,
TeamDeleteInput,
TodoWriteInput,
ToolUseContent,
ToolExecutionInput,
SkillInput,
WebSearchInput,
ArtifactInput,
WebFetchInput,
WorkflowToolInput,
MonitorInput,
MonitorOutput,
ScheduleWakeupInput,
ScheduleWakeupOutput,
CronCreateInput,
CronCreateOutput,
CronListInput,
CronListOutput,
CronDeleteInput,
CronDeleteOutput,
WriteInput,
# Tool output types
AskUserQuestionOutput,
BashOutput,
DeleteOutput,
EditOutput,
ExitPlanModeOutput,
ReadOutput,
SendMessageOutput,
TaskCreateOutput,
TaskListOutput,
TaskOutput,
TaskOutputResult,
TaskStopOutput,
TaskUpdateOutput,
TeamCreateOutput,
TeamDeleteOutput,
ToolResultContent,
ToolExecutionOutput,
WebSearchOutput,
ArtifactOutput,
WebFetchOutput,
WriteOutput,
)
from ..renderer import (
Renderer,
RenderingContext,
TemplateMessage,
generate_template_messages,
prepare_projects_index,
title_for_projects_index,
)
from ..lanes import CrossLinks, annotate_lanes, teammate_links
from ..render_cache import markdown_cache, pygments_cache
from ..renderer_timings import (
DEBUG_TIMING,
log_timing,
report_cache_statistics,
report_timing_statistics,
set_timing_var,
)
from ..utils import (
CLASSIC_THEME,
DEFAULT_THEME,
normalize_theme,
collect_trunk_session_ids,
format_timestamp,
get_warmup_session_ids,
resume_command_for_session,
split_websearch_queries,
)
from .system_formatters import (
format_away_summary_content,
format_hook_attachment_content,
format_hook_summary_content,
format_session_header_content,
format_system_content,
)
from .user_formatters import (
format_bash_input_content,
format_bash_output_content,
format_command_output_content,
format_compacted_summary_content,
format_slash_command_content,
format_user_memory_content,
format_user_slash_command_content,
format_user_text_model_content,
format_workflow_sidechannel_user_content,
)
from .assistant_formatters import (
format_assistant_text_content,
format_thinking_content,
format_unknown_content,
)
from .teammate_formatter import (
format_sendmessage_input as _format_sendmessage_input,
format_sendmessage_output as _format_sendmessage_output,
format_task_input_teammate_extras,
format_task_output_teammate_extras,
format_taskcreate_input as _format_taskcreate_input,
format_taskcreate_output as _format_taskcreate_output,
format_tasklist_output as _format_tasklist_output,
format_taskupdate_input as _format_taskupdate_input,
format_taskupdate_output as _format_taskupdate_output,
format_teamcreate_input as _format_teamcreate_input,
format_teamcreate_output as _format_teamcreate_output,
format_teamdelete_input as _format_teamdelete_input,
format_teamdelete_output as _format_teamdelete_output,
format_teammate_content,
)
from .async_formatter import (
format_task_notification_content as _format_task_notification_content,
format_taskoutput_input as _format_taskoutput_input,
format_taskoutput_output as _format_taskoutput_output,
)
from .tool_formatters import (
format_askuserquestion_input,
format_askuserquestion_output,
format_bash_input,
format_bash_output,
format_delete_input,
format_delete_output,
format_edit_input,
format_edit_output,
format_exitplanmode_input,
format_exitplanmode_output,
format_multiedit_input,
format_read_input,
format_read_output,
format_task_input,
format_task_prompt_preview,
format_task_output,
format_taskstop_input,
format_taskstop_output,
format_todowrite_input,
format_tool_result_content_raw,
format_tool_execution_input,
format_tool_execution_output,
format_grep_input,
format_websearch_input,
format_websearch_output,
format_artifact_input,
format_artifact_output,
format_webfetch_input,
format_workflow_input,
format_workflow_phase_content,
format_workflow_agent_content,
format_webfetch_output,
format_monitor_input,
format_monitor_output,
format_schedulewakeup_input,
format_schedulewakeup_output,
format_croncreate_input,
format_croncreate_output,
format_cronlist_input,
format_cronlist_output,
format_crondelete_input,
format_crondelete_output,
format_write_input,
format_write_output,
render_params_table,
)
from .minimal_theme import LaneAttrs, lane_attributes
from .utils import (
css_class_from_message,
escape_html,
get_message_emoji,
get_template_environment,
is_memory_path,
is_session_header,
memory_short_path,
render_markdown_collapsible,
)
if TYPE_CHECKING:
from ..cache import CacheManager
from ..fragment_store import RenderFragmentStore
def check_html_version(html_file_path: Path) -> Optional[str]:
"""Check the version of an existing HTML file from its comment.
Returns:
The version string if found, None if no version comment or file doesn't exist.
"""
# is_file() (not exists()) so a non-regular destination — e.g.
# /dev/stdout, which is a pipe when stdout is piped — is treated as
# "no version" rather than opened read-only, which would deadlock the
# version sniff on readline() (issue #223).
if not html_file_path.is_file():
return None
try:
with open(html_file_path, "r", encoding="utf-8") as f:
# Read only the first few lines to find the version comment
for _ in range(5): # Check first 5 lines
line = f.readline()
if not line:
break
# Look for comment like: <!-- Generated by claude-code-log v0.3.4 -->
if "<!-- Generated by claude-code-log v" in line:
# Extract version between 'v' and ' -->'
start = line.find("v") + 1
end = line.find(" -->")
if start > 0 and end > start:
return line[start:end]
except (IOError, UnicodeDecodeError):
pass
return None
def html_generator_stamp(theme: str = DEFAULT_THEME) -> str:
"""What ``check_html_version`` reads back from a page rendered now.
The generator comment is ``<!-- Generated by claude-code-log v{stamp} -->``.
For the classic theme the stamp is the bare library version — exactly
what pages carried before themes existed, so classic output stays
byte-identical. Any other theme appends `` theme=<name>``, which makes
every version-marker staleness check (``is_outdated`` and the cache's
``is_transcript_stale`` / ``get_stale_sessions`` / ``is_page_stale``)
treat a page written in another theme as outdated: themes overwrite the
same filenames, so this stamp is the only thing telling them apart.
Older releases parse the whole stamp as the version, so they see a
minimal page as outdated too.
"""
version = get_library_version()
theme = normalize_theme(theme)
if theme == CLASSIC_THEME:
return version
return f"{version} theme={theme}"
def check_html_theme(html_file_path: Path) -> Optional[str]:
"""The theme an existing page was rendered with, from its stamp.
``None`` when the file has no generator comment (missing, not ours);
``"classic"`` for a stamp without a ``theme=`` part.
"""
stamp = check_html_version(html_file_path)
if stamp is None:
return None
_version, sep, theme = stamp.partition(" theme=")
return theme if sep else CLASSIC_THEME
def _build_html_project_tree(template_projects: list[Any]) -> dict[str, Any]:
"""Build a nested directory tree from project paths for the HTML index.
Each project lands at the directory level of its ``html_file``'s
parent (i.e. the rel-dest directory under the index root). The
returned shape is a recursive dict:
::
{
"_projects": [TemplateProject, ...], # leaves at this level
"<subdir-name>": <subtree>,
}
Directories are sorted alphabetically by the recursive template
macro; the ``_projects`` lists keep their insertion order (which
is the by-last-modified order set in ``prepare_projects_index``).
"""
def _to_posix(s: str) -> str:
return s.replace("\\", "/")
root: dict[str, Any] = {}
for project in template_projects:
# Use html_file's parent path components as the directory chain.
url = _to_posix(project.html_file)
parts = url.split("/")
node = root
# All but the last component are directories.
for part in parts[:-1]:
if not part:
continue
if part not in node or not isinstance(node[part], dict):
node[part] = {}
node = node[part]
node.setdefault("_projects", []).append(project)
return root
class HtmlRenderer(Renderer):
"""HTML renderer for Claude Code transcripts."""
# Consulted by Renderer._dispatch_format Strategy 2: plugin-defined
# content classes contributing a ``format_html`` method get picked up
# here. See dev-docs/plugins.md §5 for the resolution order.
#
# v1 contract: ``format_html`` MUST return a real string. The
# absence of the method on a plugin class drives the fallback —
# ``_dispatch_format`` (overridden below) synthesizes HTML from
# the class-side ``format_markdown`` via wenmode when only the
# Markdown side is implemented. There is no None-as-sentinel.
_class_dispatch_format: str = "html"
def _dispatch_format(self, obj: Any, message: "TemplateMessage") -> str:
"""HtmlRenderer-specific dispatch with Markdown→HTML synthesis.
Resolution order on the actual class (`type(obj)`):
1. Class defines ``format_html`` in its ``__dict__`` → use it
verbatim. The return MUST be a real string (no None sentinel).
2. Class defines ``format_markdown`` (but not ``format_html``)
in its ``__dict__`` → synthesize HTML by rendering the
Markdown via wenmode, wrapped in ``<div class="markdown">``
so theme rules scoped under ``.markdown`` fire. By
definition the synthesized output is Markdown-derived, so
the wrap is automatic — plugin authors don't need
``has_markdown = True`` for this path.
3. Neither on the actual class → defer to the base MRO walk
(which finds renderer-side ``format_<ClassName>`` methods
for built-in content classes, or class-side methods on
ancestors).
Step 2 deliberately wins over an ancestor's renderer-side
``format_<ClassName>``: a plugin author who defined
``format_markdown`` on their subclass meant for their Markdown
to drive the rendering, not for the parent class's built-in
renderer behaviour to take over.
"""
from .utils import render_markdown
# ``obj`` is intentionally untyped (``Any``); the class-side
# methods we look up on its ``__dict__`` are plugin-defined.
obj_cls = cast("type[object]", type(obj))
html_method = obj_cls.__dict__.get("format_html")
if html_method is not None:
return cast(str, html_method(obj, self, message))
md_method = obj_cls.__dict__.get("format_markdown")
if md_method is not None:
md_source = cast(str, md_method(obj, self, message))
return f'<div class="markdown">{render_markdown(md_source)}</div>'
return super()._dispatch_format(obj, message)
def __init__(self, image_export_mode: str = "embedded"):
"""Initialize the HTML renderer.
Args:
image_export_mode: Image export mode - "placeholder", "embedded", or "referenced".
"""
super().__init__()
self.image_export_mode = image_export_mode
# Per-conversion fragment store (step 3, work/render-format-once.md):
# set by the converter so the combined-page pass and the per-session
# pass share each message's formatted fragment instead of formatting
# it twice. None (the default) formats every message fresh.
self.fragment_store: "Optional[RenderFragmentStore]" = None
self._output_dir: Path | None = None
# session_id -> {teammate_id -> color}, snapshotted from the
# RenderingContext at the start of each render. Formatters look
# up the per-session map via self._colors_for(message) so
# combined transcripts don't cross-contaminate teammate colors
# between sessions.
self._teammate_colors_by_session: dict[str, dict[str, str]] = {}
# session_id -> {task_id -> subject}, populated by
# `_populate_task_metadata` from TaskCreate/TaskList tool_results
# so TaskCreate / TaskUpdate tool_use titles can surface the
# human-readable subject. Empty for sessions without task
# activity.
self._task_subjects_by_session: dict[str, dict[str, str]] = {}
# session_id -> {tool_use_id -> task_id}, populated alongside
# task_subjects so the TaskCreate tool_use title can render the
# backend-assigned ``#N`` (TaskCreateInput itself doesn't carry
# the id; it's minted on creation and only appears on the
# tool_result).
self._task_id_by_tool_use: dict[str, dict[str, str]] = {}
# RenderingContext snapshot for the current render, so format methods
# can resolve a message's pair partner (pair_first/pair_last) by index
# — mirrors MarkdownRenderer._ctx. Reset each render.
self._ctx: Optional[RenderingContext] = None
# -------------------------------------------------------------------------
# Private Utility Methods
# -------------------------------------------------------------------------
def _colors_for(self, message: TemplateMessage) -> dict[str, str]:
"""Return the teammate_id→color map scoped to *message*'s session.
Empty dict when the session has no known teammate colors yet.
Scoping matters for combined transcripts (see
RenderingContext.teammate_colors).
"""
sid = message.meta.session_id if message.meta else ""
return self._teammate_colors_by_session.get(sid, {})
def _askuserquestion_questions_for(
self, message: TemplateMessage
) -> dict[str, "AskUserQuestionItem"]:
"""Map question-text → original question for *message*'s pair partner.
Used by the AskUserQuestion result formatter to recover the offered
options/header when its own structured data lacks them (text-fallback
and clarify-rejection paths), by reaching into the paired tool_use's
``AskUserQuestionInput``.
"""
if self._ctx is None or message.pair_first is None:
return {}
pair_msg = self._ctx.get(message.pair_first)
if pair_msg is None or not isinstance(pair_msg.content, ToolUseMessage):
return {}
input_content = pair_msg.content.input
if not isinstance(input_content, AskUserQuestionInput):
return {}
return {q.question: q for q in input_content.questions if q.question}
def _collapse_askuserquestion_pairs(self, ctx: RenderingContext) -> None:
"""Make answered AskUserQuestion results self-contained, single cards.
For each result paired with its tool_use: bake the offered
options/header/multiSelect from the input onto the result's answers (so
the result card shows the full question even on the text-fallback and
clarify-rejection paths), then drop the result's pair role so it renders
as a standalone card. The paired input card is ghosted separately by
``format_AskUserQuestionInput`` / ``title_ToolUseMessage`` — its
``pair_last`` link stays intact so that ghosting still fires (#180).
"""
for msg in ctx.messages:
if msg is None:
continue # ghosted slot (ghosting epic Phase 1)
content = msg.content
if not isinstance(content, ToolResultMessage):
continue
output = content.output
if not isinstance(output, AskUserQuestionOutput):
continue
if msg.pair_first is None:
continue
input_msg = ctx.get(msg.pair_first)
if input_msg is None or not isinstance(input_msg.content, ToolUseMessage):
continue
input_content = input_msg.content.input
if not isinstance(input_content, AskUserQuestionInput):
continue
qmap = {q.question: q for q in input_content.questions if q.question}
for ans in output.answers:
q = qmap.get(ans.question)
if q is None:
continue
if not ans.options:
ans.options = list(q.options)
if ans.header is None:
ans.header = q.header
if not ans.multi_select:
ans.multi_select = q.multiSelect
# Render the result standalone — no dangling "second half of a pair"
# merge band now that its companion input card is ghosted.
msg.pair_first = None
msg.pair_duration = None
def _paired_answer_supersedes(self, message: TemplateMessage) -> bool:
"""True when *message* (an AskUserQuestion tool_use) is paired with a
result that already re-renders the questions + the user's choice.
In that case the input card is pure duplication and is ghosted. When
there is no such pair (e.g. a transcript captured while still blocked
on the question), the input card stays.
"""
if self._ctx is None or not message.is_first_in_pair:
return False
result_msg = self._ctx.get(message.pair_last) if message.pair_last else None
if result_msg is None or not isinstance(result_msg.content, ToolResultMessage):
return False
return isinstance(result_msg.content.output, AskUserQuestionOutput)
def _format_image(self, image: ImageContent) -> str:
"""Format image based on export mode."""
from ..image_export import export_image
src = export_image(
image,
self.image_export_mode,
output_dir=self._output_dir,
)
if src is None:
return "[Image]"
return f'<img src="{src}" alt="image" class="uploaded-image" />'
# -------------------------------------------------------------------------
# System Content Formatters
# -------------------------------------------------------------------------
def format_SystemMessage(self, content: SystemMessage, _: TemplateMessage) -> str:
return format_system_content(content)
def format_HookSummaryMessage(
self, content: HookSummaryMessage, _: TemplateMessage
) -> str:
return format_hook_summary_content(content)
def format_HookAttachmentMessage(
self, content: HookAttachmentMessage, _: TemplateMessage
) -> str:
return format_hook_attachment_content(content)
def format_AwaySummaryMessage(
self, content: AwaySummaryMessage, _: TemplateMessage
) -> str:
return format_away_summary_content(content)
def format_SessionHeaderMessage(
self, content: SessionHeaderMessage, _: TemplateMessage
) -> str:
return format_session_header_content(content)
# -------------------------------------------------------------------------
# User Content Formatters
# -------------------------------------------------------------------------
def format_UserTextMessage(
self, content: UserTextMessage, message: TemplateMessage
) -> str:
# User prompts grafted from a workflow agent's side-channel are large
# prose+JSON hybrids: render them as collapsible Markdown with the
# embedded JSON blocks extracted into params tables (#174 follow-up).
if message.in_workflow_sidechannel:
return format_workflow_sidechannel_user_content(
content, image_formatter=self._format_image
)
return format_user_text_model_content(
content, image_formatter=self._format_image
)
def format_UserSlashCommandMessage(
self, content: UserSlashCommandMessage, _: TemplateMessage
) -> str:
return format_user_slash_command_content(content)
def format_SlashCommandMessage(
self, content: SlashCommandMessage, _: TemplateMessage
) -> str:
return format_slash_command_content(content)
def format_CommandOutputMessage(
self, content: CommandOutputMessage, _: TemplateMessage
) -> str:
return format_command_output_content(content)
def format_BashInputMessage(
self, content: BashInputMessage, _: TemplateMessage
) -> str:
return format_bash_input_content(content)
def format_BashOutputMessage(
self, content: BashOutputMessage, _: TemplateMessage
) -> str:
return format_bash_output_content(content)
def format_CompactedSummaryMessage(
self, content: CompactedSummaryMessage, _: TemplateMessage
) -> str:
return format_compacted_summary_content(content)
def format_UserMemoryMessage(
self, content: UserMemoryMessage, _: TemplateMessage
) -> str:
return format_user_memory_content(content)
def format_TeammateMessage(
self, content: TeammateMessage, _: TemplateMessage
) -> str:
"""Format → one colored card per <teammate-message> block.
Passes the session-wide teammate_colors map so blocks without an
inline color still inherit the teammate's learned color.
"""
return format_teammate_content(content, self._colors_for(_))
def format_TaskNotificationMessage(
self, content: TaskNotificationMessage, _: TemplateMessage
) -> str:
"""Format → metadata `<dl>` + collapsible Markdown body for an
async-agent ``<task-notification>`` user entry (issue #90).
At ``RenderingDepth.AGENT`` a duplicate-flagged notification renders
empty so the rendering loop's "skip empty messages" elision
drops the card — the spawn-fold already shows the answer in
place, and "ghosting" via empty output avoids the index-remap
cascade that deleting the message would trigger (ancestry
classes, backlinks, session nav anchors).
"""
if normalize_theme(self.theme) == "minimal":
# Minimal theme: the notification is the async branch's merge
# row, so the agent's answer is shown here — at the time it
# arrived — and the spawn only links to it (format_TaskOutput).
# A long answer is a two-line preview, like the sync agent's on
# its merge row (format_TaskOutput, P8).
return _format_task_notification_content(
content, include_duplicate=True, preview=True
)
if self.depth == RenderingDepth.AGENT and content.result_is_duplicate:
return ""
return _format_task_notification_content(content)
# -------------------------------------------------------------------------
# Assistant Content Formatters
# -------------------------------------------------------------------------
def format_AssistantTextMessage(
self, content: AssistantTextMessage, _: TemplateMessage
) -> str:
return format_assistant_text_content(
content, image_formatter=self._format_image
)
def format_ThinkingMessage(
self, content: ThinkingMessage, _: TemplateMessage
) -> str:
"""Format → <details class='thinking'>...</details> (foldable if >10 lines)."""
return format_thinking_content(content, line_threshold=10)
def format_UnknownMessage(self, content: UnknownMessage, _: TemplateMessage) -> str:
"""Format → <pre class='unknown'>JSON dump</pre>."""
return format_unknown_content(content)
def format_WorkflowPhaseMessage(
self, content: WorkflowPhaseMessage, _: TemplateMessage
) -> str:
"""Format → spliced workflow phase card body (depth + agent count)."""
return format_workflow_phase_content(content)
def format_WorkflowAgentMessage(
self, content: WorkflowAgentMessage, _: TemplateMessage
) -> str:
"""Format → spliced workflow agent card body (meta line + result)."""
return format_workflow_agent_content(content)
# -------------------------------------------------------------------------
# Tool Input Formatters
# -------------------------------------------------------------------------
def format_BashInput(self, input: BashInput, _: TemplateMessage) -> str:
"""Format → <pre>$ command</pre> (a long one previews in minimal, P8)."""
return format_bash_input(
input, collapse=normalize_theme(self.theme) == "minimal"
)
def format_ReadInput(self, input: ReadInput, _: TemplateMessage) -> str:
"""Format → <table class='params'>file_path | ...</table>."""
return format_read_input(input)
def format_WriteInput(self, input: WriteInput, _: TemplateMessage) -> str:
"""Format → file path + syntax-highlighted content preview."""
return format_write_input(input)
def format_DeleteInput(self, input: DeleteInput, _: TemplateMessage) -> str:
"""Format → empty body; the path is shown in the title."""
return format_delete_input(input)
def format_EditInput(self, input: EditInput, _: TemplateMessage) -> str:
"""Format → file path + diff of old_string/new_string (a long diff
previews in the minimal theme, P8)."""
return format_edit_input(
input, collapse=normalize_theme(self.theme) == "minimal"
)
def format_MultiEditInput(self, input: MultiEditInput, _: TemplateMessage) -> str:
"""Format → file path + multiple diffs."""
return format_multiedit_input(
input, collapse=normalize_theme(self.theme) == "minimal"
)
def format_TaskInput(self, input: TaskInput, _: TemplateMessage) -> str:
"""Format → prompt text, plus teammate-spawn extras when relevant.
Minimal theme (P7c compact spawn rows): the prompt is a 2-line
preview whenever it is longer than that (the shared ``<details>``
preview, full text one click away), and the ``Run background`` row
is left out — the call line's ``[async …]`` already says so (the
title shows it exactly when ``run_in_background`` is set).
"""
if normalize_theme(self.theme) == "minimal":
base = format_task_prompt_preview(input.prompt)
extras = format_task_input_teammate_extras(
input, self._colors_for(_), include_run=False
)
return base + extras if extras else base
base = format_task_input(input)
extras = format_task_input_teammate_extras(input, self._colors_for(_))
return base + extras if extras else base
def format_TodoWriteInput(self, input: TodoWriteInput, _: TemplateMessage) -> str:
"""Format → <ul class='todo-list'>...</ul>."""
return format_todowrite_input(input)
def format_AskUserQuestionInput(
self, input: AskUserQuestionInput, message: TemplateMessage
) -> str:
"""Format → questions as definition list.
Ghosted (empty) when a paired result already re-renders the questions
plus the user's choice — see ``_paired_answer_supersedes``.
"""
if self._paired_answer_supersedes(message):
return ""
return format_askuserquestion_input(input)
def format_ExitPlanModeInput(
self, input: ExitPlanModeInput, _: TemplateMessage
) -> str:
"""Format → empty string (no content)."""
return format_exitplanmode_input(input)
def format_GrepInput(self, input: GrepInput, _: TemplateMessage) -> str:
"""Format → params table (path, glob, type, etc.) without pattern."""
return format_grep_input(input)
def format_WebSearchInput(self, input: WebSearchInput, _: TemplateMessage) -> str:
"""Format → search query display."""
return format_websearch_input(input)
def format_SkillInput(self, _input: SkillInput, _: TemplateMessage) -> str:
"""Format → empty: skill name moves to the title, body folds in via skill_body."""
return ""
# --- Teammate-feature tool inputs --------------------------------------
def format_TeamCreateInput(self, input: TeamCreateInput, _: TemplateMessage) -> str:
"""Format → team-card with team_name / description / agent_type."""
return _format_teamcreate_input(input)
def format_TeamDeleteInput(self, input: TeamDeleteInput, _: TemplateMessage) -> str:
"""Format → empty placeholder (TeamDelete takes no meaningful params)."""
return _format_teamdelete_input(input)
def format_TaskCreateInput(self, input: TaskCreateInput, _: TemplateMessage) -> str:
"""Format → task-create card."""
return _format_taskcreate_input(input)
def format_TaskUpdateInput(self, input: TaskUpdateInput, _: TemplateMessage) -> str:
"""Format → task-update card (colored owner badge when present)."""
return _format_taskupdate_input(input, self._colors_for(_))
def format_TaskListInput(self, input: TaskListInput, _: TemplateMessage) -> str:
"""Format → empty placeholder (TaskList takes no params)."""
del input # TaskListInput has no surfaces worth rendering
return ""
def format_SendMessageInput(
self, input: SendMessageInput, _: TemplateMessage
) -> str:
"""Format → send-message card with colored recipient badge."""
return _format_sendmessage_input(input, self._colors_for(_))
def format_TaskOutputInput(self, input: TaskOutputInput, _: TemplateMessage) -> str:
"""Format → minimal TaskOutput input card (block / timeout if set)."""
return _format_taskoutput_input(input)
def format_TaskStopInput(self, input: TaskStopInput, _: TemplateMessage) -> str:
"""Format → empty (id lives in the title, no further params)."""
return format_taskstop_input(input)
def format_ToolUseContent(self, content: ToolUseContent, _: TemplateMessage) -> str:
"""Format → <table class='params'>key | value rows</table>."""
return render_params_table(content.input)
def format_ToolUseMessage(
self, content: ToolUseMessage, message: TemplateMessage
) -> str:
"""Format Skill tool_use with folded skill body (issue #93).
For every other tool_use, delegate to the base dispatcher
(→ params table). For Skill, append the expanded skill body —
set by `_pair_skill_tool_uses` from the matching isMeta=True
slash-command entry — as collapsible markdown below the params.
"""
rendered = super().format_ToolUseMessage(content, message)
if content.skill_body:
body_html = render_markdown_collapsible(
content.skill_body,
"skill-body",
line_threshold=30,
preview_line_count=10,
)
rendered = f"{rendered}\n{body_html}"
return rendered
# -------------------------------------------------------------------------
# Tool Output Formatters
# -------------------------------------------------------------------------
def format_ReadOutput(self, output: ReadOutput, _: TemplateMessage) -> str:
"""Format → syntax-highlighted file content."""
return format_read_output(output)
def format_WriteOutput(self, output: WriteOutput, _: TemplateMessage) -> str:
"""Format → status message (e.g. 'Wrote 42 bytes')."""
return format_write_output(output)
def format_DeleteOutput(self, output: DeleteOutput, _: TemplateMessage) -> str:
"""Format → deletion status message."""
return format_delete_output(output)
def format_EditOutput(self, output: EditOutput, _: TemplateMessage) -> str:
"""Format → status message (e.g. 'Applied edit')."""
return format_edit_output(output)
def format_BashOutput(self, output: BashOutput, _: TemplateMessage) -> str:
"""Format → <pre>stdout/stderr</pre>."""
return format_bash_output(output)
def format_TaskOutput(self, output: TaskOutput, _: TemplateMessage) -> str:
"""Format → markdown of task result plus teammate-metadata extras.
Minimal theme, async agent whose ``<task-notification>`` was folded
onto this spawn: the answer stays on the notification card (the
branch's merge row, see ``format_TaskNotificationMessage``) and this
card keeps the launch line plus a link to it; the agent id, repeated
on the notification as its Task ID, is dropped here.
"""
if output.async_final_answer and normalize_theme(self.theme) == "minimal":
# The launch acknowledgement, marked so the DAG engine can fold
# it into the spawn's branch control (P7c); without JavaScript
# it reads as before.
base = format_task_output(output, include_async_answer=False)
if base:
base = f"<div class='mn-ack'>{base}</div>"
if output.async_notification_index is not None:
base += (
"<div class='mn-async-jump'><a href='#msg-d-"
f"{output.async_notification_index}'>Result ↓</a>"
" <span>with the async notification</span></div>"
)
extras = format_task_output_teammate_extras(
output, self._colors_for(_), include_agent_id=False
)
return base + extras if extras else base
if normalize_theme(self.theme) == "minimal":
# A synchronous agent's answer is its lane's merge row: a long
# one is a two-line preview with "+N lines", so a multi-screen
# report does not undo "Main only" (P8).
base = format_task_output(output, preview=True)
else:
base = format_task_output(output)
extras = format_task_output_teammate_extras(output, self._colors_for(_))
return base + extras if extras else base
def format_AskUserQuestionOutput(
self, output: AskUserQuestionOutput, message: TemplateMessage
) -> str:
"""Format → each question with its options, the chosen one highlighted.
Options/headers missing from the result's own data (text-fallback and
clarify-rejection paths) are recovered from the paired tool_use input.
"""
return format_askuserquestion_output(
output, self._askuserquestion_questions_for(message)
)
def format_ExitPlanModeOutput(
self, output: ExitPlanModeOutput, _: TemplateMessage
) -> str:
"""Format → status message."""
return format_exitplanmode_output(output)
def format_WebSearchOutput(
self, output: WebSearchOutput, _: TemplateMessage
) -> str:
"""Format → list of clickable search result links."""
return format_websearch_output(output)
# --- Teammate-feature tool outputs -------------------------------------
def format_TeamCreateOutput(
self, output: TeamCreateOutput, _: TemplateMessage
) -> str:
"""Format → team-card with team_name / lead / config path."""
return _format_teamcreate_output(output)
def format_TeamDeleteOutput(
self, output: TeamDeleteOutput, _: TemplateMessage
) -> str:
"""Format → success/refused notice; active members listed when blocked."""
return _format_teamdelete_output(output, self._colors_for(_))
def format_TaskCreateOutput(
self, output: TaskCreateOutput, _: TemplateMessage
) -> str:
"""Format → created task id + subject."""
return _format_taskcreate_output(output)
def format_TaskUpdateOutput(
self, output: TaskUpdateOutput, _: TemplateMessage
) -> str:
"""Format → task id + updated fields (+ transition if present)."""
return _format_taskupdate_output(output)
def format_TaskListOutput(self, output: TaskListOutput, _: TemplateMessage) -> str:
"""Format → <table class='task-list'> with id/status/subject/owner."""
return _format_tasklist_output(output, self._colors_for(_))
def format_SendMessageOutput(
self, output: SendMessageOutput, _: TemplateMessage
) -> str:
"""Format → sent/failed notice with colored target badge + request id."""
return _format_sendmessage_output(output, self._colors_for(_))
def format_TaskOutputResult(
self, output: TaskOutputResult, _: TemplateMessage
) -> str:
"""Format → minimal TaskOutput result card (metadata only, no transcript)."""
return _format_taskoutput_output(output)
def format_TaskStopOutput(self, output: TaskStopOutput, _: TemplateMessage) -> str:
"""Format → ``Stopped`` / ``Not stopped`` badge + message body."""
return format_taskstop_output(output)
def format_ToolResultContent(
self, output: ToolResultContent, _: TemplateMessage
) -> str:
"""Format → <pre>raw content</pre> (fallback for unknown tools)."""
return format_tool_result_content_raw(output)
def format_WebFetchInput(self, input: WebFetchInput, _: TemplateMessage) -> str:
"""Format → prompt text if long, empty if shown in title."""
return format_webfetch_input(input)
def format_WorkflowToolInput(
self, input: WorkflowToolInput, _: TemplateMessage
) -> str:
"""Format → meta header (name/description/phases) + highlighted JS script."""
return format_workflow_input(input)
def format_ToolExecutionInput(
self, input: ToolExecutionInput, _: TemplateMessage
) -> str:
"""Format opaque Codex JavaScript as an execution snippet."""
return format_tool_execution_input(input)
def format_ToolExecutionOutput(
self, output: ToolExecutionOutput, _: TemplateMessage
) -> str:
"""Format execution status and labelled result emissions."""
return format_tool_execution_output(output)
def title_ToolExecutionInput(
self, _input: ToolExecutionInput, message: TemplateMessage
) -> str:
"""Title → code-oriented execution, distinct from Workflow."""
return self._tool_title(message, "⚙️")