Merge branch 'main' into worktree-agent-abb9404cc062f4b30

# Conflicts:
#	app/lib/ui/theme/app_design.dart
This commit is contained in:
2026-12-04 00:15:07 +00:00
306 changed files with 13454 additions and 5708 deletions
@@ -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,
@@ -72,7 +81,15 @@ class ChatAutomatedPromptCard extends StatelessWidget {
final tokens = AppDesignTokens.of(context);
final density = tokens.density;
final transcript = tokens.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,
@@ -120,6 +137,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(
@@ -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;
}
@@ -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.
@@ -87,6 +96,7 @@ class ChatMessageView extends StatelessWidget {
final transcript = tokens.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
@@ -106,12 +116,16 @@ 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; a dense
// design a little less.
padding: EdgeInsets.symmetric(
vertical: transcript == TranscriptStyle.manuscript
? 12
: tokens.density.space(6),
),
// design a little less. 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
: tokens.density.space(6),
),
child: LayoutBuilder(
builder: (context, constraints) => Align(
alignment: trailingUser
@@ -122,14 +136,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,
@@ -143,6 +171,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;
@@ -200,9 +249,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'),
@@ -295,7 +346,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);
@@ -310,9 +365,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.
@@ -348,7 +409,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.
@@ -362,14 +427,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: [
@@ -384,9 +453,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
@@ -407,8 +474,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(
@@ -420,6 +486,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 ? 4 : 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
@@ -10,6 +10,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';
@@ -142,6 +143,14 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
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;
}
@@ -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;
}
@@ -0,0 +1,83 @@
import 'package:flutter/material.dart';
/// The small marks a notebook's sub-cells draw: the collapse chevron and the
/// call's status.
enum NotebookGlyphKind { collapsed, expanded, done, failed, running }
/// One [NotebookGlyphKind] stroked in [color] in a [size] square. Painted,
/// not an [Icon] (which builds five widgets), so a long transcript of tool
/// cells stays as cheap to scroll as the other designs'.
class NotebookGlyph extends StatelessWidget {
const NotebookGlyph(
this.kind, {
super.key,
required this.color,
this.size = 16,
});
final NotebookGlyphKind kind;
final Color color;
final double size;
@override
Widget build(BuildContext context) => CustomPaint(
size: Size.square(size),
painter: _GlyphPainter(kind, color, Directionality.of(context)),
);
}
class _GlyphPainter extends CustomPainter {
const _GlyphPainter(this.kind, this.color, this.direction);
final NotebookGlyphKind kind;
final Color color;
final TextDirection direction;
@override
void paint(Canvas canvas, Size size) {
final s = size.width;
final stroke = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = (s / 10).clamp(1.2, 2.0)
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round;
// Points on a unit square, mirrored for a right-to-left chevron.
Offset p(double x, double y) => Offset(
(kind == NotebookGlyphKind.collapsed && direction == TextDirection.rtl
? 1 - x
: x) *
s,
y * s,
);
Path line(List<Offset> points) {
final path = Path()..moveTo(points.first.dx, points.first.dy);
for (final point in points.skip(1)) {
path.lineTo(point.dx, point.dy);
}
return path;
}
switch (kind) {
case NotebookGlyphKind.collapsed:
canvas.drawPath(line([p(.4, .28), p(.62, .5), p(.4, .72)]), stroke);
case NotebookGlyphKind.expanded:
canvas.drawPath(line([p(.28, .4), p(.5, .62), p(.72, .4)]), stroke);
case NotebookGlyphKind.done:
canvas.drawPath(line([p(.22, .52), p(.42, .7), p(.78, .3)]), stroke);
case NotebookGlyphKind.failed:
canvas
..drawLine(p(.28, .28), p(.72, .72), stroke)
..drawLine(p(.72, .28), p(.28, .72), stroke);
case NotebookGlyphKind.running:
final dot = Paint()..color = color;
for (final x in [.25, .5, .75]) {
canvas.drawCircle(p(x, .5), s / 14, dot);
}
}
}
@override
bool shouldRepaint(_GlyphPainter old) =>
old.kind != kind || old.color != color || old.direction != direction;
}
@@ -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<NotebookGutterScope>() != 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;
// Only an empty gutter can hold other rows (an activity group's folded
// turns), so only it marks its subtree.
final row = 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: marker == null
? _label(text, style, line, TextAlign.end)
: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_label(text, style, line, TextAlign.end),
?marker,
],
),
),
),
Expanded(child: child),
],
);
},
);
return text == null ? NotebookGutterScope(child: row) : row;
}
/// 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,
),
),
),
);
}
@@ -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,
),
),
),
);
}
}
@@ -0,0 +1,296 @@
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';
import 'notebook_glyph.dart';
/// How many lines of a call's output its collapsed sub-cell previews.
const int notebookToolPreviewLines = 1;
/// 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<NotebookToolCell> createState() => _NotebookToolCellState();
}
class _NotebookToolCellState extends State<NotebookToolCell> {
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 (statusGlyph, statusColor, statusWord) = failed
? (NotebookGlyphKind.failed, ansi?.red ?? scheme.error, 'failed')
: running
? (
NotebookGlyphKind.running,
ansi?.yellow ?? scheme.tertiary,
'running',
)
: (NotebookGlyphKind.done, 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,
// A plain tap target with the pointer's click cursor rather than an
// InkWell: a transcript holds many sub-cells, and an InkWell's focus,
// actions and ink would double what each costs to build.
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
key: const Key('chat-notebook-tool-header'),
behavior: HitTestBehavior.opaque,
onTap: _toggle,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(6, 4, 10, 4),
child: Row(
children: [
NotebookGlyph(
_expanded
? NotebookGlyphKind.expanded
: NotebookGlyphKind.collapsed,
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),
NotebookGlyph(
statusGlyph,
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 NotebookCellFrame(
key: const Key('chat-notebook-tool-cell'),
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;
// The first line, and how many follow it at the line's end, under the
// duration: one line per collapsed call, as a notebook folds an output.
return _section(
Row(
key: const Key('chat-notebook-tool-preview'),
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Text(
preview,
maxLines: notebookToolPreviewLines,
softWrap: false,
overflow: TextOverflow.ellipsis,
style: error == null ? muted : muted.copyWith(color: error),
),
),
if (more > 0) const SizedBox(width: 12),
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,
4,
10,
5,
),
child: child,
),
);
}
@@ -0,0 +1,163 @@
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_glyph.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<NotebookToolCells> createState() => _NotebookToolCellsState();
}
class _NotebookToolCellsState extends State<NotebookToolCells> {
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<String>('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,
// A plain tap target, as the sub-cells' headers are (see
// NotebookToolCell): cheap to build in a long transcript.
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
key: const Key('chat-turn-activity'),
behavior: HitTestBehavior.opaque,
onTap: widget.onOpen,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 24),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(6, 2, 8, 2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.streaming)
ExcludeSemantics(
child: DefaultTextStyle.merge(
style: TextStyle(color: accent),
child: const ChatResponsePending(),
),
)
else
NotebookGlyph(
NotebookGlyphKind.collapsed,
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,
),
),
],
),
),
),
),
),
),
);
}
}
@@ -4,8 +4,9 @@ import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// What a `notify` entry says: where the notification went (the server's
/// `channels`: the operator's signed-in Pipelines `apps` and/or their `phone`),
/// or why it was not sent.
/// `channels`: the operator's signed-in Pipelines `apps`; `phone` appears only
/// in entries recorded before the server stopped publishing to a phone push
/// service), or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return '${_notifiedWhere(item)}: $title';