Merge main into flutter/route-vocabulary: adopt the session actions and artifact gallery work

This commit is contained in:
2026-10-22 03:35:46 +01:00
48 changed files with 3599 additions and 405 deletions
@@ -0,0 +1,153 @@
import '../../../core/api_gateway.dart';
import 'artifact_capture.dart';
import 'artifact_kind.dart';
import 'artifact_record.dart';
import 'artifact_selection.dart';
/// The exact server-recorded name of a visit's session export. It is the one
/// turn document that only ever opens externally.
const String sessionExportDocumentName = 'session.html';
/// The turn-protocol documents a visit records, in the order the audit surface
/// presents them. These are the same files the stage-artifact filter treats as
/// turn-owned ([systemArtifactNames]), aliased so a rename cannot make the
/// gallery and the filter disagree.
const List<String> turnDocumentNames = systemArtifactNames;
/// The exact absence wording for a missing turn document. Session absence is
/// contextual and comes from [sessionDocumentAbsence].
const String noInputDocument = 'No input recorded.';
const String noOutputDocument = 'No output recorded.';
const String noMemoryDocument = 'No memory recorded for this visit.';
/// One presented turn document of a visit.
///
/// [record] is the server's exact recorded artifact, or null when the visit did
/// not record that document. A null record is never completed from a step field
/// or another document: the entry carries [absence] instead, so the gallery can
/// show why the document is missing.
class ArtifactDocument {
const ArtifactDocument({
required this.name,
required this.record,
required this.absence,
});
final String name;
final ArtifactRecord? record;
/// The exact wording shown when [record] is null; empty when recorded.
final String absence;
/// The session export is read-only evidence: it only ever opens externally.
bool get externalOnly => name == sessionExportDocumentName;
/// Whether selecting this document opens the existing in-app renderer. A
/// session export is excluded even if the server sniffed it as text.
bool get opensInViewer {
final recorded = record;
if (recorded == null || externalOnly) return false;
return isViewerArtifact(recorded.contentType, recorded.name);
}
}
String? _text(dynamic value) {
if (value == null) return null;
final text = '$value';
return text.isEmpty ? null : text;
}
/// The web client's contextual session wording, used only when no exact
/// `session.html` artifact was recorded. A recorded session id and a missing
/// export are different facts and are never collapsed into "not recorded".
String sessionDocumentAbsence(JsonMap step) {
final export = step['session_export'];
final evidence = export is Map ? Map<String, dynamic>.from(export) : null;
final evidenceSessionId = _text(evidence?['session_id']);
final sessionId = _text(step['session_id']) ?? evidenceSessionId ?? '';
if (sessionId.isNotEmpty) {
final recoveryValue = step['session_export_recovery'];
final recovery = recoveryValue is Map
? Map<String, dynamic>.from(recoveryValue)
: null;
final recoveryStatus = _text(recovery?['status']);
final evidenceStatus = _text(evidence?['status']);
final status = recoveryStatus == 'pending' || recoveryStatus == 'running'
? 'pending recovery'
: evidenceStatus == 'complete'
? 'not available in the artifact inventory'
: evidenceStatus ?? 'not yet available';
final diagnostic = _text(evidence?['diagnostic']);
return 'Session $sessionId is recorded. Its export is $status.'
'${diagnostic == null ? '' : ' $diagnostic'}';
}
final model = _text(step['model']) != null || _text(step['provider']) != null;
final status = _text(step['status']);
final outcome = _text(step['outcome']);
if (status == 'skipped' || outcome == 'skipped') {
return 'This visit was skipped; no harness session was started.';
}
if (status == 'canceled' || status == 'interrupted') {
return 'The stage stopped before a harness session was recorded.';
}
if (model) {
if (status == 'running') return 'The stage session is being created.';
if (status == 'failed') {
final diagnostic = _text(step['diagnostic']);
return diagnostic == null
? 'The stage did not create a harness session.'
: 'The stage did not create a harness session. $diagnostic';
}
return 'Runtime error: this model stage has no recorded session identity.';
}
return 'This visit has no harness session.';
}
String _absenceFor(String name, JsonMap step) => switch (name) {
'input.md' => noInputDocument,
'output.md' => noOutputDocument,
'memory.md' => noMemoryDocument,
_ => sessionDocumentAbsence(step),
};
/// Every turn document slot of one visit, recorded or absent.
///
/// A capture whose `artifacts` field is absent yields no slots at all: a missing
/// capture is not evidence that the visit recorded no document. A visit that
/// recorded none of the four turn documents yields no slots either, so a stage
/// outside the turn protocol is never presented as four missing documents. Only
/// exact recorded names are presented; nothing is synthesized from other step
/// fields.
List<ArtifactDocument> visitDocuments(JsonMap step) {
final capture = ArtifactCapture.fromStep(step);
if (!capture.isAvailable) return const <ArtifactDocument>[];
final recorded = presentedArtifacts(capture.artifacts);
ArtifactRecord? firstNamed(String name) {
for (final artifact in recorded) {
if (artifact.name == name) return artifact;
}
return null;
}
final records = <String, ArtifactRecord>{};
for (final name in turnDocumentNames) {
final record = firstNamed(name);
if (record != null) records[name] = record;
}
if (records.isEmpty) return const <ArtifactDocument>[];
final documents = <ArtifactDocument>[];
for (final name in turnDocumentNames) {
final record = records[name];
documents.add(
record == null
? ArtifactDocument(
name: name,
record: null,
absence: _absenceFor(name, step),
)
: ArtifactDocument(name: name, record: record, absence: ''),
);
}
return List<ArtifactDocument>.unmodifiable(documents);
}
@@ -1,14 +1,17 @@
import '../../../core/api_gateway.dart';
import '../../graph/domain/stage_visits.dart';
import 'artifact_document.dart';
import 'artifact_record.dart';
import 'artifact_selection.dart';
/// One gallery group: the stage-produced artifacts of a recorded stage visit.
/// One gallery group: the stage-produced artifacts of a recorded stage visit
/// plus that visit's turn documents, recorded or explicitly absent.
class ArtifactGroup {
const ArtifactGroup({
required this.stageKey,
required this.visit,
required this.artifacts,
this.documents = const <ArtifactDocument>[],
});
final String stageKey;
@@ -18,6 +21,15 @@ class ArtifactGroup {
final int visit;
final List<ArtifactRecord> artifacts;
/// The visit's turn-document slots. Empty when the capture was unavailable,
/// so an unknown capture is never presented as four missing documents.
final List<ArtifactDocument> documents;
/// The count the gallery header reports: stage artifacts plus the turn
/// documents the server actually recorded, never an absent slot.
int get recordedCount =>
artifacts.length + documents.where((doc) => doc.record != null).length;
}
int _sequenceOf(JsonMap step) {
@@ -86,6 +98,45 @@ List<ArtifactGroup> artifactGroups(List<JsonMap> steps) {
return List<ArtifactGroup>.unmodifiable(groups);
}
String _galleryKey(String stageKey, int visit) => '$stageKey\u0000$visit';
/// The gallery's per-visit groups: stage artifacts and turn documents in one
/// section per recorded visit.
///
/// Stage-only grouping is unchanged ([artifactGroups]); this function adds the
/// turn-document slots a visit recorded and keeps a visit whose only recorded
/// files are turn documents. A visit with neither stage artifacts nor a
/// recorded document, or whose capture is unavailable, produces no group.
List<ArtifactGroup> galleryGroups(List<JsonMap> steps) {
if (steps.isEmpty) return const <ArtifactGroup>[];
final stageGroups = <String, ArtifactGroup>{
for (final group in artifactGroups(steps))
_galleryKey(group.stageKey, group.visit): group,
};
final groups = <ArtifactGroup>[];
for (final entry in visitsByStage(steps).entries) {
for (var index = 0; index < entry.value.length; index += 1) {
final step = entry.value[index];
final visit = displayVisit(step, index);
final base = stageGroups[_galleryKey(entry.key, visit)];
final documents = visitDocuments(step);
final recordedDocuments = documents.where((doc) => doc.record != null);
if ((base?.artifacts.isEmpty ?? true) && recordedDocuments.isEmpty) {
continue;
}
groups.add(
ArtifactGroup(
stageKey: entry.key,
visit: visit,
artifacts: base?.artifacts ?? const <ArtifactRecord>[],
documents: documents,
),
);
}
}
return List<ArtifactGroup>.unmodifiable(groups);
}
/// One visit's stage artifacts, excluding shared public files that an earlier
/// visit already recorded. A repeated non-public name in a later visit stays
/// because it is a different recorded artifact, not the same shared file.
@@ -6,8 +6,8 @@ import '../../../core/api_gateway.dart';
const String legacySessionMarkdownArtifact = 'session.md';
/// The files the turn protocol itself writes for every visit. They are audit
/// evidence, not stage output, so the artifact gallery lists stage files first
/// and keeps these for an audit/debug surface.
/// evidence, not stage output: the artifact gallery presents them as the visit's
/// turn documents, and the stage-file list still excludes them.
const List<String> systemArtifactNames = <String>[
'input.md',
'memory.md',
@@ -16,14 +16,15 @@ String artifactsEmptyMessage(bool executing) => executing
/// The run summary's Artifacts section header.
///
/// The recorded count is exactly the number of tiles [artifactGroups] yields;
/// the title takes its singular form for one. A run whose capture is unavailable
/// says so instead of claiming that nothing was recorded. Partial capture is
/// flagged when any visit excluded or omitted files.
/// The recorded count is the number of recorded entries [galleryGroups] yields:
/// stage files plus the turn documents the server actually recorded, never an
/// absent slot. The title takes its singular form for one. A run whose capture is
/// unavailable says so instead of claiming that nothing was recorded. Partial
/// capture is flagged when any visit excluded or omitted files.
String artifactsHeader(List<JsonMap> steps, {required bool executing}) {
final recorded = artifactGroups(
final recorded = galleryGroups(
steps,
).fold<int>(0, (sum, group) => sum + group.artifacts.length);
).fold<int>(0, (sum, group) => sum + group.recordedCount);
if (recorded == 0) {
if (executing) return artifactsEmptyMessage(true);
final unavailable = steps.any(
@@ -44,8 +45,10 @@ String artifactsHeader(List<JsonMap> steps, {required bool executing}) {
///
/// A running visit says capture pending. A finished visit whose capture field was
/// absent says capture unavailable rather than "not recorded"; only an explicitly
/// empty capture says "not recorded for this visit". Recorded counts exclude the
/// turn-owned files and the retired session markdown, so the words match tiles.
/// empty capture says "not recorded for this visit". Without [count] the recorded
/// number excludes the turn-owned files and the retired session markdown, so the
/// stage-artifact words match the stage tiles; a caller that presents the turn
/// documents too passes its own recorded entry count.
String artifactsSummary(JsonMap step, {int? count}) {
final capture = ArtifactCapture.fromStep(step);
final recorded = count ?? stageArtifacts(step).length;
@@ -36,21 +36,27 @@ String artifactVisitIdentityOf(ArtifactGroup group, ArtifactRecord artifact) {
}
/// The artifacts the viewer can page through, in gallery order: group by group,
/// each group's images, videos and markdown/text documents in recorded order.
/// Other artifacts open externally and are not part of this list. Pure: it only
/// filters and orders records the gallery already holds.
/// each group's images, videos and markdown/text documents in recorded order,
/// then the visit's recorded turn documents that open in the renderer. A session
/// export is external-only and never enters the page list. Pure: it only filters
/// and orders records the gallery already holds.
List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
final pages = <PagedArtifact>[];
void add(ArtifactGroup group, ArtifactRecord artifact) {
pages.add(
PagedArtifact(group: group, artifact: artifact, pageIndex: pages.length),
);
}
for (final group in groups) {
for (final artifact in group.artifacts) {
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
pages.add(
PagedArtifact(
group: group,
artifact: artifact,
pageIndex: pages.length,
),
);
add(group, artifact);
}
for (final document in group.documents) {
final artifact = document.record;
if (artifact == null || !document.opensInViewer) continue;
add(group, artifact);
}
}
return List<PagedArtifact>.unmodifiable(pages);
@@ -0,0 +1,124 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_document.dart';
import '../domain/artifact_groups.dart';
import 'artifact_record_row.dart';
import 'artifact_row_labels.dart';
/// One visit's turn documents, shown below its stage artifacts.
///
/// A recorded document is a normal gallery row with its recorded name, MIME and
/// size. A document the visit did not record is a non-actionable row carrying
/// the exact absence wording. The section never synthesizes a missing document
/// from another field and never offers an action for it.
class ArtifactDocumentSection extends StatelessWidget {
const ArtifactDocumentSection({
super.key,
required this.group,
this.selectedIdentity,
this.onSelected,
});
final ArtifactGroup group;
final String? selectedIdentity;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
final rows = <Widget>[
for (final document in group.documents) _row(document),
];
if (usesCupertinoHost(context)) {
return CupertinoListSection.insetGrouped(
header: Semantics(
container: true,
header: true,
child: const Text('Turn documents'),
),
hasLeading: false,
children: rows,
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
child: Semantics(
container: true,
header: true,
child: const Text('Turn documents'),
),
),
...rows,
],
);
}
Widget _row(ArtifactDocument document) {
final record = document.record;
if (record == null) return _AbsentDocumentRow(document: document);
final key = ValueKey<String>(
'${artifactVisitIdentity(group, record)}\u0000document',
);
return ArtifactRecordRow(
key: key,
group: group,
artifact: record,
selected: selectedIdentity == artifactVisitIdentity(group, record),
onSelected: onSelected,
);
}
}
/// A document the visit did not record: the recorded name and its exact absence
/// wording, with no tap target.
class _AbsentDocumentRow extends StatelessWidget {
const _AbsentDocumentRow({required this.document});
final ArtifactDocument document;
@override
Widget build(BuildContext context) {
if (!usesCupertinoHost(context)) {
// The absence line is informational product content, so it keeps the
// theme's normal secondary label colour. A disabled tile would paint both
// lines at the disabled colour (about 2.7:1 in light mode); no `onTap`
// keeps the row non-actionable without dimming it.
return ListTile(
title: Text(document.name),
subtitle: Text(
document.absence,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
);
}
final textTheme = CupertinoTheme.of(context).textTheme;
final absenceStyle = textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
return Semantics(
container: true,
child: SizedBox(
width: double.infinity,
child: Padding(
padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!,
child: DefaultTextStyle.merge(
style: textTheme.textStyle,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(document.name),
Text(document.absence, style: absenceStyle),
],
),
),
),
),
);
}
}
@@ -7,6 +7,7 @@ import '../../../ui/adaptive/host.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_document.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
@@ -76,9 +77,30 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
String? _status;
List<ArtifactGroup> _groupsOf(int? focusIndex) {
if (focusIndex == null) return artifactGroups(widget.steps);
if (focusIndex == null) return galleryGroups(widget.steps);
final group = visitArtifactGroup(widget.steps, focusIndex);
return group == null ? const <ArtifactGroup>[] : <ArtifactGroup>[group];
if (group == null) return const <ArtifactGroup>[];
// The visit pane sees the same document-enriched group the gallery shows for
// that visit, not only its recorded files.
for (final enriched in galleryGroups(widget.steps)) {
if (enriched.stageKey == group.stageKey && enriched.visit == group.visit) {
// The visit pane's own Session section opens session.html, so the
// per-visit Artifacts drill-down keeps only stage output and the other
// turn documents; the run-wide gallery still shows every document.
final documents = enriched.documents
.where((doc) => doc.record?.name != sessionExportDocumentName)
.toList(growable: false);
return <ArtifactGroup>[
ArtifactGroup(
stageKey: enriched.stageKey,
visit: enriched.visit,
artifacts: enriched.artifacts,
documents: documents,
),
];
}
}
return <ArtifactGroup>[group];
}
Future<void> _select(ArtifactGroup group, ArtifactRecord artifact) async {
@@ -86,11 +108,13 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
final resolved = artifact.hasUrl
? resolveArtifactUrl(widget.configuredEndpoint, artifact.url)
: null;
final externalOnly = artifact.name == sessionExportDocumentName;
setState(() {
_selectedIdentity = identity;
_status = null;
});
if (resolved != null &&
if (!externalOnly &&
resolved != null &&
isViewerArtifact(artifact.contentType, artifact.name)) {
await _openViewer(identity);
return;
@@ -0,0 +1,82 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_record.dart';
import 'artifact_row_labels.dart';
/// One recorded artifact row in a gallery section.
///
/// Material draws a standard [ListTile]; Cupertino draws the same content in a
/// grouped-row button. The row only reports the selection; it never resolves a
/// url, opens a preview, downloads, shares or filters.
class ArtifactRecordRow extends StatelessWidget {
const ArtifactRecordRow({
super.key,
required this.group,
required this.artifact,
required this.selected,
required this.onSelected,
});
final ArtifactGroup group;
final ArtifactRecord artifact;
final bool selected;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
if (!usesCupertinoHost(context)) {
return ListTile(
selected: selected,
title: Text(artifactDisplayName(artifact)),
subtitle: Text(artifactFactsLabel(artifact)),
trailing: selected ? const Icon(Icons.check) : null,
onTap: onSelected == null ? null : () => onSelected!(group, artifact),
);
}
final textTheme = CupertinoTheme.of(context).textTheme;
final factsStyle = textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
final content = DefaultTextStyle.merge(
style: textTheme.textStyle,
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(artifactDisplayName(artifact)),
Text(artifactFactsLabel(artifact), style: factsStyle),
],
),
),
if (selected) const Icon(CupertinoIcons.check_mark),
],
),
);
// `container` makes this row its own semantics node, so the section
// heading stays a separate header node and never covers the row.
return Semantics(
container: true,
selected: selected,
child: SizedBox(
width: double.infinity,
// A read-only row is not a button: a disabled CupertinoButton would
// still expose a button role to assistive technology.
child: onSelected == null
? Padding(
padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!,
child: content,
)
: CupertinoButton(
alignment: AlignmentDirectional.centerStart,
onPressed: () => onSelected!(group, artifact),
child: content,
),
),
);
}
}
@@ -0,0 +1,32 @@
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/gallery_navigation.dart';
/// A selection callback carrying the recorded group and the exact record the
/// operator chose, so the visit is never lost when two groups share a name.
typedef ArtifactSelected =
void Function(ArtifactGroup group, ArtifactRecord artifact);
/// The identity of [artifact] inside [group], shared by rows and the viewer.
String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) =>
artifactVisitIdentityOf(group, artifact);
/// The recorded group heading, matching the web client's group vocabulary.
String artifactGroupLabel(ArtifactGroup group) =>
'${group.stageKey} · visit ${group.visit}';
/// The displayed artifact name: a missing server name stays explicit.
String artifactDisplayName(ArtifactRecord artifact) =>
artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name;
/// The recorded MIME and byte size, never inferred from the name.
///
/// The value and its unit are joined by a non-breaking space so a narrow row
/// never wraps `120.6` away from `KiB`.
String artifactFactsLabel(ArtifactRecord artifact) {
final type = artifact.contentType.split(';').first.trim();
final mime = type.isEmpty ? 'type not recorded' : type;
final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0');
return '$mime · $size';
}
@@ -54,7 +54,7 @@ class ArtifactSelectionFacts extends StatelessWidget {
Text(artifactGroupLabel(group)),
if (recordedStep != null) ...[
const SizedBox(height: 8),
Text(artifactsSummary(recordedStep, count: group.artifacts.length)),
Text(artifactsSummary(recordedStep, count: group.recordedCount)),
for (final note in artifactCaptureNotes(recordedStep))
Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)),
],
@@ -222,8 +222,13 @@ class _Pager extends StatelessWidget {
top: false,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
// A `Row` clips the second labelled button once 2x text is wider than
// the viewport; a `Wrap` keeps both controls whole and lets them take
// separate lines, like the Cupertino pager.
child: Wrap(
alignment: WrapAlignment.spaceBetween,
spacing: 8,
runSpacing: 4,
children: [
TextButton.icon(
onPressed: hasPrevious ? onPrevious : null,
@@ -3,50 +3,28 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_document_section.dart';
import 'artifact_record_row.dart';
import 'artifact_row_labels.dart';
/// A selection callback carrying the recorded group and the exact record the
/// operator chose, so the visit is never lost when two groups share a name.
typedef ArtifactSelected =
void Function(ArtifactGroup group, ArtifactRecord artifact);
/// The identity of [artifact] inside [group], for
/// [ArtifactVisitList.selectedIdentity].
///
/// The recorded stage visit is part of the key, so two visits that both
/// recorded `result.csv` stay distinct even when their urls are identical.
/// A filename alone is never an identity.
String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) =>
artifactVisitIdentityOf(group, artifact);
/// The recorded group heading, matching the web client's group vocabulary.
String artifactGroupLabel(ArtifactGroup group) =>
'${group.stageKey} · visit ${group.visit}';
/// The displayed artifact name: a missing server name stays explicit.
String artifactDisplayName(ArtifactRecord artifact) =>
artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name;
/// The recorded MIME and byte size, never inferred from the name.
///
/// The value and its unit are joined by a non-breaking space so a narrow row
/// never wraps `120.6` away from `KiB`.
String artifactFactsLabel(ArtifactRecord artifact) {
final type = artifact.contentType.split(';').first.trim();
final mime = type.isEmpty ? 'type not recorded' : type;
final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0');
return '$mime · $size';
}
export 'artifact_row_labels.dart'
show
ArtifactSelected,
artifactDisplayName,
artifactFactsLabel,
artifactGroupLabel,
artifactVisitIdentity;
/// A read-only, selectable list of recorded artifact groups.
///
/// Each group shows its recorded stage and visit, and each row its recorded
/// filename, content type and size. Rendering uses the host's own controls:
/// Material list tiles under [MaterialApp] and grouped Cupertino list sections
/// under [CupertinoApp]. It never resolves a url, opens a preview, downloads,
/// shares or filters; the only action is [onSelected].
/// Each group shows its recorded stage and visit, its stage-produced artifacts,
/// then its turn documents. Every recorded row shows its recorded filename,
/// content type and size; a turn document the visit did not record stays a
/// non-actionable row with the exact absence wording. Rendering uses the host's
/// own controls: Material list tiles under [MaterialApp] and grouped Cupertino
/// list sections under [CupertinoApp]. It never resolves a url, opens a preview,
/// downloads, shares or filters.
class ArtifactVisitList extends StatelessWidget {
const ArtifactVisitList({
super.key,
@@ -70,7 +48,7 @@ class ArtifactVisitList extends StatelessWidget {
if (usesCupertinoHost(context)) {
return ListView(
children: [
for (final group in groups)
for (final group in groups) ...[
CupertinoListSection.insetGrouped(
// `container` keeps the heading a separate semantics node. Without
// it the heading merges into the neighbouring row button, so it is
@@ -83,15 +61,16 @@ class ArtifactVisitList extends StatelessWidget {
hasLeading: false,
children: [
for (var index = 0; index < group.artifacts.length; index += 1)
_CupertinoRow(
key: _rowKey(group, group.artifacts[index], index),
group: group,
artifact: group.artifacts[index],
selected: _isSelected(group, group.artifacts[index]),
onSelected: onSelected,
),
_row(group, group.artifacts[index], index),
],
),
if (group.documents.isNotEmpty)
ArtifactDocumentSection(
group: group,
selectedIdentity: selectedIdentity,
onSelected: onSelected,
),
],
],
);
}
@@ -107,11 +86,11 @@ class ArtifactVisitList extends StatelessWidget {
),
),
for (var index = 0; index < group.artifacts.length; index += 1)
_MaterialRow(
key: _rowKey(group, group.artifacts[index], index),
_row(group, group.artifacts[index], index),
if (group.documents.isNotEmpty)
ArtifactDocumentSection(
group: group,
artifact: group.artifacts[index],
selected: _isSelected(group, group.artifacts[index]),
selectedIdentity: selectedIdentity,
onSelected: onSelected,
),
],
@@ -119,96 +98,15 @@ class ArtifactVisitList extends StatelessWidget {
);
}
bool _isSelected(ArtifactGroup group, ArtifactRecord artifact) =>
selectedIdentity == artifactVisitIdentity(group, artifact);
static Key _rowKey(ArtifactGroup group, ArtifactRecord artifact, int index) =>
ValueKey<String>('${artifactVisitIdentity(group, artifact)}\u0000$index');
}
class _MaterialRow extends StatelessWidget {
const _MaterialRow({
super.key,
required this.group,
required this.artifact,
required this.selected,
required this.onSelected,
});
final ArtifactGroup group;
final ArtifactRecord artifact;
final bool selected;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
return ListTile(
selected: selected,
title: Text(artifactDisplayName(artifact)),
subtitle: Text(artifactFactsLabel(artifact)),
trailing: selected ? const Icon(Icons.check) : null,
onTap: onSelected == null ? null : () => onSelected!(group, artifact),
);
}
}
class _CupertinoRow extends StatelessWidget {
const _CupertinoRow({
super.key,
required this.group,
required this.artifact,
required this.selected,
required this.onSelected,
});
final ArtifactGroup group;
final ArtifactRecord artifact;
final bool selected;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
final textTheme = CupertinoTheme.of(context).textTheme;
final factsStyle = textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
final content = DefaultTextStyle.merge(
style: textTheme.textStyle,
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(artifactDisplayName(artifact)),
Text(artifactFactsLabel(artifact), style: factsStyle),
],
),
),
if (selected) const Icon(CupertinoIcons.check_mark),
],
),
);
// `container` makes this row its own semantics node, so the section
// heading stays a separate header node and never covers the row.
return Semantics(
container: true,
selected: selected,
child: SizedBox(
width: double.infinity,
// A read-only row is not a button: a disabled CupertinoButton would
// still expose a button role to assistive technology.
child: onSelected == null
? Padding(
padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!,
child: content,
)
: CupertinoButton(
alignment: AlignmentDirectional.centerStart,
onPressed: () => onSelected!(group, artifact),
child: content,
),
Widget _row(ArtifactGroup group, ArtifactRecord artifact, int index) {
return ArtifactRecordRow(
key: ValueKey<String>(
'${artifactVisitIdentity(group, artifact)}\u0000$index',
),
group: group,
artifact: artifact,
selected: selectedIdentity == artifactVisitIdentity(group, artifact),
onSelected: onSelected,
);
}
}
@@ -0,0 +1,87 @@
import 'dart:typed_data';
import 'chat_attachment_draft.dart';
import 'chat_attachment_picker_stub.dart'
if (dart.library.js_interop) 'chat_attachment_picker_web.dart'
as impl;
/// One file the operator chose in the host's file picker, with the bytes the
/// host handed back.
///
/// The seam records only what the picker supplied: the file's own name, its
/// MIME type and its bytes. It applies no name fallback and no size or count
/// policy; [ChatAttachmentDraft] owns those decisions.
class ChatPickedFile {
const ChatPickedFile({
required this.name,
required this.mime,
required this.bytes,
});
/// The file name exactly as the host recorded it, blank when the host
/// supplied none. [ChatAttachmentDraft.add] refuses a blank name rather than
/// replacing it.
final String name;
/// The MIME type the host recorded, empty when the host supplied none.
final String mime;
/// The file's complete contents as read when it was chosen.
final Uint8List bytes;
/// The recorded size, taken from the bytes that were actually read.
int get sizeBytes => bytes.length;
/// The draft row for this file. The draft still owns the blank-name and
/// total-size decisions.
ChatAttachment get attachment =>
ChatAttachment(name: name, mime: mime, sizeBytes: sizeBytes);
}
/// Opens the host's file selection and returns the files the operator chose.
///
/// A null result means the operator dismissed the picker without choosing
/// anything, which is different from an empty list. Only one selection is
/// returned per call.
typedef ChatFileSelection = Future<List<ChatPickedFile>?> Function();
/// The file picker seam for one host.
///
/// [pick] is the operator's explicit pick action: on web it opens the host's
/// native file input, and the chosen files are read before the future
/// completes. A host without a picker constructs
/// [ChatAttachmentPicker.unsupported] so the missing capability is reported
/// plainly instead of silently returning nothing. Tests inject a fake
/// [select] to exercise the seam without a browser.
class ChatAttachmentPicker {
const ChatAttachmentPicker({required ChatFileSelection this.select})
: unsupportedMessage = null;
const ChatAttachmentPicker.unsupported(String message)
: select = null,
unsupportedMessage = message;
/// The host selection, or null when this host cannot pick files.
final ChatFileSelection? select;
/// Why this host cannot pick files, when [select] is null.
final String? unsupportedMessage;
/// Whether this host can open a file selection at all.
bool get isSupported => select != null;
/// Opens the host's file selection and resolves with the chosen files, or
/// null when the operator cancelled.
///
/// Throws [UnsupportedError] with [unsupportedMessage] on a host that cannot
/// pick files.
Future<List<ChatPickedFile>?> pick() async {
final select = this.select;
if (select == null) throw UnsupportedError(unsupportedMessage!);
return select();
}
}
/// The picker for the running host.
ChatAttachmentPicker get hostChatAttachmentPicker =>
impl.hostChatAttachmentPicker;
@@ -0,0 +1,13 @@
import 'chat_attachment_picker.dart';
/// Native fallback for the chat attachment picker.
///
/// No native file-picker plugin is a dependency of this slice, so a non-web
/// host reports the missing capability instead of pretending the operator
/// cancelled. The attach control can disable itself from [isSupported] and
/// show this exact explanation.
const String chatAttachmentUnsupportedMessage =
'Attaching files is not supported on this platform yet.';
ChatAttachmentPicker get hostChatAttachmentPicker =>
const ChatAttachmentPicker.unsupported(chatAttachmentUnsupportedMessage);
@@ -0,0 +1,71 @@
import 'dart:async';
import 'dart:js_interop';
import 'package:web/web.dart' as web;
import 'chat_attachment_picker.dart';
/// The web file picker: one explicit pick action creates the host's native
/// file input, opens it and reads the files the operator chose.
///
/// The input is `multiple` and has no `accept` filter, matching the web
/// composer's attach control. Only a selection or a cancel completes the
/// future; a document without a body has nothing to open and yields null.
ChatAttachmentPicker get hostChatAttachmentPicker =>
const ChatAttachmentPicker(select: _selectFiles);
Future<List<ChatPickedFile>?> _selectFiles() {
final input = web.HTMLInputElement()
..type = 'file'
..multiple = true;
input.style.display = 'none';
final completer = Completer<List<ChatPickedFile>?>();
void finish(List<ChatPickedFile>? files) {
if (completer.isCompleted) return;
input.remove();
completer.complete(files);
}
Future<void> readSelection() async {
final selected = input.files;
if (selected == null || selected.length == 0) {
finish(null);
return;
}
try {
final files = <ChatPickedFile>[];
for (var index = 0; index < selected.length; index += 1) {
final file = selected.item(index);
if (file == null) continue;
final buffer = await file.arrayBuffer().toDart;
files.add(
ChatPickedFile(
name: file.name,
mime: file.type,
bytes: buffer.toDart.asUint8List(),
),
);
}
finish(files);
} catch (error, stackTrace) {
if (completer.isCompleted) return;
input.remove();
completer.completeError(error, stackTrace);
}
}
input.addEventListener('change', ((web.Event _) {
unawaited(readSelection());
}).toJS);
input.addEventListener('cancel', ((web.Event _) {
finish(null);
}).toJS);
final body = web.document.body;
if (body == null) return Future.value(null);
body.appendChild(input);
input.click();
return completer.future;
}
@@ -159,6 +159,40 @@ class ChatCupertinoMessage extends StatelessWidget {
}
}
/// A row action's refusal, shown at full width beneath its tile.
///
/// It must not sit in a `CupertinoListTile.subtitle`: that slot forces every
/// paragraph to one ellipsised line, which cut the server's reason down to its
/// first few words. Full width also stops a long refusal from turning a single
/// Material row into a column taller than the viewport.
class ChatRowError extends StatelessWidget {
const ChatRowError({super.key, required this.message, this.messageKey});
final String message;
/// Key placed on the message paragraph itself, so a test can assert that the
/// rendered text did not exceed its line limit.
final Key? messageKey;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
color: CupertinoColors.systemRed.resolveFrom(context),
)
: TextStyle(color: Theme.of(context).colorScheme.error);
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12),
child: DefaultTextStyle.merge(
style: style,
child: Text(message, key: messageKey),
),
);
}
}
class ChatErrorNotice extends StatelessWidget {
const ChatErrorNotice({
super.key,
@@ -198,3 +232,52 @@ class ChatLoadingIndicator extends StatelessWidget {
);
}
}
/// One-row report after hiding a session on this device, with its Undo.
///
/// The screen floats this over the list like the web's fixed report, so a long
/// message can never push the list out of the body's column.
class ChatUndoBar extends StatelessWidget {
const ChatUndoBar({super.key, required this.message, required this.onUndo});
final String message;
final VoidCallback onUndo;
@override
Widget build(BuildContext context) {
final content = Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
Expanded(
child: DefaultTextStyle.merge(
style: chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: DefaultTextStyle.of(context).style,
child: Text(message),
),
),
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino)
CupertinoButton(
padding: const EdgeInsetsDirectional.only(start: 12),
onPressed: onUndo,
child: const Text('Undo'),
)
else
TextButton(onPressed: onUndo, child: const Text('Undo')),
],
),
);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
// A standard Cupertino popup surface: the bar floats over the list, so it
// needs its own painted card and shadow to stay legible.
return CupertinoPopupSurface(child: content);
}
return Material(
elevation: 3,
borderRadius: BorderRadius.circular(8),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: content,
);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'chat_adaptive.dart';
/// Native chrome for the create dialog: standard Cupertino alert or Material
/// alert, with the same disabled/submitting state in both hosts.
class ChatCreateDialogFrame extends StatelessWidget {
const ChatCreateDialogFrame({
super.key,
required this.content,
required this.canSubmit,
required this.submitting,
required this.onCancel,
required this.onSubmit,
});
final Widget content;
final bool canSubmit;
final bool submitting;
final VoidCallback onCancel;
final VoidCallback onSubmit;
@override
Widget build(BuildContext context) {
final enabled = canSubmit && !submitting;
final label = submitting ? 'Creating…' : 'Create';
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: const Text('New chat'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: submitting ? null : onCancel,
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: enabled ? onSubmit : null,
child: Text(label),
),
],
);
}
return AlertDialog(
title: const Text('New chat'),
content: content,
actions: [
TextButton(
onPressed: submitting ? null : onCancel,
child: const Text('Cancel'),
),
FilledButton(onPressed: enabled ? onSubmit : null, child: Text(label)),
],
);
}
}
@@ -117,16 +117,27 @@ class MaterialPickerField extends StatelessWidget {
return DropdownButtonFormField<String>(
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
initialValue: value,
isExpanded: true,
// Intrinsic item height: a 2x label must not be clipped by the 48px
// default, and a real path must ellipsize instead of overflowing.
itemHeight: null,
decoration: InputDecoration(labelText: label),
selectedItemBuilder: (context) => [
for (final item in values) _fieldLabel(item),
],
items: [
for (final item in values)
DropdownMenuItem(value: item, child: Text(item)),
DropdownMenuItem(value: item, child: _fieldLabel(item)),
],
onChanged: (item) {
if (item != null) onSelected(item);
},
);
}
Widget _fieldLabel(String item) {
return Text(item, maxLines: 1, overflow: TextOverflow.ellipsis);
}
}
class CupertinoPickerField extends StatelessWidget {
@@ -0,0 +1,119 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
/// Device-local list preferences, mirroring the web client's C13 behaviour:
/// hidden ids and the newest session recency this device has read.
///
/// Titles, stars and the closed state are server-owned and deliberately absent.
class ChatSessionLocal {
const ChatSessionLocal({this.hidden = const [], this.seenAt = const {}});
final List<String> hidden;
final Map<String, int> seenAt;
bool isHidden(String id) => hidden.contains(id);
int watermark(String id) => seenAt[id] ?? 0;
ChatSessionLocal hide(String id) {
if (id.isEmpty || hidden.contains(id)) return this;
return ChatSessionLocal(hidden: [...hidden, id], seenAt: seenAt);
}
ChatSessionLocal restore(String id) {
if (!hidden.contains(id)) return this;
return ChatSessionLocal(
hidden: hidden.where((entry) => entry != id).toList(),
seenAt: seenAt,
);
}
/// Advances only for a strictly newer recency, so a stale list read can never
/// mark newer activity as already seen.
ChatSessionLocal read(String id, int updatedAt) {
if (id.isEmpty || updatedAt <= watermark(id)) return this;
return ChatSessionLocal(hidden: hidden, seenAt: {...seenAt, id: updatedAt});
}
/// The first sight of a session baselines it, so pre-existing chats are not
/// all reported as new.
ChatSessionLocal seed(Iterable<({String id, int updatedAt})> rows) {
var next = this;
for (final row in rows) {
if (row.id.isEmpty || row.updatedAt <= 0) continue;
if (next.watermark(row.id) != 0) continue;
next = ChatSessionLocal(
hidden: next.hidden,
seenAt: {...next.seenAt, row.id: row.updatedAt},
);
}
return next;
}
String encode() => jsonEncode({'hidden': hidden, 'seenAt': seenAt});
static ChatSessionLocal decode(Object? value) {
try {
final parsed = jsonDecode('$value');
if (parsed is! Map) return const ChatSessionLocal();
final hidden = parsed['hidden'];
final seenAt = parsed['seenAt'];
return ChatSessionLocal(
hidden: hidden is List
? hidden.whereType<String>().where((id) => id.isNotEmpty).toList()
: const [],
seenAt: seenAt is Map
? {
for (final entry in seenAt.entries)
if (entry.key is String && entry.value is int)
'${entry.key}': entry.value as int,
}
: const {},
);
} catch (_) {
return const ChatSessionLocal();
}
}
}
abstract interface class ChatSessionLocalStore {
Future<ChatSessionLocal> load();
Future<void> save(ChatSessionLocal state);
}
/// `shared_preferences`-backed storage; unavailable storage degrades to the
/// in-memory choice instead of failing the list.
class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
const SharedPreferencesChatSessionLocalStore();
static const key = 'pipelines.chat.local.v1';
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<ChatSessionLocal> load() async {
final preferences = await _preferences();
try {
return ChatSessionLocal.decode(preferences?.getString(key));
} catch (_) {
return const ChatSessionLocal();
}
}
@override
Future<void> save(ChatSessionLocal state) async {
final preferences = await _preferences();
try {
await preferences?.setString(key, state.encode());
} catch (_) {
// Storage may be unavailable; the in-memory choice still applies.
}
}
}
@@ -22,7 +22,10 @@ class ChatSessionsBody extends StatelessWidget {
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
required this.onClearSearch,
required this.isUnseen,
required this.errorFor,
});
final List<JsonMap> sessions;
@@ -34,7 +37,10 @@ class ChatSessionsBody extends StatelessWidget {
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
final VoidCallback onClearSearch;
final bool Function(JsonMap) isUnseen;
final String? Function(String sessionId) errorFor;
@override
Widget build(BuildContext context) {
@@ -79,7 +85,10 @@ class ChatSessionsBody extends StatelessWidget {
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
onClearSearch: clearSearch,
isUnseen: isUnseen,
errorFor: errorFor,
);
}
return MaterialSessionList(
@@ -91,7 +100,10 @@ class ChatSessionsBody extends StatelessWidget {
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
onClearSearch: clearSearch,
isUnseen: isUnseen,
errorFor: errorFor,
);
}
}
@@ -3,26 +3,63 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../../../core/transport/connection_state.dart';
import '../../data/chat_repository.dart';
import 'chat_session_local.dart';
/// Owns the session list, its refresh generation and the row actions.
/// Owns the session list, its refresh generation and the shared row actions.
///
/// A refresh that finishes after a newer one (or after the screen is gone) is
/// discarded, so a slow reply can never replace fresher state.
/// discarded, so a slow reply can never replace fresher state. Accepted
/// mutations always re-read the server list; only this device's hidden ids and
/// read watermark are local.
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository);
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
: _localStore =
localStore ?? const SharedPreferencesChatSessionLocalStore();
ChatRepository repository;
final ChatSessionLocalStore _localStore;
ChatSessionLocal _local = const ChatSessionLocal();
final Map<String, String> _actionErrors = {};
List<JsonMap> _sessions = const [];
String? _error;
String? _lastHidden;
bool _loading = true;
bool _localLoaded = false;
Future<void>? _localLoading;
bool _disposed = false;
int _generation = 0;
List<JsonMap> get sessions => _sessions;
List<JsonMap> get sessions => [
for (final session in _sessions)
if (!_local.isHidden('${session['id'] ?? ''}')) session,
];
String? get error => _error;
bool get loading => _loading;
/// The row an action failed on; the message is the server's own words.
String? errorFor(String sessionId) => _actionErrors[sessionId];
/// The last hidden session, while its Undo is still offered.
String? get lastHidden => _lastHidden;
bool isUnseen(JsonMap session) {
final id = '${session['id'] ?? ''}';
// Closed chats keep their recency from the close, but they are not new
// work: both the web list and the Android list suppress unseen there.
if (!_localLoaded ||
id.isEmpty ||
session['running'] == true ||
session['closed_at'] != null ||
session['closed'] == true) {
return false;
}
final updatedAt = _millis(session['updated_at']);
return updatedAt > 0 && updatedAt > _local.watermark(id);
}
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
@@ -35,10 +72,14 @@ class ChatSessionsController extends ChangeNotifier {
_loading = true;
_error = null;
_notify();
// Device preferences never gate the server read: a slow platform store
// must not hide the list or delay the first request.
unawaited(_ensureLocal());
try {
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_seedLocal();
_loading = false;
_notify();
} catch (error) {
@@ -50,52 +91,150 @@ class ChatSessionsController extends ChangeNotifier {
}
Future<void> star(String sessionId, bool starred) =>
_mutate(() => repository.star(sessionId, starred));
_mutate(sessionId, () => repository.star(sessionId, starred));
Future<void> close(String sessionId) =>
_mutate(() => repository.close(sessionId));
_mutate(sessionId, () => repository.close(sessionId));
Future<void> reopen(String sessionId) =>
_mutate(() => repository.reopen(sessionId));
_mutate(sessionId, () => repository.reopen(sessionId));
Future<void> rename(String sessionId, String title) =>
_mutate(() => repository.rename(sessionId, title));
/// Renames through the shared server field. Throws the server's refusal so the
/// open dialog can keep it in view; success refreshes the list from the server.
///
/// The dialog owns the refusal, so no row error is stored: the same sentence
/// must not also stick under the list row.
Future<void> renameOrThrow(String sessionId, String title) async {
await repository.rename(sessionId, title);
_actionErrors.remove(sessionId);
await refresh();
}
Future<JsonMap?> create({
/// Creates one session and returns the server's `chat_session`. A reply
/// without one is refused rather than opening an invented row.
Future<JsonMap> createOrThrow({
required String title,
required String directory,
required String backend,
required String instructions,
required String operationId,
}) async {
try {
final reply = await repository.create(
title: title,
directory: directory,
backend: backend,
operationId: operationId,
instructions: instructions,
final reply = await repository.create(
title: title,
directory: directory,
backend: backend,
operationId: operationId,
instructions: instructions,
);
final session = reply['chat_session'];
if (session is! Map) {
// The web reports exactly this refusal, so the dialog shows the same
// sentence instead of a Dart `Bad state:` prefix.
throw const ProtocolError(
'The server did not return the new chat session.',
);
// Opening the created chat must not wait for the list refresh: the dialog
// has already closed, so a slow listing would look like a failed create.
unawaited(refresh());
final session = reply['chat_session'];
return session is Map ? Map<String, dynamic>.from(session) : null;
}
// Opening the created chat must not wait for the list refresh: the dialog
// has already closed, so a slow listing would look like a failed create.
unawaited(refresh());
return Map<String, dynamic>.from(session);
}
/// Records that this device has read [session]'s current recency.
Future<void> markOpened(JsonMap session) async {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
await _ensureLocal();
final next = _local.read(id, _millis(session['updated_at']));
if (identical(next, _local)) return;
_local = next;
_notify();
await _persist();
}
/// Hides one row on this device only; the server row is untouched.
Future<void> hide(String sessionId) async {
await _ensureLocal();
final next = _local.hide(sessionId);
if (identical(next, _local)) return;
_local = next;
_lastHidden = sessionId;
_notify();
await _persist();
}
Future<void> undoHide() async {
final id = _lastHidden;
if (id == null) return;
_local = _local.restore(id);
_lastHidden = null;
_notify();
await _persist();
}
void dismissUndo() {
if (_lastHidden == null) return;
_lastHidden = null;
_notify();
}
Future<void> _mutate(
String sessionId,
Future<JsonMap> Function() action,
) async {
try {
await action();
_actionErrors.remove(sessionId);
await refresh();
} catch (error) {
_error = '$error';
_actionErrors[sessionId] = '$error';
_notify();
return null;
}
}
Future<void> _mutate(Future<JsonMap> Function() action) async {
Future<void> _ensureLocal() => _localLoading ??= _loadLocal();
Future<void> _loadLocal() async {
try {
await action();
await refresh();
} catch (error) {
_error = '$error';
_notify();
_local = await _localStore.load();
} catch (_) {
_local = const ChatSessionLocal();
}
_localLoaded = true;
_seedLocal();
_notify();
}
void _seedLocal() {
if (!_localLoaded) return;
final next = _local.seed([
for (final session in _sessions)
(
id: '${session['id'] ?? ''}',
updatedAt: _millis(session['updated_at']),
),
]);
if (identical(next, _local)) return;
_local = next;
unawaited(_persist());
}
Future<void> _persist() async {
try {
await _localStore.save(_local);
} catch (_) {
// The in-memory choice still applies for this session.
}
}
static int _millis(Object? value) {
if (value is int) return value > 0 ? value : 0;
if (value is num) return value > 0 ? value.toInt() : 0;
final text = '${value ?? ''}'.trim();
if (text.isEmpty) return 0;
final number = int.tryParse(text);
if (number != null) return number > 0 ? number : 0;
return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0;
}
void _notify() {
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_session_local.dart';
import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart';
import 'create_chat_dialog.dart';
@@ -20,6 +21,7 @@ class ChatSessionsScreen extends StatefulWidget {
required this.onOpen,
this.embedded = false,
this.syncToken = 0,
this.localStore,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
@@ -31,6 +33,9 @@ class ChatSessionsScreen extends StatefulWidget {
/// closed elsewhere during the gap must not stay invisible until Refresh.
final int syncToken;
/// Overrides the device-local hidden/read store in tests.
final ChatSessionLocalStore? localStore;
@override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
}
@@ -38,8 +43,10 @@ class ChatSessionsScreen extends StatefulWidget {
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
late final ChatSessionsController _controller = ChatSessionsController(
ChatRepository(widget.gateway),
localStore: widget.localStore,
)..refresh();
final _search = TextEditingController();
Timer? _undoTimer;
@override
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
@@ -53,6 +60,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
@override
void dispose() {
_undoTimer?.cancel();
_controller.dispose();
_search.dispose();
super.dispose();
@@ -61,9 +69,12 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
String _sessionId(JsonMap session) => '${session['id'] ?? ''}';
Future<void> _rename(JsonMap session) async {
final title = await showRenameChatDialog(context, session);
if (title == null || !mounted) return;
await _controller.rename(_sessionId(session), title);
final id = _sessionId(session);
await showRenameChatDialog(
context,
session,
onSubmit: (title) => _controller.renameOrThrow(id, title),
);
}
Future<void> _close(JsonMap session) async {
@@ -73,27 +84,47 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
}
Future<void> _newChat() async {
// One id per create intent: a refusal retried in the dialog reuses it.
final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}';
final draft = await showChatCreateDialog(
final session = await showChatCreateDialog(
context,
repository: _controller.repository,
);
if (draft == null || !mounted) return;
final session = await _controller.create(
title: draft.title,
directory: draft.directory,
backend: draft.backend,
instructions: draft.instructions,
operationId: operationId,
onSubmit: (draft, id) => _controller.createOrThrow(
title: draft.title,
directory: draft.directory,
backend: draft.backend,
instructions: draft.instructions,
operationId: id,
),
);
if (session != null && mounted) widget.onOpen(session);
}
void _open(JsonMap session) {
unawaited(_controller.markOpened(session));
widget.onOpen(session);
}
Future<void> _hide(JsonMap session) async {
await _controller.hide(_sessionId(session));
_undoTimer?.cancel();
_undoTimer = Timer(const Duration(seconds: 8), () {
if (mounted) _controller.dismissUndo();
});
}
Future<void> _undoHide() async {
_undoTimer?.cancel();
await _controller.undoHide();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final controls = chatControlsStyleOf(context);
final body = Column(
children: [
ChatSearchField(
@@ -106,23 +137,50 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
onRetry: _controller.refresh,
),
Expanded(
child: ChatSessionsBody(
sessions: _controller.sessions,
query: _search.text,
loading: _controller.loading,
error: _controller.error,
onOpen: widget.onOpen,
onRename: _rename,
onClose: _close,
onReopen: (session) => _controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onClearSearch: () {
_search.clear();
setState(() {});
},
child: Stack(
children: [
ChatSessionsBody(
sessions: _controller.sessions,
query: _search.text,
loading: _controller.loading,
error: _controller.error,
onOpen: _open,
onRename: _rename,
onClose: _close,
onReopen: (session) =>
_controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onHide: _hide,
onClearSearch: () {
_search.clear();
setState(() {});
},
isUnseen: _controller.isUnseen,
errorFor: _controller.errorFor,
),
// The web's hide report is a fixed overlay: replacing or
// growing it must never move the list or overflow the screen.
// A standalone Material screen keeps it clear of the FAB.
if (_controller.lastHidden != null)
Positioned(
left: 8,
right: 8,
bottom:
!widget.embedded &&
controls == ChatControlsStyle.material
? 88
: 8,
child: ChatUndoBar(
key: const Key('chat-undo-hide'),
message:
'Hidden on this device; the chat stays on the server.',
onUndo: _undoHide,
),
),
],
),
),
],
@@ -1,8 +1,10 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_create_dialog_frame.dart';
import 'chat_create_fields.dart';
class ChatDraft {
@@ -19,20 +21,37 @@ class ChatDraft {
final String instructions;
}
Future<ChatDraft?> showChatCreateDialog(
/// The dialog sends the create itself so a refusal can keep the operator's
/// draft and the server's words in place. [operationId] is minted once per
/// create intent and reused across retries, so a retry cannot create twice.
Future<JsonMap?> showChatCreateDialog(
BuildContext context, {
required ChatRepository repository,
required String operationId,
required Future<JsonMap> Function(ChatDraft draft, String operationId)
onSubmit,
}) {
final dialog = CreateChatDialog(repository: repository);
final dialog = CreateChatDialog(
repository: repository,
operationId: operationId,
onSubmit: onSubmit,
);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<ChatDraft>(context: context, builder: (_) => dialog)
: showDialog<ChatDraft>(context: context, builder: (_) => dialog);
? showCupertinoDialog<JsonMap>(context: context, builder: (_) => dialog)
: showDialog<JsonMap>(context: context, builder: (_) => dialog);
}
class CreateChatDialog extends StatefulWidget {
const CreateChatDialog({super.key, required this.repository});
const CreateChatDialog({
super.key,
required this.repository,
required this.operationId,
required this.onSubmit,
});
final ChatRepository repository;
final String operationId;
final Future<JsonMap> Function(ChatDraft draft, String operationId) onSubmit;
@override
State<CreateChatDialog> createState() => _CreateChatDialogState();
@@ -48,6 +67,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
String? _catalogError;
String? _formError;
bool _loading = true;
bool _submitting = false;
int _attempt = 0;
@override
@@ -106,23 +126,37 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
_directories.isNotEmpty &&
_backends.isNotEmpty;
void _submit() {
if (!_catalogReady) return;
Future<void> _submit() async {
if (!_catalogReady || _submitting) return;
final title = _name.text.trim();
final directory = _directory ?? '';
if (title.isEmpty || directory.isEmpty) {
setState(() => _formError = 'Enter a name and server directory.');
return;
}
Navigator.pop(
context,
ChatDraft(
title: title,
directory: directory,
backend: _backend ?? '',
instructions: _instructions.text,
),
);
setState(() {
_submitting = true;
_formError = null;
});
try {
final session = await widget.onSubmit(
ChatDraft(
title: title,
directory: directory,
backend: _backend ?? '',
instructions: _instructions.text,
),
widget.operationId,
);
if (!mounted) return;
Navigator.pop(context, session);
} catch (error) {
if (!mounted) return;
setState(() {
_submitting = false;
_formError = '$error';
});
}
}
@override
@@ -181,42 +215,25 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
),
if (_formError != null) ...[
const SizedBox(height: 8),
Text(_formError!),
Text(
_formError!,
style: TextStyle(
color: cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
),
),
],
],
),
);
if (cupertino) {
return CupertinoAlertDialog(
title: const Text('New chat'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
);
}
return AlertDialog(
title: const Text('New chat'),
return ChatCreateDialogFrame(
content: content,
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
canSubmit: _catalogReady,
submitting: _submitting,
onCancel: () => Navigator.pop(context),
onSubmit: _submit,
);
}
}
@@ -5,19 +5,28 @@ import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
/// Renames one session. Save is disabled while the trimmed name is blank,
/// matching the web dialog.
Future<String?> showRenameChatDialog(BuildContext context, JsonMap session) {
final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session));
/// Renames one session through the shared server field. Save is disabled while
/// the trimmed name is blank, matching the web dialog. A refusal keeps the
/// dialog open with the server's own words.
Future<String?> showRenameChatDialog(
BuildContext context,
JsonMap session, {
required Future<void> Function(String title) onSubmit,
}) {
final dialog = _RenameChatDialog(
initialTitle: chatSessionTitle(session),
onSubmit: onSubmit,
);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
: showDialog<String>(context: context, builder: (_) => dialog);
}
class _RenameChatDialog extends StatefulWidget {
const _RenameChatDialog({required this.initialTitle});
const _RenameChatDialog({required this.initialTitle, required this.onSubmit});
final String initialTitle;
final Future<void> Function(String title) onSubmit;
@override
State<_RenameChatDialog> createState() => _RenameChatDialogState();
@@ -30,6 +39,8 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
baseOffset: 0,
extentOffset: widget.initialTitle.length,
);
String? _error;
bool _saving = false;
@override
void dispose() {
@@ -37,10 +48,25 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
super.dispose();
}
void _save() {
Future<void> _save() async {
if (_saving) return;
final title = _title.text.trim();
if (title.isEmpty) return;
Navigator.pop(context, title);
setState(() {
_saving = true;
_error = null;
});
try {
await widget.onSubmit(title);
if (!mounted) return;
Navigator.pop(context, title);
} catch (error) {
if (!mounted) return;
setState(() {
_saving = false;
_error = '$error';
});
}
}
@override
@@ -48,7 +74,8 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
return ValueListenableBuilder<TextEditingValue>(
valueListenable: _title,
builder: (context, value, _) {
final canSave = value.text.trim().isNotEmpty;
final canSave = !_saving && value.text.trim().isNotEmpty;
final error = _error;
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: const Text('Rename chat'),
@@ -63,11 +90,20 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
),
const SizedBox(height: 8),
const Text('This name is shared with every device.'),
if (error != null) ...[
const SizedBox(height: 8),
Text(
error,
style: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
],
],
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
onPressed: _saving ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
@@ -79,20 +115,36 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
);
}
return AlertDialog(
// A long server refusal plus a 2x helper text can exceed the dialog
// height at 320px; scroll the content instead of clipping it.
scrollable: true,
title: const Text('Rename chat'),
content: TextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Name',
helperText: 'This name is shared with every device.',
helperMaxLines: 2,
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Name',
helperText: 'This name is shared with every device.',
helperMaxLines: 2,
),
),
if (error != null) ...[
const SizedBox(height: 8),
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
],
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
onPressed: _saving ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
@@ -6,7 +6,7 @@ import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'session_row_style.dart';
enum SessionAction { rename, close, reopen }
enum SessionAction { rename, close, reopen, hide }
/// The close confirmation's body, matching the web client's explanation.
String closeChatConfirmation(String title) =>
@@ -115,6 +115,7 @@ List<({SessionAction action, String label})> _items(JsonMap session) {
isClosed
? (action: SessionAction.reopen, label: 'Reopen')
: (action: SessionAction.close, label: 'Close chat…'),
(action: SessionAction.hide, label: 'Hide on this device'),
];
}
@@ -18,7 +18,10 @@ class CupertinoSessionList extends StatelessWidget {
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
required this.onClearSearch,
required this.isUnseen,
required this.errorFor,
});
final List<ChatSessionSection> sections;
@@ -29,7 +32,10 @@ class CupertinoSessionList extends StatelessWidget {
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
final VoidCallback? onClearSearch;
final bool Function(JsonMap) isUnseen;
final String? Function(String sessionId) errorFor;
@override
Widget build(BuildContext context) {
@@ -57,50 +63,67 @@ class CupertinoSessionList extends StatelessWidget {
? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}'
: section.title,
),
children: [
for (final session in group.sessions)
_CupertinoSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
],
children: [for (final session in group.sessions) ..._row(session)],
),
];
}
/// The tile plus its refusal. `CupertinoListTile` forces its subtitle to one
/// ellipsised line, so the server's words go in their own full-width row
/// inside the same native card.
List<Widget> _row(JsonMap session) {
final id = '${session['id'] ?? ''}';
final error = errorFor(id);
return [
_CupertinoSessionRow(
session: session,
duplicateTitles: duplicateTitles,
unseen: isUnseen(session),
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
),
if (error != null)
ChatRowError(message: error, messageKey: Key('chat-row-error-$id')),
];
}
}
class _CupertinoSessionRow extends StatelessWidget {
const _CupertinoSessionRow({
required this.session,
required this.duplicateTitles,
required this.unseen,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
});
final JsonMap session;
final Set<String> duplicateTitles;
final bool unseen;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
final subtitle = sessionSubtitle(session, unseen: unseen);
return CupertinoListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionCupertinoIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
subtitle: Text(subtitle),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@@ -129,6 +152,8 @@ class _CupertinoSessionRow extends StatelessWidget {
onClose(session);
case SessionAction.reopen:
onReopen(session);
case SessionAction.hide:
onHide(session);
}
}
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_style.dart';
@@ -17,7 +18,10 @@ class MaterialSessionList extends StatelessWidget {
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
required this.onClearSearch,
required this.isUnseen,
required this.errorFor,
});
final List<ChatSessionSection> sections;
@@ -28,7 +32,10 @@ class MaterialSessionList extends StatelessWidget {
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
final VoidCallback? onClearSearch;
final bool Function(JsonMap) isUnseen;
final String? Function(String sessionId) errorFor;
@override
Widget build(BuildContext context) {
@@ -64,40 +71,57 @@ class MaterialSessionList extends StatelessWidget {
group.directory.isEmpty ? 'No directory' : group.directory,
),
),
for (final session in group.sessions)
_MaterialSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
for (final session in group.sessions) ..._row(session),
],
],
);
}
/// The tile plus its refusal at full width (a long sentence in `subtitle`
/// made the row taller than the viewport at 320px with 2x text).
List<Widget> _row(JsonMap session) {
final id = '${session['id'] ?? ''}';
final error = errorFor(id);
return [
_MaterialSessionRow(
session: session,
duplicateTitles: duplicateTitles,
unseen: isUnseen(session),
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
),
if (error != null)
ChatRowError(message: error, messageKey: Key('chat-row-error-$id')),
];
}
}
class _MaterialSessionRow extends StatelessWidget {
const _MaterialSessionRow({
required this.session,
required this.duplicateTitles,
required this.unseen,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
});
final JsonMap session;
final Set<String> duplicateTitles;
final bool unseen;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
@override
Widget build(BuildContext context) {
@@ -106,7 +130,7 @@ class _MaterialSessionRow extends StatelessWidget {
key: Key('chat-row-$id'),
leading: Icon(sessionMaterialIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
subtitle: Text(sessionSubtitle(session, unseen: unseen)),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@@ -135,6 +159,8 @@ class _MaterialSessionRow extends StatelessWidget {
onClose(session);
case SessionAction.reopen:
onReopen(session);
case SessionAction.hide:
onHide(session);
}
}
}
@@ -23,11 +23,11 @@ String sessionActionsLabel(JsonMap session, Set<String> duplicateTitles) {
: 'Chat actions for $title';
}
String sessionSubtitle(JsonMap session) {
String sessionSubtitle(JsonMap session, {bool? unseen}) {
final directory = '${session['directory'] ?? ''}';
switch (chatSessionActivity(
running: session['running'] == true,
unseen: session['unseen'] == true,
unseen: unseen ?? session['unseen'] == true,
)) {
case 'streaming':
return '$directory · Streaming';