Merge branch 'worktree-agent-a785be85dc8fbff78'
This commit is contained in:
@@ -19,7 +19,9 @@ import '../domain/chat_commands.dart';
|
||||
import 'chat_command_actions.dart';
|
||||
import 'chat_command_palette.dart';
|
||||
import 'chat_composer_controller.dart';
|
||||
import 'chat_send_later_menu.dart';
|
||||
import 'chat_send_usage_ring.dart';
|
||||
import '../domain/chat_send_later.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_composer_paste_focus.dart';
|
||||
import 'chat_harness_command_loader.dart';
|
||||
@@ -792,8 +794,9 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
/// Builds the chips' exact wire parts and hands them to the composer with the
|
||||
/// draft's text and operation id. The chips clear with the text as the
|
||||
/// prompt leaves; a refusal that restores the text restores them too, so
|
||||
/// the draft and its files stay together.
|
||||
Future<void> _send() async {
|
||||
/// the draft and its files stay together. A [sendAt] (epoch ms, from
|
||||
/// "Send later…") asks the server to hold the message until then.
|
||||
Future<void> _send({int sendAt = 0}) async {
|
||||
final composer = widget.composer;
|
||||
if (_uploading || composer.sending || composer.draft.trim().isEmpty) {
|
||||
return;
|
||||
@@ -849,7 +852,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
if (keptAttachments.isNotEmpty) {
|
||||
setState(() => _replaceAttachments(const [], const []));
|
||||
}
|
||||
final accepted = await composer.send(attachments: parts);
|
||||
final accepted = await composer.send(attachments: parts, sendAt: sendAt);
|
||||
if (!mounted || accepted || keptAttachments.isEmpty) return;
|
||||
if (_attachments.isEmpty && composer.draft == sentText) {
|
||||
setState(() => _replaceAttachments(keptAttachments, keptBytes));
|
||||
@@ -1354,21 +1357,38 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
// One shape with or without usage (a report never remounts the
|
||||
// button): the hover text can grow with usage, while assistive
|
||||
// technology still names the button by its label alone.
|
||||
button: (tooltip) => Semantics(
|
||||
label: label,
|
||||
child: Tooltip(
|
||||
message: tooltip,
|
||||
excludeFromSemantics: true,
|
||||
child: IconButton.filled(
|
||||
key: const Key('chat-composer-primary'),
|
||||
style: tinted == null
|
||||
? null
|
||||
: IconButton.styleFrom(
|
||||
backgroundColor: tinted.primary,
|
||||
foregroundColor: tinted.onPrimary,
|
||||
),
|
||||
onPressed: enabled ? press : null,
|
||||
icon: const Icon(Icons.arrow_upward),
|
||||
button: (tooltip) => ChatSendLaterMenu(
|
||||
// Only an ordinary message can be scheduled, not a command or a
|
||||
// shell line.
|
||||
enabled:
|
||||
enabled &&
|
||||
!_paletteCompletes() &&
|
||||
!chatDraftIsShell(composer.draft) &&
|
||||
chatCommandWord(composer.draft) == null,
|
||||
info: tooltip == label ? null : tooltip.substring(label.length).trim(),
|
||||
usageReset: (now) => chatSendLaterUsageReset(usage?.accountUsage, now),
|
||||
onSchedule: (at) => unawaited(_send(sendAt: at.millisecondsSinceEpoch)),
|
||||
builder: (context, open) => Semantics(
|
||||
label: label,
|
||||
child: Tooltip(
|
||||
message: tooltip,
|
||||
excludeFromSemantics: true,
|
||||
// On an enabled button a touch long-press opens Send later…,
|
||||
// whose menu repeats the usage line; a disabled one shows the
|
||||
// tooltip. A pointer still shows the tooltip on hover.
|
||||
triggerMode: enabled ? TooltipTriggerMode.manual : null,
|
||||
child: IconButton.filled(
|
||||
onLongPress: open,
|
||||
key: const Key('chat-composer-primary'),
|
||||
style: tinted == null
|
||||
? null
|
||||
: IconButton.styleFrom(
|
||||
backgroundColor: tinted.primary,
|
||||
foregroundColor: tinted.onPrimary,
|
||||
),
|
||||
onPressed: enabled ? press : null,
|
||||
icon: const Icon(Icons.arrow_upward),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../domain/chat_send_later.dart';
|
||||
import 'chat_schedule_time.dart';
|
||||
|
||||
const String chatSendLaterLabel = 'Send later…';
|
||||
const String chatSendLaterPickLabel = 'Pick a time…';
|
||||
|
||||
/// The send button's secondary action: right-click, long-press, the context
|
||||
/// menu key or Shift+F10 on it (or the screen reader's custom action) opens
|
||||
/// "Send later…" with quick times and a time picker. A chosen time is handed
|
||||
/// to [onSchedule]; the message takes the ordinary send path with `send_at`.
|
||||
///
|
||||
/// On touch the long-press opens this menu instead of the button's tooltip,
|
||||
/// so the tooltip's account and usage line ([info]) heads the menu.
|
||||
class ChatSendLaterMenu extends StatefulWidget {
|
||||
const ChatSendLaterMenu({
|
||||
super.key,
|
||||
required this.enabled,
|
||||
required this.onSchedule,
|
||||
required this.builder,
|
||||
this.info,
|
||||
this.usageReset,
|
||||
this.now = DateTime.now,
|
||||
});
|
||||
|
||||
/// Whether the draft is a message that can be scheduled.
|
||||
final bool enabled;
|
||||
final String? info;
|
||||
final DateTime? Function(DateTime now)? usageReset;
|
||||
final void Function(DateTime at) onSchedule;
|
||||
|
||||
/// Builds the send button, given the callback that opens the menu.
|
||||
final Widget Function(BuildContext context, VoidCallback open) builder;
|
||||
final DateTime Function() now;
|
||||
|
||||
@override
|
||||
State<ChatSendLaterMenu> createState() => _ChatSendLaterMenuState();
|
||||
}
|
||||
|
||||
class _ChatSendLaterMenuState extends State<ChatSendLaterMenu> {
|
||||
final _menu = MenuController();
|
||||
|
||||
void _open([Offset? position]) {
|
||||
if (_menu.isOpen) _menu.close();
|
||||
setState(() {});
|
||||
_menu.open(position: position);
|
||||
}
|
||||
|
||||
Future<void> _pickTime() async {
|
||||
final now = widget.now();
|
||||
final initial = TimeOfDay.fromDateTime(now.add(const Duration(hours: 1)));
|
||||
final picked = await showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay(hour: initial.hour, minute: 0),
|
||||
helpText: 'Send at',
|
||||
// The same 24-hour clock as "Scheduled · sends at 21:03".
|
||||
builder: (context, child) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
|
||||
child: child!,
|
||||
),
|
||||
);
|
||||
if (!mounted || picked == null || !widget.enabled) return;
|
||||
widget.onSchedule(
|
||||
chatSendLaterAt(widget.now(), picked.hour, picked.minute),
|
||||
);
|
||||
}
|
||||
|
||||
String _label(BuildContext context, ChatSendLaterChoice choice) {
|
||||
final time = chatScheduleTime(context, choice.at, now: widget.now);
|
||||
return switch (choice.kind) {
|
||||
ChatSendLaterKind.halfHour => 'In 30 minutes · $time',
|
||||
ChatSendLaterKind.hour => 'In 1 hour · $time',
|
||||
ChatSendLaterKind.tomorrowMorning => 'Tomorrow at 9:00',
|
||||
ChatSendLaterKind.usageReset => 'At usage reset · $time',
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final now = widget.now();
|
||||
final choices = chatSendLaterChoices(
|
||||
now,
|
||||
usageReset: widget.usageReset?.call(now),
|
||||
);
|
||||
final theme = Theme.of(context);
|
||||
final info = widget.info;
|
||||
return MenuAnchor(
|
||||
controller: _menu,
|
||||
menuChildren: [
|
||||
if (info != null && info.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
child: Text(
|
||||
info,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
key: const Key('chat-send-later-title'),
|
||||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.schedule_send,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
Text(chatSendLaterLabel, style: theme.textTheme.titleSmall),
|
||||
],
|
||||
),
|
||||
),
|
||||
for (final choice in choices)
|
||||
MenuItemButton(
|
||||
key: Key('chat-send-later-${choice.kind.name}'),
|
||||
onPressed: widget.enabled
|
||||
? () => widget.onSchedule(choice.at)
|
||||
: null,
|
||||
child: Text(_label(context, choice)),
|
||||
),
|
||||
MenuItemButton(
|
||||
key: const Key('chat-send-later-pick'),
|
||||
leadingIcon: const Icon(Icons.access_time),
|
||||
onPressed: widget.enabled ? _pickTime : null,
|
||||
child: const Text(chatSendLaterPickLabel),
|
||||
),
|
||||
],
|
||||
child: CallbackShortcuts(
|
||||
bindings: {
|
||||
const SingleActivator(LogicalKeyboardKey.contextMenu): _open,
|
||||
const SingleActivator(LogicalKeyboardKey.f10, shift: true): _open,
|
||||
},
|
||||
child: GestureDetector(
|
||||
onSecondaryTapUp: (details) => _open(details.localPosition),
|
||||
child: Semantics(
|
||||
customSemanticsActions: {
|
||||
const CustomSemanticsAction(label: chatSendLaterLabel): _open,
|
||||
},
|
||||
child: widget.builder(context, _open),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
/// The harness last used to create a chat, per directory and anywhere, kept
|
||||
/// on this device so the create dialog can offer it again.
|
||||
abstract interface class ChatCreateHarnessStore {
|
||||
/// The harness last used in [directory], or null.
|
||||
Future<String?> read(String directory);
|
||||
|
||||
/// The harness last used to create any chat, or null.
|
||||
Future<String?> readLast();
|
||||
|
||||
Future<void> write(String directory, String backend);
|
||||
}
|
||||
|
||||
/// The harness the create dialog starts on: the one last used in the
|
||||
/// directory, else the one last used anywhere, else OpenCode, else the
|
||||
/// server's first harness. A remembered harness the server no longer offers
|
||||
/// is skipped.
|
||||
String chatDefaultHarness(
|
||||
List<String> offered, {
|
||||
String? directoryLast,
|
||||
String? anywhereLast,
|
||||
}) {
|
||||
for (final candidate in [directoryLast, anywhereLast, 'opencode']) {
|
||||
if (candidate != null && offered.contains(candidate)) return candidate;
|
||||
}
|
||||
return offered.first;
|
||||
}
|
||||
|
||||
class SharedPreferencesChatCreateHarnessStore
|
||||
implements ChatCreateHarnessStore {
|
||||
const SharedPreferencesChatCreateHarnessStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
|
||||
String _key(String suffix) =>
|
||||
scopedServerKey('pipelines.chat.createHarness.v1.$suffix', serverId);
|
||||
|
||||
Future<String?> _get(String key) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final value = prefs.getString(key);
|
||||
return value == null || value.isEmpty ? null : value;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read(String directory) => _get(_key('dir|$directory'));
|
||||
|
||||
@override
|
||||
Future<String?> readLast() => _get(_key('last'));
|
||||
|
||||
@override
|
||||
Future<void> write(String directory, String backend) async {
|
||||
if (backend.isEmpty) return;
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_key('dir|$directory'), backend);
|
||||
await prefs.setString(_key('last'), backend);
|
||||
} catch (_) {
|
||||
// Remembering is a convenience; the chat is still created.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for tests and hosts without preferences.
|
||||
class MemoryChatCreateHarnessStore implements ChatCreateHarnessStore {
|
||||
MemoryChatCreateHarnessStore({Map<String, String>? byDirectory, this.last})
|
||||
: byDirectory = byDirectory ?? {};
|
||||
|
||||
final Map<String, String> byDirectory;
|
||||
String? last;
|
||||
|
||||
@override
|
||||
Future<String?> read(String directory) async => byDirectory[directory];
|
||||
|
||||
@override
|
||||
Future<String?> readLast() async => last;
|
||||
|
||||
@override
|
||||
Future<void> write(String directory, String backend) async {
|
||||
byDirectory[directory] = backend;
|
||||
last = backend;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
export '../domain/chat_default_name.dart' show defaultChatName;
|
||||
|
||||
/// Whether a new chat starts with a prompt, and which, for one harness and
|
||||
/// directory: the last choice made there.
|
||||
typedef ChatCreatePrompt = ({bool send, String text});
|
||||
@@ -55,17 +57,3 @@ class SharedPreferencesChatCreatePromptStore implements ChatCreatePromptStore {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default chat name: the directory's last folder and the harness, as in
|
||||
/// "Pipelines Codex".
|
||||
String defaultChatName(String directory, String harnessLabel) {
|
||||
final parts = directory
|
||||
.split('/')
|
||||
.where((part) => part.isNotEmpty && part != '~')
|
||||
.toList();
|
||||
final leaf = parts.isEmpty ? 'Home' : parts.last;
|
||||
final folder = leaf.isEmpty
|
||||
? 'Home'
|
||||
: '${leaf[0].toUpperCase()}${leaf.substring(1)}';
|
||||
return '$folder $harnessLabel';
|
||||
}
|
||||
|
||||
@@ -200,12 +200,13 @@ class ChatRepository {
|
||||
String backend = 'opencode',
|
||||
String instructions = '',
|
||||
}) {
|
||||
if (title.trim().isEmpty || directory.trim().isEmpty) {
|
||||
throw ArgumentError('Enter a chat name and choose a directory.');
|
||||
if (directory.trim().isEmpty) {
|
||||
throw ArgumentError('Choose a directory.');
|
||||
}
|
||||
// A blank title leaves naming the chat to its harness.
|
||||
return gateway.call('chat_create', {
|
||||
'chat_create': {
|
||||
'title': title.trim(),
|
||||
if (title.trim().isNotEmpty) 'title': title.trim(),
|
||||
'directory': directory.trim(),
|
||||
'operation_id': operationId,
|
||||
if (backend.isNotEmpty && backend != 'opencode') 'backend': backend,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/// A chat's default name, shown until the operator or the harness names it.
|
||||
library;
|
||||
|
||||
/// The web's names for the chat harnesses; an unknown one shows as sent.
|
||||
String chatBackendLabel(String backend) => switch (backend) {
|
||||
'codex' => 'Codex',
|
||||
'claude' => 'Claude',
|
||||
'pi' => 'Pi',
|
||||
'opencode' => 'OpenCode',
|
||||
_ => backend,
|
||||
};
|
||||
|
||||
/// The default chat name: the directory's last folder and the harness, as in
|
||||
/// "Pipelines Codex".
|
||||
String defaultChatName(String directory, String harnessLabel) {
|
||||
final parts = directory
|
||||
.split('/')
|
||||
.where((part) => part.isNotEmpty && part != '~')
|
||||
.toList();
|
||||
final leaf = parts.isEmpty ? 'Home' : parts.last;
|
||||
final folder = leaf.isEmpty
|
||||
? 'Home'
|
||||
: '${leaf[0].toUpperCase()}${leaf.substring(1)}';
|
||||
return '$folder $harnessLabel';
|
||||
}
|
||||
|
||||
/// OpenCode's placeholder for a session it has not named yet
|
||||
/// ("New session - 2026-12-02T09:00:00.000Z").
|
||||
final RegExp _harnessPlaceholder = RegExp(
|
||||
r'^(New|Child) session - \d{4}-\d{2}-\d{2}T',
|
||||
);
|
||||
|
||||
/// The title a harness gave a chat, or null while it has none of its own
|
||||
/// (blank, or only its placeholder).
|
||||
String? chatHarnessTitle(String title) {
|
||||
final trimmed = title.trim();
|
||||
if (trimmed.isEmpty || _harnessPlaceholder.hasMatch(trimmed)) return null;
|
||||
return title;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/// "Send later…": the quick times the composer offers for scheduling the
|
||||
/// operator's own message (the server holds it until `send_at`).
|
||||
library;
|
||||
|
||||
import 'chat_account_usage.dart';
|
||||
import 'chat_usage_limit.dart';
|
||||
|
||||
enum ChatSendLaterKind { halfHour, hour, tomorrowMorning, usageReset }
|
||||
|
||||
typedef ChatSendLaterChoice = ({ChatSendLaterKind kind, DateTime at});
|
||||
|
||||
/// When the account's quota is back: the exhausted limit's reset if one is
|
||||
/// reported, else the next reported window reset; a minute later, as
|
||||
/// auto-continue does. Null when no reset time is known.
|
||||
DateTime? chatSendLaterUsageReset(ChatAccountUsage? usage, DateTime now) {
|
||||
final limit = chatUsageLimit(usage, now);
|
||||
if (limit != null) return limit.sendAt;
|
||||
if (usage == null || usage.unsupported) return null;
|
||||
int? next;
|
||||
for (final window in usage.windows) {
|
||||
final at = window.resetsAt;
|
||||
if (at <= now.millisecondsSinceEpoch) continue;
|
||||
if (next == null || at < next) next = at;
|
||||
}
|
||||
if (next == null) return null;
|
||||
return DateTime.fromMillisecondsSinceEpoch(next).add(chatScheduleMargin);
|
||||
}
|
||||
|
||||
/// In 30 minutes, in 1 hour, tomorrow at 9:00 and, when known, at the usage
|
||||
/// reset.
|
||||
List<ChatSendLaterChoice> chatSendLaterChoices(
|
||||
DateTime now, {
|
||||
DateTime? usageReset,
|
||||
}) {
|
||||
final local = now.toLocal();
|
||||
return [
|
||||
(
|
||||
kind: ChatSendLaterKind.halfHour,
|
||||
at: local.add(const Duration(minutes: 30)),
|
||||
),
|
||||
(kind: ChatSendLaterKind.hour, at: local.add(const Duration(hours: 1))),
|
||||
(
|
||||
kind: ChatSendLaterKind.tomorrowMorning,
|
||||
at: DateTime(local.year, local.month, local.day + 1, 9),
|
||||
),
|
||||
if (usageReset != null && usageReset.isAfter(now))
|
||||
(kind: ChatSendLaterKind.usageReset, at: usageReset.toLocal()),
|
||||
];
|
||||
}
|
||||
|
||||
/// A picked time of day: today when it is still ahead, else tomorrow.
|
||||
DateTime chatSendLaterAt(DateTime now, int hour, int minute) {
|
||||
final local = now.toLocal();
|
||||
final today = DateTime(local.year, local.month, local.day, hour, minute);
|
||||
return today.isAfter(local)
|
||||
? today
|
||||
: DateTime(local.year, local.month, local.day + 1, hour, minute);
|
||||
}
|
||||
@@ -1,9 +1,22 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_default_name.dart';
|
||||
|
||||
/// Pure session-list operations. Unknown server fields remain on each row.
|
||||
///
|
||||
/// A chat's title is the operator's name for it or else the harness's own;
|
||||
/// until the harness names an unnamed chat it shows the default name
|
||||
/// ("Pipelines Codex") from its directory and harness.
|
||||
String chatSessionTitle(JsonMap session) {
|
||||
final title = '${session['title'] ?? ''}';
|
||||
if (title.trim().isNotEmpty) return title;
|
||||
final title = chatHarnessTitle('${session['title'] ?? ''}');
|
||||
if (title != null) return title;
|
||||
final directory = '${session['directory'] ?? ''}'.trim();
|
||||
if (directory.isNotEmpty) {
|
||||
final backend = '${session['backend'] ?? ''}'.trim();
|
||||
return defaultChatName(
|
||||
directory,
|
||||
chatBackendLabel(backend.isEmpty ? 'opencode' : backend),
|
||||
);
|
||||
}
|
||||
final id = '${session['id'] ?? ''}';
|
||||
return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../domain/chat_default_name.dart';
|
||||
|
||||
export '../../domain/chat_default_name.dart' show chatBackendLabel;
|
||||
|
||||
/// The web's directory prompt, also the directory picker's label.
|
||||
const String chatCreatePrompt = 'Where should this chat live?';
|
||||
|
||||
@@ -25,15 +29,6 @@ String chatDirectoryLabel(String choice, List<String> directories) {
|
||||
return '$chatHomeLabel — $home';
|
||||
}
|
||||
|
||||
/// The web's names for the chat harnesses; an unknown one shows as sent.
|
||||
String chatBackendLabel(String backend) => switch (backend) {
|
||||
'codex' => 'Codex',
|
||||
'claude' => 'Claude',
|
||||
'pi' => 'Pi',
|
||||
'opencode' => 'OpenCode',
|
||||
_ => backend,
|
||||
};
|
||||
|
||||
/// The create dialog's server catalog area: loading, error with retry, the
|
||||
/// directory choices and, only when the server offers more than one, the
|
||||
/// harness choice.
|
||||
@@ -101,13 +96,18 @@ class ChatCatalogFields extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
if (backends.length > 1)
|
||||
MaterialPickerField(
|
||||
fieldKey: const Key('chat-create-backend'),
|
||||
label: 'Chat harness',
|
||||
value: backend,
|
||||
values: backends,
|
||||
labelOf: chatBackendLabel,
|
||||
onSelected: onBackend,
|
||||
// Keyed by the value so the harness remembered for a folder,
|
||||
// read after the field first shows, replaces its initial value.
|
||||
KeyedSubtree(
|
||||
key: ValueKey('chat-create-backend-$backend'),
|
||||
child: MaterialPickerField(
|
||||
fieldKey: const Key('chat-create-backend'),
|
||||
label: 'Chat harness',
|
||||
value: backend,
|
||||
values: backends,
|
||||
labelOf: chatBackendLabel,
|
||||
onSelected: onBackend,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../../../core/servers/server_scope.dart';
|
||||
import '../../data/chat_create_harness_store.dart';
|
||||
import '../../data/chat_create_prompt_store.dart';
|
||||
import '../../data/chat_repository.dart';
|
||||
import '../../data/directory_listing.dart';
|
||||
@@ -20,6 +21,7 @@ const String chatCreateInstructionsHelper =
|
||||
"repository's AGENTS.md and skills.";
|
||||
const String chatCreateModelNote =
|
||||
"New chats start with the server's default model.";
|
||||
const String chatCreateNameHelper = "Leave empty to use the harness's title";
|
||||
|
||||
class ChatDraft {
|
||||
const ChatDraft({
|
||||
@@ -29,6 +31,7 @@ class ChatDraft {
|
||||
required this.instructions,
|
||||
});
|
||||
|
||||
/// The operator's name for the chat; empty leaves naming to the harness.
|
||||
final String title;
|
||||
final String directory;
|
||||
final String backend;
|
||||
@@ -45,6 +48,7 @@ Future<JsonMap?> showChatCreateDialog(
|
||||
required Future<JsonMap> Function(ChatDraft draft, String operationId)
|
||||
onSubmit,
|
||||
ChatCreatePromptStore? prompts,
|
||||
ChatCreateHarnessStore? harnesses,
|
||||
}) {
|
||||
final dialog = ServerContext.forServer(
|
||||
context,
|
||||
@@ -54,6 +58,7 @@ Future<JsonMap?> showChatCreateDialog(
|
||||
operationId: operationId,
|
||||
onSubmit: onSubmit,
|
||||
prompts: prompts,
|
||||
harnesses: harnesses,
|
||||
),
|
||||
);
|
||||
return showDialog<JsonMap>(context: context, builder: (_) => dialog);
|
||||
@@ -66,11 +71,15 @@ class CreateChatDialog extends StatefulWidget {
|
||||
required this.operationId,
|
||||
required this.onSubmit,
|
||||
this.prompts,
|
||||
this.harnesses,
|
||||
});
|
||||
|
||||
/// The last first-prompt choice per harness and directory.
|
||||
final ChatCreatePromptStore? prompts;
|
||||
|
||||
/// The harness last used per directory and anywhere.
|
||||
final ChatCreateHarnessStore? harnesses;
|
||||
|
||||
final ChatRepository repository;
|
||||
final String operationId;
|
||||
final Future<JsonMap> Function(ChatDraft draft, String operationId) onSubmit;
|
||||
@@ -85,12 +94,21 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
SharedPreferencesChatCreatePromptStore(
|
||||
serverId: serverStorageScope(serverIdentity(widget.repository.gateway)),
|
||||
);
|
||||
late final ChatCreateHarnessStore _harnesses =
|
||||
widget.harnesses ??
|
||||
SharedPreferencesChatCreateHarnessStore(
|
||||
serverId: serverStorageScope(serverIdentity(widget.repository.gateway)),
|
||||
);
|
||||
final _instructions = TextEditingController();
|
||||
final _name = TextEditingController();
|
||||
|
||||
/// The name follows the folder and harness until the operator edits it.
|
||||
bool _nameEdited = false;
|
||||
|
||||
/// An explicit harness pick is kept unless the next folder remembers one.
|
||||
bool _backendTouched = false;
|
||||
int _harnessRecall = 0;
|
||||
|
||||
/// Whether the new chat starts with the prompt below.
|
||||
bool _sendPrompt = false;
|
||||
|
||||
@@ -142,14 +160,12 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
_directory = chatDirectoryChoices(_directories).contains(_directory)
|
||||
? _directory
|
||||
: chatHomeDirectory;
|
||||
_backend = _backends.contains(_backend)
|
||||
_backend = _backendTouched && _backends.contains(_backend)
|
||||
? _backend
|
||||
: _backends.contains('opencode')
|
||||
? 'opencode'
|
||||
: _backends.first;
|
||||
: chatDefaultHarness(_backends);
|
||||
_loading = false;
|
||||
});
|
||||
_choiceChanged();
|
||||
_directoryChanged();
|
||||
} catch (error) {
|
||||
if (!mounted || attempt != _attempt) return;
|
||||
setState(() {
|
||||
@@ -159,6 +175,31 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder pick: the name follows at once, and the harness last used there
|
||||
/// (else anywhere) becomes the default once read, unless the operator
|
||||
/// picked a harness and this folder remembers none.
|
||||
Future<void> _directoryChanged() async {
|
||||
_choiceChanged();
|
||||
final directory = _directory ?? chatHomeDirectory;
|
||||
final recall = ++_harnessRecall;
|
||||
final remembered = await Future.wait([
|
||||
_harnesses.read(directory),
|
||||
_harnesses.readLast(),
|
||||
]);
|
||||
if (!mounted || recall != _harnessRecall || _backends.isEmpty) return;
|
||||
final here = remembered[0];
|
||||
final next = _backendTouched && !_backends.contains(here)
|
||||
? _backend
|
||||
: chatDefaultHarness(
|
||||
_backends,
|
||||
directoryLast: here,
|
||||
anywhereLast: remembered[1],
|
||||
);
|
||||
if (next == _backend) return;
|
||||
setState(() => _backend = next);
|
||||
_choiceChanged();
|
||||
}
|
||||
|
||||
bool get _catalogReady => !_loading && _catalogError == null;
|
||||
bool get _promptReady => !_sendPrompt || _instructions.text.trim().isNotEmpty;
|
||||
|
||||
@@ -249,7 +290,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
_directory = chosen;
|
||||
}
|
||||
});
|
||||
_choiceChanged();
|
||||
_directoryChanged();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
@@ -270,9 +311,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
final name = _name.text.trim();
|
||||
final session = await widget.onSubmit(
|
||||
ChatDraft(
|
||||
title: name.isEmpty
|
||||
? defaultChatName(directory, chatBackendLabel(backend))
|
||||
: name,
|
||||
title: name,
|
||||
directory: directory,
|
||||
backend: backend,
|
||||
instructions: sendPrompt ? promptText : '',
|
||||
@@ -281,6 +320,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
);
|
||||
// Only an actually sent prompt becomes Last used. Starting a promptless
|
||||
// chat must not erase a saved preset (or wait for its pending read).
|
||||
unawaited(_harnesses.write(directory, backend));
|
||||
if (sendPrompt) {
|
||||
unawaited(
|
||||
_prompts.write(backend, directory, (
|
||||
@@ -316,10 +356,14 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
backend: _backend,
|
||||
onDirectory: (value) {
|
||||
setState(() => _directory = value);
|
||||
_choiceChanged();
|
||||
_directoryChanged();
|
||||
},
|
||||
onBackend: (value) {
|
||||
setState(() => _backend = value);
|
||||
setState(() {
|
||||
_backend = value;
|
||||
_backendTouched = true;
|
||||
});
|
||||
_harnessRecall++;
|
||||
_choiceChanged();
|
||||
},
|
||||
onRetry: _loadCatalog,
|
||||
@@ -332,6 +376,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
key: const Key('chat-create-name'),
|
||||
controller: _name,
|
||||
onChanged: (_) => _nameEdited = true,
|
||||
decoration: const InputDecoration(helperText: chatCreateNameHelper),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ChatPromptChooser(
|
||||
|
||||
@@ -14,7 +14,7 @@ import 'chat_markdown_speech.dart';
|
||||
import 'chat_message_bubble.dart';
|
||||
import '../../speech/speech.dart';
|
||||
import 'chat_table_cell_measure.dart';
|
||||
import 'chat_table_column_width.dart';
|
||||
import 'chat_table_viewport.dart';
|
||||
|
||||
/// Renders one assistant text part with native text widgets and the host's own
|
||||
/// theme roles. Links (`http`, `https`, `mailto` and `www.` hosts only) open
|
||||
@@ -233,11 +233,12 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
),
|
||||
);
|
||||
case MarkdownTable(header: final header, rows: final rows):
|
||||
// Cells wrap to the transcript width; the table never scrolls sideways.
|
||||
return Table(
|
||||
defaultColumnWidth: ChatTableColumnWidth(header.length),
|
||||
// Cells wrap at word boundaries to the transcript width; a table
|
||||
// whose longest words cannot fit scrolls sideways instead.
|
||||
return ChatTableViewport(
|
||||
columns: header.length,
|
||||
border: TableBorder.all(color: _dividerColor(context)),
|
||||
children: [
|
||||
rows: [
|
||||
TableRow(
|
||||
decoration: BoxDecoration(color: _headerFill(context)),
|
||||
children: [
|
||||
|
||||
@@ -2,18 +2,20 @@ import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// Sizes a markdown table column to its content but lets it wrap to fit the
|
||||
/// transcript instead of scrolling sideways.
|
||||
/// Sizes a markdown table column to its content, wrapping at word boundaries
|
||||
/// when the table is wider than the transcript.
|
||||
///
|
||||
/// A column asks for its widest line ([IntrinsicColumnWidth]). When the table
|
||||
/// is wider than its container, [Table] shrinks columns towards their minimum,
|
||||
/// which is normally the longest single word. That floor is capped at an equal
|
||||
/// share of the container, so a long identifier or URL breaks inside its cell
|
||||
/// rather than pushing the table past the edge.
|
||||
/// is wider than its container, [Table] shrinks columns towards their minimum:
|
||||
/// the longest single word, so a word never breaks inside itself. Only a
|
||||
/// token wider than [tokenCap] (about forty characters: a URL or a hash) may
|
||||
/// break, down to an equal share of the transcript ([shareCap]), so one cell
|
||||
/// cannot force the whole table to scroll sideways.
|
||||
class ChatTableColumnWidth extends TableColumnWidth {
|
||||
const ChatTableColumnWidth(this.columnCount);
|
||||
const ChatTableColumnWidth({required this.tokenCap, required this.shareCap});
|
||||
|
||||
final int columnCount;
|
||||
final double tokenCap;
|
||||
final double shareCap;
|
||||
|
||||
static const _content = IntrinsicColumnWidth();
|
||||
|
||||
@@ -23,9 +25,9 @@ class ChatTableColumnWidth extends TableColumnWidth {
|
||||
|
||||
@override
|
||||
double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
|
||||
final words = _content.minIntrinsicWidth(cells, containerWidth);
|
||||
if (!containerWidth.isFinite || columnCount < 1) return words;
|
||||
return math.min(words, containerWidth / columnCount);
|
||||
final word = _content.minIntrinsicWidth(cells, containerWidth);
|
||||
if (word <= tokenCap) return word;
|
||||
return math.min(tokenCap, shareCap);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'chat_table_column_width.dart';
|
||||
import 'chat_transcript_selection.dart';
|
||||
|
||||
/// About forty characters of body text: the widest a column's minimum may be
|
||||
/// (see ChatTableColumnWidth), in multiples of the font size.
|
||||
const double chatTableTokenCapEms = 22;
|
||||
|
||||
/// A markdown table in the transcript: it fits the transcript's width,
|
||||
/// wrapping its cells at word boundaries, whenever every column's longest
|
||||
/// word fits. Only when they cannot does the table keep those minimums and
|
||||
/// scroll sideways, with the same affordance code blocks use.
|
||||
class ChatTableViewport extends StatelessWidget {
|
||||
const ChatTableViewport({
|
||||
super.key,
|
||||
required this.columns,
|
||||
required this.rows,
|
||||
this.border,
|
||||
});
|
||||
|
||||
final int columns;
|
||||
final List<TableRow> rows;
|
||||
final TableBorder? border;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final em = DefaultTextStyle.of(context).style.fontSize ?? 14;
|
||||
final tokenCap =
|
||||
MediaQuery.textScalerOf(context).scale(em) * chatTableTokenCapEms;
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final share = width.isFinite && columns > 0
|
||||
? width / columns
|
||||
: double.infinity;
|
||||
return ChatTranscriptHorizontalScrollView(
|
||||
label: 'table',
|
||||
child: ChatTableFit(
|
||||
width: width,
|
||||
child: Table(
|
||||
defaultColumnWidth: ChatTableColumnWidth(
|
||||
tokenCap: tokenCap,
|
||||
shareCap: share,
|
||||
),
|
||||
border: border,
|
||||
children: rows,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays its child out at [width], or at the child's minimum intrinsic width
|
||||
/// when that is wider, so a table inside a horizontal scroll view wraps to the
|
||||
/// visible width instead of taking its widest line.
|
||||
class ChatTableFit extends SingleChildRenderObjectWidget {
|
||||
const ChatTableFit({super.key, required this.width, required super.child});
|
||||
|
||||
final double width;
|
||||
|
||||
@override
|
||||
RenderChatTableFit createRenderObject(BuildContext context) =>
|
||||
RenderChatTableFit(width);
|
||||
|
||||
@override
|
||||
void updateRenderObject(
|
||||
BuildContext context,
|
||||
RenderChatTableFit renderObject,
|
||||
) => renderObject.width = width;
|
||||
}
|
||||
|
||||
class RenderChatTableFit extends RenderProxyBox {
|
||||
RenderChatTableFit(this._width);
|
||||
|
||||
double _width;
|
||||
set width(double value) {
|
||||
if (value == _width) return;
|
||||
_width = value;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
@override
|
||||
void performLayout() {
|
||||
final child = this.child;
|
||||
if (child == null) {
|
||||
size = constraints.smallest;
|
||||
return;
|
||||
}
|
||||
var width = _width;
|
||||
if (width.isFinite) {
|
||||
width = math.max(width, child.getMinIntrinsicWidth(double.infinity));
|
||||
}
|
||||
child.layout(
|
||||
BoxConstraints(maxWidth: math.min(width, constraints.maxWidth)),
|
||||
parentUsesSize: true,
|
||||
);
|
||||
size = constraints.constrain(child.size);
|
||||
}
|
||||
}
|
||||
@@ -252,6 +252,11 @@ void main() {
|
||||
'operation_id': 'create',
|
||||
},
|
||||
});
|
||||
// No name: the harness names the chat, so no title is sent.
|
||||
await repo.create(title: ' ', directory: '~', operationId: 'bare');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_create': {'directory': '~', 'operation_id': 'bare'},
|
||||
});
|
||||
await repo.selectModel('s', 'provider', 'model');
|
||||
expect(gateway.calls.last.type, 'chat_model');
|
||||
gateway.calls.clear();
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'chat_composer_bar_fixtures.dart';
|
||||
|
||||
final _send = find.byKey(const Key('chat-composer-primary'));
|
||||
|
||||
Future<ComposerBarGateway> _pumpDraft(WidgetTester tester, String text) async {
|
||||
final gateway = ComposerBarGateway()..page = fixtureTurn();
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
composerThread(gateway, newOperationId: () => 'op/1'),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(find.byKey(const Key('chat-composer-field')), text);
|
||||
await tester.pump();
|
||||
return gateway;
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('right-click on Send schedules the message with send_at', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = await _pumpDraft(tester, 'Check the deploy');
|
||||
final before = DateTime.now();
|
||||
await tester.tap(_send, buttons: kSecondaryButton);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Send later…'), findsOneWidget);
|
||||
expect(find.text('Tomorrow at 9:00'), findsOneWidget);
|
||||
// No usage report: no reset time to offer.
|
||||
expect(find.byKey(const Key('chat-send-later-usageReset')), findsNothing);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-send-later-hour')));
|
||||
await tester.pumpAndSettle();
|
||||
final body = gateway.promptBodies.single;
|
||||
expect(body['text'], 'Check the deploy');
|
||||
final sendAt = DateTime.fromMillisecondsSinceEpoch(body['send_at'] as int);
|
||||
expect(sendAt.difference(before).inMinutes, inInclusiveRange(59, 61));
|
||||
expect(fieldText(tester), isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('long-press opens it on touch, and Send still sends now', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = await _pumpDraft(tester, 'Now please');
|
||||
await tester.longPress(_send);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-send-later-halfHour')), findsOneWidget);
|
||||
await tester.tapAt(const Offset(5, 5));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(_send);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.promptBodies.single.containsKey('send_at'), isFalse);
|
||||
});
|
||||
|
||||
testWidgets('the keyboard opens it from Send with Shift+F10', (tester) async {
|
||||
final gateway = await _pumpDraft(tester, 'Later');
|
||||
// Focus the Send button itself, as Tab would.
|
||||
Focus.of(tester.element(find.byIcon(Icons.arrow_upward))).requestFocus();
|
||||
await tester.pump();
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.f10);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-send-later-tomorrowMorning')), findsOne);
|
||||
await tester.tap(find.byKey(const Key('chat-send-later-tomorrowMorning')));
|
||||
await tester.pumpAndSettle();
|
||||
final at = DateTime.fromMillisecondsSinceEpoch(
|
||||
gateway.promptBodies.single['send_at'] as int,
|
||||
);
|
||||
expect((at.hour, at.minute), (9, 0));
|
||||
});
|
||||
|
||||
testWidgets('a slash command cannot be scheduled', (tester) async {
|
||||
final gateway = await _pumpDraft(tester, '/compact');
|
||||
await tester.tap(_send, buttons: kSecondaryButton);
|
||||
await tester.pumpAndSettle();
|
||||
final item = tester.widget<MenuItemButton>(
|
||||
find.byKey(const Key('chat-send-later-hour')),
|
||||
);
|
||||
expect(item.onPressed, isNull);
|
||||
expect(gateway.promptBodies, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_default_name.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_sessions.dart';
|
||||
|
||||
void main() {
|
||||
test('an operator or harness title is shown as is', () {
|
||||
expect(
|
||||
chatSessionTitle({'id': 's', 'title': 'Fix login', 'directory': '/a'}),
|
||||
'Fix login',
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'an untitled chat shows the default name until the harness names it',
|
||||
() {
|
||||
expect(
|
||||
chatSessionTitle({
|
||||
'id': 'ses_1',
|
||||
'title': '',
|
||||
'directory': '/work/pipelines',
|
||||
'backend': 'codex',
|
||||
}),
|
||||
'Pipelines Codex',
|
||||
);
|
||||
expect(
|
||||
chatSessionTitle({
|
||||
'id': 'ses_2',
|
||||
'title': 'New session - 2026-12-02T09:00:00.000Z',
|
||||
'directory': '/work/site',
|
||||
'backend': 'opencode',
|
||||
}),
|
||||
'Site OpenCode',
|
||||
);
|
||||
// No backend field: an older server's chats are OpenCode.
|
||||
expect(
|
||||
chatSessionTitle({'id': 'ses_3', 'directory': '/work/site'}),
|
||||
'Site OpenCode',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('a row without a directory still falls back to its id', () {
|
||||
expect(chatSessionTitle({'id': 'ses_abc'}), 'ses_abc');
|
||||
expect(chatSessionTitle(const {}), 'Untitled chat');
|
||||
});
|
||||
|
||||
test('only blank titles and the placeholder count as unnamed', () {
|
||||
expect(chatHarnessTitle(' '), isNull);
|
||||
expect(chatHarnessTitle('Child session - 2026-01-01T00:00:00Z'), isNull);
|
||||
expect(chatHarnessTitle('New session notes'), 'New session notes');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_send_later.dart';
|
||||
|
||||
ChatAccountUsage _usage(List<ChatQuotaWindow> windows) => ChatAccountUsage(
|
||||
harness: 'Claude Code',
|
||||
plan: 'max',
|
||||
asOf: 0,
|
||||
windows: windows,
|
||||
unsupported: false,
|
||||
);
|
||||
|
||||
void main() {
|
||||
final now = DateTime(2026, 12, 2, 14, 10);
|
||||
|
||||
test('quick times: 30 minutes, an hour, tomorrow at 9:00', () {
|
||||
final choices = chatSendLaterChoices(now);
|
||||
expect(choices.map((c) => c.kind), [
|
||||
ChatSendLaterKind.halfHour,
|
||||
ChatSendLaterKind.hour,
|
||||
ChatSendLaterKind.tomorrowMorning,
|
||||
]);
|
||||
expect(choices[0].at, DateTime(2026, 12, 2, 14, 40));
|
||||
expect(choices[1].at, DateTime(2026, 12, 2, 15, 10));
|
||||
expect(choices[2].at, DateTime(2026, 12, 3, 9));
|
||||
});
|
||||
|
||||
test('the usage reset is offered only when it is known and ahead', () {
|
||||
final reset = DateTime(2026, 12, 2, 17, 21);
|
||||
expect(chatSendLaterChoices(now, usageReset: reset).last, (
|
||||
kind: ChatSendLaterKind.usageReset,
|
||||
at: reset,
|
||||
));
|
||||
expect(
|
||||
chatSendLaterChoices(now, usageReset: now).map((c) => c.kind),
|
||||
isNot(contains(ChatSendLaterKind.usageReset)),
|
||||
);
|
||||
});
|
||||
|
||||
test('the reset: an exhausted window first, else the next reset', () {
|
||||
final soon = DateTime(2026, 12, 2, 17, 20).millisecondsSinceEpoch;
|
||||
final later = DateTime(2026, 12, 5, 9).millisecondsSinceEpoch;
|
||||
final reset = chatSendLaterUsageReset(
|
||||
_usage([
|
||||
ChatQuotaWindow(
|
||||
id: 'five_hour',
|
||||
label: '5-hour',
|
||||
usedPercent: 40,
|
||||
resetsAt: soon,
|
||||
),
|
||||
ChatQuotaWindow(
|
||||
id: 'week',
|
||||
label: 'Weekly',
|
||||
usedPercent: 100,
|
||||
resetsAt: later,
|
||||
),
|
||||
]),
|
||||
now,
|
||||
);
|
||||
expect(reset, DateTime(2026, 12, 5, 9, 1));
|
||||
expect(
|
||||
chatSendLaterUsageReset(
|
||||
_usage([
|
||||
ChatQuotaWindow(
|
||||
id: 'five_hour',
|
||||
label: '5-hour',
|
||||
usedPercent: 40,
|
||||
resetsAt: soon,
|
||||
),
|
||||
]),
|
||||
now,
|
||||
),
|
||||
DateTime(2026, 12, 2, 17, 21),
|
||||
);
|
||||
expect(chatSendLaterUsageReset(_usage(const []), now), isNull);
|
||||
expect(chatSendLaterUsageReset(null, now), isNull);
|
||||
});
|
||||
|
||||
test('a picked time is today when ahead, else tomorrow', () {
|
||||
expect(chatSendLaterAt(now, 18, 30), DateTime(2026, 12, 2, 18, 30));
|
||||
expect(chatSendLaterAt(now, 8, 0), DateTime(2026, 12, 3, 8));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/data/chat_create_harness_store.dart';
|
||||
import 'package:pipelines_app/features/chat/data/chat_create_prompt_store.dart';
|
||||
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/sessions/create_chat_dialog.dart';
|
||||
|
||||
import 'fake_chat_gateway.dart';
|
||||
|
||||
class _NoPrompts implements ChatCreatePromptStore {
|
||||
@override
|
||||
Future<ChatCreatePrompt?> read(String backend, String directory) async =>
|
||||
null;
|
||||
|
||||
@override
|
||||
Future<void> write(String b, String d, ChatCreatePrompt v) async {}
|
||||
}
|
||||
|
||||
Future<List<ChatDraft>> _open(
|
||||
WidgetTester tester,
|
||||
ChatCreateHarnessStore harnesses,
|
||||
) async {
|
||||
final sent = <ChatDraft>[];
|
||||
final gateway = FakeChatGateway()
|
||||
..directoriesHandler = (() async => {
|
||||
'chat_directories': ['/home/me', '/work/app', '/work/site'],
|
||||
})
|
||||
..backendsHandler = (() async => {
|
||||
'chat_backends': ['claude', 'codex', 'opencode'],
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: CreateChatDialog(
|
||||
repository: ChatRepository(gateway),
|
||||
operationId: 'op',
|
||||
prompts: _NoPrompts(),
|
||||
harnesses: harnesses,
|
||||
onSubmit: (draft, _) async {
|
||||
sent.add(draft);
|
||||
return {'id': 'new'};
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
return sent;
|
||||
}
|
||||
|
||||
String _field(WidgetTester tester, String key) => tester
|
||||
.widget<DropdownButtonFormField<String>>(find.byKey(Key(key)))
|
||||
.initialValue!;
|
||||
|
||||
String _name(WidgetTester tester) => tester
|
||||
.widget<TextField>(find.byKey(const Key('chat-create-name')))
|
||||
.controller!
|
||||
.text;
|
||||
|
||||
Future<void> _pickDirectory(WidgetTester tester, String directory) async {
|
||||
await tester.tap(find.byKey(const Key('chat-create-server-directory')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(directory).last);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> _confirm(WidgetTester tester) async {
|
||||
await tester.ensureVisible(find.byKey(const Key('chat-create-confirm')));
|
||||
await tester.tap(find.byKey(const Key('chat-create-confirm')));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('the default harness: folder, then anywhere, then OpenCode', () {
|
||||
const offered = ['claude', 'codex', 'opencode'];
|
||||
expect(
|
||||
chatDefaultHarness(offered, directoryLast: 'codex', anywhereLast: 'x'),
|
||||
'codex',
|
||||
);
|
||||
expect(
|
||||
chatDefaultHarness(offered, directoryLast: 'pi', anywhereLast: 'claude'),
|
||||
'claude',
|
||||
);
|
||||
expect(chatDefaultHarness(offered), 'opencode');
|
||||
expect(chatDefaultHarness(const ['codex', 'claude']), 'codex');
|
||||
});
|
||||
|
||||
testWidgets('the name is prefilled; cleared, the harness names the chat', (
|
||||
tester,
|
||||
) async {
|
||||
final sent = await _open(tester, MemoryChatCreateHarnessStore());
|
||||
expect(_name(tester), 'Home OpenCode');
|
||||
expect(find.text("Leave empty to use the harness's title"), findsOneWidget);
|
||||
await tester.enterText(find.byKey(const Key('chat-create-name')), '');
|
||||
await _pickDirectory(tester, '/work/app');
|
||||
// A cleared name stays cleared when the folder changes.
|
||||
expect(_name(tester), '');
|
||||
await _confirm(tester);
|
||||
expect(sent.single.title, '');
|
||||
expect(sent.single.directory, '/work/app');
|
||||
});
|
||||
|
||||
testWidgets('the harness follows the folder it was last used in', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryChatCreateHarnessStore(
|
||||
byDirectory: {'/work/app': 'codex'},
|
||||
last: 'claude',
|
||||
);
|
||||
final sent = await _open(tester, store);
|
||||
// Home remembers none: the harness last used anywhere.
|
||||
expect(_field(tester, 'chat-create-backend'), 'claude');
|
||||
expect(_name(tester), 'Home Claude');
|
||||
|
||||
await _pickDirectory(tester, '/work/app');
|
||||
expect(_field(tester, 'chat-create-backend'), 'codex');
|
||||
expect(_name(tester), 'App Codex');
|
||||
|
||||
await _confirm(tester);
|
||||
expect(sent.single.backend, 'codex');
|
||||
expect(sent.single.title, 'App Codex');
|
||||
expect(store.byDirectory['/work/app'], 'codex');
|
||||
expect(store.last, 'codex');
|
||||
});
|
||||
|
||||
testWidgets('an explicit pick stays for a folder that remembers none', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryChatCreateHarnessStore(
|
||||
byDirectory: {'/work/app': 'codex'},
|
||||
);
|
||||
await _open(tester, store);
|
||||
expect(_field(tester, 'chat-create-backend'), 'opencode');
|
||||
await tester.tap(find.byKey(const Key('chat-create-backend')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Claude').last);
|
||||
await tester.pumpAndSettle();
|
||||
await _pickDirectory(tester, '/work/site');
|
||||
expect(_field(tester, 'chat-create-backend'), 'claude');
|
||||
await _pickDirectory(tester, '/work/app');
|
||||
expect(_field(tester, 'chat-create-backend'), 'codex');
|
||||
});
|
||||
}
|
||||
@@ -156,7 +156,7 @@ void main() {
|
||||
_host(
|
||||
child: const ChatMarkdownView(
|
||||
text:
|
||||
'```\nvery_long_identifier_very_long_identifier_very_long_identifier\n```\n\n| Heading one | Heading two | Heading three |\n| --- | --- | --- |\n| alpha alpha alpha | beta beta beta | gamma gamma gamma |',
|
||||
'```\nvery_long_identifier_very_long_identifier_very_long_identifier\n```\n\n| H1 | H2 | H3 |\n| --- | --- | --- |\n| a a a a a a a a | b b b b b b | c c c c c c |',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -23,16 +23,11 @@ void main() {
|
||||
) async {
|
||||
await pumpTable(
|
||||
tester,
|
||||
'| Item | Description | Status |\n| --- | --- | --- |\n'
|
||||
// Short words, so every column's longest word fits side by side.
|
||||
'| No | Text | Ok |\n| --- | --- | --- |\n'
|
||||
'| one | ${List.filled(30, 'word').join(' ')} | done |',
|
||||
);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(ChatMarkdownView),
|
||||
matching: find.byType(Scrollable),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsNothing);
|
||||
expect(tableRect(tester).right, lessThanOrEqualTo(screenRight));
|
||||
final description = tester.getSize(find.textContaining('word word'));
|
||||
final status = tester.getSize(find.text('done'));
|
||||
@@ -49,6 +44,44 @@ void main() {
|
||||
expect(tableRect(tester).right, lessThanOrEqualTo(screenRight));
|
||||
});
|
||||
|
||||
testWidgets('a word is never broken to fit; the table scrolls instead', (
|
||||
tester,
|
||||
) async {
|
||||
// Seven columns whose words cannot all fit 390 pixels side by side.
|
||||
const words = ['Column', 'Another', 'Heading', 'Numbers', 'Remarks'];
|
||||
await pumpTable(
|
||||
tester,
|
||||
'| ${words.join(' | ')} | Owner | Status |\n'
|
||||
'| --- | --- | --- | --- | --- | --- | --- |\n'
|
||||
'| a b | c d | e f | g h | i j | k l | m n |',
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsOneWidget);
|
||||
expect(
|
||||
find.bySemanticsLabel('Horizontally scrollable table'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(tableRect(tester).width, greaterThan(screenRight));
|
||||
// Each heading stays on one line: no word broke inside itself.
|
||||
final line = tester.getSize(find.text('Owner')).height;
|
||||
for (final word in words) {
|
||||
expect(tester.getSize(find.text(word)).height, line);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('a column keeps its longest word when the table fits', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpTable(
|
||||
tester,
|
||||
'| Column | Notes |\n| --- | --- |\n'
|
||||
'| x | ${List.filled(40, 'note').join(' ')} |',
|
||||
);
|
||||
expect(find.text('Scroll horizontally'), findsNothing);
|
||||
expect(tableRect(tester).right, lessThanOrEqualTo(screenRight));
|
||||
final header = tester.getSize(find.text('Column')).height;
|
||||
expect(header, tester.getSize(find.text('x')).height);
|
||||
});
|
||||
|
||||
testWidgets('a narrow table keeps its content width', (tester) async {
|
||||
await pumpTable(tester, '| a | b |\n| --- | --- |\n| 1 | 2 |');
|
||||
expect(tableRect(tester).width, lessThan(screenRight / 2));
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
// one with a failed command) split by background-task notices;
|
||||
// `?links=1` answers and operator turns carry a markdown link, an
|
||||
// autolink, a bare URL and URLs inside code (linked too);
|
||||
// `?tables=1` answers carry a wrapping table, one with a long token and
|
||||
// one too wide for a phone (it scrolls sideways);
|
||||
// `?timestamps=1` messages carry recorded times over two calendar days.
|
||||
import 'dart:async';
|
||||
|
||||
@@ -144,9 +146,27 @@ String _answer(int i) {
|
||||
: '';
|
||||
return '## Answer $i\n\nSome **bold** text with `code`.\n\n'
|
||||
'```dart\n${List.generate(8, (l) => 'final v$l = $i * $l;').join('\n')}'
|
||||
'\n```\n$wide\n- one\n- two\n${_links ? _answerLinks : ''}';
|
||||
'\n```\n$wide${_tables ? _answerTables : ''}\n- one\n- two\n'
|
||||
'${_links ? _answerLinks : ''}';
|
||||
}
|
||||
|
||||
bool get _tables => _params['tables'] == '1';
|
||||
|
||||
/// `?tables=1`: a table whose prose wraps to fit, one with a long unbroken
|
||||
/// token, and one whose words cannot fit a phone side by side.
|
||||
const _answerTables =
|
||||
'\n| Column | Description | Status |\n| --- | --- | --- |\n'
|
||||
'| Parser | Reads the markdown source and keeps each table cell as '
|
||||
'written, so wrapping happens only between words | Done |\n'
|
||||
'| Renderer | Lays the cells out at the transcript width | Review |\n\n'
|
||||
'| Commit | Link |\n| --- | --- |\n'
|
||||
'| 4f1c2a9 | https://example.com/pipelines/commit/'
|
||||
'4f1c2a9e0b7d3c6f5a8e1d2c3b4a5f6e7d8c9b0a |\n\n'
|
||||
'| Component | Ownership | Lifecycle | Dependencies | Deployment | '
|
||||
'Monitoring |\n| --- | --- | --- | --- | --- | --- |\n'
|
||||
'| scheduler | platform | long-lived | database | kubernetes | '
|
||||
'prometheus |\n\n';
|
||||
|
||||
const _answerLinks =
|
||||
'\nRead [the release notes](https://example.com/releases/v2) or '
|
||||
'<https://example.com/auto>; the bare https://example.com/bare/path. '
|
||||
|
||||
@@ -170,6 +170,10 @@ String? _liveRunStatus;
|
||||
bool _htmlArtifact = false;
|
||||
bool _warnings = false;
|
||||
|
||||
/// `?harnesses=1` offers three chat harnesses and two workspace folders in the
|
||||
/// New chat dialog, so its per-folder harness default can be reviewed.
|
||||
bool _harnesses = false;
|
||||
|
||||
/// `?turn=1` adds the runner-internal turn files the server records for a model
|
||||
/// visit (group `debug`) to run 7's build visit, so the Artifacts tab's hidden
|
||||
/// Debugging files group can be reviewed.
|
||||
@@ -584,13 +588,17 @@ JsonMap? probeReply(JsonMap request) {
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'chat_backends',
|
||||
'chat_backends': ['opencode'],
|
||||
'chat_backends': _harnesses
|
||||
? ['claude', 'codex', 'opencode']
|
||||
: ['opencode'],
|
||||
};
|
||||
case 'chat_directories':
|
||||
return {
|
||||
'id': id,
|
||||
'type': 'chat_directories',
|
||||
'chat_directories': ['/Users/fixture/workspace'],
|
||||
'chat_directories': _harnesses
|
||||
? ['/Users/fixture', '/Users/fixture/app', '/Users/fixture/site']
|
||||
: ['/Users/fixture/workspace'],
|
||||
};
|
||||
case 'chat_sessions':
|
||||
return {
|
||||
@@ -963,6 +971,7 @@ Future<void> main() async {
|
||||
probeUsage = params['usage'] == '1';
|
||||
_htmlArtifact = params['html'] == '1';
|
||||
_warnings = params['warnings'] == '1';
|
||||
_harnesses = params['harnesses'] == '1';
|
||||
_turnFiles = params['turn'] == '1';
|
||||
final route = params['route'];
|
||||
final opensRoute = route != null && route.startsWith('/');
|
||||
|
||||
@@ -555,7 +555,9 @@ func (c *Chat) ActivateSkill(ctx context.Context, id, skill string) error {
|
||||
|
||||
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
body := struct {
|
||||
Title string `json:"title"`
|
||||
// Omitted when blank, so OpenCode gives the session its placeholder
|
||||
// title and later names it from the conversation.
|
||||
Title string `json:"title,omitempty"`
|
||||
Location struct {
|
||||
Directory string `json:"directory"`
|
||||
} `json:"location"`
|
||||
|
||||
@@ -838,6 +838,26 @@ func TestChatCreatePostsSessionEndpoint(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCreateWithoutTitleOmitsIt pins that an unnamed chat sends no title,
|
||||
// so OpenCode keeps its placeholder and later names the session itself.
|
||||
func TestChatCreateWithoutTitleOmitsIt(t *testing.T) {
|
||||
var body string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
body = string(data)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":{"id":"ses_new","title":"New session - 2026-12-02T09:00:00.000Z","location":{"directory":"/work"}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
if _, err := chat.Create(context.Background(), "", "/work"); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if body != `{"location":{"directory":"/work"}}` {
|
||||
t.Fatalf("create body = %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCreateRejectsMalformedSession pins that a response without a valid
|
||||
// session id is an error, not a silent empty success.
|
||||
func TestChatCreateRejectsMalformedSession(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// A chat created without a name records no operator title, so the list shows
|
||||
// the harness's own title for it; a named chat keeps the operator's name.
|
||||
func TestChatCreateWithoutTitleListsTheHarnessTitle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
store := newOperatorStore(t)
|
||||
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_untitled"}}
|
||||
var created protocol.Message
|
||||
handleChatCreate(ctx, protocol.Message{ID: "c1", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Directory: dir, OperationID: "op-untitled"}}, broker, store, func(message protocol.Message) error {
|
||||
created = message
|
||||
return nil
|
||||
})
|
||||
if created.Type != protocol.ChatCreate {
|
||||
t.Fatalf("create reply = %#v", created)
|
||||
}
|
||||
if _, title, _ := broker.createQuery(); title != "" {
|
||||
t.Fatalf("harness asked to create %q, want no title", title)
|
||||
}
|
||||
rows, err := store.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].Title != "" {
|
||||
t.Fatalf("registry rows = %+v, want one without a title", rows)
|
||||
}
|
||||
|
||||
broker.mu.Lock()
|
||||
broker.sessions = []protocol.ChatSession{{ID: "ses_untitled", Title: "Fix the flaky test"}}
|
||||
broker.mu.Unlock()
|
||||
var listed protocol.Message
|
||||
handleChatSessions(ctx, protocol.Message{ID: "list", Type: protocol.ChatSessions}, broker, nil, store, func(message protocol.Message) error {
|
||||
listed = message
|
||||
return nil
|
||||
})
|
||||
if len(listed.ChatSessions) != 1 || listed.ChatSessions[0].Title != "Fix the flaky test" {
|
||||
t.Fatalf("listed = %+v, want the harness title", listed.ChatSessions)
|
||||
}
|
||||
}
|
||||
@@ -158,9 +158,8 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
if operationID == "" {
|
||||
operationID = chatClientToken()
|
||||
}
|
||||
if title == "" {
|
||||
title = "New chat"
|
||||
}
|
||||
// A blank title records no operator title: the list then shows the
|
||||
// harness's own title for the chat (see handleChatSessions).
|
||||
resolved, err := resolveChatDirectory(directory)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
|
||||
Reference in New Issue
Block a user