Merge main into macos-self-update

This commit is contained in:
2026-11-13 14:34:21 +00:00
56 changed files with 1972 additions and 130 deletions
+100
View File
@@ -0,0 +1,100 @@
import 'package:flutter/material.dart';
import '../core/api_gateway.dart';
import '../features/chat/chat_runtime.dart';
import '../features/chat/ui/sessions/chat_create_fields.dart';
import '../features/settings/settings_store.dart';
import 'open_in_chat_preferences.dart';
typedef OpenInChat = Future<void> Function(BuildContext context);
String runChatReference(JsonMap run) {
final id = run['id'];
// A run summary names its pipeline in `name`; `title` is the run's own
// title, empty for an untitled run.
final title = '${run['title'] ?? ''}'.trim();
final pipeline =
'${run['pipeline_name'] ?? run['pipeline'] ?? run['name'] ?? ''}'.trim();
final version = '${run['pipeline_version'] ?? run['version'] ?? ''}'.trim();
final status = '${run['status'] ?? ''}'.trim();
return 'About Pipelines run #$id "${title.isEmpty ? 'Run $id' : title}" '
'(pipeline "${pipeline.isEmpty ? 'unknown' : pipeline}"'
'${version.isEmpty ? '' : ' v$version'}, status $status). '
'Inspect it with `pipelines inspect $id`.';
}
String pipelineChatReference(int id, String name, int version) =>
'About pipeline "$name" (id $id, version $version). '
'Show it with `pipelines show "$name"`; to change it, draft with '
'`pipelines edit` and publish with `pipelines submit`.';
/// Creates and opens a chat without showing the general-purpose create dialog.
/// The caller supplies the already-resolved directory so run and pipeline
/// screens can apply their own workspace provenance rules.
Future<void> openReferenceInChat({
required BuildContext context,
required ChatRuntime runtime,
required ValueChanged<String> selectChat,
required String directory,
required String title,
required String draft,
}) async {
try {
// Match the New chat dialog: prefer OpenCode when it is available, but
// use the first server-advertised harness on installations where it is
// not. Do not invent a backend when the catalog cannot be read.
final repository = runtime.sessions.repository;
final backends = await repository.backends();
final chosen = await OpenInChatPreferences.load(repository.gateway);
// The harness chosen in Settings → Open in chat, when the server offers it.
final backend = backends.contains(chosen.harness)
? chosen.harness
: backends.contains('opencode')
? 'opencode'
: backends.first;
final session = await runtime.sessions.createOrThrow(
title: title,
directory: directory.trim().isEmpty ? chatHomeDirectory : directory,
backend: backend,
instructions: '',
operationId: 'open-in-chat-${DateTime.now().microsecondsSinceEpoch}',
);
final id = '${session['id'] ?? ''}';
if (id.isEmpty) throw StateError('The new chat has no id.');
if (chosen.hasModel && backend == chosen.harness) {
try {
await repository.selectModel(id, chosen.provider, chosen.model);
} catch (error) {
// The chat still opens on the harness default; say why.
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Opened with the default model: ${chosen.model} is not '
'available ($error).',
),
),
);
}
}
}
runtime.opened[id] = session;
runtime.pendingDrafts[id] = draft;
runtime.openedForWork.add(id);
selectChat(id);
runtime.composerFocus.request(id);
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Could not open in chat: $error')));
}
}
}
Future<String> settingsWorkspace(String serverId) async {
final values = await SharedPreferencesSettingsStore(
serverId: serverId,
).load();
return values.workspace.trim();
}
@@ -0,0 +1,43 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../core/api_gateway.dart';
import '../core/servers/server_scope.dart';
const openInChatPreferenceKey = 'pipelines.openInChat.v1';
/// The harness and model Open in chat starts its chats with, per server and
/// device. Empty fields mean the default: the New chat dialog's harness and
/// the harness's own default model.
class OpenInChatPreferences {
const OpenInChatPreferences({
this.harness = '',
this.provider = '',
this.model = '',
});
final String harness;
final String provider;
final String model;
bool get hasModel => provider.isNotEmpty && model.isNotEmpty;
static String _key(ApiGateway gateway) => scopedServerKey(
openInChatPreferenceKey,
serverStorageScope(serverIdentity(gateway)),
);
static Future<OpenInChatPreferences> load(ApiGateway gateway) async {
final values =
(await SharedPreferences.getInstance()).getStringList(_key(gateway)) ??
const [];
String at(int index) => index < values.length ? values[index].trim() : '';
return OpenInChatPreferences(harness: at(0), provider: at(1), model: at(2));
}
Future<bool> save(ApiGateway gateway) async =>
(await SharedPreferences.getInstance()).setStringList(_key(gateway), [
harness,
provider,
model,
]);
}
+65 -1
View File
@@ -7,7 +7,7 @@ import '../features/runs/domain/run_tab_counts.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart'; import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/material.dart';
import '../core/api_gateway.dart'; import '../core/api_gateway.dart';
import '../core/servers/server_scope.dart'; import '../core/servers/server_scope.dart';
@@ -48,6 +48,8 @@ import '../shell/windows/window_store.dart';
import 'app_terminals.dart'; import 'app_terminals.dart';
import '../features/chat/chat_runtime.dart'; import '../features/chat/chat_runtime.dart';
import '../features/chat/windows/chat_windows.dart'; import '../features/chat/windows/chat_windows.dart';
import 'open_in_chat.dart';
import '../features/pipelines/pipeline_models.dart';
import '../features/chat/workspace/chat_float_store.dart'; import '../features/chat/workspace/chat_float_store.dart';
import '../features/terminal/terminal_layout.dart'; import '../features/terminal/terminal_layout.dart';
import 'app_route.dart'; import 'app_route.dart';
@@ -144,6 +146,63 @@ class PipelinesApp extends StatefulWidget {
class _PipelinesAppState extends State<PipelinesApp> class _PipelinesAppState extends State<PipelinesApp>
with WidgetsBindingObserver { with WidgetsBindingObserver {
Future<void> _openRunInChat(BuildContext context, JsonMap run) async {
try {
final directory = '${run['workspace'] ?? run['directory'] ?? ''}'.trim();
final fallback = directory.isEmpty
? await settingsWorkspace(serverIdentity(_session.gateway) ?? '')
: directory;
if (!context.mounted) return;
await openReferenceInChat(
context: context,
runtime: _chatRuntime,
selectChat: (id) => _delegate.goTo(AppRoute.chatSession(id)),
directory: fallback,
title:
'Run #${run['id']}: ${'${run['title'] ?? run['name'] ?? ''}'.trim()}',
draft: runChatReference(run),
);
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Could not open in chat: $error')),
);
}
}
}
Future<void> _openPipelineInChat(
BuildContext context,
PipelineSummary pipeline,
PipelineRun? latestRun,
) async {
try {
final directory = latestRun?.workspace.trim() ?? '';
final fallback = directory.isEmpty
? await settingsWorkspace(serverIdentity(_session.gateway) ?? '')
: directory;
if (!context.mounted) return;
await openReferenceInChat(
context: context,
runtime: _chatRuntime,
selectChat: (id) => _delegate.goTo(AppRoute.chatSession(id)),
directory: fallback,
title: 'Pipeline: ${pipeline.displayName}',
draft: pipelineChatReference(
pipeline.id,
pipeline.displayName,
pipeline.version,
),
);
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Could not open in chat: $error')),
);
}
}
}
late final AppSession _session; late final AppSession _session;
late final AppRouterDelegate _delegate; late final AppRouterDelegate _delegate;
late final ElevationPrompt _elevationPrompt = elevationDialogPrompt( late final ElevationPrompt _elevationPrompt = elevationDialogPrompt(
@@ -941,6 +1000,10 @@ class _PipelinesAppState extends State<PipelinesApp>
_delegate.goTo(AppRoute.runsForPipeline(id)), _delegate.goTo(AppRoute.runsForPipeline(id)),
onOpenSchedules: _delegate.openSchedules, onOpenSchedules: _delegate.openSchedules,
onOpenSettings: () => _delegate.goTo(AppRoute.settings), onOpenSettings: () => _delegate.goTo(AppRoute.settings),
onOpenInChat: (context, detail, run) =>
_openPipelineInChat(context, detail, run),
onOpenPipelineInChat: (context, summary, run) =>
_openPipelineInChat(context, summary, run),
// The open pipeline is part of the route, so Back steps out of it. // The open pipeline is part of the route, so Back steps out of it.
onSelectionChanged: (id) { onSelectionChanged: (id) {
final current = _delegate.route; final current = _delegate.route;
@@ -983,6 +1046,7 @@ class _PipelinesAppState extends State<PipelinesApp>
), ),
onOpenPipeline: (id, version) => onOpenPipeline: (id, version) =>
_delegate.goTo(AppRoute.pipeline(id, version: version)), _delegate.goTo(AppRoute.pipeline(id, version: version)),
onOpenInChat: _openRunInChat,
), ),
), ),
AppDestination.chat: (_) => ChatDestination( AppDestination.chat: (_) => ChatDestination(
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../features/pipelines/screen.dart'; import '../features/pipelines/screen.dart';
import '../features/pipelines/pipeline_models.dart';
import '../ui/adaptive/top_bar_notices.dart'; import '../ui/adaptive/top_bar_notices.dart';
import 'app_session.dart'; import 'app_session.dart';
import 'connection_status.dart'; import 'connection_status.dart';
@@ -29,6 +30,8 @@ class PipelinesDestination extends StatelessWidget {
this.initialVersion = 0, this.initialVersion = 0,
this.initialStageKey, this.initialStageKey,
this.legacyPendingEndpoints = const [], this.legacyPendingEndpoints = const [],
this.onOpenInChat,
this.onOpenPipelineInChat,
}); });
final AppSession session; final AppSession session;
@@ -58,6 +61,10 @@ class PipelinesDestination extends StatelessWidget {
/// The definition stage a deep link names, or null for no stage request. /// The definition stage a deep link names, or null for no stage request.
final String? initialStageKey; final String? initialStageKey;
final List<String> legacyPendingEndpoints; final List<String> legacyPendingEndpoints;
final Future<void> Function(BuildContext, PipelineDetail, PipelineRun?)?
onOpenInChat;
final Future<void> Function(BuildContext, PipelineSummary, PipelineRun?)?
onOpenPipelineInChat;
@override @override
Widget build(BuildContext context) => AnimatedBuilder( Widget build(BuildContext context) => AnimatedBuilder(
@@ -91,6 +98,8 @@ class PipelinesDestination extends StatelessWidget {
onOpenSchedules: onOpenSchedules, onOpenSchedules: onOpenSchedules,
onOpenSettings: onOpenSettings, onOpenSettings: onOpenSettings,
onSelectionChanged: onSelectionChanged, onSelectionChanged: onSelectionChanged,
onOpenInChat: onOpenInChat,
onOpenPipelineInChat: onOpenPipelineInChat,
initialPipelineId: initialPipelineId, initialPipelineId: initialPipelineId,
initialVersion: initialVersion, initialVersion: initialVersion,
initialStageKey: initialStageKey, initialStageKey: initialStageKey,
@@ -10,6 +10,7 @@ import 'app_session.dart';
import 'connection_status.dart'; import 'connection_status.dart';
import 'pending_run_scope.dart'; import 'pending_run_scope.dart';
import 'server_endpoint.dart'; import 'server_endpoint.dart';
import '../core/api_gateway.dart';
/// The Runs destination: the loaded screen plus an honest connection status. /// The Runs destination: the loaded screen plus an honest connection status.
/// ///
@@ -34,6 +35,7 @@ class RunsDestination extends StatelessWidget {
this.listRefreshToken = 0, this.listRefreshToken = 0,
this.notifications, this.notifications,
this.attention, this.attention,
this.onOpenInChat,
}); });
final AppSession session; final AppSession session;
@@ -65,6 +67,7 @@ class RunsDestination extends StatelessWidget {
/// The app-level attention controller the shell's Runs tab badge reads. /// The app-level attention controller the shell's Runs tab badge reads.
final AttentionController? attention; final AttentionController? attention;
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
@override @override
Widget build(BuildContext context) => AnimatedBuilder( Widget build(BuildContext context) => AnimatedBuilder(
@@ -109,5 +112,6 @@ class RunsDestination extends StatelessWidget {
onBack: onBack, onBack: onBack,
onPipelineFilterChanged: onPipelineFilterChanged, onPipelineFilterChanged: onPipelineFilterChanged,
onOpenPipeline: onOpenPipeline, onOpenPipeline: onOpenPipeline,
onOpenInChat: onOpenInChat,
); );
} }
@@ -91,6 +91,7 @@ Widget buildChatPaneContent({
sessionId: sessionId, sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(), title: '${row?['title'] ?? ''}'.trim(),
session: row, session: row,
initialDraft: runtime.pendingDrafts.remove(sessionId),
syncToken: placement.syncToken, syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions, scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts, transcripts: runtime.transcripts,
+10
View File
@@ -96,6 +96,16 @@ class ChatRuntime extends ChangeNotifier {
/// link) resolves the same row without a second list request. /// link) resolves the same row without a second list request.
final Map<String, JsonMap> opened = {}; final Map<String, JsonMap> opened = {};
/// Drafts seeded by an external action such as Open in chat. They are
/// consumed by the first composer for that session.
final Map<String, String> pendingDrafts = {};
/// Chats an external action (Open in chat) opened for the operator to work
/// in: the chat screen shows each beside the active chat rather than in
/// its place, makes it active and puts the keyboard in its composer once
/// it is on screen.
final Set<String> openedForWork = {};
/// Each row as the list last reported it (without its live `running`), so /// Each row as the list last reported it (without its live `running`), so
/// [adoptRows] adopts only what a re-read changed. /// [adoptRows] adopts only what a re-read changed.
final Map<String, JsonMap> _listed = {}; final Map<String, JsonMap> _listed = {};
@@ -2,6 +2,8 @@ part of 'screen.dart';
/// Pane layout, focus and route publication for one Chat destination visit. /// Pane layout, focus and route publication for one Chat destination visit.
mixin _ChatScreenWorkspace on State<ChatScreen> { mixin _ChatScreenWorkspace on State<ChatScreen> {
final _sessionsKey = GlobalKey<ChatSessionsScreenState>();
Map<String, JsonMap> get _openedSessions; Map<String, JsonMap> get _openedSessions;
ChatComposerFocusRequests get _composerFocus; ChatComposerFocusRequests get _composerFocus;
ChatPaneCommands get _paneCommands; ChatPaneCommands get _paneCommands;
@@ -46,6 +48,10 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
activeSessionId: selected, activeSessionId: selected,
visibleSessionIds: _visibleSidebarSessions, visibleSessionIds: _visibleSidebarSessions,
onOpen: _openSidebarSession, onOpen: _openSidebarSession,
onNewChat: () {
final state = _sessionsKey.currentState;
if (state != null) unawaited(state.newChat());
},
onExpand: () => _setSidebarMode(ChatSidebarMode.expanded), onExpand: () => _setSidebarMode(ChatSidebarMode.expanded),
), ),
], ],
@@ -80,6 +86,25 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
ChatSectionFolds get _foldsForSidebar; ChatSectionFolds get _foldsForSidebar;
void _openSidebarSession(JsonMap session); void _openSidebarSession(JsonMap session);
void _dropSession(
ChatWorkspacePane target,
Object data,
ChatWorkspaceDropZone zone,
) {
if (data is! JsonMap) return;
final sessionId = '${data['id'] ?? ''}';
if (sessionId.isEmpty) return;
final windows = widget.windows;
final floating = windows?.windows
.where((window) => window.contentId == sessionId)
.firstOrNull;
if (floating != null) windows!.manager.close(floating.id);
_openedSessions[sessionId] = data;
_workspaceVisible = true;
_workspace.dropSession(sessionId, target.id, zone);
_composerFocus.request(sessionId);
}
final ChatWorkspaceController _workspace = ChatWorkspaceController(); final ChatWorkspaceController _workspace = ChatWorkspaceController();
ChatOpenWorkspaceController? _openWorkspace; ChatOpenWorkspaceController? _openWorkspace;
bool _applyingServerWorkspace = false; bool _applyingServerWorkspace = false;
@@ -278,14 +303,12 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
String? _publishedWorkspaceSession; String? _publishedWorkspaceSession;
String _workspaceSignature = ''; String _workspaceSignature = '';
/// Ctrl+Tab cycles the floating chat windows while any is shown, from the /// Ctrl+Tab cycles a single tiled pane through the open chats in sidebar
/// tiling as well (see [ChatWindows]). With none shown it cycles the /// order. The pane is replaced in place so its retained view keeps the
/// retained panes, even when the sidebar or toolbar owns focus, and over a /// transcript and draft. With multiple panes it cycles those panes. A
/// single pane it does nothing: it never brings up a chat that is not /// focused floating chat window handles the key itself (see [ChatWindows]).
/// visible in the tiling. Command+Tab stays with the operating system's /// Command+Tab stays with the operating system's application switcher, and
/// application switcher. While the app's terminal is shown, Ctrl+Tab moves /// the terminal keeps Ctrl+Tab for its own tabs.
/// between its tabs instead. A floating window that is not a chat, or any
/// other window holding the keyboard, keeps the key.
bool _cycleChatKey(KeyEvent event) { bool _cycleChatKey(KeyEvent event) {
final keyboard = HardwareKeyboard.instance; final keyboard = HardwareKeyboard.instance;
if (event is! KeyDownEvent || if (event is! KeyDownEvent ||
@@ -298,8 +321,48 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
!_chatOwnsKeyboard()) { !_chatOwnsKeyboard()) {
return false; return false;
} }
if (widget.windows?.raiseTopFromTiling() ?? false) return true; if (!_workspaceVisible || _workspace.paneCount == 0) return false;
if (!_workspaceVisible || _workspace.paneCount < 2) return false; if (_workspace.paneCount == 1) {
final pane = _workspace.activePane;
if (pane == null) return false;
final floating = widget.windows?.floatingSessionIds.toSet() ?? const {};
final sessions = chatSessionsShown(
_sessionsForSidebar.sessions
.where(
(row) =>
row['closed_at'] == null &&
row['closed'] != true &&
!floating.contains('${row['id'] ?? ''}'),
)
.toList(),
query: '',
// Cycling is independent of a collapsed section: the sidebar's
// ordering is still used, but every open-chat row remains reachable.
isOpen: (_) => true,
);
final active = sessions.indexWhere(
(row) => '${row['id'] ?? ''}' == pane.sessionId,
);
if (sessions.length < 2 || active < 0) return false;
final direction = keyboard.isShiftPressed ? -1 : 1;
final target = sessions[(active + direction) % sessions.length];
final targetId = '${target['id'] ?? ''}';
if (targetId.isEmpty) return false;
_workspace.replacePaneSession(pane.id, targetId);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted ||
!_workspaceVisible ||
_workspace.activePane?.sessionId != targetId) {
return;
}
final destination = ShellBarScope.maybeOf(context)?.registry.focus;
if (destination == null || destination == AppDestination.chat) {
_composerFocus.request(targetId);
}
});
WidgetsBinding.instance.ensureVisualUpdate();
return true;
}
final panes = _workspace.panes; final panes = _workspace.panes;
final active = panes.indexWhere( final active = panes.indexWhere(
(pane) => pane.id == _workspace.activePaneId, (pane) => pane.id == _workspace.activePaneId,
@@ -467,6 +530,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
paneTitle: (pane) => paneTitle: (pane) =>
'${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}',
onFocusPane: (pane) => _composerFocus.request(pane.sessionId), onFocusPane: (pane) => _composerFocus.request(pane.sessionId),
onDrop: _dropSession,
paneBuilder: (context, pane, active) { paneBuilder: (context, pane, active) {
final scope = ChatWorkspacePaneScope.maybeOf(context); final scope = ChatWorkspacePaneScope.maybeOf(context);
final topShared = scope?.topEdgeShared ?? false; final topShared = scope?.topEdgeShared ?? false;
@@ -114,6 +114,7 @@ class ChatThreadView extends StatefulWidget {
this.scrollPositions, this.scrollPositions,
this.transcripts, this.transcripts,
this.initialNotice, this.initialNotice,
this.initialDraft,
this.onNewSession, this.onNewSession,
this.onSessionRenamed, this.onSessionRenamed,
this.onSessionClosed, this.onSessionClosed,
@@ -157,6 +158,9 @@ class ChatThreadView extends StatefulWidget {
/// the `/new` notice for a session it just created and opened. /// the `/new` notice for a session it just created and opened.
final String? initialNotice; final String? initialNotice;
/// A draft supplied by an external deep action; it is never sent.
final String? initialDraft;
/// `/new` moved this chat to a fresh native session; the destination swaps /// `/new` moved this chat to a fresh native session; the destination swaps
/// the row in place, opens the new id with the notice and refreshes the /// the row in place, opens the new id with the notice and refreshes the
/// list. Without a destination the notice shows here instead. /// list. Without a destination the notice shows here instead.
@@ -528,6 +532,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
onAccepted: (send, queued) => onAccepted: (send, queued) =>
_controller.promptAccepted(send.operationId, queued: queued), _controller.promptAccepted(send.operationId, queued: queued),
); );
if (widget.initialDraft != null) {
unawaited(composer.setDraft(widget.initialDraft!));
}
// A message a previous visit sent but never saw accepted comes back as // A message a previous visit sent but never saw accepted comes back as
// "Not sent" unless the history read shows the server has it. // "Not sent" unless the history read shows the server has it.
unawaited( unawaited(
+31 -1
View File
@@ -354,6 +354,34 @@ class _ChatScreenState extends State<ChatScreen>
widget.onBack?.call(); widget.onBack?.call();
} }
/// Opens the chat the route names. A chat opened for work from elsewhere
/// (Open in chat) goes beside the active chat on a wide layout instead of
/// replacing it, and takes the keyboard once its composer is built.
void _openRouted(String id) {
if (!_runtime.openedForWork.remove(id)) {
_workspace.open(id);
return;
}
final beside =
!_page.open &&
showsListBesideDetail(context) &&
_workspace.paneCount > 0 &&
!_workspace.holdsSession(id);
if (beside) {
_workspace.splitActive(id, ChatSplitAxis.horizontal);
} else {
_workspace.open(id);
}
_composerFocus.request(id);
// The composer may be built a frame later (a new pane, a switched tab);
// ask again then so the request is never lost to the switch.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _workspace.activePane?.sessionId == id) {
_composerFocus.request(id);
}
});
}
/// On a phone the open chat is a real page above the main screen. /// On a phone the open chat is a real page above the main screen.
final DetailPageHost _page = DetailPageHost(); final DetailPageHost _page = DetailPageHost();
@@ -379,7 +407,7 @@ class _ChatScreenState extends State<ChatScreen>
if (id != null && id.isNotEmpty) { if (id != null && id.isNotEmpty) {
_workspaceVisible = true; _workspaceVisible = true;
_publishedWorkspaceSession = id; _publishedWorkspaceSession = id;
_workspace.open(id); _openRouted(id);
} else if (widget.onSessionSelected != null) { } else if (widget.onSessionSelected != null) {
_workspaceVisible = false; _workspaceVisible = false;
} }
@@ -485,12 +513,14 @@ class _ChatScreenState extends State<ChatScreen>
// The session list pads its first row by the bar's height itself, so it // The session list pads its first row by the bar's height itself, so it
// scrolls behind the shell's floating bar like the other lists. // scrolls behind the shell's floating bar like the other lists.
final sessions = ChatSessionsScreen( final sessions = ChatSessionsScreen(
key: _sessionsKey,
gateway: widget.gateway, gateway: widget.gateway,
embedded: true, embedded: true,
syncToken: widget.syncToken, syncToken: widget.syncToken,
controller: _sessions, controller: _sessions,
folds: _folds, folds: _folds,
onOpen: _openBySelection, onOpen: _openBySelection,
draggable: beside,
onOpenBeside: beside ? _openBeside : null, onOpenBeside: beside ? _openBeside : null,
onOpenBelow: _openBelow, onOpenBelow: _openBelow,
onFloat: _floatsHere ? _floatSession : null, onFloat: _floatsHere ? _floatSession : null,
@@ -23,6 +23,7 @@ class ChatCompactSidebar extends StatelessWidget {
required this.activeSessionId, required this.activeSessionId,
this.visibleSessionIds = const {}, this.visibleSessionIds = const {},
required this.onOpen, required this.onOpen,
required this.onNewChat,
required this.onExpand, required this.onExpand,
this.navigation, this.navigation,
}); });
@@ -31,6 +32,7 @@ class ChatCompactSidebar extends StatelessWidget {
final String? activeSessionId; final String? activeSessionId;
final Set<String> visibleSessionIds; final Set<String> visibleSessionIds;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final VoidCallback onNewChat;
final VoidCallback onExpand; final VoidCallback onExpand;
final Widget? navigation; final Widget? navigation;
static const width = 72.0; static const width = 72.0;
@@ -82,6 +84,38 @@ class ChatCompactSidebar extends StatelessWidget {
final color = final color =
chatColorShade(context, chatSessionColor(row)) ?? chatColorShade(context, chatSessionColor(row)) ??
Theme.of(context).colorScheme.primary; Theme.of(context).colorScheme.primary;
final button = _button(
context,
details,
ExcludeSemantics(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ChatCompactAvatar(
title: title,
color: color,
active: selected,
visible: visible,
running: running,
backgroundTasks: backgroundTasks,
unread: unread,
),
if (machineName case final name?)
Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.labelSmall,
),
],
),
),
() {
unawaited(controller.markOpened(row));
onOpen(row);
},
selected: selected,
);
return ChatVisibilityMarker( return ChatVisibilityMarker(
sessionId: id, sessionId: id,
color: color, color: color,
@@ -92,37 +126,29 @@ class ChatCompactSidebar extends StatelessWidget {
? Duration.zero ? Duration.zero
: const Duration(milliseconds: 200), : const Duration(milliseconds: 200),
color: selected ? Colors.transparent : color.withValues(alpha: .07), color: selected ? Colors.transparent : color.withValues(alpha: .07),
child: _button( child: Draggable<JsonMap>(
context, // A mouse drags at once (a click still opens the chat); the chip
details, // follows the pointer.
ExcludeSemantics( dragAnchorStrategy: pointerDragAnchorStrategy,
child: Column( data: row,
mainAxisSize: MainAxisSize.min, feedback: Material(
children: [ elevation: 4,
ChatCompactAvatar( borderRadius: BorderRadius.circular(20),
title: title, child: Chip(
color: color, avatar: ChatCompactAvatar(
active: selected, title: title,
visible: visible, color: color,
running: running, active: false,
backgroundTasks: backgroundTasks, visible: false,
unread: unread, running: running,
), backgroundTasks: backgroundTasks,
if (machineName case final name?) unread: unread,
Text( ),
name, label: Text(title),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.labelSmall,
),
],
), ),
), ),
() { childWhenDragging: Opacity(opacity: .35, child: button),
unawaited(controller.markOpened(row)); child: button,
onOpen(row);
},
selected: selected,
), ),
), ),
); );
@@ -135,6 +161,7 @@ class ChatCompactSidebar extends StatelessWidget {
width: width, width: width,
child: Column( child: Column(
children: [ children: [
_button(context, 'New chat', const Icon(Icons.add), onNewChat),
_button( _button(
context, context,
'Expand chat list', 'Expand chat list',
@@ -33,6 +33,7 @@ class ChatSessionsBody extends StatelessWidget {
required this.error, required this.error,
required this.onOpen, required this.onOpen,
this.onOpenBeside, this.onOpenBeside,
this.draggable = false,
this.onOpenBelow, this.onOpenBelow,
this.onFloat, this.onFloat,
this.paneMenu, this.paneMenu,
@@ -65,6 +66,7 @@ class ChatSessionsBody extends StatelessWidget {
final String? error; final String? error;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap>? onOpenBeside; final ValueChanged<JsonMap>? onOpenBeside;
final bool draggable;
final ValueChanged<JsonMap>? onOpenBelow; final ValueChanged<JsonMap>? onOpenBelow;
final ValueChanged<JsonMap>? onFloat; final ValueChanged<JsonMap>? onFloat;
final SessionPaneMenu? paneMenu; final SessionPaneMenu? paneMenu;
@@ -104,6 +106,7 @@ class ChatSessionsBody extends StatelessWidget {
duplicateTitles: duplicateTitles, duplicateTitles: duplicateTitles,
onOpen: onOpen, onOpen: onOpen,
onOpenBeside: onOpenBeside, onOpenBeside: onOpenBeside,
draggable: draggable,
onOpenBelow: onOpenBelow, onOpenBelow: onOpenBelow,
onFloat: onFloat, onFloat: onFloat,
paneMenu: paneMenu, paneMenu: paneMenu,
@@ -33,6 +33,7 @@ class ChatSessionsScreen extends StatefulWidget {
required this.gateway, required this.gateway,
required this.onOpen, required this.onOpen,
this.onOpenBeside, this.onOpenBeside,
this.draggable = false,
this.onOpenBelow, this.onOpenBelow,
this.onFloat, this.onFloat,
this.paneMenu, this.paneMenu,
@@ -52,6 +53,7 @@ class ChatSessionsScreen extends StatefulWidget {
/// Optional split-pane actions; absent when the host cannot offer a split. /// Optional split-pane actions; absent when the host cannot offer a split.
final ValueChanged<JsonMap>? onOpenBeside; final ValueChanged<JsonMap>? onOpenBeside;
final bool draggable;
final ValueChanged<JsonMap>? onOpenBelow; final ValueChanged<JsonMap>? onOpenBelow;
/// Floats the chat in a window over the app; absent when it cannot. /// Floats the chat in a window over the app; absent when it cannot.
@@ -98,10 +100,10 @@ class ChatSessionsScreen extends StatefulWidget {
final ChatSectionFolds? folds; final ChatSectionFolds? folds;
@override @override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState(); ChatSessionsScreenState createState() => ChatSessionsScreenState();
} }
class _ChatSessionsScreenState extends State<ChatSessionsScreen> { class ChatSessionsScreenState extends State<ChatSessionsScreen> {
late final ChatSessionsController _controller = late final ChatSessionsController _controller =
(widget.controller ?? (widget.controller ??
ChatSessionsController( ChatSessionsController(
@@ -233,6 +235,9 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
if (session != null && mounted) widget.onOpen(session); if (session != null && mounted) widget.onOpen(session);
} }
/// Starts the same machine picker and create dialog used by the list action.
Future<void> newChat() => _newChat();
void _markOpened(JsonMap session) => void _markOpened(JsonMap session) =>
unawaited(_controller.markOpened(session)); unawaited(_controller.markOpened(session));
@@ -333,6 +338,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
onOpenBeside: widget.onOpenBeside == null onOpenBeside: widget.onOpenBeside == null
? null ? null
: _openBeside, : _openBeside,
draggable: widget.draggable,
onOpenBelow: widget.onOpenBelow == null onOpenBelow: widget.onOpenBelow == null
? null ? null
: _openBelow, : _openBelow,
@@ -88,6 +88,7 @@ SessionListItem chatSessionRowItem(
required Set<String> duplicateTitles, required Set<String> duplicateTitles,
required bool Function(JsonMap) isUnseen, required bool Function(JsonMap) isUnseen,
required ValueChanged<JsonMap> onOpen, required ValueChanged<JsonMap> onOpen,
bool draggable = false,
ValueChanged<JsonMap>? onOpenBeside, ValueChanged<JsonMap>? onOpenBeside,
ValueChanged<JsonMap>? onOpenBelow, ValueChanged<JsonMap>? onOpenBelow,
ValueChanged<JsonMap>? onFloat, ValueChanged<JsonMap>? onFloat,
@@ -112,6 +113,7 @@ SessionListItem chatSessionRowItem(
unseen: isUnseen(session), unseen: isUnseen(session),
divider: divider, divider: divider,
onOpen: onOpen, onOpen: onOpen,
draggable: draggable,
onOpenBeside: onOpenBeside, onOpenBeside: onOpenBeside,
onOpenBelow: onOpenBelow, onOpenBelow: onOpenBelow,
onFloat: onFloat, onFloat: onFloat,
@@ -14,6 +14,7 @@ class MaterialSessionList extends StatelessWidget {
required this.emptyMessage, required this.emptyMessage,
required this.duplicateTitles, required this.duplicateTitles,
required this.onOpen, required this.onOpen,
this.draggable = false,
this.onOpenBeside, this.onOpenBeside,
this.onOpenBelow, this.onOpenBelow,
this.onFloat, this.onFloat,
@@ -42,6 +43,7 @@ class MaterialSessionList extends StatelessWidget {
final String? emptyMessage; final String? emptyMessage;
final Set<String> duplicateTitles; final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final bool draggable;
final ValueChanged<JsonMap>? onOpenBeside; final ValueChanged<JsonMap>? onOpenBeside;
final ValueChanged<JsonMap>? onOpenBelow; final ValueChanged<JsonMap>? onOpenBelow;
final ValueChanged<JsonMap>? onFloat; final ValueChanged<JsonMap>? onFloat;
@@ -117,6 +119,7 @@ class MaterialSessionList extends StatelessWidget {
duplicateTitles: duplicateTitles, duplicateTitles: duplicateTitles,
isUnseen: isUnseen, isUnseen: isUnseen,
onOpen: onOpen, onOpen: onOpen,
draggable: draggable,
onOpenBeside: onOpenBeside, onOpenBeside: onOpenBeside,
onOpenBelow: onOpenBelow, onOpenBelow: onOpenBelow,
onFloat: onFloat, onFloat: onFloat,
@@ -44,12 +44,14 @@ class ChatSessionRow extends StatelessWidget {
this.duplicateTitles = const {}, this.duplicateTitles = const {},
this.onLongPress, this.onLongPress,
this.selectionOnly = false, this.selectionOnly = false,
this.draggable = false,
}); });
final JsonMap session; final JsonMap session;
/// A choosing surface keeps the normal row content but offers only opening. /// A choosing surface keeps the normal row content but offers only opening.
final bool selectionOnly; final bool selectionOnly;
final bool draggable;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap>? onOpenBeside; final ValueChanged<JsonMap>? onOpenBeside;
final ValueChanged<JsonMap>? onOpenBelow; final ValueChanged<JsonMap>? onOpenBelow;
@@ -78,7 +80,27 @@ class ChatSessionRow extends StatelessWidget {
color: tint == null ? background : Color.alphaBlend(tint, background), color: tint == null ? background : Color.alphaBlend(tint, background),
marker: marker, marker: marker,
markerWidth: visible ? (selected ? 10 : 3) : 0, markerWidth: visible ? (selected ? 10 : 3) : 0,
child: _marked(context, id, marker, accent), child: draggable
? Draggable<JsonMap>(
// A mouse drags at once (a click still opens the chat); the chip
// follows the pointer.
dragAnchorStrategy: pointerDragAnchorStrategy,
data: session,
feedback: Material(
elevation: 4,
borderRadius: BorderRadius.circular(20),
child: Chip(
avatar: ChatSessionAvatar(session: session),
label: Text(chatSessionTitle(session)),
),
),
childWhenDragging: Opacity(
opacity: .35,
child: _marked(context, id, marker, accent),
),
child: _marked(context, id, marker, accent),
)
: _marked(context, id, marker, accent),
); );
} }
@@ -21,6 +21,7 @@ Widget memoChatSessionRow({
required bool unseen, required bool unseen,
required bool divider, required bool divider,
required ValueChanged<JsonMap> onOpen, required ValueChanged<JsonMap> onOpen,
bool draggable = false,
ValueChanged<JsonMap>? onOpenBeside, ValueChanged<JsonMap>? onOpenBeside,
ValueChanged<JsonMap>? onOpenBelow, ValueChanged<JsonMap>? onOpenBelow,
ValueChanged<JsonMap>? onFloat, ValueChanged<JsonMap>? onFloat,
@@ -43,6 +44,7 @@ Widget memoChatSessionRow({
unseen, unseen,
divider, divider,
onOpen, onOpen,
draggable,
onOpenBeside, onOpenBeside,
onOpenBelow, onOpenBelow,
onFloat, onFloat,
@@ -63,6 +65,7 @@ Widget memoChatSessionRow({
unseen: unseen, unseen: unseen,
divider: divider, divider: divider,
onOpen: onOpen, onOpen: onOpen,
draggable: draggable,
onOpenBeside: onOpenBeside, onOpenBeside: onOpenBeside,
onOpenBelow: onOpenBelow, onOpenBelow: onOpenBelow,
onFloat: onFloat, onFloat: onFloat,
@@ -17,12 +17,14 @@ import 'chat_pane_switch_motion.dart';
import 'chat_pane_backdrop.dart'; import 'chat_pane_backdrop.dart';
import 'chat_pane_dim.dart'; import 'chat_pane_dim.dart';
import 'chat_workspace_pane_scope.dart'; import 'chat_workspace_pane_scope.dart';
import 'chat_workspace_drop.dart';
import 'chat_workspace_surface.dart'; import 'chat_workspace_surface.dart';
import '../../../ui/input/keyboard_owner.dart'; import '../../../ui/input/keyboard_owner.dart';
export 'chat_workspace_controller.dart'; export 'chat_workspace_controller.dart';
export 'chat_workspace_geometry.dart' show ChatPaneDirection; export 'chat_workspace_geometry.dart' show ChatPaneDirection;
export 'chat_workspace_pane_scope.dart'; export 'chat_workspace_pane_scope.dart';
export 'chat_workspace_drop.dart';
typedef ChatWorkspacePaneBuilder = typedef ChatWorkspacePaneBuilder =
Widget Function(BuildContext context, ChatWorkspacePane pane, bool active); Widget Function(BuildContext context, ChatWorkspacePane pane, bool active);
@@ -35,6 +37,7 @@ class ChatWorkspace extends StatefulWidget {
required this.controller, required this.controller,
required this.paneBuilder, required this.paneBuilder,
this.onFocusPane, this.onFocusPane,
this.onDrop,
this.shortcutsEnabled = true, this.shortcutsEnabled = true,
this.singlePane = false, this.singlePane = false,
this.mobilePeeks = false, this.mobilePeeks = false,
@@ -71,6 +74,7 @@ class ChatWorkspace extends StatefulWidget {
/// Keyboard navigation only: the owner can focus the target composer. /// Keyboard navigation only: the owner can focus the target composer.
/// Pointer activation leaves text-selection and pointer focus alone. /// Pointer activation leaves text-selection and pointer focus alone.
final ValueChanged<ChatWorkspacePane>? onFocusPane; final ValueChanged<ChatWorkspacePane>? onFocusPane;
final void Function(ChatWorkspacePane, Object, ChatWorkspaceDropZone)? onDrop;
@override @override
State<ChatWorkspace> createState() => _ChatWorkspaceState(); State<ChatWorkspace> createState() => _ChatWorkspaceState();
@@ -393,6 +397,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
sharedEdges, sharedEdges,
moveTargets[pane.id], moveTargets[pane.id],
), ),
onDrop: widget.onDrop,
); );
}, },
), ),
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
import 'chat_workspace_nodes.dart'; import 'chat_workspace_nodes.dart';
import 'chat_workspace_reconcile.dart'; import 'chat_workspace_reconcile.dart';
import 'chat_workspace_snapshot.dart'; import 'chat_workspace_snapshot.dart';
import 'chat_workspace_drop.dart';
export 'chat_workspace_nodes.dart'; export 'chat_workspace_nodes.dart';
@@ -237,6 +238,73 @@ class ChatWorkspaceController extends ChangeNotifier {
_changed(); _changed();
} }
/// Places a dragged chat into a pane without ever creating a duplicate.
void dropSession(
String sessionId,
String targetPaneId,
ChatWorkspaceDropZone zone,
) {
if (sessionId.isEmpty || _root == null) return;
final target = panes.where((pane) => pane.id == targetPaneId).firstOrNull;
if (target == null) return;
final source = panes
.where((pane) => pane.sessionId == sessionId)
.firstOrNull;
if (source?.id == target.id) {
activate(target.id);
return;
}
if (zone == ChatWorkspaceDropZone.replace) {
if (source == null) {
_root = _replace(
_root!,
target.id,
ChatWorkspacePane(target.id, sessionId),
);
} else {
_root = swapChatWorkspacePanes(_root!, source, target);
}
_active = target.id;
_changed();
return;
}
if (source != null) close(source.id);
final axis = zone == ChatWorkspaceDropZone.right
? ChatSplitAxis.horizontal
: ChatSplitAxis.vertical;
final current = panes.where((pane) => pane.id == target.id).firstOrNull;
if (current == null) return;
_root = _replace(
_root!,
current.id,
ChatWorkspaceSplit(
_id('split'),
axis,
current,
ChatWorkspacePane(_id('pane'), sessionId),
),
);
_active = panes.last.id;
_changed();
}
/// Replaces a pane after its caller has already validated [newId]. Unlike
/// [replaceSession], this does not ask the window host to show a floating
/// chat; keyboard cycling filters those chats before calling this method.
void replacePaneSession(String paneId, String newId) {
if (newId.isEmpty) return;
final pane = panes.where((p) => p.id == paneId).firstOrNull;
if (pane == null) return;
final existing = panes.where((p) => p.sessionId == newId).firstOrNull;
if (existing != null) {
close(pane.id);
activate(existing.id);
return;
}
_root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, newId));
_changed();
}
ChatWorkspaceNode _replace( ChatWorkspaceNode _replace(
ChatWorkspaceNode node, ChatWorkspaceNode node,
String id, String id,
@@ -0,0 +1,134 @@
import 'package:flutter/material.dart';
import 'chat_workspace_nodes.dart';
enum ChatWorkspaceDropZone { replace, right, bottom }
class ChatWorkspaceDropTarget extends StatefulWidget {
const ChatWorkspaceDropTarget({
super.key,
required this.pane,
required this.rect,
required this.onDrop,
});
final ChatWorkspacePane pane;
final Rect rect;
final void Function(ChatWorkspacePane, Object, ChatWorkspaceDropZone) onDrop;
@override
State<ChatWorkspaceDropTarget> createState() =>
_ChatWorkspaceDropTargetState();
}
class _ChatWorkspaceDropTargetState extends State<ChatWorkspaceDropTarget> {
ChatWorkspaceDropZone? _zone;
ChatWorkspaceDropZone _zoneAt(Offset local) {
if (local.dx >= widget.rect.width * .75) {
return ChatWorkspaceDropZone.right;
}
if (local.dy >= widget.rect.height * .75) {
return ChatWorkspaceDropZone.bottom;
}
return ChatWorkspaceDropZone.replace;
}
@override
Widget build(BuildContext context) => DragTarget<Object>(
onWillAcceptWithDetails: (_) => true,
onMove: (details) {
final box = context.findRenderObject() as RenderBox?;
if (box == null) return;
final zone = _zoneAt(box.globalToLocal(details.offset));
if (_zone != zone) setState(() => _zone = zone);
},
onLeave: (_) {
if (mounted) setState(() => _zone = null);
},
onAcceptWithDetails: (details) {
final box = context.findRenderObject() as RenderBox?;
final zone = box == null
? ChatWorkspaceDropZone.replace
: _zoneAt(box.globalToLocal(details.offset));
setState(() => _zone = null);
widget.onDrop(widget.pane, details.data, zone);
},
builder: (context, candidates, rejected) {
final zone = _zone;
if (zone == null) return const SizedBox.expand();
final scheme = Theme.of(context).colorScheme;
final (alignment, width, height, icon, label) = switch (zone) {
ChatWorkspaceDropZone.replace => (
Alignment.center,
1.0,
1.0,
Icons.swap_horiz,
'Show here',
),
ChatWorkspaceDropZone.right => (
Alignment.centerRight,
.5,
1.0,
Icons.vertical_split_outlined,
'Open to the right',
),
ChatWorkspaceDropZone.bottom => (
Alignment.bottomCenter,
1.0,
.5,
Icons.horizontal_split_outlined,
'Open below',
),
};
// Only the area that will receive the chat is marked: the whole pane
// to replace its chat, or the half a new split will take.
return IgnorePointer(
child: Align(
alignment: alignment,
child: FractionallySizedBox(
widthFactor: width,
heightFactor: height,
child: Padding(
padding: const EdgeInsets.all(8),
child: DecoratedBox(
key: ValueKey('chat-drop-zone-${zone.name}'),
decoration: BoxDecoration(
color: scheme.primary.withValues(alpha: .14),
border: Border.all(color: scheme.primary, width: 2),
borderRadius: BorderRadius.circular(16),
),
child: Center(
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.primaryContainer,
borderRadius: BorderRadius.circular(24),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: scheme.onPrimaryContainer),
const SizedBox(width: 8),
Text(
label,
style: Theme.of(context).textTheme.labelLarge
?.copyWith(color: scheme.onPrimaryContainer),
),
],
),
),
),
),
),
),
),
),
);
},
);
}
@@ -13,6 +13,7 @@ import 'chat_motion_viewport.dart';
import 'chat_workspace_controller.dart'; import 'chat_workspace_controller.dart';
import 'chat_workspace_divider.dart'; import 'chat_workspace_divider.dart';
import 'chat_workspace_geometry.dart'; import 'chat_workspace_geometry.dart';
import 'chat_workspace_drop.dart';
/// Rendering only: retained live panes stay stable siblings, while the outgoing /// Rendering only: retained live panes stay stable siblings, while the outgoing
/// picture and mobile drag target sit alongside them in the same clipped stack. /// picture and mobile drag target sit alongside them in the same clipped stack.
@@ -30,6 +31,7 @@ Widget chatWorkspaceSurface({
required List<ChatWorkspacePane> panes, required List<ChatWorkspacePane> panes,
required Widget Function(ChatWorkspacePane) paneView, required Widget Function(ChatWorkspacePane) paneView,
Widget Function(ChatWorkspacePane)? stageStrip, Widget Function(ChatWorkspacePane)? stageStrip,
void Function(ChatWorkspacePane, Object, ChatWorkspaceDropZone)? onDrop,
}) { }) {
final moving = Listenable.merge([ final moving = Listenable.merge([
motion.animation, motion.animation,
@@ -145,6 +147,17 @@ Widget chatWorkspaceSurface({
rect: stage.rectFor(layout.stageId)!, rect: stage.rectFor(layout.stageId)!,
size: size, size: size,
), ),
if (!collapsed && mobile == null && onDrop != null)
for (final pane in panes)
if (geometry.panes[pane.id] case final rect?)
Positioned.fromRect(
rect: rect,
child: ChatWorkspaceDropTarget(
pane: pane,
rect: rect,
onDrop: onDrop,
),
),
if (mobile?.peekId != null && !motion.isAnimating) if (mobile?.peekId != null && !motion.isAnimating)
Positioned( Positioned(
top: mobile!.contentHeight - 12, top: mobile!.contentHeight - 12,
@@ -224,6 +224,7 @@ class PipelineRun {
required this.createdAt, required this.createdAt,
required this.finishedAt, required this.finishedAt,
required this.executing, required this.executing,
this.workspace = '',
}); });
factory PipelineRun.fromJson(PipelineJson json) => PipelineRun( factory PipelineRun.fromJson(PipelineJson json) => PipelineRun(
@@ -233,6 +234,7 @@ class PipelineRun {
createdAt: _string(json['created_at']), createdAt: _string(json['created_at']),
finishedAt: _string(json['finished_at']), finishedAt: _string(json['finished_at']),
executing: json['executing'] == true, executing: json['executing'] == true,
workspace: '${json['workspace'] ?? ''}',
); );
final int id; final int id;
@@ -241,6 +243,7 @@ class PipelineRun {
final String createdAt; final String createdAt;
final String finishedAt; final String finishedAt;
final bool executing; final bool executing;
final String workspace;
} }
/// Timestamps decide recency; a higher run id breaks an exact tie or two bad /// Timestamps decide recency; a higher run id breaks an exact tie or two bad
+15 -2
View File
@@ -41,6 +41,8 @@ class PipelinesScreen extends StatefulWidget {
this.initialPipelineId, this.initialPipelineId,
this.initialVersion = 0, this.initialVersion = 0,
this.initialStageKey, this.initialStageKey,
this.onOpenInChat,
this.onOpenPipelineInChat,
}); });
final ApiGateway gateway; final ApiGateway gateway;
@@ -87,6 +89,10 @@ class PipelinesScreen extends StatefulWidget {
/// pane; a key the pinned version does not declare opens the Graph tab with /// pane; a key the pinned version does not declare opens the Graph tab with
/// nothing selected. Null keeps the ordinary default tab. /// nothing selected. Null keeps the ordinary default tab.
final String? initialStageKey; final String? initialStageKey;
final Future<void> Function(BuildContext, PipelineDetail, PipelineRun?)?
onOpenInChat;
final Future<void> Function(BuildContext, PipelineSummary, PipelineRun?)?
onOpenPipelineInChat;
@override @override
State<PipelinesScreen> createState() => _PipelinesScreenState(); State<PipelinesScreen> createState() => _PipelinesScreenState();
@@ -235,6 +241,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
showBack: false, showBack: false,
onRunStarted: widget.onRunStarted, onRunStarted: widget.onRunStarted,
onViewPipelineRuns: widget.onViewPipelineRuns, onViewPipelineRuns: widget.onViewPipelineRuns,
onOpenInChat: widget.onOpenInChat,
stageKey: stageKey, stageKey: stageKey,
stagePipelineId: widget.initialPipelineId, stagePipelineId: widget.initialPipelineId,
stageVersion: widget.initialVersion, stageVersion: widget.initialVersion,
@@ -252,12 +259,18 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
); );
if (!wide) { if (!wide) {
return ContentWidth( return ContentWidth(
child: PipelineListPanel(controller: _controller), child: PipelineListPanel(
controller: _controller,
onOpenInChat: widget.onOpenPipelineInChat,
),
); );
} }
return ListDetailPanes( return ListDetailPanes(
list: ContentWidth( list: ContentWidth(
child: PipelineListPanel(controller: _controller), child: PipelineListPanel(
controller: _controller,
onOpenInChat: widget.onOpenPipelineInChat,
),
), ),
detailIdentity: _controller.selectedId, detailIdentity: _controller.selectedId,
detail: _controller.hasSelection detail: _controller.hasSelection
@@ -18,17 +18,29 @@ String archiveConfirmation(String name) =>
Widget pipelineActionsMenu( Widget pipelineActionsMenu(
BuildContext context, BuildContext context,
PipelinesController controller, PipelinesController controller,
PipelineDetail detail, PipelineDetail detail, {
) { Future<void> Function(BuildContext, PipelineDetail, PipelineRun?)?
onOpenInChat,
}) {
final archived = detail.archived; final archived = detail.archived;
final label = archived ? 'Unarchive' : 'Archive…'; final label = archived ? 'Unarchive' : 'Archive…';
void run(BuildContext context) => void run(BuildContext context) =>
archiveOrUnarchive(context, controller, detail); archiveOrUnarchive(context, controller, detail);
return SegmentedOverflowAction( return SegmentedOverflowAction(
overflowEntry: SegmentedOverflowEntry( overflowEntry: SegmentedOverflowEntry(
label: archived ? 'Unarchive pipeline' : 'Archive pipeline…', label: 'Pipeline actions',
icon: Icons.archive_outlined, icon: Icons.archive_outlined,
onPressed: () => run(context), choices: [
SegmentedMenuChoice(
label: archived ? 'Unarchive pipeline' : 'Archive pipeline…',
onSelected: () => run(context),
),
if (onOpenInChat != null)
SegmentedMenuChoice(
label: 'Open in chat',
onSelected: () => onOpenInChat(context, detail, null),
),
],
), ),
child: AppOverflowMenu<bool>( child: AppOverflowMenu<bool>(
key: const Key('pipeline-actions-menu'), key: const Key('pipeline-actions-menu'),
@@ -40,8 +52,15 @@ Widget pipelineActionsMenu(
value: true, value: true,
label: label, label: label,
), ),
if (onOpenInChat != null)
const AppMenuAction<bool>(
value: false,
label: 'Open in chat',
icon: Icons.chat_bubble_outline,
),
], ],
onSelected: (context, _) => run(context), onSelected: (context, value) =>
value ? run(context) : onOpenInChat!(context, detail, null),
), ),
); );
} }
@@ -45,6 +45,7 @@ class PipelineDetailPanel extends StatefulWidget {
this.stagePipelineId, this.stagePipelineId,
this.stageVersion = 0, this.stageVersion = 0,
this.stageRequest = 0, this.stageRequest = 0,
this.onOpenInChat,
}) : assert( }) : assert(
stageKey == null || stagePipelineId != null, stageKey == null || stagePipelineId != null,
'a routed stage names the pipeline it belongs to', 'a routed stage names the pipeline it belongs to',
@@ -77,6 +78,8 @@ class PipelineDetailPanel extends StatefulWidget {
/// definition pane even though the pinned detail may be re-read in place. A /// definition pane even though the pinned detail may be re-read in place. A
/// later version switch from this screen is not a new route request. /// later version switch from this screen is not a new route request.
final int stageRequest; final int stageRequest;
final Future<void> Function(BuildContext, PipelineDetail, PipelineRun?)?
onOpenInChat;
@override @override
State<PipelineDetailPanel> createState() => _PipelineDetailPanelState(); State<PipelineDetailPanel> createState() => _PipelineDetailPanelState();
@@ -420,7 +423,18 @@ class _PipelineDetailPanelState extends State<PipelineDetailPanel> {
onRunStarted: widget.onRunStarted, onRunStarted: widget.onRunStarted,
inBar: true, inBar: true,
), ),
pipelineActionsMenu(context, _controller, detail), pipelineActionsMenu(
context,
_controller,
detail,
onOpenInChat: widget.onOpenInChat == null
? null
: (context, detail, _) => widget.onOpenInChat!(
context,
detail,
_controller.latestRuns[detail.id],
),
),
]; ];
Widget _source(BuildContext context, PipelineDetail detail) { Widget _source(BuildContext context, PipelineDetail detail) {
@@ -14,6 +14,7 @@ import '../pipelines_controller.dart';
import 'pipeline_controls.dart'; import 'pipeline_controls.dart';
import 'pipeline_filter_page.dart'; import 'pipeline_filter_page.dart';
import 'pipeline_scope_control.dart'; import 'pipeline_scope_control.dart';
import '../../../ui/layout/app_overflow_menu.dart';
/// The list's horizontal rhythm, matching the web's toolbar and row inset /// The list's horizontal rhythm, matching the web's toolbar and row inset
/// (`var(--space-s)`: 12px). The detail pane keeps its own content padding. /// (`var(--space-s)`: 12px). The detail pane keeps its own content padding.
@@ -21,9 +22,15 @@ const double kPipelineListInset = 12;
/// The left/top pane: filter and sort controls, then the truthful list states. /// The left/top pane: filter and sort controls, then the truthful list states.
class PipelineListPanel extends StatelessWidget { class PipelineListPanel extends StatelessWidget {
const PipelineListPanel({super.key, required this.controller}); const PipelineListPanel({
super.key,
required this.controller,
this.onOpenInChat,
});
final PipelinesController controller; final PipelinesController controller;
final Future<void> Function(BuildContext, PipelineSummary, PipelineRun?)?
onOpenInChat;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -264,6 +271,22 @@ class PipelineListPanel extends StatelessWidget {
: Text( : Text(
ServerContext.metadata(context, runStateLabel(badge.state)), ServerContext.metadata(context, runStateLabel(badge.state)),
), ),
menu: onOpenInChat == null
? null
: AppOverflowMenu<bool>(
key: Key('pipeline-row-more-menu-${pipeline.id}'),
label: 'Pipeline actions',
sheetTitle: pipeline.displayName,
actions: const [
AppMenuAction<bool>(
value: true,
label: 'Open in chat',
icon: Icons.chat_bubble_outline,
),
],
onSelected: (context, _) =>
onOpenInChat!(context, pipeline, run),
),
); );
}, },
); );
+4
View File
@@ -53,6 +53,7 @@ class RunsScreen extends StatefulWidget {
this.attention, this.attention,
this.sortStore = const SharedPreferencesRunsSortStore(), this.sortStore = const SharedPreferencesRunsSortStore(),
this.pendingRunStore = const SharedPreferencesPendingRunStore(''), this.pendingRunStore = const SharedPreferencesPendingRunStore(''),
this.onOpenInChat,
}); });
final ApiGateway gateway; final ApiGateway gateway;
@@ -103,6 +104,7 @@ class RunsScreen extends StatefulWidget {
/// Where a New run's pending launch intent persists, under the same endpoint /// Where a New run's pending launch intent persists, under the same endpoint
/// scope the Pipelines tab uses. Tests inject a memory store. /// scope the Pipelines tab uses. Tests inject a memory store.
final PendingRunStore pendingRunStore; final PendingRunStore pendingRunStore;
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
@override @override
State<RunsScreen> createState() => _RunsScreenState(); State<RunsScreen> createState() => _RunsScreenState();
@@ -300,6 +302,7 @@ class _RunsScreenState extends State<RunsScreen> {
onBack: onBack, onBack: onBack,
onRunOpened: _select, onRunOpened: _select,
onOpenPipeline: widget.onOpenPipeline, onOpenPipeline: widget.onOpenPipeline,
onOpenInChat: widget.onOpenInChat,
initialStageKey: widget.initialStageKey, initialStageKey: widget.initialStageKey,
initialVisit: widget.initialVisit, initialVisit: widget.initialVisit,
); );
@@ -354,6 +357,7 @@ class _RunsScreenState extends State<RunsScreen> {
attentionNow: widget.attentionNow, attentionNow: widget.attentionNow,
notifications: widget.notifications, notifications: widget.notifications,
attention: widget.attention, attention: widget.attention,
onOpenInChat: widget.onOpenInChat,
), ),
), ),
); );
@@ -24,6 +24,7 @@ class RunDetailView extends StatefulWidget {
this.onOpenPipeline, this.onOpenPipeline,
this.initialStageKey, this.initialStageKey,
this.initialVisit, this.initialVisit,
this.onOpenInChat,
}); });
final RunsController controller; final RunsController controller;
@@ -44,6 +45,7 @@ class RunDetailView extends StatefulWidget {
/// plain detail. /// plain detail.
final String? initialStageKey; final String? initialStageKey;
final int? initialVisit; final int? initialVisit;
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
@override @override
State<RunDetailView> createState() => _RunDetailViewState(); State<RunDetailView> createState() => _RunDetailViewState();
@@ -114,6 +116,7 @@ class _RunDetailViewState extends State<RunDetailView> {
onRunChanged: widget.controller.acceptRunDetail, onRunChanged: widget.controller.acceptRunDetail,
onRunOpened: widget.onRunOpened, onRunOpened: widget.onRunOpened,
onDeleted: widget.controller.applyDeletion, onDeleted: widget.controller.applyDeletion,
onOpenInChat: widget.onOpenInChat,
); );
if (inShellBar) { if (inShellBar) {
return ShellBar( return ShellBar(
+8 -1
View File
@@ -35,6 +35,7 @@ class RunListRow extends StatelessWidget {
this.checked = false, this.checked = false,
this.onToggle, this.onToggle,
this.onLongPress, this.onLongPress,
this.onOpenInChat,
}); });
final JsonMap run; final JsonMap run;
@@ -56,6 +57,7 @@ class RunListRow extends StatelessWidget {
/// Enters select mode from a touch long-press. /// Enters select mode from a touch long-press.
final VoidCallback? onLongPress; final VoidCallback? onLongPress;
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -140,13 +142,18 @@ class RunListRow extends StatelessWidget {
!selecting && !selecting &&
gateway != null && gateway != null &&
onRunChanged != null && onRunChanged != null &&
showRunMoreMenu(run, deletable: onDeleted != null) showRunMoreMenu(
run,
deletable: onDeleted != null,
canOpenInChat: onOpenInChat != null,
)
? RunMoreMenu( ? RunMoreMenu(
run: run, run: run,
gateway: gateway!, gateway: gateway!,
onRunChanged: onRunChanged!, onRunChanged: onRunChanged!,
onRunOpened: onRunOpened, onRunOpened: onRunOpened,
onDeleted: onDeleted, onDeleted: onDeleted,
onOpenInChat: onOpenInChat,
menuKey: ValueKey('run-list-more-menu-$id'), menuKey: ValueKey('run-list-more-menu-$id'),
) )
: null, : null,
+24 -3
View File
@@ -16,14 +16,21 @@ import '../domain/run_models.dart' show runIdentity;
const runMoreMenuKey = ValueKey<String>('run-more-menu'); const runMoreMenuKey = ValueKey<String>('run-more-menu');
const deleteRunActionKey = ValueKey<String>('run-delete-action'); const deleteRunActionKey = ValueKey<String>('run-delete-action');
const deleteRunActionLabel = 'Delete run'; const deleteRunActionLabel = 'Delete run';
const openRunInChatActionKey = ValueKey<String>('run-open-in-chat-action');
const openRunInChatActionLabel = 'Open in chat';
/// Whether the run has anything for its more menu. [deletable] says the host /// Whether the run has anything for its more menu. [deletable] says the host
/// can apply a deletion, so a finished run offers Delete run. /// can apply a deletion, so a finished run offers Delete run.
bool showRunMoreMenu(JsonMap run, {bool deletable = false}) => bool showRunMoreMenu(
JsonMap run, {
bool deletable = false,
bool canOpenInChat = false,
}) =>
runTitleId(run) != null || runTitleId(run) != null ||
canScheduleRun(run) || canScheduleRun(run) ||
_canRetry(run) || _canRetry(run) ||
(deletable && runIsDeletable(run)); (deletable && runIsDeletable(run)) ||
canOpenInChat;
/// The run's own name for its action sheet: its title or pipeline, else /// The run's own name for its action sheet: its title or pipeline, else
/// `Run <id>`, as its list row shows it. /// `Run <id>`, as its list row shows it.
@@ -34,7 +41,7 @@ String runMoreMenuTitle(JsonMap run) {
bool _canRetry(JsonMap run) => retryRunId(run) != null && canRetryRun(run); bool _canRetry(JsonMap run) => retryRunId(run) != null && canRetryRun(run);
enum _RunMoreItem { retry, rename, schedule, delete } enum _RunMoreItem { retry, rename, schedule, delete, openInChat }
/// Each item keeps the key its standalone button had. /// Each item keeps the key its standalone button had.
Key _keyOf(_RunMoreItem item) => switch (item) { Key _keyOf(_RunMoreItem item) => switch (item) {
@@ -42,6 +49,7 @@ Key _keyOf(_RunMoreItem item) => switch (item) {
_RunMoreItem.rename => runTitleActionKey, _RunMoreItem.rename => runTitleActionKey,
_RunMoreItem.schedule => scheduleRunActionKey, _RunMoreItem.schedule => scheduleRunActionKey,
_RunMoreItem.delete => deleteRunActionKey, _RunMoreItem.delete => deleteRunActionKey,
_RunMoreItem.openInChat => openRunInChatActionKey,
}; };
/// The run detail's more menu: Retry (failed runs only), Rename and Schedule /// The run detail's more menu: Retry (failed runs only), Rename and Schedule
@@ -56,6 +64,7 @@ class RunMoreMenu extends StatefulWidget {
required this.onRunChanged, required this.onRunChanged,
this.onRunOpened, this.onRunOpened,
this.onDeleted, this.onDeleted,
this.onOpenInChat,
this.menuKey = runMoreMenuKey, this.menuKey = runMoreMenuKey,
}); });
@@ -68,6 +77,7 @@ class RunMoreMenu extends StatefulWidget {
/// Applies an answered deletion; without it the menu offers no Delete run. /// Applies an answered deletion; without it the menu offers no Delete run.
final ValueChanged<RunsDeletion>? onDeleted; final ValueChanged<RunsDeletion>? onDeleted;
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
/// Detail menus retain the shared key; list rows supply a per-run key. /// Detail menus retain the shared key; list rows supply a per-run key.
final Key menuKey; final Key menuKey;
@@ -86,6 +96,8 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
if (canScheduleRun(run)) (_RunMoreItem.schedule, scheduleRunActionLabel), if (canScheduleRun(run)) (_RunMoreItem.schedule, scheduleRunActionLabel),
if (widget.onDeleted != null && runIsDeletable(run)) if (widget.onDeleted != null && runIsDeletable(run))
(_RunMoreItem.delete, deleteRunActionLabel), (_RunMoreItem.delete, deleteRunActionLabel),
if (widget.onOpenInChat != null)
(_RunMoreItem.openInChat, openRunInChatActionLabel),
]; ];
void _pick(BuildContext context, _RunMoreItem item) { void _pick(BuildContext context, _RunMoreItem item) {
@@ -117,6 +129,8 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
gateway: widget.gateway, gateway: widget.gateway,
onDeleted: widget.onDeleted!, onDeleted: widget.onDeleted!,
); );
case _RunMoreItem.openInChat:
widget.onOpenInChat!(context, run);
} }
} }
@@ -131,6 +145,13 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
key: _keyOf(item), key: _keyOf(item),
value: item, value: item,
label: label, label: label,
icon: switch (item) {
_RunMoreItem.retry => Icons.replay,
_RunMoreItem.rename => Icons.edit_outlined,
_RunMoreItem.schedule => Icons.schedule,
_RunMoreItem.delete => Icons.delete_outline,
_RunMoreItem.openInChat => Icons.chat_bubble_outline,
},
destructive: item == _RunMoreItem.delete, destructive: item == _RunMoreItem.delete,
), ),
], ],
+5 -1
View File
@@ -32,10 +32,12 @@ class RunsList extends StatelessWidget {
this.notifications, this.notifications,
this.attention, this.attention,
this.active = true, this.active = true,
this.onOpenInChat,
}); });
/// False while a run detail covers the list; the bar is then the run's. /// False while a run detail covers the list; the bar is then the run's.
final bool active; final bool active;
final Future<void> Function(BuildContext, JsonMap)? onOpenInChat;
final RunsController controller; final RunsController controller;
final ValueChanged<num> onSelected; final ValueChanged<num> onSelected;
@@ -166,7 +168,8 @@ class RunsList extends StatelessWidget {
// A server with no runs at all is not a filter problem: say what the list // A server with no runs at all is not a filter problem: say what the list
// is for and where its first run comes from. A free-text query counts as // is for and where its first run comes from. A free-text query counts as
// a filter too, so a search on an empty server reads as "nothing found". // a filter too, so a search on an empty server reads as "nothing found".
final noRunsAtAll = controller.runs.isEmpty && final noRunsAtAll =
controller.runs.isEmpty &&
controller.activeFilterCount == 0 && controller.activeFilterCount == 0 &&
controller.query.trim().isEmpty; controller.query.trim().isEmpty;
return BelowTopBar( return BelowTopBar(
@@ -340,6 +343,7 @@ class RunsList extends StatelessWidget {
gateway: controller.repository.gateway, gateway: controller.repository.gateway,
onRunChanged: controller.acceptRunDetail, onRunChanged: controller.acceptRunDetail,
onRunOpened: onSelected, onRunOpened: onSelected,
onOpenInChat: onOpenInChat,
); );
} }
} }
@@ -156,10 +156,10 @@ class KeyboardShortcutRegistry {
if (!web) if (!web)
const KeyboardShortcutEntry( const KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat, group: KeyboardShortcutGroup.chat,
action: 'Cycle chat panes and floating chats', action: 'Cycle chats and floating chat panes',
keys: 'Ctrl+Tab, Ctrl+Shift+Tab', keys: 'Ctrl+Tab, Ctrl+Shift+Tab',
caveat: caveat:
'While the terminal is shown, Ctrl+Tab moves between its tabs instead.', 'With one tiled pane, cycles open sidebar chats (excluding closed, hidden and floating chats); with multiple panes, cycles panes. While the terminal is shown, Ctrl+Tab moves between its tabs instead.',
), ),
const KeyboardShortcutEntry( const KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat, group: KeyboardShortcutGroup.chat,
@@ -0,0 +1,186 @@
import 'package:flutter/material.dart';
import '../../application/open_in_chat_preferences.dart';
import '../../core/api_gateway.dart';
import '../chat/data/chat_repository.dart';
import 'settings_group.dart';
/// The harness and model Open in chat (a run's or pipeline's More menu)
/// starts its chats with. The server lists models only for an existing chat,
/// so a harness's models come from its most recent chat; with none, only the
/// harness default is offered.
class SettingsOpenInChatSection extends StatefulWidget {
const SettingsOpenInChatSection({super.key, required this.gateway});
final ApiGateway gateway;
@override
State<SettingsOpenInChatSection> createState() =>
_SettingsOpenInChatSectionState();
}
class _SettingsOpenInChatSectionState extends State<SettingsOpenInChatSection> {
late final ChatRepository _chats = ChatRepository(widget.gateway);
OpenInChatPreferences _chosen = const OpenInChatPreferences();
List<String>? _harnesses;
List<JsonMap> _models = const [];
bool _loadingModels = false;
String? _error;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
final chosen = await OpenInChatPreferences.load(widget.gateway);
final harnesses = await _chats.backends();
if (!mounted) return;
setState(() {
_chosen = chosen;
_harnesses = harnesses;
});
await _loadModels(chosen.harness);
} catch (error) {
if (mounted) setState(() => _error = '$error');
}
}
/// The models of [harness]'s most recent chat, or none.
Future<void> _loadModels(String harness) async {
setState(() {
_models = const [];
_loadingModels = harness.isNotEmpty;
});
if (harness.isEmpty) return;
try {
final sessions = await _chats.sessions();
final latest =
sessions.where((session) => session['backend'] == harness).toList()
..sort(
(a, b) => '${b['updated_at'] ?? ''}'.compareTo(
'${a['updated_at'] ?? ''}',
),
);
final models = latest.isEmpty
? const <JsonMap>[]
: await _chats.models('${latest.first['id']}');
if (mounted && _chosen.harness == harness) {
setState(() {
_models = models;
_loadingModels = false;
});
}
} catch (_) {
if (mounted) setState(() => _loadingModels = false);
}
}
Future<void> _save(OpenInChatPreferences next) async {
setState(() => _chosen = next);
await next.save(widget.gateway);
}
@override
Widget build(BuildContext context) {
final harnesses = _harnesses;
final error = _error;
return SettingsGroup(
title: 'Open in chat',
footer: Text(
'Used when a run or pipeline is opened in a new chat. Models come '
"from this harness's most recent chat.",
),
children: [
if (error != null)
ListTile(
leading: const Icon(Icons.error_outline),
title: const Text('Could not load the harnesses'),
subtitle: Text(error),
trailing: TextButton(
onPressed: () {
setState(() => _error = null);
_load();
},
child: const Text('Retry'),
),
)
else if (harnesses == null)
const ListTile(
leading: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
title: Text('Loading harnesses…'),
)
else ...[
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: DropdownMenu<String>(
key: const Key('open-in-chat-harness'),
expandedInsets: EdgeInsets.zero,
label: const Text('Harness'),
initialSelection: harnesses.contains(_chosen.harness)
? _chosen.harness
: '',
dropdownMenuEntries: [
const DropdownMenuEntry(value: '', label: 'Default'),
for (final harness in harnesses)
DropdownMenuEntry(value: harness, label: harness),
],
onSelected: (harness) async {
final value = harness ?? '';
if (value == _chosen.harness) return;
await _save(OpenInChatPreferences(harness: value));
await _loadModels(value);
},
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
child: DropdownMenu<String>(
key: ValueKey('open-in-chat-model-${_chosen.harness}'),
expandedInsets: EdgeInsets.zero,
enabled: _chosen.harness.isNotEmpty && !_loadingModels,
label: Text(_loadingModels ? 'Loading models…' : 'Model'),
initialSelection: _chosen.hasModel
? '${_chosen.provider}/${_chosen.model}'
: '',
dropdownMenuEntries: [
const DropdownMenuEntry(value: '', label: 'Harness default'),
if (_chosen.hasModel &&
!_models.any(
(m) =>
'${m['provider']}/${m['id']}' ==
'${_chosen.provider}/${_chosen.model}',
))
DropdownMenuEntry(
value: '${_chosen.provider}/${_chosen.model}',
label: _chosen.model,
),
for (final model in _models)
DropdownMenuEntry(
value: '${model['provider']}/${model['id']}',
label: '${model['name'] ?? model['id']}',
),
],
onSelected: (value) {
final picked = value ?? '';
final slash = picked.indexOf('/');
_save(
OpenInChatPreferences(
harness: _chosen.harness,
provider: slash < 0 ? '' : picked.substring(0, slash),
model: slash < 0 ? '' : picked.substring(slash + 1),
),
);
},
),
),
],
],
);
}
}
@@ -106,6 +106,13 @@ extension _SettingsPageSections on _SettingsScreenState {
workspaceField: _workspaceField, workspaceField: _workspaceField,
), ),
), ),
SettingsSection(
id: 'open-in-chat',
title: 'Open in chat',
keywords: 'open in chat run pipeline harness model default new chat',
lazy: true,
builder: (_) => SettingsOpenInChatSection(gateway: widget.client),
),
if (widget.notifications case final notifications?) if (widget.notifications case final notifications?)
SettingsSection( SettingsSection(
id: 'notifications', id: 'notifications',
@@ -43,6 +43,7 @@ import 'settings_row.dart';
import 'settings_read_aloud_section.dart'; import 'settings_read_aloud_section.dart';
import '../chat/speech/speech_controller.dart'; import '../chat/speech/speech_controller.dart';
import 'settings_open_in_chat_section.dart';
part 'settings_page_sections.dart'; part 'settings_page_sections.dart';
/// The Settings destination: one searchable page of grouped Material sections. /// The Settings destination: one searchable page of grouped Material sections.
+6 -1
View File
@@ -306,7 +306,12 @@ class _SegmentedBarState extends State<SegmentedBar> {
excluding: entries.isEmpty, excluding: entries.isEmpty,
child: SegmentedPress( child: SegmentedPress(
tint: widget.foregroundColor, tint: widget.foregroundColor,
child: SegmentedMoreButton(entries: entries), child: widget.separateActionIslands
? SegmentedPill(
fill: widget.pillColor,
child: SegmentedMoreButton(entries: entries),
)
: SegmentedMoreButton(entries: entries),
), ),
), ),
actions: [ actions: [
+23
View File
@@ -0,0 +1,23 @@
# Compact sidebar New chat
The compact chat rail now keeps a Material `+` action above its scrolling
session list. Its callback reaches the mounted `ChatSessionsScreenState` and
invokes the existing `_newChat` flow, so machine selection, harness discovery,
and the create dialog remain shared with the expanded list action.
## Regression coverage
- `test/features/chat/ui/sessions/chat_visibility_marker_test.dart`: the rail
exposes the `New chat` tooltip and invokes its callback.
- `test/features/chat/ui/sessions/chat_machine_creation_test.dart`: the
existing expanded-list flow still selects a machine before harness discovery.
- `test/features/chat/ui/sessions/chat_sessions_floating_bar_test.dart`: the
expanded list still has exactly one New chat action in its bar.
## Verification
- `tool/memwatch/full.sh 'test/features/chat/ui/sessions/chat_visibility_marker_test.dart test/features/chat/ui/sessions/chat_state_legibility_test.dart test/features/chat/ui/sessions/chat_machine_creation_test.dart test/features/chat/ui/sessions/chat_sessions_floating_bar_test.dart'`: 10 passed.
- `tool/analyze.sh`: clean.
- Browser captures: desktop 1600x1000 compact rail in light and dark themes,
including the New chat tooltip, are in the shared artifact
`public/chat-compact-sidebar/`.
+23 -25
View File
@@ -41,10 +41,11 @@ every destination and come back at app start without Chat being opened.
takes the keyboard. Open order is the order the windows were opened (a takes the keyboard. Open order is the order the windows were opened (a
restored window keeps its saved place), so a raise does not change the restored window keeps its saved place), so a raise does not change the
cycle; the stacking order does change on a raise. cycle; the stacking order does change on a raise.
- **With no chat window shown**, Ctrl+Tab cycles the tiled panes only and - **With no chat window focused**, Ctrl+Tab cycles the tiled panes and the
the keys focus the chosen pane's composer. With one tiled pane it does keys focus the chosen pane's composer. With exactly one tiled pane it
nothing. A chat shown before, or a minimised or floating chat, is never cycles all open chats in sidebar order, replacing that pane while keeping
swapped in. its transcript and draft; closed, hidden-on-this-device and floating
chats are skipped. With two or more panes it cycles the panes only.
- Command+Tab stays with the system. While the terminal claims tab keys - Command+Tab stays with the system. While the terminal claims tab keys
(shown) Ctrl+Tab switches terminal tabs. A keyboard held by another window (shown) Ctrl+Tab switches terminal tabs. A keyboard held by another window
(a run, terminal) is left to that window. Alt+` (`windowCycleShortcut`) (a run, terminal) is left to that window. Alt+` (`windowCycleShortcut`)
@@ -80,36 +81,33 @@ every destination and come back at app start without Chat being opened.
## Checks ## Checks
- Focused, 2026-11-12, `tool/memwatch/full.sh` over - Focused, 2026-11-13, `tool/memwatch/full.sh` over
`test/features/chat/chat_floating_pane_test.dart`, `test/features/chat/chat_floating_pane_test.dart`,
`test/features/chat/chat_keyboard_focus_test.dart`, `test/features/chat/chat_keyboard_focus_test.dart`,
`test/features/chat/chat_control_tab_test.dart`, `test/features/chat/chat_control_tab_test.dart`,
`test/features/chat/windows/chat_windows_test.dart` and `test/features/chat/windows/chat_windows_test.dart`,
`test/features/terminal/terminal_chat_tab_test.dart`: 38 passed, 0 failed. `test/features/terminal/terminal_chat_tab_test.dart`, the keyboard
Related Ctrl+Tab users, `tool/memwatch/full.sh` over shortcuts registry test and related Ctrl+Tab users: 70 passed, 0 failed.
This included `tool/memwatch/full.sh` over
`test/shell/destination_shortcuts_test.dart`, `test/shell/destination_shortcuts_test.dart`,
`test/shell/tab_history_back_test.dart`, `test/shell/search_escape_test.dart` `test/shell/tab_history_back_test.dart`, `test/shell/search_escape_test.dart`
and `test/features/chat/shell/chat_shell_terminal_test.dart`: 26 passed, and `test/features/chat/shell/chat_shell_terminal_test.dart`: 26 passed,
0 failed. 0 failed.
- New in the first file: Ctrl+Tab and Ctrl+Shift+Tab over three floating chats - Floating-window Ctrl+Tab and Ctrl+Shift+Tab over three floating chats cycle
cycle in open order, not stacking order (order, wrap, composer focus, in open order, not stacking order (order, wrap, composer focus, Command+Tab
Command+Tab ignored). With the tiling focused Ctrl+Tab goes to the top-most ignored). With the tiling focused, a single tiled pane cycles the open,
shown window and leaves the panes alone; with one shown window it does device-visible sidebar chats and skips closed, hidden and floating chats;
nothing; with the window minimised the panes cycle and the window stays multiple tiled panes cycle panes. A terminal that claims tab keys keeps
hidden. With one tiled pane and a minimised chat, Ctrl+Tab does nothing and Ctrl+Tab over a focused chat window.
shows nothing. A terminal that claims tab keys keeps Ctrl+Tab over a focused - Changed: a single tiled pane now cycles the open, device-visible sidebar
chat window. chats in list order, skips closed, hidden-on-this-device and floating chats,
- Removed: the single-pane recent-chat swap (the chat shown before, opened wraps in both directions, and focuses the replacement composer. Multiple
back into the pane), with its tests in `chat_keyboard_focus_test.dart`. A panes and focused floating windows retain their existing cycles.
single pane with no shown window now does nothing on Ctrl+Tab, so
`chat_control_tab_test.dart` no longer expects the composer to take focus
from the sidebar.
- `tool/analyze.sh` on `lib/features/chat` and the three chat test files: - `tool/analyze.sh` on `lib/features/chat` and the three chat test files:
clean. clean.
- Affected states: two or more floating chats; one floating chat shown; - Affected states: a single tiled pane with open chats; shown or minimised
floating chat minimised with one tiled pane; tiling focused with windows floating chats; two or more tiled panes; a focused floating window; the
shown and with none; a window focused; the terminal shown (claimed); terminal shown (claimed); Command+Tab.
Command+Tab.
- Not covered: the terminal's own tab switching (the test app has no terminal - Not covered: the terminal's own tab switching (the test app has no terminal
surface), real browser or device keys, and captures (ui-review's). surface), real browser or device keys, and captures (ui-review's).
- Observed, not changed: in the widget harness, floating from a pane's More - Observed, not changed: in the widget harness, floating from a pane's More
+13
View File
@@ -0,0 +1,13 @@
# Drag chats onto panes
Implemented desktop chat dragging from expanded rows and compact avatars. A
drop in a pane replaces it; the right and bottom edge zones split horizontally
or vertically. Existing open chats move without duplicates, and floating chat
windows close before docking into the selected pane.
Focused regression: `tool/memwatch/full.sh
'test/features/chat/workspace/chat_workspace_test.dart'` — 11 passed.
`tool/analyze.sh` — clean.
Browser captures and full UI-review fixture coverage were not run in this
implementation stage.
+21
View File
@@ -0,0 +1,21 @@
# Open in chat
Runs and pipelines expose **Open in chat** in their overflow menus. The action
creates a chat using the New chat backend catalog rule (OpenCode when
available, otherwise the first advertised harness) in the run/latest-run
workspace, or the saved Settings workspace and finally `~`, then routes to the
Chat tab. The generated reference is seeded as an unsent composer draft and
requests composer focus. Settings and create failures show an error without
changing chat state. On narrow pipeline detail layouts, the segmented More
sheet includes both Archive/Unarchive and Open in chat. Settings fallback reads
the workspace for the active server identity rather than an unscoped preference.
Focused regression coverage is in `test/application/open_in_chat_test.dart`:
run list desktop menu, run detail phone sheet, pipeline list row menu, and
pipeline detail phone overflow all assert selection reaches the callback with
the expected entity and latest run. The existing schedule/menu and pipeline
destination tests also pass. The full-app browser probe now supports stateful
`chat_create`, catalog, session, and transcript replies, so a rendered menu
selection can show the created chat and seeded composer rather than stopping at
an unsupported-request error. Browser and phone/desktop captures were not run
in this implementation stage.
+17
View File
@@ -0,0 +1,17 @@
# Narrow chat More island
The generated overflow `More` control now uses `SegmentedPill` when action
islands are separate, matching the height and symmetric insets of the other
action islands. This covers desktop menu anchors and phone action-sheet
buttons because both are hosted by the same pill.
## Checks
- `tool/memwatch/full.sh 'test/ui/adaptive/segmented_bar_overflow_test.dart'`
— 10 passed.
- `tool/analyze.sh` — clean.
The regression test covers a narrow, all-overflowed action row and checks equal
left/right and top/bottom insets for the More button, plus height parity with a
multi-action island. Browser before/after captures were not run in this
implementation stage.
+373
View File
@@ -0,0 +1,373 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/application/open_in_chat.dart';
import 'package:pipelines_app/application/open_in_chat_preferences.dart';
import 'package:pipelines_app/features/chat/chat_runtime.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_create_fields.dart';
import 'package:pipelines_app/features/pipelines/pipeline_models.dart';
import 'package:pipelines_app/features/pipelines/pipeline_repository.dart';
import 'package:pipelines_app/features/pipelines/pipelines_controller.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_archive_action.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_list_panel.dart';
import 'package:pipelines_app/features/runs/ui/run_list_row.dart';
import 'package:pipelines_app/features/runs/ui/run_more_menu.dart';
import '../features/chat/ui/sessions/fake_chat_gateway.dart';
import '../features/pipelines/fixtures.dart';
import '../features/pipelines/test_helpers.dart';
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
testWidgets('the harness and model chosen in Settings start the chat', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
final gateway = FakeChatGateway()
..backendsHandler = () async => const {
'chat_backends': ['opencode', 'claude'],
};
await const OpenInChatPreferences(
harness: 'claude',
provider: 'anthropic',
model: 'claude-opus-5-5',
).save(gateway);
final runtime = ChatRuntime(gateway: gateway);
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
await openReferenceInChat(
context: tester.element(find.byType(Scaffold)),
runtime: runtime,
selectChat: (_) {},
directory: '/work/run',
title: 'Run #42: Build',
draft: 'About Pipelines run #42.',
);
final create = gateway.lastFields('chat_create')!['chat_create'] as Map;
expect(create['backend'], 'claude');
final model = gateway.lastFields('chat_model')!['chat_model'] as Map;
expect(model['session_id'], 'created');
expect(model['provider'], 'anthropic');
expect(model['model'], 'claude-opus-5-5');
// Opened for work: beside the active chat, with the keyboard in it.
expect(runtime.openedForWork, contains('created'));
runtime.dispose();
});
testWidgets('a harness the server no longer offers falls back to the '
'default, without the saved model', (tester) async {
SharedPreferences.setMockInitialValues({});
final gateway = FakeChatGateway()
..backendsHandler = () async => const {
'chat_backends': ['opencode', 'codex'],
};
await const OpenInChatPreferences(
harness: 'claude',
provider: 'anthropic',
model: 'claude-opus-5-5',
).save(gateway);
final runtime = ChatRuntime(gateway: gateway);
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
await openReferenceInChat(
context: tester.element(find.byType(Scaffold)),
runtime: runtime,
selectChat: (_) {},
directory: '/work/run',
title: 'Run #42: Build',
draft: 'About Pipelines run #42.',
);
final create = gateway.lastFields('chat_create')!['chat_create'] as Map;
// The default harness (OpenCode) is the request's default: not claude.
expect(create['backend'], anyOf(isNull, 'opencode'));
expect(gateway.lastFields('chat_model'), isNull);
runtime.dispose();
});
test('a run summary names its pipeline in name', () {
final draft = runChatReference({
'id': 7,
'name': 'release',
'title': 'Ship notes',
'version': 3,
'status': 'failed',
});
expect(
draft,
'About Pipelines run #7 "Ship notes" (pipeline "release" v3, '
'status failed). Inspect it with `pipelines inspect 7`.',
);
final untitled = runChatReference({
'id': 8,
'name': 'release',
'version': 3,
'status': 'succeeded',
});
expect(untitled, contains('run #8 "Run 8" (pipeline "release" v3'));
final unversioned = runChatReference({
'id': 9,
'name': 'release',
'status': 'running',
});
expect(unversioned, contains('(pipeline "release", status running)'));
});
test('run references contain the exact inspect command', () {
expect(
runChatReference({
'id': 42,
'title': 'Nightly build',
'pipeline_name': 'Deploy',
'pipeline_version': 3,
'status': 'failed',
}),
'About Pipelines run #42 "Nightly build" (pipeline "Deploy" v3, '
'status failed). Inspect it with `pipelines inspect 42`.',
);
});
test('pipeline references contain show and edit guidance', () {
expect(
pipelineChatReference(7, 'Deploy', 4),
'About pipeline "Deploy" (id 7, version 4). Show it with '
'`pipelines show "Deploy"`; to change it, draft with `pipelines edit` '
'and publish with `pipelines submit`.',
);
});
test('open in chat keeps the more menu available', () {
expect(showRunMoreMenu({'id': 42}, canOpenInChat: true), isTrue);
});
test('pipeline latest run retains its workspace', () {
final run = PipelineRun.fromJson({
'id': 9,
'pipeline_id': 7,
'workspace': '/work/deploy',
});
expect(run.workspace, '/work/deploy');
});
testWidgets(
'open in chat uses the catalog backend, draft, route, and focus',
(tester) async {
final gateway = FakeChatGateway()
..backendsHandler = () async => const {
'chat_backends': ['codex', 'claude'],
};
final runtime = ChatRuntime(gateway: gateway);
String? selected;
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
await openReferenceInChat(
context: tester.element(find.byType(Scaffold)),
runtime: runtime,
selectChat: (id) => selected = id,
directory: '/work/run',
title: 'Run #42: Build',
draft: 'About Pipelines run #42.',
);
final create = gateway.lastFields('chat_create')!['chat_create'] as Map;
expect(create['backend'], 'codex');
expect(create['directory'], '/work/run');
expect(selected, 'created');
expect(runtime.pendingDrafts['created'], 'About Pipelines run #42.');
expect(runtime.composerFocus.take('created'), isTrue);
runtime.dispose();
},
);
testWidgets('open in chat falls back to the default folder', (tester) async {
final gateway = FakeChatGateway();
final runtime = ChatRuntime(gateway: gateway);
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
await openReferenceInChat(
context: tester.element(find.byType(Scaffold)),
runtime: runtime,
selectChat: (_) {},
directory: '',
title: 'Pipeline: Deploy',
draft: 'About pipeline "Deploy".',
);
final create = gateway.lastFields('chat_create')!['chat_create'] as Map;
expect(create['directory'], chatHomeDirectory);
runtime.dispose();
});
testWidgets('create failure leaves navigation and chat state unchanged', (
tester,
) async {
final gateway = FakeChatGateway()..failures['chat_create'] = 'refused';
final runtime = ChatRuntime(gateway: gateway);
String? selected;
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
await openReferenceInChat(
context: tester.element(find.byType(Scaffold)),
runtime: runtime,
selectChat: (id) => selected = id,
directory: '/work/run',
title: 'Run #42: Build',
draft: 'About Pipelines run #42.',
);
await tester.pump();
expect(selected, isNull);
expect(runtime.opened, isEmpty);
expect(find.textContaining('Could not open in chat'), findsOneWidget);
runtime.dispose();
});
testWidgets('run list More selects Open in chat on desktop', (tester) async {
final run = <String, dynamic>{
'id': 42,
'title': 'Build',
'status': 'failed',
'created_at': '2026-10-17T19:00:00',
};
JsonMap? selected;
final gateway = FakeChatGateway();
tester.view.physicalSize = const Size(900, 700);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunListRow(
run: run,
now: DateTime(2026, 10, 18),
gateway: gateway,
onRunChanged: (_) {},
onOpenInChat: (context, value) async => selected = value,
),
),
),
);
await tester.tap(find.byKey(const Key('run-list-more-menu-42')));
await tester.pumpAndSettle();
expect(find.text('Open in chat'), findsOneWidget);
await tester.tap(find.text('Open in chat'));
expect(selected, same(run));
});
testWidgets('run detail More selects Open in chat from the phone sheet', (
tester,
) async {
final run = <String, dynamic>{'id': 42, 'title': 'Build'};
JsonMap? selected;
final gateway = FakeChatGateway();
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: [
RunMoreMenu(
run: run,
gateway: gateway,
onRunChanged: (_) {},
onOpenInChat: (context, value) async => selected = value,
),
],
),
),
),
);
await tester.tap(find.byTooltip('More actions'));
await tester.pumpAndSettle();
expect(find.text('Open in chat'), findsOneWidget);
await tester.tap(find.text('Open in chat'));
expect(selected, same(run));
});
testWidgets('pipeline list row More selects Open in chat with latest run', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
final controller = PipelinesController(PipelinesRepository(gateway));
addTearDown(controller.dispose);
await controller.load();
PipelineSummary? selected;
PipelineRun? selectedRun;
tester.view.physicalSize = const Size(900, 700);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: PipelineListPanel(
controller: controller,
onOpenInChat: (context, pipeline, run) async {
selected = pipeline;
selectedRun = run;
},
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-row-more-menu-1')));
await tester.pumpAndSettle();
expect(find.text('Open in chat'), findsOneWidget);
await tester.tap(find.text('Open in chat'));
expect(selected?.id, 1);
expect(selectedRun?.id, 42);
});
testWidgets(
'pipeline detail actions select Open in chat from phone overflow',
(tester) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
final controller = PipelinesController(PipelinesRepository(gateway));
addTearDown(controller.dispose);
final detail = PipelineDetail.fromJson(fixture.details.first);
PipelineDetail? selected;
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => pipelineActionsMenu(
context,
controller,
detail,
onOpenInChat: (context, value, run) async => selected = value,
),
),
),
),
);
await tester.tap(find.byTooltip('Pipeline actions'));
await tester.pumpAndSettle();
expect(find.text('Open in chat'), findsOneWidget);
await tester.tap(find.text('Open in chat'));
expect(selected?.id, detail.id);
},
);
}
@@ -12,12 +12,17 @@ import 'package:pipelines_app/shell/destination.dart';
import 'conversation/chat_thread_fixtures.dart'; import 'conversation/chat_thread_fixtures.dart';
class _Gateway extends FakeChatGateway { class _Gateway extends FakeChatGateway {
_Gateway({this.rows = const ['a', 'b', 'c']});
final List<String> rows;
@override @override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) { Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') { if (type == 'chat_sessions') {
return Future.value({ return Future.value({
'chat_sessions': [ 'chat_sessions': [
for (final id in ['a', 'b', 'c']) {'id': id, 'title': 'Chat $id'}, for (final id in rows)
{'id': id, 'title': 'Chat $id', if (id == 'closed') 'closed_at': 1},
], ],
}); });
} }
@@ -57,12 +62,16 @@ Future<void> _chord(
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
Future<void> _setup(WidgetTester tester, {bool open = true}) async { Future<void> _setup(
WidgetTester tester, {
bool open = true,
List<String> rows = const ['a', 'b', 'c'],
}) async {
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1800, 1000); tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1; tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset); addTearDown(tester.view.reset);
final gateway = _Gateway()..history = (_) async => chatPage([]); final gateway = _Gateway(rows: rows)..history = (_) async => chatPage([]);
addTearDown(gateway.close); addTearDown(gateway.close);
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
@@ -133,20 +142,44 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
}); });
testWidgets('single pane with no shown window does nothing; empty workspace ' testWidgets(
'does not consume', (tester) async { 'single pane cycles list chats; empty workspace does not consume',
await _setup(tester, open: false); (tester) async {
await _chord(tester); await _setup(tester, open: false);
expect(find.byType(ChatWorkspace), findsNothing); await _chord(tester);
expect(find.byType(ChatWorkspace), findsNothing);
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
_focusSidebar(tester);
await tester.pumpAndSettle();
await _chord(tester);
expect(find.byType(ChatWorkspace), findsOneWidget);
expect(_workspace(tester).paneCount, 1);
expect(_workspace(tester).activePane?.sessionId, 'b');
expect(_editable(tester, 'b').focusNode.hasPrimaryFocus, isTrue);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets('single pane skips closed and hidden-on-this-device chats', (
tester,
) async {
await _setup(tester, open: false, rows: ['a', 'hidden', 'c', 'closed']);
await tester.tap(_actions('hidden'));
await tester.pumpAndSettle();
await tester.tap(find.text('Hide on this device'));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-row-a'))); await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
_focusSidebar(tester); _focusSidebar(tester);
await tester.pumpAndSettle();
await _chord(tester); await _chord(tester);
expect(find.byType(ChatWorkspace), findsOneWidget); expect(_workspace(tester).activePane?.sessionId, 'c');
expect(_workspace(tester).paneCount, 1); await _chord(tester);
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse); expect(_workspace(tester).activePane?.sessionId, 'a');
expect(_editable(tester, 'a').controller.text, isEmpty);
await _chord(tester, reverse: true);
expect(_workspace(tester).activePane?.sessionId, 'c');
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
}); });
@@ -592,10 +592,8 @@ void main() {
await app.stop(tester); await app.stop(tester);
}); });
testWidgets('with the tiling focused Ctrl+Tab goes to the top-most shown ' testWidgets('with the tiling focused Ctrl+Tab cycles the single pane chat '
'window, and cycles the panes only when no window is shown', ( 'list and cycles panes when there are multiple panes', (tester) async {
tester,
) async {
await _saved('a', 'b', 'c'); await _saved('a', 'b', 'c');
final app = _App(_Store()); final app = _App(_Store());
await app.start(tester); await app.start(tester);
@@ -603,20 +601,20 @@ void main() {
expect(app.floating, ['c']); expect(app.floating, ['c']);
final controller = _workspace(tester); final controller = _workspace(tester);
// A window is shown: from the tiling, Ctrl+Tab takes the keyboard to it // A shown floating chat is skipped while the single tiled pane cycles the
// and the panes stay where they are. // remaining open chats.
await tester.tapAt(tester.getCenter(_input('a'))); await tester.tapAt(tester.getCenter(_input('a')));
await tester.pump(); await tester.pump();
expect(controller.activePane?.sessionId, 'a'); expect(controller.activePane?.sessionId, 'a');
await _tab(tester); await _tab(tester);
expect(controller.activePane?.sessionId, 'a'); expect(controller.activePane?.sessionId, 'b');
expect(_composerFocused(tester, 'c'), isTrue); expect(_composerFocused(tester, 'b'), isTrue);
expect(app.floating, ['c']); expect(app.floating, ['c']);
// A single shown window has nothing to cycle to. // It wraps back to the other non-floating chat.
await _tab(tester); await _tab(tester);
expect(controller.activePane?.sessionId, 'a'); expect(controller.activePane?.sessionId, 'a');
expect(_composerFocused(tester, 'c'), isTrue); expect(_composerFocused(tester, 'a'), isTrue);
expect(app.floating, ['c']); expect(app.floating, ['c']);
// No window shown: the panes cycle and the hidden window stays hidden. // No window shown: the panes cycle and the hidden window stays hidden.
@@ -150,28 +150,25 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
}); });
testWidgets('Control Tab over one pane does nothing: it never brings up ' testWidgets('Control Tab over one pane cycles the sidebar chats in both '
'another chat', (tester) async { 'directions', (tester) async {
await _setup(tester); await _setup(tester);
await _openRow(tester, 'a'); await _openRow(tester, 'a');
final workspace = _workspace(tester); final workspace = _workspace(tester);
await _controlTab(tester);
expect(workspace.activePane?.sessionId, 'a');
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse);
// Opening b replaces the lone pane; a is no longer shown anywhere.
await _openRow(tester, 'b');
await tester.enterText(_input('b'), 'Draft B');
await _focusSidebar(tester); await _focusSidebar(tester);
for (final shift in [false, true]) { for (final id in ['b', 'c', 'a']) {
await _controlTab(tester, shift: shift); await _controlTab(tester);
expect(workspace.paneCount, 1); expect(workspace.activePane?.sessionId, id);
expect(workspace.activePane?.sessionId, 'b'); expect(_editable(tester, id).focusNode.hasPrimaryFocus, isTrue);
expect(_editable(tester, 'b').focusNode.hasPrimaryFocus, isFalse); }
expect(_editable(tester, 'b').controller.text, 'Draft B'); await _focusSidebar(tester);
for (final id in ['c', 'b', 'a']) {
await _controlTab(tester, shift: true);
expect(workspace.activePane?.sessionId, id);
expect(_editable(tester, id).focusNode.hasPrimaryFocus, isTrue);
} }
// Two panes cycle the panes, not the history. // Two panes still cycle panes, not the chat list.
await _openRow(tester, 'c'); await _openRow(tester, 'c');
await tester.tap(_actions('a')); await tester.tap(_actions('a'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@@ -0,0 +1,115 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/chat_runtime.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart';
import 'conversation/chat_thread_fixtures.dart';
class _Gateway extends FakeChatGateway {
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final id in ['a', 'b', 'new'])
{'id': id, 'title': 'Chat $id', 'directory': '/home/$id'},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
return super.call(type, fields);
}
}
ChatWorkspaceController _workspace(WidgetTester tester) => tester
.widget<ChatWorkspace>(find.byType(ChatWorkspace, skipOffstage: false))
.controller;
void main() {
testWidgets('a chat opened for work goes beside the active chat, becomes '
'active and takes the keyboard', (tester) async {
final layout = ChatWorkspaceController()..open('a');
SharedPreferences.setMockInitialValues({
chatWorkspacePreferenceKey: layout.snapshot()!.encode(),
});
tester.view.physicalSize = const Size(1600, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = _Gateway()..history = (_) async => chatPage([]);
addTearDown(gateway.close);
final runtime = ChatRuntime(gateway: gateway);
addTearDown(runtime.dispose);
Widget screen(String? routed) => MaterialApp(
home: Scaffold(
body: ChatScreen(
gateway: gateway,
runtime: runtime,
persistWorkspace: true,
initialSessionId: routed,
onSessionSelected: (_) {},
onBack: () {},
),
),
);
await tester.pumpWidget(screen('a'));
await tester.pumpAndSettle();
expect(_workspace(tester).panes.map((p) => p.sessionId), ['a']);
runtime.openedForWork.add('new');
await tester.pumpWidget(screen('new'));
await tester.pumpAndSettle();
final workspace = _workspace(tester);
expect(workspace.panes.map((p) => p.sessionId), ['a', 'new']);
expect(workspace.activePane?.sessionId, 'new');
expect(runtime.openedForWork, isEmpty);
final composer = tester
.widgetList<EditableText>(
find.descendant(
of: find.byKey(const ValueKey('chat-composer-new')),
matching: find.byType(EditableText),
),
)
.first;
expect(composer.focusNode.hasFocus, isTrue);
});
testWidgets('an ordinary routed chat still opens in the active pane', (
tester,
) async {
final layout = ChatWorkspaceController()..open('a');
SharedPreferences.setMockInitialValues({
chatWorkspacePreferenceKey: layout.snapshot()!.encode(),
});
tester.view.physicalSize = const Size(1600, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = _Gateway()..history = (_) async => chatPage([]);
addTearDown(gateway.close);
final runtime = ChatRuntime(gateway: gateway);
addTearDown(runtime.dispose);
Widget screen(String? routed) => MaterialApp(
home: Scaffold(
body: ChatScreen(
gateway: gateway,
runtime: runtime,
persistWorkspace: true,
initialSessionId: routed,
onSessionSelected: (_) {},
onBack: () {},
),
),
);
await tester.pumpWidget(screen('a'));
await tester.pumpAndSettle();
await tester.pumpWidget(screen('b'));
await tester.pumpAndSettle();
expect(_workspace(tester).panes.map((p) => p.sessionId), ['b']);
});
}
@@ -150,12 +150,12 @@ void main() {
); );
final header = find.byKey(const Key('chat-thread-header')); final header = find.byKey(const Key('chat-thread-header'));
expect(find.byKey(const Key('chat-mode')), findsNothing); expect(find.byKey(const Key('chat-mode')), findsNothing);
// The round Back, the title pill and the actions pill, which always // The round Back, the title pill, and the two action pills (including the
// carries the More menu, so it is never drawn empty. A narrow bar moves // More menu), so the More control is never drawn empty. A narrow bar moves
// the Files toggle into that menu. // the Files toggle into that menu.
expect( expect(
find.descendant(of: header, matching: find.byType(SegmentedPill)), find.descendant(of: header, matching: find.byType(SegmentedPill)),
findsNWidgets(3), findsNWidgets(4),
); );
expect( expect(
find.descendant( find.descendant(
@@ -85,6 +85,7 @@ void main() {
activeSessionId: null, activeSessionId: null,
visibleSessionIds: const {'a'}, visibleSessionIds: const {'a'},
onOpen: (_) {}, onOpen: (_) {},
onNewChat: () {},
onExpand: () {}, onExpand: () {},
navigation: const Text('Destinations'), navigation: const Text('Destinations'),
), ),
@@ -139,6 +140,7 @@ void main() {
activeSessionId: 'a', activeSessionId: 'a',
visibleSessionIds: const {'a', 'b'}, visibleSessionIds: const {'a', 'b'},
onOpen: (_) {}, onOpen: (_) {},
onNewChat: () {},
onExpand: () {}, onExpand: () {},
), ),
), ),
@@ -107,6 +107,7 @@ void main() {
await controller.refresh(); await controller.refresh();
final folds = ChatSectionFolds(); final folds = ChatSectionFolds();
addTearDown(folds.dispose); addTearDown(folds.dispose);
var newChatPressed = false;
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
home: Scaffold( home: Scaffold(
@@ -116,12 +117,16 @@ void main() {
activeSessionId: 'a', activeSessionId: 'a',
visibleSessionIds: const {'a', 'b'}, visibleSessionIds: const {'a', 'b'},
onOpen: (_) {}, onOpen: (_) {},
onNewChat: () => newChatPressed = true,
onExpand: () {}, onExpand: () {},
), ),
), ),
), ),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byTooltip('New chat'), findsOneWidget);
await tester.tap(find.byTooltip('New chat'));
expect(newChatPressed, isTrue);
expect(find.byTooltip('Expand chat list'), findsOneWidget); expect(find.byTooltip('Expand chat list'), findsOneWidget);
expect(edge(tester, 'a').width, 10); expect(edge(tester, 'a').width, 10);
expect(edge(tester, 'b').width, 3); expect(edge(tester, 'b').width, 3);
@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_drop.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_nodes.dart';
void main() {
Future<List<ChatWorkspaceDropZone>> pumpPane(WidgetTester tester) async {
tester.view.physicalSize = const Size(1200, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final drops = <ChatWorkspaceDropZone>[];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Row(
children: [
const SizedBox(
width: 200,
child: Draggable<String>(
data: 'b',
// As the chat list does: the feedback sits at the pointer.
dragAnchorStrategy: pointerDragAnchorStrategy,
feedback: Text('chat b'),
child: Text('source'),
),
),
SizedBox(
width: 800,
height: 600,
child: ChatWorkspaceDropTarget(
pane: const ChatWorkspacePane('pane-a', 'a'),
rect: const Rect.fromLTWH(0, 0, 800, 600),
onDrop: (_, _, zone) => drops.add(zone),
),
),
],
),
),
),
);
return drops;
}
// The pane occupies x 200..1000, y 0..600.
for (final (name, point, zone) in [
('centre', const Offset(500, 250), ChatWorkspaceDropZone.replace),
('right edge', const Offset(950, 250), ChatWorkspaceDropZone.right),
('bottom edge', const Offset(500, 560), ChatWorkspaceDropZone.bottom),
]) {
testWidgets('a mouse drag over the $name marks only that zone and drops '
'there', (tester) async {
final drops = await pumpPane(tester);
final gesture = await tester.startGesture(
tester.getCenter(find.text('source')),
);
// No long press: a plain drag starts at once.
await gesture.moveBy(const Offset(20, 0));
await gesture.moveTo(point);
await tester.pump();
await tester.pump();
expect(
find.byKey(ValueKey('chat-drop-zone-${zone.name}')),
findsOneWidget,
);
for (final other in ChatWorkspaceDropZone.values) {
if (other == zone) continue;
expect(
find.byKey(ValueKey('chat-drop-zone-${other.name}')),
findsNothing,
);
}
await gesture.up();
await tester.pump();
expect(drops, [zone]);
expect(find.byKey(ValueKey('chat-drop-zone-${zone.name}')), findsNothing);
});
}
}
@@ -84,6 +84,37 @@ void main() {
expect(controller.panes.last.sessionId, 'new-two'); expect(controller.panes.last.sessionId, 'new-two');
}); });
test('drop replaces, splits and moves without duplicating a chat', () {
final controller = ChatWorkspaceController()
..open('one')
..splitActive('two', ChatSplitAxis.horizontal);
addTearDown(controller.dispose);
final first = controller.panes.first;
final second = controller.panes.last;
controller.dropSession('three', first.id, ChatWorkspaceDropZone.replace);
expect(controller.panes.map((pane) => pane.sessionId), ['three', 'two']);
controller.dropSession('four', second.id, ChatWorkspaceDropZone.right);
expect(controller.panes.map((pane) => pane.sessionId), [
'three',
'two',
'four',
]);
expect(
controller.panes.where((pane) => pane.sessionId == 'three'),
hasLength(1),
);
final four = controller.panes.last;
controller.dropSession('three', four.id, ChatWorkspaceDropZone.bottom);
expect(
controller.panes.where((pane) => pane.sessionId == 'three'),
hasLength(1),
);
expect(controller.activePane?.sessionId, 'three');
});
test( test(
'geometry clamps visible sizes but retains ratios and spatial neighbors', 'geometry clamps visible sizes but retains ratios and spatial neighbors',
() { () {
@@ -18,7 +18,7 @@ const _implemented = [
'Stop a running chat', 'Stop a running chat',
'Focus the neighbouring chat pane', 'Focus the neighbouring chat pane',
'Move the active chat pane', 'Move the active chat pane',
'Cycle chat panes and floating chats', 'Cycle chats and floating chat panes',
'Resize panes with a focused divider', 'Resize panes with a focused divider',
'Scroll a wide transcript block', 'Scroll a wide transcript block',
'Show or hide floating chats', 'Show or hide floating chats',
@@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/application/open_in_chat_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/settings/settings_open_in_chat_section.dart';
import '../chat/ui/sessions/fake_chat_gateway.dart';
class _Gateway extends FakeChatGateway {
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
switch (type) {
case 'chat_backends':
return {
'chat_backends': ['opencode', 'claude'],
};
case 'chat_sessions':
return {
'chat_sessions': [
{'id': 'old', 'backend': 'claude', 'updated_at': '2026-01-01'},
{'id': 'new', 'backend': 'claude', 'updated_at': '2026-02-01'},
],
};
case 'chat_models':
final session = (fields['chat_query'] as Map)['session_id'];
return {
'chat_models': [
{
'id': 'claude-opus-5-5',
'provider': 'anthropic',
'name': 'Opus from $session',
},
],
};
}
return super.call(type, fields);
}
}
void main() {
testWidgets('choosing a harness and model saves them for Open in chat', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
final gateway = _Gateway();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsOpenInChatSection(gateway: gateway),
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Open in chat'), findsOneWidget);
await tester.tap(find.byKey(const Key('open-in-chat-harness')));
await tester.pumpAndSettle();
await tester.tap(find.text('claude').last);
await tester.pumpAndSettle();
expect((await OpenInChatPreferences.load(gateway)).harness, 'claude');
// Models come from the harness's most recent chat.
await tester.tap(find.byKey(const ValueKey('open-in-chat-model-claude')));
await tester.pumpAndSettle();
expect(find.text('Opus from new'), findsWidgets);
await tester.tap(find.text('Opus from new').last);
await tester.pumpAndSettle();
final saved = await OpenInChatPreferences.load(gateway);
expect(saved.provider, 'anthropic');
expect(saved.model, 'claude-opus-5-5');
});
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart'; import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart';
import 'package:pipelines_app/ui/adaptive/segmented_bar_pieces.dart';
void _size(WidgetTester tester, double width) { void _size(WidgetTester tester, double width) {
tester.view.physicalSize = Size(width, 700); tester.view.physicalSize = Size(width, 700);
@@ -142,6 +143,54 @@ void main() {
expect(find.bySemanticsLabel('More actions'), findsNothing); expect(find.bySemanticsLabel('More actions'), findsNothing);
}); });
testWidgets('$host: a lone More action is centred in its separate island', (
tester,
) async {
_size(tester, 180);
await _pump(
tester,
_app(
SegmentedBar(
title: 'Runs',
separateActionIslands: true,
actions: [
for (final name in ['Filter', 'Sort', 'Select', 'Usage', 'View'])
SegmentedOverflowAction(
overflowEntry: SegmentedOverflowEntry(
label: name,
icon: Icons.filter_list,
),
child: _icon(name, () {}),
),
],
),
),
);
final more = find.byKey(segmentedMoreKey).hitTestable();
expect(more, findsOneWidget);
final pill = tester.getRect(find.byType(SegmentedPill).last);
final button = tester.getRect(more);
expect(pill.height, segmentedPieceHeight());
expect(button.left - pill.left, closeTo(pill.right - button.right, 0.1));
expect(button.top - pill.top, closeTo(pill.bottom - button.bottom, 0.1));
await tester.pumpWidget(
_app(
SegmentedBar(
title: 'Runs',
separateActionIslands: true,
actions: [_icon('Needs you', () {}), _icon('Usage', () {})],
),
),
);
await tester.pump();
expect(
tester.getRect(find.byType(SegmentedPill).last).height,
pill.height,
);
});
testWidgets('$host: a longer title keeps a readable share at 240px', ( testWidgets('$host: a longer title keeps a readable share at 240px', (
tester, tester,
) async { ) async {
@@ -170,6 +170,12 @@ bool _warnings = false;
/// visit (group `debug`) to run 7's build visit, so the Artifacts tab's hidden /// visit (group `debug`) to run 7's build visit, so the Artifacts tab's hidden
/// Debugging files group can be reviewed. /// Debugging files group can be reviewed.
bool _turnFiles = false; bool _turnFiles = false;
/// Chats created during a rendered probe. Keeping these in the fixture makes
/// the real Open in chat flow observable instead of turning the create request
/// into the same "unsupported request" error as an incomplete server.
final _probeChats = <String, JsonMap>{};
int _probeChatSequence = 0;
const List<String> _turnFileNames = [ const List<String> _turnFileNames = [
'input.md', 'input.md',
'memory.md', 'memory.md',
@@ -549,6 +555,78 @@ JsonMap? probeReply(JsonMap request) {
'type': 'pipeline', 'type': 'pipeline',
'detail': probePipelineDetail(pipelineId, version is int ? version : 0), 'detail': probePipelineDetail(pipelineId, version is int ? version : 0),
}; };
case 'chat_backends':
return {
'id': id,
'type': 'chat_backends',
'chat_backends': ['opencode'],
};
case 'chat_directories':
return {
'id': id,
'type': 'chat_directories',
'chat_directories': ['/Users/fixture/workspace'],
};
case 'chat_sessions':
return {
'id': id,
'type': 'chat_sessions',
'chat_sessions': _probeChats.values.toList(),
};
case 'chat_create':
final body = request['chat_create'];
if (body is! Map) {
return error('Fixture refused a malformed chat create.');
}
final chatId = 'probe-chat-${++_probeChatSequence}';
final session = <String, dynamic>{
'id': chatId,
'title': '${body['title'] ?? ''}',
'directory': '${body['directory'] ?? ''}',
'backend': '${body['backend'] ?? 'opencode'}',
'model': 'fixture-model',
'created_at': '2026-10-20T09:00:00Z',
'closed_at': null,
};
_probeChats[chatId] = session;
return {'id': id, 'type': 'chat_created', 'chat_session': session};
case 'chat_models':
return {
'id': id,
'type': 'chat_models',
'chat_models': [
{'provider': 'fixture', 'model': 'fixture-model'},
],
};
case 'chat_modes':
return {
'id': id,
'type': 'chat_modes',
'chat_modes': const [
{'mode': 'default', 'name': 'Default'},
],
'chat_mode': const {'mode': 'default'},
};
case 'chat_messages':
return {
'id': id,
'type': 'chat_messages',
'chat_history': const {
'messages': <JsonMap>[],
'next_cursor': '',
'has_more': false,
},
};
case 'chat_subscribe':
return {'id': id, 'type': 'chat_subscribed'};
case 'chat_shells':
return {'id': id, 'type': 'chat_shells', 'chat_shells': const []};
case 'chat_automations':
return {
'id': id,
'type': 'chat_automations',
'chat_automations': const [],
};
case 'archive_pipeline': case 'archive_pipeline':
case 'unarchive_pipeline': case 'unarchive_pipeline':
// Mirrors the server: an enabled schedule blocks archiving. // Mirrors the server: an enabled schedule blocks archiving.
+9 -1
View File
@@ -13,7 +13,15 @@ task with the least ceremony, and keep work small enough to verify.
`pipelines list` shows the registered workflows; `pipelines runs` shows history. `pipelines list` shows the registered workflows; `pipelines runs` shows history.
Start a run with `pipelines run <name> "<task>"`, and inspect it with Start a run with `pipelines run <name> "<task>"`, and inspect it with
`pipelines inspect <id>`. `pipelines wait <id>` blocks until it finishes. `pipelines inspect <id>`.
After starting a run, always follow it with `pipelines wait <id>` until it
finishes; never start a run and move on without waiting. Run the wait as a
background command (one per run, or one loop over several ids) so the session is
notified the moment the run ends, then read its result with
`pipelines inspect <id> --json` and act on it: land, retry, or fix and report.
Do not poll with repeated `pipelines runs` calls, and do not tell the user a run
is done, or will be reported, without a wait covering it.
A failed run keeps its worktree and commits. Read `pipelines inspect <id> --json` A failed run keeps its worktree and commits. Read `pipelines inspect <id> --json`
before deciding: resume the failed stage (`pipelines retry <id>`), fix directly, before deciding: resume the failed stage (`pipelines retry <id>`), fix directly,