From 113063b040ccb503019e0fedefd5d815f0ff283c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 23:24:03 +0000 Subject: [PATCH] Notebook design: numbered In/Out cells, tool sub-cells and an input-cell composer Adds the Notebook design (TranscriptStyle.cells, ComposerStyle.cell), a white/charcoal IDE theme with light grey cells, hairlines and 5px corners. Co-Authored-By: Claude Opus 5.5 --- .../chat/conversation/chat_composer_bar.dart | 9 + .../chat/conversation/chat_thread_view.dart | 47 ++- .../chat/conversation/composer_cell.dart | 94 ++++++ .../chat/domain/chat_cell_numbers.dart | 25 ++ .../ui/transcript/chat_automated_prompt.dart | 20 +- .../ui/transcript/chat_message_bubble.dart | 3 + .../chat/ui/transcript/chat_message_view.dart | 136 +++++++-- .../transcript/chat_turn_activity_view.dart | 9 + .../notebook/notebook_cell_frame.dart | 119 ++++++++ .../transcript/notebook/notebook_gutter.dart | 187 ++++++++++++ .../notebook/notebook_input_cell.dart | 150 ++++++++++ .../notebook/notebook_tool_cell.dart | 281 +++++++++++++++++ .../notebook/notebook_tool_cells.dart | 154 ++++++++++ app/lib/ui/theme/app_design.dart | 22 ++ app/lib/ui/theme/app_design_styles.dart | 9 + app/lib/ui/theme/notebook_controls.dart | 159 ++++++++++ app/lib/ui/theme/notebook_palette.dart | 107 +++++++ app/lib/ui/theme/notebook_theme.dart | 208 +++++++++++++ app/notes/design-notebook.md | 85 ++++++ .../transcript/notebook_transcript_test.dart | 283 ++++++++++++++++++ app/test/ui/theme/notebook_design_test.dart | 128 ++++++++ 21 files changed, 2202 insertions(+), 33 deletions(-) create mode 100644 app/lib/features/chat/conversation/composer_cell.dart create mode 100644 app/lib/features/chat/domain/chat_cell_numbers.dart create mode 100644 app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart create mode 100644 app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart create mode 100644 app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart create mode 100644 app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart create mode 100644 app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart create mode 100644 app/lib/ui/theme/notebook_controls.dart create mode 100644 app/lib/ui/theme/notebook_palette.dart create mode 100644 app/lib/ui/theme/notebook_theme.dart create mode 100644 app/notes/design-notebook.md create mode 100644 app/test/features/chat/ui/transcript/notebook_transcript_test.dart create mode 100644 app/test/ui/theme/notebook_design_test.dart diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 415dc12c..5892b2d8 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -34,6 +34,7 @@ import 'composer_focus_request.dart'; import 'composer_focus_restore.dart'; import 'chat_bar_tint.dart'; import 'composer_focus_ring.dart'; +import 'composer_cell.dart'; import 'composer_underline.dart'; import '../../../ui/theme/app_design_tokens.dart'; import 'composer_running_border.dart'; @@ -1120,6 +1121,14 @@ class _ChatComposerBarState extends State { child: child, ); } + if (tokens.composer == ComposerStyle.cell) { + return ComposerCell( + focus: _focus, + accent: accent, + running: widget.running, + child: child, + ); + } final shape = tokens.shape(_pillShape); return Stack( children: [ diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index fba71e0c..a84a548a 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -13,6 +13,7 @@ import '../../../shell/list_detail_policy.dart'; import '../data/chat_attachment_images.dart'; import '../data/chat_repository.dart'; import '../domain/chat_activity_detail.dart'; +import '../domain/chat_cell_numbers.dart'; import '../domain/chat_notice.dart'; import '../domain/chat_harness_commands.dart'; import '../domain/chat_attachment_picker.dart'; @@ -31,6 +32,8 @@ import '../ui/transcript/chat_find_highlight.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_bubble.dart'; import '../ui/transcript/chat_message_view.dart'; +import '../ui/transcript/notebook/notebook_gutter.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../ui/transcript/chat_message_timestamp.dart'; import '../ui/transcript/chat_turn_activity_view.dart'; import '../domain/chat_transcript_days.dart'; @@ -306,6 +309,10 @@ class _ChatThreadViewState extends State with ChatFindHost { final _sentEntrances = ChatSentEntrances(); final _rowWidgets = ChatRowWidgets(); + /// Under a notebook transcript, each turn's cell number by row key + /// ([chatCellNumbers]); empty under every other transcript. + Map _cellNumbers = const {}; + /// The floating bar and composer, reused while their inputs hold so a /// streamed delta does not rebuild the conversation's chrome. final _chrome = ChatRowWidgets(); @@ -1247,6 +1254,9 @@ class _ChatThreadViewState extends State with ChatFindHost { ), _controller.turnDiffs, ); + final cells = + AppDesignTokens.of(context).transcript == TranscriptStyle.cells; + _cellNumbers = cells ? chatCellNumbers(allRows) : const {}; // A transcript held from before a socket gap may still say a compaction is // running even when the repair's read is refused. That running state is // stale, so no compaction notice is derived from it until a fresh read or @@ -1415,17 +1425,21 @@ class _ChatThreadViewState extends State with ChatFindHost { child: Builder( builder: (_) => _entering( rows[index], - _transcriptRow( + _inNotebookGutter( + cells, rows[index], - keys[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition( - rows[index], - ) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, + _transcriptRow( + rows[index], + keys[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition( + rows[index], + ) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, + ), ), ), ), @@ -1930,10 +1944,12 @@ class _ChatThreadViewState extends State with ChatFindHost { // write, never mutated, so a deep-equal row is the same content. Permission // chips carry objects that compare by identity, so a row with chips is // always rebuilt. + final cell = _cellNumbers['${row['key'] ?? ''}']; return _rowWidgets.widgetFor( key, row, [ + cell, delivery, onRemove != null, sendAt, @@ -1944,6 +1960,7 @@ class _ChatThreadViewState extends State with ChatFindHost { ], () => ChatMessageView( row: row, + cell: cell, speechScope: widget.sessionId, scheduleShown: sendAt != null, // The same reader id as the reply's Read aloud button, so the spoken @@ -1969,6 +1986,16 @@ class _ChatThreadViewState extends State with ChatFindHost { ); } + /// Under a notebook transcript, a row that is not a cell (a shell run, a + /// notice, an activity group) behind an empty gutter, so it keeps to the + /// cells' column; a cell draws its own gutter. + Widget _inNotebookGutter(bool cells, JsonMap row, Widget child) { + if (!cells) return child; + final kind = row['kind']; + if (kind == 'user' || kind == 'assistant') return child; + return NotebookGutterRow(child: child); + } + /// A user row in the entrance a just-sent message plays; every user row is /// wrapped, so its server copy replacing it keeps the same element. Widget _entering(JsonMap row, Widget child) { diff --git a/app/lib/features/chat/conversation/composer_cell.dart b/app/lib/features/chat/conversation/composer_cell.dart new file mode 100644 index 00000000..a93cb242 --- /dev/null +++ b/app/lib/features/chat/conversation/composer_cell.dart @@ -0,0 +1,94 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/glass_bar.dart'; +import '../../../ui/theme/app_design_tokens.dart'; +import '../ui/transcript/notebook/notebook_cell_frame.dart'; +import '../ui/transcript/notebook/notebook_gutter.dart'; +import 'composer_focus_ring.dart'; + +/// The composer under a design whose composer is a notebook cell +/// ([ComposerStyle.cell], Notebook): the next, empty input cell, `In [ ]:` +/// in the gutter beside a light grey cell holding the field and its +/// controls. The cell's frame and bar take [accent] while the field has +/// focus; while a turn runs a thin moving line runs along its foot. It +/// floats over the transcript, so it stands on the page's own colour. +class ComposerCell extends StatelessWidget { + const ComposerCell({ + super.key, + required this.focus, + required this.accent, + required this.running, + required this.child, + }); + + final FocusNode focus; + + /// The chat's focus colour (the host's primary for a chat with none). + final Color accent; + + /// Whether a turn is running. + final bool running; + final Widget child; + + /// The cell's padding: the pill's edge gap and, past it, the same 3px + /// the usage ring keeps from the send button, so the ring never meets + /// the cell's hairline. + static const double _inset = GlassBarMetrics.fieldEdgeGap + 3; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final cell = ListenableBuilder( + listenable: focus, + child: Padding(padding: const EdgeInsets.all(_inset), child: child), + builder: (context, field) { + final focused = focus.hasFocus; + return NotebookCellFrame( + key: const Key('chat-composer-cell-frame'), + fill: scheme.surfaceContainerLow, + border: focused ? accent : scheme.outlineVariant, + bar: focused ? accent : scheme.outline, + padding: const EdgeInsetsDirectional.only(start: notebookCellBar), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field!, + if (running) + Padding( + padding: const EdgeInsetsDirectional.only( + start: notebookCellTextInset - notebookCellBar, + end: notebookCellTextInset, + bottom: 1, + ), + child: LinearProgressIndicator( + key: const Key('chat-composer-running-rule'), + minHeight: ComposerFocusRing.ringWidth, + color: accent, + backgroundColor: scheme.outlineVariant, + ), + ), + ], + ), + ); + }, + ); + return Material( + key: const Key('chat-composer-cell'), + // The page itself, so the cell reads as the next one on the sheet. + color: Theme.of(context).scaffoldBackgroundColor, + child: Padding( + padding: const EdgeInsets.only(top: 4), + child: NotebookGutterRow( + label: notebookInLabel(null), + color: notebookInColor(scheme), + // The label on the field's first line: the cell's padding, then + // the field's own. + top: _inset + 16, + inline: false, + child: cell, + ), + ), + ); + } +} diff --git a/app/lib/features/chat/domain/chat_cell_numbers.dart b/app/lib/features/chat/domain/chat_cell_numbers.dart new file mode 100644 index 00000000..881c3efe --- /dev/null +++ b/app/lib/features/chat/domain/chat_cell_numbers.dart @@ -0,0 +1,25 @@ +import '../../../core/api_gateway.dart'; + +/// A notebook transcript's cell numbers by row key: each operator turn +/// (a `user` row, typed or sent on the operator's behalf) takes the next +/// number from 1 in transcript order, and every agent row (`assistant`) that +/// follows takes its prompt's number, so `In [n]:` and `Out [n]:` pair up. +/// +/// Derived from the turn's position, never stored: the same history always +/// numbers the same way, so a reload keeps every cell's number. An agent +/// row before any operator turn has none (`Out [ ]:`). +Map chatCellNumbers(Iterable rows) { + final numbers = {}; + var turn = 0; + for (final row in rows) { + final key = '${row['key'] ?? ''}'; + switch (row['kind']) { + case 'user': + turn++; + if (key.isNotEmpty) numbers[key] = turn; + case 'assistant': + if (turn > 0 && key.isNotEmpty) numbers[key] = turn; + } + } + return numbers; +} diff --git a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart index 23b89ad3..3e6fbed4 100644 --- a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart +++ b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart @@ -6,6 +6,8 @@ import '../../conversation/chat_schedule_time.dart'; import '../../domain/chat_prompt_origin.dart'; import 'chat_copy_button.dart'; import 'chat_hover_actions.dart'; +import 'notebook/notebook_cell_frame.dart'; +import 'notebook/notebook_input_cell.dart'; import 'paper/paper_editorial_note.dart'; import 'paper/paper_quote.dart'; import 'terminal/terminal_glyphs.dart'; @@ -18,6 +20,13 @@ String chatAutomatedPromptLabel(ChatPromptOrigin origin) => switch (origin) { _ => '', }; +/// A notebook cell's tag for an automated prompt: a follow-up or an +/// auto-continue was scheduled; a switch of account continues at once. +String chatAutomatedPromptTag(ChatPromptOrigin origin) => switch (origin) { + ChatPromptOrigin.autoSwitch => 'switched', + _ => 'scheduled', +}; + IconData _icon(ChatPromptOrigin origin) => switch (origin) { ChatPromptOrigin.followup => Icons.update, ChatPromptOrigin.autoContinue => Icons.autorenew, @@ -70,7 +79,15 @@ class ChatAutomatedPromptCard extends StatelessWidget { ), ); final transcript = AppDesignTokens.of(context).transcript; - final card = transcript == TranscriptStyle.manuscript + final card = transcript == TranscriptStyle.cells + ? NotebookScheduledCell( + tag: chatAutomatedPromptTag(prompt.origin), + label: label, + detail: detail, + body: body, + hasBody: prompt.body.trim().isNotEmpty, + ) + : transcript == TranscriptStyle.manuscript ? PaperEditorialNote( label: label, detail: detail, @@ -111,6 +128,7 @@ class ChatAutomatedPromptCard extends StatelessWidget { final footerInset = switch (transcript) { TranscriptStyle.prompt => 8 + terminalGlyphColumn(context), TranscriptStyle.manuscript => paperQuoteTextInset, + TranscriptStyle.cells => notebookCellTextInset, TranscriptStyle.bubbles => 14.0, }; return ChatHoverRegion( diff --git a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart index 464fba1f..f69b71ba 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../../ui/theme/app_design_tokens.dart'; import '../sessions/chat_color_palette.dart'; +import 'notebook/notebook_input_cell.dart'; import 'paper/paper_quote.dart'; import 'terminal/terminal_prompt_line.dart'; @@ -51,6 +52,8 @@ class ChatUserBubble extends StatelessWidget { return TerminalPromptLine(child: child); case TranscriptStyle.manuscript: return PaperQuote(child: child); + case TranscriptStyle.cells: + return NotebookInputCell(child: child); case TranscriptStyle.bubbles: break; } diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index e14c7062..4596063a 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -18,6 +18,9 @@ import 'chat_link_text.dart'; import 'chat_message_bubble.dart'; import 'chat_turn_activity_view.dart'; import 'native_disclosure.dart'; +import 'notebook/notebook_cell_frame.dart'; +import 'notebook/notebook_gutter.dart'; +import 'notebook/notebook_tool_cell.dart'; import 'paper/paper_quote.dart'; import 'terminal/terminal_glyphs.dart'; import 'chat_message_timestamp.dart'; @@ -38,8 +41,14 @@ class ChatMessageView extends StatelessWidget { this.images, this.speechScope = 'chat', this.scheduleShown = false, + this.cell, }); + /// The turn's number under a notebook transcript (`In [n]:` and + /// `Out [n]:`, see [chatCellNumbers]); null for a prompt not yet run or + /// an answer without one. Other transcripts ignore it. + final int? cell; + /// Whether [footer] already says the message is scheduled (its delivery /// line reads "Scheduled · sends at …"), so the operator's own scheduled /// message needs no second mark. @@ -86,6 +95,7 @@ class ChatMessageView extends StatelessWidget { final transcript = AppDesignTokens.of(context).transcript; final trailingUser = user && !automated && transcript == TranscriptStyle.bubbles; + final cells = transcript == TranscriptStyle.cells; // No visible role label: side and surface say who spoke and the row's // semantics label names the role. The operator's turn is a neutral bubble // that shrinks to its content; the agent's answer sits on the page with no @@ -105,9 +115,13 @@ class ChatMessageView extends StatelessWidget { child: Padding( // A manuscript leaves a little more air between turns, as a page // spaces its paragraphs, since no bubble sets them apart. - padding: EdgeInsets.symmetric( - vertical: transcript == TranscriptStyle.manuscript ? 12 : 6, - ), + // A notebook keeps a turn's In and Out cells close and sets the + // next turn further off, so each prompt and its answer read as one. + padding: cells + ? EdgeInsets.only(top: user ? 6 : 3, bottom: user ? 3 : 6) + : EdgeInsets.symmetric( + vertical: transcript == TranscriptStyle.manuscript ? 12 : 6, + ), child: LayoutBuilder( builder: (context, constraints) => Align( alignment: trailingUser @@ -118,14 +132,28 @@ class ChatMessageView extends StatelessWidget { // sides read as a conversation; the answer keeps a readable // measure on a wide pane. constraints: BoxConstraints( + // A notebook's cells span the reading column, edge to edge + // with the composer's input cell. maxWidth: trailingUser ? (constraints.maxWidth * 0.85).clamp(0, 560).toDouble() + : cells + ? double.infinity : 720 + gutter, ), child: automated - ? _automatedTurn(origin, content) + ? _inCell( + context, + _automatedTurn(origin, content), + line: Theme.of(context).textTheme.labelMedium, + enabled: cells, + ) : user - ? _userTurn(content, body, origin, transcript: transcript) + ? _inCell( + context, + _userTurn(content, body, origin, transcript: transcript), + line: chatMessageTextStyle(context), + enabled: cells, + ) : _agentRow( context, content, @@ -139,6 +167,27 @@ class ChatMessageView extends StatelessWidget { ); } + /// Under a notebook, the operator's turn in its gutter: `In [n]:` on the + /// input cell's first line. + Widget _inCell( + BuildContext context, + Widget turn, { + required TextStyle? line, + required bool enabled, + }) { + if (!enabled) return turn; + final thumbnails = _partsOf( + _userMessage, + ).any((part) => _isFile(part) && chatPartIsThumbnail(part)); + return NotebookGutterRow( + label: notebookInLabel(cell), + color: notebookInColor(Theme.of(context).colorScheme), + top: thumbnails ? 0 : notebookCellPadding.top, + line: thumbnails ? null : line, + child: turn, + ); + } + Color _secondaryColor(BuildContext context) => Theme.of(context).colorScheme.onSurfaceVariant; @@ -196,9 +245,11 @@ class ChatMessageView extends StatelessWidget { Padding( // Under a manuscript the line starts at the quoted text. padding: EdgeInsetsDirectional.only( - start: transcript == TranscriptStyle.manuscript - ? paperQuoteTextInset - : 0, + start: switch (transcript) { + TranscriptStyle.manuscript => paperQuoteTextInset, + TranscriptStyle.cells => notebookCellTextInset, + _ => 0, + }, ), child: Wrap( key: const Key('chat-message-footer'), @@ -291,7 +342,11 @@ class ChatMessageView extends StatelessWidget { ), ], ); - if (gutter <= 0) { + // A notebook keeps its Out cell's top on the In cell's rhythm: its + // actions trail the footer line, and the Copy gutter stays empty. + final cells = + AppDesignTokens.of(context).transcript == TranscriptStyle.cells; + if (gutter <= 0 || cells) { // Without a gutter the actions trail the footer line; a pointer device // shows them while the answer is hovered or one has focus. final row = actions(Axis.horizontal); @@ -306,9 +361,15 @@ class ChatMessageView extends StatelessWidget { child: child!, ), ); - return ChatHoverRegion( + final region = ChatHoverRegion( child: _agentTurn(context, content, answer, reveal), ); + return gutter <= 0 + ? region + : Padding( + padding: EdgeInsetsDirectional.only(start: gutter), + child: region, + ); } // The gutter is one button wide: Read aloud stacks above Copy, and stays // shown on a desktop while this reply reads. @@ -344,7 +405,11 @@ class ChatMessageView extends StatelessWidget { for (final part in parts) if (isChatToolPart(part)) part, ]; - final terminal = AppDesignTokens.of(context).terminal; + final transcript = AppDesignTokens.of(context).transcript; + final terminal = transcript == TranscriptStyle.prompt; + final cells = transcript == TranscriptStyle.cells; + // A notebook's answer text starts in the cells' text column. + final inset = cells ? notebookCellTextInset : chatAgentContentInset; final model = '${row['model'] ?? ''}'.trim(); // The metadata line: the model that answered and the time, muted; the // actions (when not in the gutter) trail it. @@ -358,14 +423,18 @@ class ChatMessageView extends StatelessWidget { if (chatMessageCreatedAt(row) case final time?) ChatMessageTimestamp(createdAt: time), ]; - return Column( + final activity = + row['streaming'] == true || + reasoning.isNotEmpty || + tools.isNotEmpty || + (row['activityRecords'] as List? ?? const []).isNotEmpty; + final turn = Column( mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: cells + ? CrossAxisAlignment.stretch + : CrossAxisAlignment.start, children: [ - if (row['streaming'] == true || - reasoning.isNotEmpty || - tools.isNotEmpty || - (row['activityRecords'] as List? ?? const []).isNotEmpty) + if (activity) ChatTurnActivityView( key: const Key('chat-stable-turn-activity'), parts: [ @@ -380,9 +449,7 @@ class ChatMessageView extends StatelessWidget { if (content.isNotEmpty) const SizedBox(height: 6), if (content.isNotEmpty) Padding( - padding: const EdgeInsets.symmetric( - horizontal: chatAgentContentInset, - ), + padding: EdgeInsets.symmetric(horizontal: inset), child: terminal ? _terminalAnswer(context, answer) : answer, ), // Settled permissions, questions and changes: meta rows that, like @@ -403,8 +470,7 @@ class ChatMessageView extends StatelessWidget { padding: EdgeInsetsDirectional.only( start: meta.isEmpty ? 0 - : chatAgentContentInset + - (terminal ? terminalGlyphColumn(context) : 0), + : inset + (terminal ? terminalGlyphColumn(context) : 0), end: chatAgentContentInset, ), child: Wrap( @@ -416,6 +482,32 @@ class ChatMessageView extends StatelessWidget { ), ], ); + if (!cells) return turn; + // A notebook's Out cell: `Out [n]:` on the first sub-cell's line (or + // the answer's), and while the turn runs Jupyter's `[*]` beneath it. + final scheme = Theme.of(context).colorScheme; + return NotebookGutterRow( + label: notebookOutLabel(cell), + color: notebookOutColor(scheme), + top: activity ? 5 : 0, + line: activity + ? notebookToolStyle(context) + : chatMessageTextStyle(context), + marker: row['streaming'] == true + ? Semantics( + label: 'Running', + child: Text( + '[*]', + key: const Key('chat-notebook-busy'), + style: notebookGutterStyle( + context, + AppDesignTokens.of(context).ansi?.yellow ?? scheme.primary, + ).copyWith(fontWeight: FontWeight.w700), + ), + ) + : null, + child: turn, + ); } /// The answer under a terminal design: a dot in the glyph column, as a diff --git a/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart b/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart index 0f0ff06f..88cd955e 100644 --- a/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart @@ -9,6 +9,7 @@ import '../../../../ui/theme/app_design_tokens.dart'; import 'chat_response_pending.dart'; import 'chat_turn_activity_details.dart'; import 'chat_turn_chip.dart'; +import 'notebook/notebook_tool_cells.dart'; import 'paper/paper_activity_note.dart'; import 'terminal/terminal_activity_rows.dart'; @@ -140,6 +141,14 @@ class _ChatTurnActivityViewState extends State { failed: data.failed, onOpen: _open, ); + case TranscriptStyle.cells: + return NotebookToolCells( + data: data, + status: label, + streaming: widget.streaming, + seconds: seconds, + onOpen: _open, + ); case TranscriptStyle.bubbles: break; } diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart new file mode 100644 index 00000000..eaa75c8f --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; + +import '../../../../../ui/theme/app_design_tokens.dart'; + +/// The width of an input cell's accent bar along its leading edge. +const double notebookCellBar = 3; + +/// Where a cell's text starts from its leading edge: past the bar, then a +/// gap. Output text, footers and the composer's field start here too, so +/// every cell's text shares one column. +const double notebookCellTextInset = 12; + +/// The padding of a cell's content: [notebookCellTextInset] at the start, +/// a little less above and below. +const EdgeInsetsDirectional notebookCellPadding = + EdgeInsetsDirectional.fromSTEB( + notebookCellTextInset, + 8, + notebookCellTextInset, + 8, + ); + +/// The corner radius cells take: the design's, else a notebook's 5px. +double notebookCellRadius(BuildContext context) => + AppDesignTokens.of(context).radius ?? 5; + +/// A notebook cell's frame: a [fill] in the design's corners inside a +/// hairline [border], and an optional accent [bar] along the leading edge +/// clipped to the corners. Painted in one pass, with no layer, so a long +/// transcript of cells costs one picture per cell. +class NotebookCellFrame extends StatelessWidget { + const NotebookCellFrame({ + super.key, + required this.fill, + required this.border, + this.bar, + this.padding = notebookCellPadding, + this.width, + required this.child, + }); + + /// A fixed width (`double.infinity` to span a column that would shrink + /// the cell to its content); null to size to the parent's constraints. + final double? width; + + final Color fill; + final Color border; + final Color? bar; + final EdgeInsetsGeometry padding; + final Widget child; + + @override + Widget build(BuildContext context) => CustomPaint( + painter: NotebookCellPainter( + fill: fill, + border: border, + bar: bar, + radius: notebookCellRadius(context), + direction: Directionality.of(context), + ), + child: SizedBox( + width: width, + child: Padding(padding: padding, child: child), + ), + ); +} + +/// Paints [NotebookCellFrame]: fill, leading bar and a 1px border. +class NotebookCellPainter extends CustomPainter { + NotebookCellPainter({ + required this.fill, + required this.border, + required this.bar, + required this.radius, + required this.direction, + }); + + final Color fill; + final Color border; + final Color? bar; + final double radius; + final TextDirection direction; + + @override + void paint(Canvas canvas, Size size) { + final rect = Offset.zero & size; + final rounded = RRect.fromRectAndRadius(rect, Radius.circular(radius)); + canvas.drawRRect(rounded, Paint()..color = fill); + final accent = bar; + if (accent != null) { + final left = direction == TextDirection.ltr + ? 0.0 + : size.width - notebookCellBar; + canvas + ..save() + ..clipRRect(rounded) + ..drawRect( + Rect.fromLTWH(left, 0, notebookCellBar, size.height), + Paint()..color = accent, + ) + ..restore(); + } + canvas.drawRRect( + rounded.deflate(0.5), + Paint() + ..color = border + ..style = PaintingStyle.stroke + ..strokeWidth = 1, + ); + } + + @override + bool shouldRepaint(NotebookCellPainter old) => + old.fill != fill || + old.border != border || + old.bar != bar || + old.radius != radius || + old.direction != direction; +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart new file mode 100644 index 00000000..331e15d8 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart @@ -0,0 +1,187 @@ +import 'package:flutter/material.dart'; + +import '../../../../../ui/text/monospace.dart'; +import '../chat_message_bubble.dart'; + +/// Below this width a cell's gutter collapses: its label sits inline above +/// the cell instead of beside it, so a phone keeps the whole width for text. +const double notebookCompactWidth = 600; + +/// The gap between a gutter label's end and its cell. +const double notebookGutterGap = 8; + +/// An input cell's label: `In [n]:`, or `In [ ]:` for one not yet run. +String notebookInLabel(int? number) => 'In [${number ?? ' '}]:'; + +/// An output cell's label: `Out [n]:`, or `Out [ ]:` without a prompt. +String notebookOutLabel(int? number) => 'Out [${number ?? ' '}]:'; + +/// The style of gutter labels: the bundled monospace a step under the +/// reading size, in [color]. +TextStyle notebookGutterStyle(BuildContext context, Color color) => TextStyle( + fontFamily: appMonospaceFamily, + fontSize: (chatMessageTextStyle(context)?.fontSize ?? 15) * 0.8, + height: 1.2, + letterSpacing: 0, + color: color, +); + +/// The gutter's fixed width: ten monospace characters (`Out [123]:`) at the +/// label size, scaled with the operator's text, and the gap. Every cell +/// shares it, so labels right-align to one column. +double notebookGutterWidth(BuildContext context) { + final size = (chatMessageTextStyle(context)?.fontSize ?? 15) * 0.8; + // RobotoMono advances 0.6 em per character. + return MediaQuery.textScalerOf(context).scale(size) * 0.6 * 10 + + notebookGutterGap; +} + +/// The muted colour of an `In` label: the accent pulled towards the +/// secondary ink, as a notebook tints its input prompt. +Color notebookInColor(ColorScheme scheme) => + Color.lerp(scheme.onSurfaceVariant, scheme.primary, 0.55)!; + +/// The muted colour of an `Out` label: the tertiary (a notebook's output +/// orange) pulled towards the secondary ink. +Color notebookOutColor(ColorScheme scheme) => + Color.lerp(scheme.onSurfaceVariant, scheme.tertiary, 0.55)!; + +/// Marks a subtree already inside a cell gutter, so a row nested in another +/// (an activity group's folded turns) does not indent twice. +class NotebookGutterScope extends InheritedWidget { + const NotebookGutterScope({super.key, required super.child}); + + static bool inside(BuildContext context) => + context.getInheritedWidgetOfExactType() != null; + + @override + bool updateShouldNotify(NotebookGutterScope old) => false; +} + +/// One transcript row in a notebook: a fixed-width gutter holding [label] +/// right-aligned (with an optional [marker] beneath it), then the cell. +/// [line] is the style of the cell's first line: the label sits on that +/// line's baseline, [top] below the row's top. Without a label the gutter +/// is empty, so rows that are not cells still keep to the cells' column. +/// Narrower than [notebookCompactWidth], the label moves inline above the +/// cell and the gutter goes. +class NotebookGutterRow extends StatelessWidget { + const NotebookGutterRow({ + super.key, + this.label, + this.color, + this.top = 0, + this.line, + this.marker, + this.inline = true, + required this.child, + }); + + /// Whether a narrow row shows the label inline above the cell; false + /// drops it there (the composer, whose cell needs no number on a phone). + final bool inline; + + final String? label; + final Color? color; + final double top; + final TextStyle? line; + final Widget? marker; + final Widget child; + + @override + Widget build(BuildContext context) { + if (NotebookGutterScope.inside(context)) return child; + final scheme = Theme.of(context).colorScheme; + final style = notebookGutterStyle( + context, + color ?? scheme.onSurfaceVariant, + ); + final text = label; + return NotebookGutterScope( + child: LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth < notebookCompactWidth) { + if (text == null || !inline) return child; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.only( + start: 2, + bottom: 3, + ), + child: Row( + children: [ + _label(text, style, null, TextAlign.start), + if (marker case final marker?) ...[ + const SizedBox(width: 6), + marker, + ], + ], + ), + ), + child, + ], + ); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: notebookGutterWidth(context), + child: text == null + ? null + : Padding( + padding: EdgeInsetsDirectional.only( + top: top, + end: notebookGutterGap, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + _label(text, style, line, TextAlign.end), + ?marker, + ], + ), + ), + ), + Expanded(child: child), + ], + ); + }, + ), + ); + } + + /// The label, kept out of a transcript selection (a copied answer has no + /// prompt numbers in it) and out of semantics (the row already names + /// whose message it is). On [line]'s strut it shares that line's + /// baseline. + Widget _label( + String text, + TextStyle style, + TextStyle? line, + TextAlign align, + ) => ExcludeSemantics( + child: SelectionContainer.disabled( + child: Text( + text, + key: const Key('chat-notebook-gutter-label'), + textAlign: align, + maxLines: 1, + softWrap: false, + style: style, + strutStyle: line == null + ? null + : StrutStyle( + fontFamily: line.fontFamily, + fontFamilyFallback: line.fontFamilyFallback, + fontSize: line.fontSize, + height: line.height, + forceStrutHeight: true, + ), + ), + ), + ); +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart new file mode 100644 index 00000000..55c69e6f --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; + +import '../../sessions/chat_color_palette.dart'; +import '../chat_message_bubble.dart'; +import 'notebook_cell_frame.dart'; + +/// How strongly a coloured chat's shade tints its input cells over the +/// cell grey: a hint of the colour, not a wash. +const double notebookInputTint = 0.07; + +/// The operator's turn under a notebook transcript: an input cell in the +/// light cell grey (tinted faintly by the chat's colour), framed by a +/// hairline, with a thin accent bar in the chat's colour (the accent for a +/// chat with none) along its leading edge. It spans the reading column. +class NotebookInputCell extends StatelessWidget { + const NotebookInputCell({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final shade = chatColorShade(context, ChatBubbleColor.of(context)); + final base = scheme.surfaceContainerLow; + return Material( + key: const Key('chat-notebook-input-cell'), + type: MaterialType.transparency, + child: NotebookCellFrame( + fill: shade == null + ? base + : Color.alphaBlend( + shade.withValues(alpha: notebookInputTint), + base, + ), + border: scheme.outlineVariant, + bar: shade ?? scheme.primary, + child: child, + ), + ); + } +} + +/// A prompt the agent or the server sent (a follow-up, an auto-continue, a +/// switch of account) under a notebook transcript: an input cell like the +/// operator's, its bar in the muted outline rather than the chat's colour, +/// headed by a small [tag] ("scheduled") and the [detail] of when; the +/// prompt's [body] beneath. +class NotebookScheduledCell extends StatelessWidget { + const NotebookScheduledCell({ + super.key, + required this.tag, + required this.label, + this.detail, + required this.body, + required this.hasBody, + }); + + /// The tag's word: `scheduled`, `auto-continue` or `switched`. + final String tag; + + /// What sent it, e.g. `Follow-up from agent`. + final String label; + final String? detail; + final Widget body; + final bool hasBody; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final muted = theme.textTheme.labelMedium?.copyWith( + color: scheme.onSurfaceVariant, + ); + final header = SelectionContainer.disabled( + child: Wrap( + key: const Key('chat-automated-prompt-header'), + spacing: 6, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + NotebookTag(tag, key: const Key('chat-notebook-scheduled-tag')), + Text(label, style: muted?.copyWith(fontWeight: FontWeight.w600)), + if (detail != null) Text('· $detail', style: muted), + ], + ), + ); + // A cell spans the column, as the operator's own do. + return Material( + key: const Key('chat-automated-prompt'), + type: MaterialType.transparency, + child: NotebookCellFrame( + width: double.infinity, + fill: scheme.surfaceContainerLow, + border: scheme.outlineVariant, + bar: scheme.outline, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + header, + if (hasBody) ...[ + const SizedBox(height: 4), + DefaultTextStyle.merge( + style: chatMessageTextStyle( + context, + )?.copyWith(color: scheme.onSurfaceVariant), + child: body, + ), + ], + ], + ), + ), + ); + } +} + +/// A notebook's small tag: a word in a hairline box in 3px corners, the +/// cell grey a step darker, as an IDE marks a cell's state. +class NotebookTag extends StatelessWidget { + const NotebookTag(this.text, {super.key, this.color}); + + final String text; + + /// The tag's ink; the secondary ink by default. + final Color? color; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerHigh, + border: Border.all(color: scheme.outlineVariant), + borderRadius: const BorderRadius.all(Radius.circular(3)), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + child: Text( + text, + style: theme.textTheme.labelSmall?.copyWith( + color: color ?? scheme.onSurfaceVariant, + letterSpacing: 0.2, + height: 1.3, + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart new file mode 100644 index 00000000..359396af --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart @@ -0,0 +1,281 @@ +import 'package:flutter/material.dart'; + +import '../../../../../core/api_gateway.dart'; +import '../../../../../ui/text/monospace.dart'; +import '../../../../../ui/theme/app_design_tokens.dart'; +import '../../../domain/chat_tool_calls.dart'; +import '../chat_message_bubble.dart'; +import 'notebook_cell_frame.dart'; + +/// How many lines of a call's output its collapsed sub-cell previews. +const int notebookToolPreviewLines = 3; + +/// The most lines an expanded sub-cell draws in place; the rest stay in the +/// activity details. +const int notebookToolExpandedLines = 400; + +/// Where a sub-cell's text starts: past the collapse chevron, so the +/// preview and the output line up under the tool's name. +const double notebookToolTextInset = 26; + +/// The monospace style of a tool sub-cell at the reading size's step down. +TextStyle notebookToolStyle(BuildContext context) => TextStyle( + fontFamily: appMonospaceFamily, + fontSize: (chatMessageTextStyle(context)?.fontSize ?? 15) * 0.82, + height: 1.4, + letterSpacing: 0, + color: Theme.of(context).colorScheme.onSurface, +); + +/// The first [notebookToolPreviewLines] non-blank lines of [text] and how +/// many lines follow them. +({String preview, int more}) notebookToolPreview(String text) { + final lines = text.trimRight().split('\n'); + var start = 0; + while (start < lines.length && lines[start].trim().isEmpty) { + start++; + } + final end = (start + notebookToolPreviewLines).clamp(0, lines.length); + return ( + preview: lines.sublist(start, end).map((l) => l.trimRight()).join('\n'), + more: lines.length - end, + ); +} + +/// One tool call as a notebook sub-cell: a header with the collapse +/// chevron, the tool's name and arguments, and its duration and status on +/// the right; beneath it, collapsed, the first lines of the output with +/// "+N lines", or, expanded in place, the call's input and output. The +/// expanded body is built only once opened. +class NotebookToolCell extends StatefulWidget { + const NotebookToolCell({super.key, required this.call}); + + final JsonMap call; + + @override + State createState() => _NotebookToolCellState(); +} + +class _NotebookToolCellState extends State { + bool _expanded = false; + + // The preview of the last output seen, so a running turn's ticking + // rebuilds do not split a long output again. + String? _source; + ({String preview, int more}) _preview = (preview: '', more: 0); + + void _toggle() => setState(() => _expanded = !_expanded); + + ({String preview, int more}) _previewOf(String text) { + if (!identical(text, _source) && text != _source) { + _source = text; + _preview = notebookToolPreview(text); + } + return _preview; + } + + @override + Widget build(BuildContext context) { + final call = widget.call; + final scheme = Theme.of(context).colorScheme; + final ansi = AppDesignTokens.of(context).ansi; + final style = notebookToolStyle(context); + final muted = style.copyWith(color: scheme.onSurfaceVariant); + final failed = chatToolFailed(call); + final running = chatToolRunning(call); + final name = chatToolLabel(call); + final detail = chatToolDetail(call); + final millis = chatToolDurationMillis(call); + final output = running + ? '' + : failed + ? chatToolErrorText(call) + : chatToolOutputText(call); + final (statusIcon, statusColor, statusWord) = failed + ? (Icons.close, ansi?.red ?? scheme.error, 'failed') + : running + ? (Icons.more_horiz, ansi?.yellow ?? scheme.tertiary, 'running') + : (Icons.check, ansi?.green ?? scheme.primary, 'done'); + final header = Semantics( + button: true, + expanded: _expanded, + label: [ + name, + ?detail, + if (millis != null) formatChatToolDuration(millis), + statusWord, + ].join(', '), + excludeSemantics: true, + onTap: _toggle, + child: InkWell( + key: const Key('chat-notebook-tool-header'), + onTap: _toggle, + borderRadius: BorderRadius.circular(notebookCellRadius(context)), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(6, 5, 10, 5), + child: Row( + children: [ + Icon( + _expanded ? Icons.expand_more : Icons.chevron_right, + size: 18, + color: scheme.onSurfaceVariant, + ), + const SizedBox(width: 2), + Expanded( + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: name, + style: const TextStyle(fontWeight: FontWeight.w700), + ), + if (detail != null) + TextSpan(text: ' $detail', style: muted), + ], + ), + style: style, + maxLines: 1, + softWrap: false, + overflow: TextOverflow.ellipsis, + ), + ), + if (millis != null) ...[ + const SizedBox(width: 12), + Text( + formatChatToolDuration(millis), + key: const Key('chat-notebook-tool-duration'), + style: muted, + ), + ], + const SizedBox(width: 8), + Icon( + statusIcon, + key: const Key('chat-notebook-tool-status'), + size: 15, + color: statusColor, + ), + ], + ), + ), + ), + ); + final body = _expanded + ? _expandedBody(call, style, muted, failed ? statusColor : null) + : _collapsedBody(output, style, muted, failed ? statusColor : null); + return Material( + key: const Key('chat-notebook-tool-cell'), + type: MaterialType.transparency, + child: NotebookCellFrame( + fill: scheme.surfaceContainerLow, + border: scheme.outlineVariant, + padding: EdgeInsets.zero, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [header, ?body], + ), + ), + ); + } + + Widget? _collapsedBody( + String output, + TextStyle style, + TextStyle muted, + Color? error, + ) { + if (output.trim().isEmpty) return null; + final (:preview, :more) = _previewOf(output); + if (preview.isEmpty) return null; + return _section( + Column( + key: const Key('chat-notebook-tool-preview'), + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + preview, + maxLines: notebookToolPreviewLines, + softWrap: false, + overflow: TextOverflow.ellipsis, + style: error == null ? muted : muted.copyWith(color: error), + ), + if (more > 0) + Text( + '+$more ${more == 1 ? 'line' : 'lines'}', + key: const Key('chat-notebook-tool-more'), + style: muted.copyWith( + fontStyle: FontStyle.italic, + color: Theme.of(context).colorScheme.outline, + ), + ), + ], + ), + ); + } + + Widget _expandedBody( + JsonMap call, + TextStyle style, + TextStyle muted, + Color? error, + ) { + final input = chatToolInputText(call).trimRight(); + final running = chatToolRunning(call); + final output = running + ? 'running…' + : error != null + ? chatToolErrorText(call) + : chatToolOutputText(call); + final lines = output.trimRight().split('\n'); + final cut = lines.length > notebookToolExpandedLines; + final shown = cut + ? lines.take(notebookToolExpandedLines).join('\n') + : output.trimRight(); + final heading = muted.copyWith( + fontSize: (muted.fontSize ?? 12) * 0.9, + fontWeight: FontWeight.w600, + ); + return _section( + Column( + key: const Key('chat-notebook-tool-output'), + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (input.isNotEmpty) ...[ + Text('input', style: heading), + Text(input, style: muted), + const SizedBox(height: 6), + ], + Text(error != null ? 'error' : 'output', style: heading), + Text( + shown, + style: error == null ? style : style.copyWith(color: error), + ), + if (cut) + Text( + '… ${lines.length - notebookToolExpandedLines} more lines ' + 'in the activity details', + style: muted.copyWith(fontStyle: FontStyle.italic), + ), + ], + ), + ); + } + + /// A body section under the header's hairline, its text under the name. + Widget _section(Widget child) => DecoratedBox( + decoration: BoxDecoration( + border: Border( + top: BorderSide(color: Theme.of(context).colorScheme.outlineVariant), + ), + ), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB( + notebookToolTextInset, + 5, + 10, + 6, + ), + child: child, + ), + ); +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart new file mode 100644 index 00000000..668d52d2 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart @@ -0,0 +1,154 @@ +import 'package:flutter/material.dart'; + +import '../../../../../core/api_gateway.dart'; +import '../../../../../ui/theme/app_design_tokens.dart'; +import '../../../domain/chat_turn_activity.dart'; +import '../chat_response_pending.dart'; +import 'notebook_cell_frame.dart'; +import 'notebook_tool_cell.dart'; + +/// How many of a turn's calls the Out cell lists before folding the earlier +/// ones behind "Show N earlier". +const int notebookToolMaxCalls = 8; + +/// The gap between two sub-cells. +const double notebookSubCellGap = 4; + +/// A turn's activity under a notebook transcript: each tool call as a +/// collapsible sub-cell ([NotebookToolCell]), the latest +/// [notebookToolMaxCalls] shown and the rest behind one "Show N earlier" +/// line, then the turn's status line: while it runs, what it is doing and +/// for how long in the accent; once settled, its summary ("Used 3 tools"). +/// The status line opens the activity details, as every design's does. +class NotebookToolCells extends StatefulWidget { + const NotebookToolCells({ + super.key, + required this.data, + required this.status, + required this.streaming, + required this.onOpen, + this.seconds = 0, + }); + + final ChatTurnActivityData data; + final String status; + final bool streaming; + final VoidCallback onOpen; + final int seconds; + + @override + State createState() => _NotebookToolCellsState(); +} + +class _NotebookToolCellsState extends State { + bool _all = false; + + @override + Widget build(BuildContext context) { + final calls = widget.data.tools; + final shown = _all || calls.length <= notebookToolMaxCalls + ? calls + : calls.sublist(calls.length - notebookToolMaxCalls); + final hidden = calls.length - shown.length; + return Column( + key: const Key('chat-notebook-tool-cells'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (hidden > 0) _earlier(context, hidden), + for (var index = 0; index < shown.length; index++) + Padding( + key: ValueKey('chat-notebook-tool-${_id(shown[index])}'), + padding: const EdgeInsets.only(bottom: notebookSubCellGap), + child: NotebookToolCell(call: shown[index]), + ), + _statusLine(context), + ], + ); + } + + String _id(JsonMap call) => '${call['id'] ?? identityHashCode(call)}'; + + Widget _earlier(BuildContext context, int hidden) { + final scheme = Theme.of(context).colorScheme; + return Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton( + key: const Key('chat-notebook-tool-earlier'), + style: TextButton.styleFrom( + minimumSize: const Size(0, 28), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + foregroundColor: scheme.onSurfaceVariant, + textStyle: notebookToolStyle(context), + ), + onPressed: () => setState(() => _all = true), + child: Text( + 'Show $hidden earlier tool ${hidden == 1 ? 'call' : 'calls'}', + ), + ), + ); + } + + /// The turn's status: the pending dots and the live label while it runs, + /// else the muted summary with a chevron. Opens the activity details. + Widget _statusLine(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final accent = AppDesignTokens.of(context).ansi?.yellow ?? scheme.primary; + final failed = widget.data.failed && !widget.streaming; + final color = widget.streaming + ? accent + : failed + ? scheme.error + : scheme.onSurfaceVariant; + final style = notebookToolStyle(context).copyWith(color: color); + final text = widget.streaming + ? '${widget.data.label}… ${widget.seconds}s' + : widget.status; + return Semantics( + button: true, + label: '${widget.status}, expand for details', + excludeSemantics: true, + onTap: widget.onOpen, + child: Align( + alignment: AlignmentDirectional.centerStart, + widthFactor: 1, + child: InkWell( + key: const Key('chat-turn-activity'), + onTap: widget.onOpen, + borderRadius: BorderRadius.circular(notebookCellRadius(context)), + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 28), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(6, 3, 8, 3), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.streaming) + ExcludeSemantics( + child: DefaultTextStyle.merge( + style: TextStyle(color: accent), + child: const ChatResponsePending(), + ), + ) + else + Icon(Icons.chevron_right, size: 18, color: color), + const SizedBox(width: 2), + Flexible( + child: Text( + text, + key: const Key('chat-notebook-status'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style, + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/ui/theme/app_design.dart b/app/lib/ui/theme/app_design.dart index 99494e51..6cd168e4 100644 --- a/app/lib/ui/theme/app_design.dart +++ b/app/lib/ui/theme/app_design.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'app_design_tokens.dart'; import 'app_theme.dart'; +import 'notebook_theme.dart'; import 'paper_theme.dart'; import 'terminal_theme.dart'; @@ -49,6 +50,14 @@ enum AppDesign { 'paper', 'Paper', 'Warm paper, serif reading text and ink colours; calm for long reads.', + ), + + /// A notebook IDE look: the chat as numbered In/Out cells with tool calls + /// as collapsible sub-cells, light grey cells and hairline borders. + notebook( + 'notebook', + 'Notebook', + 'Numbered In/Out cells, like Jupyter; tidy for tool-heavy work.', ); const AppDesign(this.id, this.label, this.description); @@ -100,6 +109,7 @@ enum AppDesign { (standard, Brightness.dark) => appDarkTheme(fontFamily: fontFamily), (terminal, _) => terminalTheme(brightness), (paper, _) => paperTheme(brightness, fontFamily: fontFamily), + (notebook, _) => notebookTheme(brightness, fontFamily: fontFamily), }; /// Whether the device's interface font applies under this design (Paper @@ -147,6 +157,18 @@ enum AppDesign { Color(0xFF221E19), Color(0xFF2C4F86), ), + notebook => + dark + ? const DesignSwatch( + Color(0xFF17181A), + Color(0xFFE4E5E7), + Color(0xFF7FB0F0), + ) + : const DesignSwatch( + Color(0xFFFFFFFF), + Color(0xFF1F2124), + Color(0xFF1F5FBF), + ), }; } } diff --git a/app/lib/ui/theme/app_design_styles.dart b/app/lib/ui/theme/app_design_styles.dart index ff36b944..2538bf52 100644 --- a/app/lib/ui/theme/app_design_styles.dart +++ b/app/lib/ui/theme/app_design_styles.dart @@ -16,6 +16,11 @@ enum TranscriptStyle { /// small-caps label, answers as prose, activity as a muted marginal note /// and injected prompts as italic editorial notes (Paper). manuscript, + + /// A notebook: each operator prompt an "In [n]:" input cell and each + /// answer its "Out [n]:" cell, numbered per turn in a fixed-width gutter, + /// with tool calls as collapsible sub-cells (Notebook). + cells, } /// How the chat composer frames its writing area. @@ -27,6 +32,10 @@ enum ComposerStyle { /// An open writing area on the page with a rule beneath it that takes /// the accent while the field has focus. underline, + + /// A notebook's empty input cell, "In [ ]:" in the gutter beside a light + /// grey cell whose frame takes the accent while the field has focus. + cell, } /// How a list (AppListRow) marks the row that is open. Every style keeps diff --git a/app/lib/ui/theme/notebook_controls.dart b/app/lib/ui/theme/notebook_controls.dart new file mode 100644 index 00000000..f66b225d --- /dev/null +++ b/app/lib/ui/theme/notebook_controls.dart @@ -0,0 +1,159 @@ +import 'package:flutter/material.dart'; + +import 'notebook_theme.dart'; + +const Color _clear = Color(0x00000000); + +// Kept per colour: a tab indicator and a resolver compare by identity, so +// fresh ones would make a rebuilt theme unequal to the last +// (test/perf/design_bench_test.dart). +final Map _tabIndicators = {}; +final Map<(Color, Color), WidgetStateBorderSide> _checkboxSides = {}; + +/// [base] with Notebook's controls: buttons, menus, chips, fields, search +/// bars, tabs, segmented buttons, switches, checkboxes, sliders, badges and +/// progress in [notebookRadius] corners with hairline outlines, no +/// elevation and the IDE blue; fields are boxed. +ThemeData notebookControls(ThemeData base, NotebookSurfaces surfaces) { + final scheme = base.colorScheme; + const rounded = NotebookSurfaces.rounded; + ButtonStyle buttons(ButtonStyle? style) => + (style ?? const ButtonStyle()).copyWith( + shape: const WidgetStatePropertyAll(rounded), + elevation: const WidgetStatePropertyAll(0), + shadowColor: const WidgetStatePropertyAll(_clear), + ); + final outline = WidgetStatePropertyAll(BorderSide(color: scheme.outline)); + final menu = MenuStyle( + backgroundColor: WidgetStatePropertyAll(surfaces.floating), + elevation: const WidgetStatePropertyAll(NotebookSurfaces.floatElevation), + shadowColor: WidgetStatePropertyAll(surfaces.shadow), + surfaceTintColor: const WidgetStatePropertyAll(_clear), + shape: WidgetStatePropertyAll(surfaces.framed), + padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(vertical: 4)), + ); + final field = OutlineInputBorder( + borderRadius: NotebookSurfaces.corners, + borderSide: BorderSide(color: scheme.outlineVariant), + ); + return base.copyWith( + menuTheme: MenuThemeData(style: menu), + dropdownMenuTheme: DropdownMenuThemeData(menuStyle: menu), + menuButtonTheme: MenuButtonThemeData( + style: MenuItemButton.styleFrom(shape: rounded), + ), + filledButtonTheme: FilledButtonThemeData( + style: buttons(base.filledButtonTheme.style), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: buttons(base.elevatedButtonTheme.style).copyWith( + backgroundColor: WidgetStatePropertyAll(scheme.surfaceContainerLow), + side: WidgetStatePropertyAll(surfaces.hairline), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: buttons(base.outlinedButtonTheme.style).copyWith(side: outline), + ), + textButtonTheme: TextButtonThemeData( + style: buttons(base.textButtonTheme.style), + ), + iconButtonTheme: IconButtonThemeData( + style: buttons(base.iconButtonTheme.style), + ), + segmentedButtonTheme: SegmentedButtonThemeData( + style: buttons( + base.segmentedButtonTheme.style, + ).copyWith(side: WidgetStatePropertyAll(surfaces.hairline)), + ), + floatingActionButtonTheme: FloatingActionButtonThemeData( + elevation: 0, + focusElevation: 0, + hoverElevation: 0, + highlightElevation: 0, + backgroundColor: scheme.surfaceContainerLow, + foregroundColor: scheme.primary, + shape: RoundedRectangleBorder( + borderRadius: NotebookSurfaces.corners, + side: BorderSide(color: scheme.outline), + ), + ), + // A chip is a small grey tag in the cell's grey, hairline framed. + chipTheme: ChipThemeData( + backgroundColor: scheme.surfaceContainerLow, + selectedColor: scheme.primaryContainer, + shape: surfaces.framed, + side: surfaces.hairline, + elevation: 0, + pressElevation: 0, + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + ), + // A field is a boxed cell in the design's corners. Only the base border: + // a field that sets `InputBorder.none` (the composer, which draws its + // own input cell) keeps none in every state. + inputDecorationTheme: InputDecorationTheme(isDense: true, border: field), + searchBarTheme: SearchBarThemeData( + elevation: const WidgetStatePropertyAll(0), + shape: const WidgetStatePropertyAll(rounded), + side: WidgetStatePropertyAll(surfaces.hairline), + backgroundColor: WidgetStatePropertyAll(scheme.surfaceContainerLow), + surfaceTintColor: const WidgetStatePropertyAll(_clear), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 12), + ), + ), + listTileTheme: const ListTileThemeData(shape: rounded), + expansionTileTheme: const ExpansionTileThemeData( + shape: Border(), + collapsedShape: Border(), + ), + tabBarTheme: TabBarThemeData( + dividerColor: scheme.outlineVariant, + labelColor: scheme.onSurface, + unselectedLabelColor: scheme.onSurfaceVariant, + indicatorSize: TabBarIndicatorSize.tab, + indicator: _tabIndicators[scheme.primary] ??= UnderlineTabIndicator( + borderSide: BorderSide(color: scheme.primary, width: 2), + ), + ), + checkboxTheme: CheckboxThemeData( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(3)), + ), + side: _checkboxSides[(scheme.primary, scheme.outline)] ??= + WidgetStateBorderSide.resolveWith( + (states) => states.contains(WidgetState.selected) + ? BorderSide(color: scheme.primary, width: 1.5) + : BorderSide(color: scheme.outline, width: 1.5), + ), + ), + sliderTheme: SliderThemeData( + trackHeight: 3, + activeTrackColor: scheme.primary, + inactiveTrackColor: scheme.outlineVariant, + thumbColor: scheme.primary, + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 7, + elevation: 0, + pressedElevation: 0, + ), + overlayShape: const RoundSliderOverlayShape(overlayRadius: 16), + valueIndicatorColor: scheme.inverseSurface, + valueIndicatorTextStyle: TextStyle(color: scheme.onInverseSurface), + ), + badgeTheme: BadgeThemeData( + backgroundColor: scheme.primary, + textColor: scheme.onPrimary, + padding: const EdgeInsets.symmetric(horizontal: 4), + ), + progressIndicatorTheme: ProgressIndicatorThemeData( + color: scheme.primary, + linearTrackColor: scheme.outlineVariant, + circularTrackColor: _clear, + linearMinHeight: 2, + ), + scrollbarTheme: const ScrollbarThemeData( + radius: Radius.circular(3), + thickness: WidgetStatePropertyAll(6), + ), + ); +} diff --git a/app/lib/ui/theme/notebook_palette.dart b/app/lib/ui/theme/notebook_palette.dart new file mode 100644 index 00000000..f06fdaa6 --- /dev/null +++ b/app/lib/ui/theme/notebook_palette.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; + +import 'app_design_tokens.dart'; + +/// Notebook's status accents on its white page: a notebook IDE's clear +/// status colours, a step darker so they read on a light grey cell. +const AnsiAccents notebookLightAccents = AnsiAccents( + green: Color(0xFF2E7D32), + cyan: Color(0xFF00838F), + yellow: Color(0xFFA15C00), + red: Color(0xFFC62828), + magenta: Color(0xFF8E3A8A), + blue: Color(0xFF1F5FBF), +); + +/// Notebook's status accents on its dark page. +const AnsiAccents notebookDarkAccents = AnsiAccents( + green: Color(0xFF86C98A), + cyan: Color(0xFF6FCFDA), + yellow: Color(0xFFF0B35E), + red: Color(0xFFF08C86), + magenta: Color(0xFFD29BD6), + blue: Color(0xFF7FB0F0), +); + +/// Notebook's colour scheme: a white page (a neutral charcoal in dark) with +/// light grey cells a step off it, near-black ink with a mid-grey secondary +/// ink, hairline borders and one clear IDE blue. The tertiary role is the +/// warm orange a notebook gives its output prompt ("Out [n]:"). +ColorScheme notebookColorScheme(Brightness brightness) { + if (brightness == Brightness.dark) { + return const ColorScheme( + brightness: Brightness.dark, + primary: Color(0xFF7FB0F0), + onPrimary: Color(0xFF0A2A52), + primaryContainer: Color(0xFF1D3553), + onPrimaryContainer: Color(0xFFD3E5FB), + secondary: Color(0xFFA7B6C0), + onSecondary: Color(0xFF1B2A33), + secondaryContainer: Color(0xFF2B3338), + onSecondaryContainer: Color(0xFFDCE6EC), + tertiary: Color(0xFFEFA07C), + onTertiary: Color(0xFF4A1A08), + tertiaryContainer: Color(0xFF47291D), + onTertiaryContainer: Color(0xFFFBDCCD), + error: Color(0xFFF08C86), + onError: Color(0xFF4D0E0B), + errorContainer: Color(0xFF5A1E1B), + onErrorContainer: Color(0xFFFAD8D5), + surface: Color(0xFF17181A), + onSurface: Color(0xFFE4E5E7), + onSurfaceVariant: Color(0xFFA2A5AB), + surfaceDim: Color(0xFF131416), + surfaceBright: Color(0xFF3A3B3F), + surfaceContainerLowest: Color(0xFF121315), + surfaceContainerLow: Color(0xFF1F2023), + surfaceContainer: Color(0xFF232427), + surfaceContainerHigh: Color(0xFF2A2B2F), + surfaceContainerHighest: Color(0xFF313236), + outline: Color(0xFF5C5F66), + outlineVariant: Color(0xFF333539), + shadow: Color(0xFF000000), + scrim: Color(0xFF000000), + inverseSurface: Color(0xFFE4E5E7), + onInverseSurface: Color(0xFF232427), + inversePrimary: Color(0xFF1F5FBF), + surfaceTint: Color(0x00000000), + ); + } + return const ColorScheme( + brightness: Brightness.light, + primary: Color(0xFF1F5FBF), + onPrimary: Color(0xFFFFFFFF), + primaryContainer: Color(0xFFE3ECFA), + onPrimaryContainer: Color(0xFF0B3470), + secondary: Color(0xFF52626D), + onSecondary: Color(0xFFFFFFFF), + secondaryContainer: Color(0xFFE9EEF2), + onSecondaryContainer: Color(0xFF1F2D35), + tertiary: Color(0xFFC0532A), + onTertiary: Color(0xFFFFFFFF), + tertiaryContainer: Color(0xFFFBE9E1), + onTertiaryContainer: Color(0xFF4A1A08), + error: Color(0xFFC62828), + onError: Color(0xFFFFFFFF), + errorContainer: Color(0xFFFDECEA), + onErrorContainer: Color(0xFF5F1212), + surface: Color(0xFFFFFFFF), + onSurface: Color(0xFF1F2124), + onSurfaceVariant: Color(0xFF5F6368), + surfaceDim: Color(0xFFE6E7E9), + surfaceBright: Color(0xFFFFFFFF), + surfaceContainerLowest: Color(0xFFFFFFFF), + surfaceContainerLow: Color(0xFFF7F7F8), + surfaceContainer: Color(0xFFF2F3F4), + surfaceContainerHigh: Color(0xFFECEDEF), + surfaceContainerHighest: Color(0xFFE5E6E8), + outline: Color(0xFFB4B7BC), + outlineVariant: Color(0xFFE1E3E6), + shadow: Color(0xFF1B1D21), + scrim: Color(0xFF000000), + inverseSurface: Color(0xFF2B2D31), + onInverseSurface: Color(0xFFF2F3F4), + inversePrimary: Color(0xFF7FB0F0), + surfaceTint: Color(0x00000000), + ); +} diff --git a/app/lib/ui/theme/notebook_theme.dart b/app/lib/ui/theme/notebook_theme.dart new file mode 100644 index 00000000..30c8318e --- /dev/null +++ b/app/lib/ui/theme/notebook_theme.dart @@ -0,0 +1,208 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import 'app_design.dart'; +import 'app_design_tokens.dart'; +import 'app_theme.dart'; +import 'notebook_controls.dart'; +import 'notebook_palette.dart'; + +/// Notebook's corner radius: cells, cards, fields, menus, dialogs, chips and +/// buttons all take it, a notebook IDE's small soft corner. +const double notebookRadius = 5; + +/// Notebook's reading type: the interface sans a step under the body size on +/// an airy line, as a notebook sets its markdown cells. +const ReadingType notebookReading = ReadingType(height: 1.5, scale: 15 / 16); + +/// Notebook's surfaces: a white page, light grey cells, hairline borders and +/// a faint shadow only under the pieces that float (menus, dialogs, sheets, +/// snack bars), as an IDE draws its popups. +class NotebookSurfaces { + NotebookSurfaces(this.scheme); + + final ColorScheme scheme; + + static const BorderRadius corners = BorderRadius.all( + Radius.circular(notebookRadius), + ); + + /// A floating piece's elevation: just enough shadow to lift it. + static const double floatElevation = 2; + + Color get shadow => scheme.shadow.withValues( + alpha: scheme.brightness == Brightness.dark ? 0.55 : 0.18, + ); + + BorderSide get hairline => BorderSide(color: scheme.outlineVariant); + + /// The page white (or the dark page's raised grey) a floating piece takes. + Color get floating => scheme.brightness == Brightness.dark + ? scheme.surfaceContainerHigh + : scheme.surfaceContainerLowest; + + RoundedRectangleBorder get framed => + RoundedRectangleBorder(borderRadius: corners, side: hairline); + + static const RoundedRectangleBorder rounded = RoundedRectangleBorder( + borderRadius: corners, + ); +} + +/// The Notebook design's theme: a clean light page (a charcoal one in dark) +/// with light grey cells, hairline borders, [notebookRadius] corners, the +/// device's interface sans for chrome and the bundled monospace for code +/// and the cells' gutter labels; the chat is drawn as numbered In/Out cells +/// ([TranscriptStyle.cells]) with an input cell for the composer. +ThemeData notebookTheme(Brightness brightness, {String? fontFamily}) { + final scheme = notebookColorScheme(brightness); + final surfaces = NotebookSurfaces(scheme); + final dark = brightness == Brightness.dark; + final base = ThemeData( + platform: kIsWeb ? TargetPlatform.android : null, + colorScheme: scheme, + fontFamily: fontFamily, + scaffoldBackgroundColor: scheme.surface, + canvasColor: scheme.surface, + pageTransitionsTheme: appPageTransitions, + dividerColor: scheme.outlineVariant, + shadowColor: surfaces.shadow, + extensions: [ + AppDesignTokens( + design: AppDesign.notebook, + radius: notebookRadius, + flat: true, + frame: scheme.outlineVariant, + panel: dark + ? scheme.surfaceContainerLow + : scheme.surfaceContainerLowest, + ansi: dark ? notebookDarkAccents : notebookLightAccents, + transcript: TranscriptStyle.cells, + composer: ComposerStyle.cell, + selectedRow: SelectedRowStyle.washed, + reading: notebookReading, + chatColorSaturation: 0.7, + ), + ], + ); + final text = notebookTextTheme(base.textTheme); + final floatingShape = surfaces.framed; + return notebookControls( + base.copyWith( + textTheme: text, + primaryTextTheme: notebookTextTheme(base.primaryTextTheme), + // A toolbar: the page colour, a hairline beneath and a compact title. + appBarTheme: AppBarTheme( + backgroundColor: scheme.surface, + foregroundColor: scheme.onSurface, + surfaceTintColor: const Color(0x00000000), + elevation: 0, + scrolledUnderElevation: 0, + titleTextStyle: text.titleMedium?.copyWith(color: scheme.onSurface), + shape: Border(bottom: surfaces.hairline), + ), + cardTheme: CardThemeData( + elevation: 0, + shadowColor: const Color(0x00000000), + surfaceTintColor: const Color(0x00000000), + shape: surfaces.framed, + ), + dialogTheme: DialogThemeData( + backgroundColor: surfaces.floating, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: floatingShape, + titleTextStyle: text.titleMedium?.copyWith(color: scheme.onSurface), + ), + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: surfaces.floating, + modalBackgroundColor: surfaces.floating, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + modalElevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: RoundedRectangleBorder( + borderRadius: const BorderRadius.vertical( + top: Radius.circular(notebookRadius), + ), + side: surfaces.hairline, + ), + dragHandleColor: scheme.outline, + ), + popupMenuTheme: PopupMenuThemeData( + color: surfaces.floating, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: floatingShape, + menuPadding: const EdgeInsets.symmetric(vertical: 4), + ), + snackBarTheme: SnackBarThemeData( + backgroundColor: scheme.inverseSurface, + contentTextStyle: text.bodyMedium?.copyWith( + color: scheme.onInverseSurface, + ), + actionTextColor: scheme.inversePrimary, + elevation: NotebookSurfaces.floatElevation, + shape: NotebookSurfaces.rounded, + ), + tooltipTheme: TooltipThemeData( + decoration: BoxDecoration( + color: scheme.inverseSurface, + borderRadius: const BorderRadius.all(Radius.circular(4)), + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + textStyle: text.bodySmall?.copyWith(color: scheme.onInverseSurface), + ), + dividerTheme: DividerThemeData( + color: scheme.outlineVariant, + thickness: 1, + space: 1, + ), + navigationRailTheme: NavigationRailThemeData( + backgroundColor: scheme.surface, + elevation: 0, + indicatorColor: scheme.primaryContainer, + indicatorShape: NotebookSurfaces.rounded, + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: scheme.surface, + elevation: 0, + indicatorColor: scheme.primaryContainer, + indicatorShape: NotebookSurfaces.rounded, + surfaceTintColor: const Color(0x00000000), + ), + drawerTheme: DrawerThemeData( + backgroundColor: scheme.surface, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: const RoundedRectangleBorder(), + ), + textSelectionTheme: TextSelectionThemeData( + cursorColor: scheme.primary, + selectionColor: scheme.primary.withValues(alpha: dark ? 0.32 : 0.2), + selectionHandleColor: scheme.primary, + ), + ), + surfaces, + ); +} + +/// [base] for Notebook: the interface sans throughout with titles a little +/// tighter and semibold, as an IDE heads its panes, and no added tracking on +/// labels. +TextTheme notebookTextTheme(TextTheme base) { + TextStyle? title(TextStyle? style, double size) => style?.copyWith( + fontSize: size, + fontWeight: FontWeight.w600, + letterSpacing: 0, + ); + return base.copyWith( + headlineSmall: title(base.headlineSmall, 22), + titleLarge: title(base.titleLarge, 19), + titleMedium: title(base.titleMedium, 15), + titleSmall: base.titleSmall?.copyWith(fontWeight: FontWeight.w600), + ); +} diff --git a/app/notes/design-notebook.md b/app/notes/design-notebook.md new file mode 100644 index 00000000..05deb4f8 --- /dev/null +++ b/app/notes/design-notebook.md @@ -0,0 +1,85 @@ +# Notebook design + +A notebook IDE look (Settings > Design > Notebook, id `notebook`): the chat +as numbered Jupyter-style In/Out cells with tool calls as collapsible +sub-cells, a white page (neutral charcoal in dark), light grey cells, +hairline borders, 5px corners, the device's interface sans for chrome and +the bundled RobotoMono for code, tool sub-cells and gutter labels. + +## Tokens and modes + +`notebookTheme()` (`lib/ui/theme/notebook_theme.dart`, palette and controls +beside it) sets: + +- `transcript: TranscriptStyle.cells` (new). Other designs never take it. +- `composer: ComposerStyle.cell` (new): `composer_cell.dart`. +- `selectedRow: washed` (left accent bar plus a light fill), `radius: 5`, + `flat`, `frame: outlineVariant`, `panel`: white (raised grey in dark), + Notebook ANSI accents, `chatColorSaturation: 0.7`. +- `reading`: the interface sans at 15/16 of `bodyLarge`, line height 1.5. + +Both new enum values are additions; every existing design keeps its own +value, so nothing else changes. Exhaustive switches on `TranscriptStyle` +gained a `cells` case (bubble, activity view, automated prompt). + +## The cells transcript + +`lib/features/chat/ui/transcript/notebook/`: + +- `notebook_gutter.dart`: `NotebookGutterRow`, a fixed-width gutter (ten + monospace characters at 0.8 of the reading size, scaled with text, plus an + 8px gap) holding the right-aligned label on the cell's first-line strut, so + it shares that line's baseline. Below 600px of row width (a phone) the label moves + inline above the cell. Rows that are not cells (shell runs, notices, + activity groups) get an empty gutter (`chat_thread_view.dart`), and a + `NotebookGutterScope` stops nested rows indenting twice. +- `notebook_input_cell.dart`: the operator's `In [n]:` cell (cell grey, 7% + of the chat colour, 3px bar in the chat colour, else the accent); the + scheduled cell for follow-ups, auto-continues (tag `scheduled`) and account + switches (tag `switched`) with an outline bar; `NotebookTag`. +- `notebook_tool_cells.dart` / `notebook_tool_cell.dart`: each tool call a + sub-cell: chevron, bold name and dim arguments, duration and a status icon + on the right; collapsed it previews the first 3 output lines and + "+N lines"; the header expands it in place (input and up to 400 output + lines, built only when open). The latest 8 calls show, earlier ones behind + "Show N earlier tool calls". The status line under them ("Used 6 tools · + 1 failed", or the live label and seconds) opens Activity details. +- `notebook_cell_frame.dart`: one `CustomPainter` per cell (fill, clipped + leading bar, 1px border), no layers. + +Numbering: `chatCellNumbers()` (`domain/chat_cell_numbers.dart`) numbers +operator turns from 1 in transcript order and gives each following answer +its prompt's number. It is derived, not stored, so a reload numbers the same; +with older history not yet loaded, numbering starts at the oldest loaded +turn (the server sends no absolute turn index). Queued or unsent prompts read +`In [ ]:`. A running answer shows `[*]` under its `Out [n]:`. The thread view +passes the number into `ChatMessageView.cell` (and the row cache's deps), +only under the cells transcript. + +Under cells, answers keep their Read aloud/Copy on the footer line (shown on +hover) rather than the left Copy gutter, so short Out cells keep the +In/Out rhythm: 10px above an In cell, 3px between In and Out. + +## Composer + +`ComposerCell`: `In [ ]:` in the same gutter, the field in a cell-grey frame +whose border and bar take the chat's accent on focus; a 2px running line at +its foot while a turn runs. Padding is the pill's 4px edge gap plus 3px, so +the usage ring (40px send button, 3px gap, following the 5px radius) clears +the cell's hairline. The send keys are unchanged. + +## Still default + +Markdown inside answers (headings, lists, code blocks) uses the standard +transcript styling in the interface font; chips, permission cards, task +cards, the chat stack discs and the graph follow the generic flat/radius/ +panel/frame tokens with no Notebook-specific code. Typography is Material's +apart from semibold, tighter titles. + +## Perf + +No `saveLayer`, blur or clip layers: cells paint in one picture each; the +expanded output is built only when opened; a tool cell memoises its preview +so a running turn's one-second tick does not resplit outputs. The theme is +value-equal on rebuild (identity-compared resolvers and indicators cached +per colour). Run the design budget (tool/perf/README.md) after changes. diff --git a/app/test/features/chat/ui/transcript/notebook_transcript_test.dart b/app/test/features/chat/ui/transcript/notebook_transcript_test.dart new file mode 100644 index 00000000..9e6a4bdf --- /dev/null +++ b/app/test/features/chat/ui/transcript/notebook_transcript_test.dart @@ -0,0 +1,283 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_cell_numbers.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_input_cell.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_tool_cell.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_tool_cells.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/paper/paper_quote.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/terminal/terminal_activity_rows.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/terminal/terminal_prompt_line.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; + +JsonMap _row(JsonMap message) => transcriptRows([message]).single; + +final JsonMap _operator = _row({ + 'id': 'u1', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Fix the Windows paths.'}, + ], +}); + +JsonMap _tool(String id, String name, String status, {String output = ''}) => { + 'type': 'tool', + 'id': id, + 'name': name, + 'time': {'created': 1000, 'completed': 2200}, + 'state': { + 'status': status, + 'input': {'command': 'go test ./...'}, + if (output.isNotEmpty) + 'content': [ + {'type': 'text', 'text': output}, + ], + if (status == 'error') 'error': {'message': 'exit status 1'}, + }, +}; + +const String _longOutput = 'ok pkg/a\nok pkg/b\nok pkg/c\nok pkg/d\nPASS'; + +JsonMap _agent({bool streaming = false}) => { + ..._row({ + 'id': 'a1', + 'role': 'assistant', + 'parts': [ + _tool('t1', 'Bash', 'completed', output: _longOutput), + _tool('t2', 'Read', 'error'), + {'type': 'text', 'text': 'Fixed the separators.'}, + ], + }), + if (streaming) 'streaming': true, +}; + +final JsonMap _followup = _row({ + 'id': 'f1', + 'role': 'user', + 'origin': 'followup', + 'client': 'Agent follow-up', + 'parts': [ + {'type': 'text', 'text': 'Check whether run 42 finished.'}, + ], +}); + +Widget _host( + AppDesign design, + List<(JsonMap, int?)> rows, { + double width = 900, +}) => MaterialApp( + theme: design.light(), + home: Scaffold( + body: Center( + child: SizedBox( + width: width, + child: ListView( + children: [ + for (final (row, cell) in rows) + ChatMessageView( + row: row, + cell: cell, + textBuilder: chatMarkdownText, + ), + ], + ), + ), + ), + ), +); + +Finder _label(String text) => find.byWidgetPredicate( + (widget) => + widget is Text && + widget.key == const Key('chat-notebook-gutter-label') && + widget.data == text, +); + +void main() { + test('cells number each operator turn and pair its answers', () { + final rows = [ + {'kind': 'assistant', 'key': 'early'}, + {'kind': 'user', 'key': 'u1'}, + {'kind': 'assistant', 'key': 'a1'}, + {'kind': 'system_notice', 'key': 'n1'}, + {'kind': 'assistant', 'key': 'a1b'}, + {'kind': 'user', 'key': 'f1'}, + {'kind': 'assistant', 'key': 'chat-pending-response'}, + ]; + expect(chatCellNumbers(rows), { + 'u1': 1, + 'a1': 1, + 'a1b': 1, + 'f1': 2, + 'chat-pending-response': 2, + }); + // Derived from the turn order alone: the same history numbers the same. + expect(chatCellNumbers(rows), chatCellNumbers([...rows])); + }); + + testWidgets('Notebook: In and Out cells with right-aligned gutter labels', ( + tester, + ) async { + await tester.pumpWidget( + _host(AppDesign.notebook, [(_operator, 3), (_agent(), 3)]), + ); + expect(find.byType(NotebookInputCell), findsOneWidget); + expect(find.byType(TerminalPromptLine), findsNothing); + expect(find.byType(PaperQuote), findsNothing); + final inLabel = _label('In [3]:'); + final outLabel = _label('Out [3]:'); + expect(inLabel, findsOneWidget); + expect(outLabel, findsOneWidget); + // One gutter: both labels end in the same column, left of the cells. + expect( + tester.getTopRight(inLabel).dx, + closeTo(tester.getTopRight(outLabel).dx, 0.5), + ); + final cell = find.byType(NotebookInputCell); + expect( + tester.getTopRight(inLabel).dx, + lessThan(tester.getTopLeft(cell).dx), + ); + // The prompt's and the answer's text share one column. + expect( + tester.getTopLeft(find.text('Fix the Windows paths.')).dx, + closeTo(tester.getTopLeft(find.text('Fixed the separators.')).dx, 0.5), + ); + // The label sits on the prompt's first line. + final labelBox = tester.getRect(inLabel); + final textBox = tester.getRect(find.text('Fix the Windows paths.')); + expect(labelBox.bottom, closeTo(textBox.bottom, 3)); + }); + + testWidgets('Notebook: a prompt not yet run reads In [ ]:', (tester) async { + await tester.pumpWidget(_host(AppDesign.notebook, [(_operator, null)])); + expect(_label('In [ ]:'), findsOneWidget); + }); + + testWidgets('Notebook: tool calls are collapsed sub-cells that expand in ' + 'place', (tester) async { + await tester.pumpWidget(_host(AppDesign.notebook, [(_agent(), 1)])); + expect(find.byType(NotebookToolCells), findsOneWidget); + expect(find.byType(TerminalActivityRows), findsNothing); + final cells = find.byType(NotebookToolCell); + expect(cells, findsNWidgets(2)); + // Collapsed: the first lines of the output, "+N lines", the duration and + // the status on the right. + expect(find.byKey(const Key('chat-notebook-tool-preview')), findsWidgets); + expect(find.text('+2 lines'), findsOneWidget); + expect(find.text('1.2s'), findsNWidgets(2)); + expect(find.byKey(const Key('chat-notebook-tool-output')), findsNothing); + expect(find.textContaining('PASS'), findsNothing); + + await tester.tap(find.byKey(const Key('chat-notebook-tool-header')).first); + await tester.pump(); + expect(find.byKey(const Key('chat-notebook-tool-output')), findsOneWidget); + expect(find.textContaining('PASS'), findsOneWidget); + expect(find.text('+2 lines'), findsNothing); + + await tester.tap(find.byKey(const Key('chat-notebook-tool-header')).first); + await tester.pump(); + expect(find.byKey(const Key('chat-notebook-tool-output')), findsNothing); + + // The status line still opens the activity details. + await tester.tap(find.byKey(const Key('chat-turn-activity'))); + await tester.pumpAndSettle(); + expect(find.text('Activity details'), findsOneWidget); + }); + + testWidgets('Notebook: a long turn folds its earlier calls', (tester) async { + final row = _row({ + 'id': 'a9', + 'role': 'assistant', + 'parts': [ + for (var i = 0; i < notebookToolMaxCalls + 3; i++) + _tool('t$i', 'Read', 'completed', output: 'line $i'), + ], + }); + await tester.pumpWidget(_host(AppDesign.notebook, [(row, 1)])); + expect(find.byType(NotebookToolCell), findsNWidgets(notebookToolMaxCalls)); + await tester.tap(find.byKey(const Key('chat-notebook-tool-earlier'))); + await tester.pump(); + expect( + find.byType(NotebookToolCell), + findsNWidgets(notebookToolMaxCalls + 3), + ); + }); + + testWidgets('Notebook: a running turn shows Jupyter\'s [*] busy marker', ( + tester, + ) async { + await tester.pumpWidget( + _host(AppDesign.notebook, [(_agent(streaming: true), 2)]), + ); + expect(_label('Out [2]:'), findsOneWidget); + final busy = find.byKey(const Key('chat-notebook-busy')); + expect(busy, findsOneWidget); + expect(tester.widget(busy).data, '[*]'); + expect( + tester.getTopLeft(busy).dy, + greaterThan(tester.getTopLeft(_label('Out [2]:')).dy), + ); + await tester.pumpWidget(_host(AppDesign.notebook, [(_agent(), 2)])); + expect(find.byKey(const Key('chat-notebook-busy')), findsNothing); + }); + + testWidgets('Notebook: a follow-up is an In cell with a scheduled tag', ( + tester, + ) async { + await tester.pumpWidget(_host(AppDesign.notebook, [(_followup, 4)])); + expect(_label('In [4]:'), findsOneWidget); + expect(find.byType(NotebookScheduledCell), findsOneWidget); + final tag = find.byKey(const Key('chat-notebook-scheduled-tag')); + expect( + find.descendant(of: tag, matching: find.text('scheduled')), + findsOneWidget, + ); + expect(find.text('Follow-up from agent'), findsOneWidget); + expect(find.text('Check whether run 42 finished.'), findsOneWidget); + }); + + testWidgets('Notebook: at phone width the gutter collapses to an inline ' + 'label above the cell', (tester) async { + await tester.pumpWidget( + _host(AppDesign.notebook, [(_operator, 1), (_agent(), 1)], width: 380), + ); + final label = _label('In [1]:'); + final cell = find.byType(NotebookInputCell); + expect( + tester.getBottomLeft(label).dy, + lessThanOrEqualTo(tester.getTopLeft(cell).dy), + ); + expect(tester.getTopLeft(label).dx, closeTo(tester.getTopLeft(cell).dx, 4)); + }); + + for (final design in [ + AppDesign.standard, + AppDesign.terminal, + AppDesign.paper, + ]) { + testWidgets('${design.label} is unchanged: no cells, even with a number', ( + tester, + ) async { + await tester.pumpWidget( + _host(design, [ + (_operator, 1), + (_agent(streaming: true), 1), + (_followup, 2), + ]), + ); + expect(find.byKey(const Key('chat-notebook-gutter-label')), findsNothing); + expect(find.byType(NotebookInputCell), findsNothing); + expect(find.byType(NotebookToolCells), findsNothing); + expect(find.byType(NotebookScheduledCell), findsNothing); + expect(find.byKey(const Key('chat-notebook-busy')), findsNothing); + if (design == AppDesign.standard) { + expect(find.byType(ChatUserBubble), findsOneWidget); + } + }); + } +} diff --git a/app/test/ui/theme/notebook_design_test.dart b/app/test/ui/theme/notebook_design_test.dart new file mode 100644 index 00000000..c02f0f6f --- /dev/null +++ b/app/test/ui/theme/notebook_design_test.dart @@ -0,0 +1,128 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_cell_frame.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_tokens.dart'; + +import '../../features/chat/conversation/chat_composer_bar_fixtures.dart'; + +ThemeData _theme(Brightness brightness, {String? font}) => + brightness == Brightness.dark + ? AppDesign.notebook.dark(fontFamily: font) + : AppDesign.notebook.light(fontFamily: font); + +Widget _thread(ComposerBarGateway gateway, AppDesign design) => MaterialApp( + theme: design.light(), + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + session: const {'id': 's', 'directory': '/Users/ada/repos/tank'}, + syncToken: 0, + onBack: () {}, + drafts: MemoryChatDraftStore(), + ), + ), +); + +void main() { + test('Notebook is listed with a stable id, a label and one line', () { + expect(AppDesign.fromId('notebook'), AppDesign.notebook); + expect(AppDesign.notebook.label, 'Notebook'); + expect(AppDesign.notebook.description, isNot(contains('\n'))); + expect(AppDesign.notebook.usesInterfaceFont, isTrue); + }); + + test('Notebook tokens: cells transcript, cell composer, washed row, ' + '4-6px corners, hairlines, flat', () { + for (final brightness in Brightness.values) { + final theme = _theme(brightness); + final tokens = theme.extension()!; + expect(tokens.design, AppDesign.notebook); + expect(tokens.transcript, TranscriptStyle.cells); + expect(tokens.terminal, isFalse); + expect(tokens.composer, ComposerStyle.cell); + expect(tokens.selectedRow, SelectedRowStyle.washed); + expect(tokens.radius, inInclusiveRange(4, 6)); + expect(tokens.flat, isTrue); + expect(tokens.frame, theme.colorScheme.outlineVariant); + expect(tokens.ansi, isNotNull); + // Reading text keeps the interface sans. + expect(tokens.reading.family, isNull); + } + }); + + test('Notebook pages: white by day, neutral charcoal by night, cells a ' + 'step off the page', () { + final light = _theme(Brightness.light); + expect(light.scaffoldBackgroundColor, const Color(0xFFFFFFFF)); + final dark = _theme(Brightness.dark); + expect( + dark.scaffoldBackgroundColor.computeLuminance(), + inExclusiveRange(0.005, 0.03), + ); + for (final theme in [light, dark]) { + final scheme = theme.colorScheme; + expect(scheme.surfaceContainerLow, isNot(scheme.surface)); + expect(scheme.onSurface, isNot(scheme.onSurfaceVariant)); + } + }); + + test('Notebook keeps the interface font and caches its themes', () { + expect( + _theme(Brightness.light, font: 'Inter').textTheme.bodyLarge?.fontFamily, + 'Inter', + ); + expect(identical(_theme(Brightness.dark), _theme(Brightness.dark)), isTrue); + expect( + AppDesign.notebook.build(Brightness.light), + _theme(Brightness.light), + ); + }); + + testWidgets('Notebook: the composer is an In [ ]: input cell whose frame ' + 'takes the accent on focus', (tester) async { + final gateway = ComposerBarGateway(); + addTearDown(gateway.close); + await tester.pumpWidget(_thread(gateway, AppDesign.notebook)); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-composer-pill')), findsNothing); + expect(find.byKey(const Key('chat-composer-underline')), findsNothing); + final cell = find.byKey(const Key('chat-composer-cell')); + expect(cell, findsOneWidget); + expect( + find.descendant(of: cell, matching: find.text('In [ ]:')), + findsOneWidget, + ); + for (final key in [ + 'chat-composer-attach', + 'chat-composer-field', + 'chat-composer-primary', + ]) { + expect( + find.descendant(of: cell, matching: find.byKey(Key(key))), + findsOneWidget, + ); + } + final scheme = Theme.of(tester.element(cell)).colorScheme; + Color frame() { + final paint = tester.widget( + find + .descendant( + of: find.byKey(const Key('chat-composer-cell-frame')), + matching: find.byType(CustomPaint), + ) + .first, + ); + return (paint.painter! as NotebookCellPainter).border; + } + + expect(frame(), scheme.outlineVariant); + await tester.tap(find.byKey(const Key('chat-composer-field'))); + await tester.pumpAndSettle(); + expect(frame(), scheme.primary); + }); +}