Merge branch 'main' into ws-files-panel
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
part of 'screen.dart';
|
||||
|
||||
/// How many chats the visit remembers for Ctrl+Tab over a single pane.
|
||||
const chatRecentSessionLimit = 8;
|
||||
|
||||
/// Keys the Chat destination answers from anywhere in it, also while the
|
||||
/// sidebar or a toolbar owns focus: a bare `/` puts the keyboard in the open
|
||||
/// chat's composer, and Ctrl+Tab over a single pane returns to the chat shown
|
||||
/// before it (and back again). Both are handled before the focus tree, like
|
||||
/// the workspace's pane cycling, and leave other destinations, popups,
|
||||
/// dialogs and any focused text field alone.
|
||||
mixin _ChatScreenKeys on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
void _open(JsonMap session, {bool focusComposer});
|
||||
|
||||
/// The chats this visit has shown in the workspace, most recent first; the
|
||||
/// active one leads it. In memory only: a reopened app starts afresh.
|
||||
final List<String> _recentSessions = [];
|
||||
|
||||
/// Moves the active pane's chat to the front. Called on every workspace
|
||||
/// change, including a restored layout, so the chat opened before the
|
||||
/// current one is always the second entry.
|
||||
@override
|
||||
void _noteRecentSession() {
|
||||
final id = _workspace.activePane?.sessionId;
|
||||
if (id == null || id.isEmpty || _recentSessions.firstOrNull == id) return;
|
||||
_recentSessions
|
||||
..remove(id)
|
||||
..insert(0, id);
|
||||
if (_recentSessions.length > chatRecentSessionLimit) {
|
||||
_recentSessions.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops [id]: a closed chat, or one `/new` moved to a fresh session.
|
||||
void _forgetRecentSession(String id) => _recentSessions.remove(id);
|
||||
|
||||
/// Drops every remembered chat: ids belong to one server.
|
||||
@override
|
||||
void _forgetRecentSessions() => _recentSessions.clear();
|
||||
|
||||
/// Over a single pane, opens the chat shown before the active one with its
|
||||
/// composer focused; false when this visit has shown no other chat.
|
||||
@override
|
||||
bool _toggleRecentChat() {
|
||||
final current = _workspace.activePane?.sessionId;
|
||||
final previous = _recentSessions
|
||||
.where((id) => id != current)
|
||||
.firstOrNull;
|
||||
if (previous == null) return false;
|
||||
_open(_rowFor(previous) ?? {'id': previous}, focusComposer: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Whether the shown destination is Chat with no popup, dialog or other
|
||||
/// route over it, so a key pressed now is meant for the open chat.
|
||||
@override
|
||||
bool _chatOwnsKeyboard() {
|
||||
final destination = ShellBarScope.maybeOf(context)?.registry.focus;
|
||||
if (destination != null && destination != AppDestination.chat) return false;
|
||||
final focusContext = FocusManager.instance.primaryFocus?.context;
|
||||
final route = focusContext == null
|
||||
? ModalRoute.of(context)
|
||||
: ModalRoute.of(focusContext);
|
||||
return route is! PopupRoute && (route == null || route.isCurrent);
|
||||
}
|
||||
|
||||
/// A bare `/` typed outside any text field focuses the active chat's
|
||||
/// composer. The composer takes focus after this frame (see
|
||||
/// [ChatComposerFocusRequests]), once the host has finished delivering the
|
||||
/// keystroke, so the slash itself is not typed into it. Inside a text field
|
||||
/// (the composer, a dialog's field) `/` stays an ordinary character.
|
||||
bool _slashFocusKey(KeyEvent event) {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (event is! KeyDownEvent ||
|
||||
event.character != '/' ||
|
||||
keyboard.isControlPressed ||
|
||||
keyboard.isMetaPressed ||
|
||||
keyboard.isAltPressed ||
|
||||
!_workspaceVisible) {
|
||||
return false;
|
||||
}
|
||||
final id = _workspace.activePane?.sessionId;
|
||||
if (id == null || _textFieldHasFocus() || !_chatOwnsKeyboard()) {
|
||||
return false;
|
||||
}
|
||||
_composerFocus.request(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Whether an editable text control holds focus, wherever it is.
|
||||
bool _textFieldHasFocus() {
|
||||
final context = FocusManager.instance.primaryFocus?.context;
|
||||
final editable = context?.findAncestorWidgetOfExactType<EditableText>();
|
||||
return editable != null && !editable.readOnly;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,10 @@ part of 'screen.dart';
|
||||
mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
Map<String, JsonMap> get _openedSessions;
|
||||
ChatComposerFocusRequests get _composerFocus;
|
||||
bool _chatOwnsKeyboard();
|
||||
bool _toggleRecentChat();
|
||||
void _noteRecentSession();
|
||||
void _forgetRecentSessions();
|
||||
JsonMap? _rowFor(String id);
|
||||
void _back();
|
||||
bool get _pageOpen;
|
||||
@@ -89,6 +93,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
_workspaceBinding = null;
|
||||
if (_workspaceScope != null && scope != _workspaceScope) {
|
||||
_workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!);
|
||||
_forgetRecentSessions();
|
||||
_workspaceVisible = false;
|
||||
_usedWorkspace = true;
|
||||
_sidebarMode = ChatSidebarMode.expanded;
|
||||
@@ -111,7 +116,9 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
String _workspaceSignature = '';
|
||||
|
||||
/// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns
|
||||
/// focus. Command+Tab stays with the operating system's application switcher.
|
||||
/// focus. Over a single pane it swaps in the chat shown before this one
|
||||
/// instead, and back again (see [_toggleRecentChat]). Command+Tab stays
|
||||
/// with the operating system's application switcher.
|
||||
bool _cycleChatKey(KeyEvent event) {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (event is! KeyDownEvent ||
|
||||
@@ -120,19 +127,12 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
keyboard.isMetaPressed ||
|
||||
keyboard.isAltPressed ||
|
||||
!_workspaceVisible ||
|
||||
_workspace.paneCount == 0) {
|
||||
return false;
|
||||
}
|
||||
final destination = ShellBarScope.maybeOf(context)?.registry.focus;
|
||||
if (destination != null && destination != AppDestination.chat) return false;
|
||||
final focusContext = FocusManager.instance.primaryFocus?.context;
|
||||
final route = focusContext == null
|
||||
? ModalRoute.of(context)
|
||||
: ModalRoute.of(focusContext);
|
||||
if (route is PopupRoute || (route != null && !route.isCurrent)) {
|
||||
_workspace.paneCount == 0 ||
|
||||
!_chatOwnsKeyboard()) {
|
||||
return false;
|
||||
}
|
||||
final panes = _workspace.panes;
|
||||
if (panes.length == 1 && _toggleRecentChat()) return true;
|
||||
final active = panes.indexWhere(
|
||||
(pane) => pane.id == _workspace.activePaneId,
|
||||
);
|
||||
@@ -156,7 +156,9 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
}
|
||||
|
||||
void _workspaceChanged() {
|
||||
if (!mounted || _workspaceBinding?.isRestoring == true) return;
|
||||
if (!mounted) return;
|
||||
_noteRecentSession();
|
||||
if (_workspaceBinding?.isRestoring == true) return;
|
||||
final signature =
|
||||
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
|
||||
if (_workspaceSignature == signature) return;
|
||||
|
||||
@@ -27,6 +27,8 @@ import '../../../ui/adaptive/pop_entrance.dart';
|
||||
import 'chat_reading_width.dart';
|
||||
import 'composer_focus_request.dart';
|
||||
import 'composer_focus_restore.dart';
|
||||
import 'composer_focus_ring.dart';
|
||||
import '../ui/sessions/chat_color_palette.dart';
|
||||
|
||||
/// The composer's placeholder when the chat names no working directory.
|
||||
const String chatComposerPlaceholder = 'Message the agent';
|
||||
@@ -49,6 +51,22 @@ bool chatEnterSends([TargetPlatform? platform]) {
|
||||
return target != TargetPlatform.android && target != TargetPlatform.iOS;
|
||||
}
|
||||
|
||||
/// The composer's gap above the bottom of the window (or its bottom safe
|
||||
/// area) on a phone, where it sits just over the keyboard or home indicator.
|
||||
const double kChatComposerBottomMargin = 12;
|
||||
|
||||
/// The same gap on a desktop host (native or a desktop browser), whose
|
||||
/// window's bottom edge is a hard frame under a pointer: the composer keeps
|
||||
/// more room from it so it does not read as stuck to the edge.
|
||||
const double kChatComposerDesktopBottomMargin = 24;
|
||||
|
||||
/// The composer's bottom gap on [platform] (the running host by default),
|
||||
/// split between phones and desktops as [chatEnterSends] is.
|
||||
double chatComposerBottomMargin([TargetPlatform? platform]) =>
|
||||
chatEnterSends(platform)
|
||||
? kChatComposerDesktopBottomMargin
|
||||
: kChatComposerBottomMargin;
|
||||
|
||||
/// The single primary control's words while a turn is and is not running.
|
||||
const String chatSendLabel = 'Send';
|
||||
const String chatStopLabel = 'Stop';
|
||||
@@ -103,8 +121,13 @@ class ChatComposerBar extends StatefulWidget {
|
||||
this.placeholder = chatComposerPlaceholder,
|
||||
this.enterSends,
|
||||
this.images,
|
||||
this.chatColor,
|
||||
});
|
||||
|
||||
/// The chat's colour name (see `chatSessionColor`), the accent of the
|
||||
/// field's focus ring; null takes the host's primary colour.
|
||||
final String? chatColor;
|
||||
|
||||
/// The transcript's image cache, told about uploaded files so the sent turn
|
||||
/// shows them without a round trip.
|
||||
final ChatAttachmentImages? images;
|
||||
@@ -717,7 +740,12 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
constraints: const BoxConstraints(maxWidth: kChatReadingWidth),
|
||||
child: Padding(
|
||||
key: const Key('chat-composer'),
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 12),
|
||||
padding: EdgeInsetsDirectional.fromSTEB(
|
||||
16,
|
||||
8,
|
||||
16,
|
||||
chatComposerBottomMargin(),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
@@ -797,22 +825,39 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
);
|
||||
}
|
||||
|
||||
static const OutlinedBorder _pillShape = RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(28)),
|
||||
);
|
||||
|
||||
/// The field and its controls in one frosted-glass surface floating over
|
||||
/// the transcript, so the composer reads as a single input rather than a
|
||||
/// row of separate controls, and the conversation shows through it.
|
||||
Widget _pill(BuildContext context, bool cupertino, Widget child) => GlassPill(
|
||||
key: const Key('chat-composer-pill'),
|
||||
cupertino: cupertino,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(28)),
|
||||
),
|
||||
// The end controls keep the same gap from the pill's sides as from its
|
||||
// bottom (and its top while the field is one line).
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
/// row of separate controls, and the conversation shows through it. While
|
||||
/// the field has focus the pill's edge takes the chat's accent.
|
||||
Widget _pill(BuildContext context, bool cupertino, Widget child) =>
|
||||
ComposerFocusRing(
|
||||
focus: _focus,
|
||||
accent: _accent(context, cupertino),
|
||||
shape: _pillShape,
|
||||
child: GlassPill(
|
||||
key: const Key('chat-composer-pill'),
|
||||
cupertino: cupertino,
|
||||
shape: _pillShape,
|
||||
// The end controls keep the same gap from the pill's sides as from
|
||||
// its bottom (and its top while the field is one line).
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/// The chat's accent: its own colour's shade for this host and brightness,
|
||||
/// else the host's primary colour.
|
||||
Color _accent(BuildContext context, bool cupertino) =>
|
||||
chatColorShade(context, widget.chatColor) ??
|
||||
(cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary);
|
||||
|
||||
/// The attach control: a host button that opens the picker, disabled when the
|
||||
/// host has no picker or one prompt is already awaiting its reply.
|
||||
|
||||
@@ -1056,6 +1056,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
placeholder: chatComposerPlaceholderFor(
|
||||
'${widget.session?['directory'] ?? ''}',
|
||||
),
|
||||
chatColor: chatSessionColor(widget.session),
|
||||
backgroundTasks: ChatBackgroundTasks(
|
||||
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
|
||||
gateway: widget.gateway,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The composer's focus indication: a thin ring in the chat's accent colour
|
||||
/// along the pill's edge and a soft glow of the same colour outside it, so
|
||||
/// a focused field shows as such without relying on its caret alone. Both
|
||||
/// fade in and out with focus; at rest unfocused nothing visible is drawn.
|
||||
///
|
||||
/// The accent is the chat's own colour (its highlight in the list) when it
|
||||
/// has one, else the host's primary colour, never the pill's background: the
|
||||
/// ring is translucent so the same tint stays subtle on a light and a dark
|
||||
/// pill.
|
||||
class ComposerFocusRing extends StatelessWidget {
|
||||
const ComposerFocusRing({
|
||||
super.key,
|
||||
required this.focus,
|
||||
required this.accent,
|
||||
required this.shape,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
/// The field's focus node; the ring follows its [FocusNode.hasFocus].
|
||||
final FocusNode focus;
|
||||
|
||||
/// The chat's accent, at full opacity; the ring and glow fade it.
|
||||
final Color accent;
|
||||
|
||||
/// The pill's shape, so the ring hugs its edge.
|
||||
final OutlinedBorder shape;
|
||||
final Widget child;
|
||||
|
||||
/// How long the ring takes to appear or fade.
|
||||
static const Duration duration = Duration(milliseconds: 160);
|
||||
|
||||
/// The ring's stroke, drawn just inside the pill's edge over its hairline.
|
||||
static const double ringWidth = 1.5;
|
||||
|
||||
/// The accent's opacity in the ring while focused.
|
||||
static const double ringOpacity = 0.6;
|
||||
|
||||
/// The accent's opacity in the glow while focused.
|
||||
static const double glowOpacity = 0.18;
|
||||
|
||||
/// The glow's blur radius; it spreads [glowSpread] past the pill first.
|
||||
static const double glowBlur = 12;
|
||||
static const double glowSpread = 1;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: focus,
|
||||
child: child,
|
||||
builder: (context, child) {
|
||||
final focused = focus.hasFocus;
|
||||
// Both decorations keep the same shape, shadow and stroke while only
|
||||
// their colours change, so the container lerps them into one fade.
|
||||
return AnimatedContainer(
|
||||
key: const Key('chat-composer-focus-ring'),
|
||||
duration: duration,
|
||||
curve: Curves.easeOutCubic,
|
||||
decoration: ShapeDecoration(
|
||||
shape: shape,
|
||||
shadows: [
|
||||
BoxShadow(
|
||||
color: accent.withValues(alpha: focused ? glowOpacity : 0),
|
||||
blurRadius: glowBlur,
|
||||
spreadRadius: glowSpread,
|
||||
),
|
||||
],
|
||||
),
|
||||
// Over the child: the pill's fill would otherwise cover the ring.
|
||||
foregroundDecoration: ShapeDecoration(
|
||||
shape: shape.copyWith(
|
||||
side: BorderSide(
|
||||
color: accent.withValues(alpha: focused ? ringOpacity : 0),
|
||||
width: ringWidth,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import 'ui/sessions/chat_sessions_body.dart';
|
||||
import 'ui/sessions/chat_sessions_controller.dart';
|
||||
import 'ui/sessions/chat_sessions_screen.dart';
|
||||
|
||||
part 'chat_screen_keys.dart';
|
||||
part 'chat_screen_workspace.dart';
|
||||
|
||||
/// The Chat destination's list/detail switch.
|
||||
@@ -73,7 +74,8 @@ class ChatScreen extends StatefulWidget {
|
||||
State<ChatScreen> createState() => _ChatScreenState();
|
||||
}
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> with _ChatScreenWorkspace {
|
||||
class _ChatScreenState extends State<ChatScreen>
|
||||
with _ChatScreenWorkspace, _ChatScreenKeys {
|
||||
/// The list's controller, shared with the mounted list screen. The list
|
||||
/// screen refreshes it on mount and swaps its repository when the socket is
|
||||
/// replaced; this destination lists created rows and re-reads after a
|
||||
@@ -141,10 +143,12 @@ class _ChatScreenState extends State<ChatScreen> with _ChatScreenWorkspace {
|
||||
_workspace.open(initial);
|
||||
_workspaceVisible = true;
|
||||
_publishedWorkspaceSession = initial;
|
||||
_noteRecentSession();
|
||||
}
|
||||
_workspace.addListener(_workspaceChanged);
|
||||
_bindWorkspacePersistence();
|
||||
HardwareKeyboard.instance.addHandler(_cycleChatKey);
|
||||
HardwareKeyboard.instance.addHandler(_slashFocusKey);
|
||||
// Seen from now on, so the press that chooses the first chat counts.
|
||||
LastPointerKind.instance;
|
||||
_sessions.addListener(_nextChanged);
|
||||
@@ -201,6 +205,7 @@ class _ChatScreenState extends State<ChatScreen> with _ChatScreenWorkspace {
|
||||
void _openBySelection(JsonMap session) =>
|
||||
_open(session, focusComposer: chatSelectionFocusesComposer(session));
|
||||
|
||||
@override
|
||||
void _open(JsonMap session, {bool focusComposer = false}) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty) return;
|
||||
@@ -254,6 +259,7 @@ class _ChatScreenState extends State<ChatScreen> with _ChatScreenWorkspace {
|
||||
if (accepted != null) _acceptedModels[id] = accepted;
|
||||
_startNotice = (id: id, notice: notice);
|
||||
_openedSessions[id] = <String, dynamic>{...session}..remove('running');
|
||||
_forgetRecentSession(previousId);
|
||||
_workspace.replaceSession(previousId, id);
|
||||
if (_workspace.paneCount == 0) _open(session);
|
||||
}
|
||||
@@ -271,6 +277,7 @@ class _ChatScreenState extends State<ChatScreen> with _ChatScreenWorkspace {
|
||||
/// `/close` was accepted: the conversation leaves, back to the list, which
|
||||
/// re-reads the closed row.
|
||||
void _closed(String sessionId) {
|
||||
_forgetRecentSession(sessionId);
|
||||
for (final pane
|
||||
in _workspace.panes
|
||||
.where((pane) => pane.sessionId == sessionId)
|
||||
@@ -391,6 +398,7 @@ class _ChatScreenState extends State<ChatScreen> with _ChatScreenWorkspace {
|
||||
@override
|
||||
void dispose() {
|
||||
HardwareKeyboard.instance.removeHandler(_cycleChatKey);
|
||||
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
|
||||
_page.dispose();
|
||||
_workspaceBinding?.dispose();
|
||||
_workspace.removeListener(_workspaceChanged);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Slash focuses the composer; Ctrl+Tab over one pane toggles recent chats
|
||||
|
||||
`lib/features/chat/chat_screen_keys.dart` (a part of `screen.dart`) adds two
|
||||
Chat-destination keys, registered on `HardwareKeyboard` for the screen's
|
||||
lifetime like the pane cycling in `chat_screen_workspace.dart`:
|
||||
|
||||
- A bare `/` (matched on the typed character, so it follows the keyboard
|
||||
layout; Ctrl/Alt/Meta chords are left alone, Ctrl+/ stays the shell's Search)
|
||||
requests focus for the active pane's composer through the existing
|
||||
`ChatComposerFocusRequests`. The composer takes it after the frame, once the
|
||||
host has finished delivering the keystroke, so the slash is not typed into
|
||||
it. Nothing happens while any editable text field has focus, while a popup
|
||||
or dialog is open, or on another destination.
|
||||
- Ctrl+Tab (and Ctrl+Shift+Tab) over a single pane swaps in the chat shown
|
||||
before the active one, composer focused, and back again. With no earlier
|
||||
chat this visit it still just focuses the composer; with two or more panes
|
||||
the existing pane cycling is unchanged.
|
||||
|
||||
The visit keeps a most-recent-first list of the chats the workspace has shown
|
||||
(bounded to eight, in memory). It is noted on every workspace change, including
|
||||
a restored layout and the routed first chat; a chat `/close`d or moved by
|
||||
`/new` is dropped, and a server switch clears it.
|
||||
|
||||
Tests: `test/features/chat/chat_keyboard_focus_test.dart`. Widget tests cannot
|
||||
show a browser's text insertion, so "the slash is not typed" rests on the
|
||||
post-frame focus request; the composer text is asserted empty.
|
||||
@@ -0,0 +1,190 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/screen.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/sessions/session_actions.dart';
|
||||
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
|
||||
import 'package:pipelines_app/shell/adaptive_shell.dart';
|
||||
import 'package:pipelines_app/shell/destination.dart';
|
||||
import 'package:shared_preferences/shared_preferences.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', 'c']) {'id': id, 'title': 'Chat $id'},
|
||||
],
|
||||
});
|
||||
}
|
||||
if (type == 'chat_shells') return Future.value({'chat_shells': []});
|
||||
return super.call(type, fields);
|
||||
}
|
||||
}
|
||||
|
||||
Finder _input(String id) => find.descendant(
|
||||
of: find.byKey(ValueKey('chat-composer-$id')),
|
||||
matching: find.byType(EditableText),
|
||||
);
|
||||
EditableText _editable(WidgetTester tester, String id) =>
|
||||
tester.widget<EditableText>(_input(id));
|
||||
Finder _actions(String id) => find.byWidgetPredicate(
|
||||
(widget) => widget is SessionActionsButton && widget.session['id'] == id,
|
||||
);
|
||||
ChatWorkspaceController _workspace(WidgetTester tester) =>
|
||||
tester.widget<ChatWorkspace>(find.byType(ChatWorkspace)).controller;
|
||||
|
||||
Future<void> _setup(WidgetTester tester) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
tester.view.physicalSize = const Size(1800, 1000);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final gateway = _Gateway()..history = (_) async => chatPage([]);
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: AdaptiveShell(
|
||||
destination: AppDestination.chat,
|
||||
destinationBodies: {
|
||||
AppDestination.chat: (_) => ChatScreen(gateway: gateway),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> _openRow(WidgetTester tester, String id) async {
|
||||
await tester.tap(find.byKey(Key('chat-row-$id')));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Puts focus on a sidebar control, outside every text field.
|
||||
Future<void> _focusSidebar(WidgetTester tester) async {
|
||||
final icon = find
|
||||
.descendant(of: _actions('a'), matching: find.byType(Icon))
|
||||
.first;
|
||||
Focus.of(tester.element(icon)).requestFocus();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<bool> _slash(WidgetTester tester) async {
|
||||
final handled = await tester.sendKeyEvent(LogicalKeyboardKey.slash);
|
||||
await tester.pumpAndSettle();
|
||||
return handled;
|
||||
}
|
||||
|
||||
Future<void> _controlTab(WidgetTester tester, {bool shift = false}) async {
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
|
||||
if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('slash outside a text field focuses the composer, untyped', (
|
||||
tester,
|
||||
) async {
|
||||
await _setup(tester);
|
||||
await _openRow(tester, 'a');
|
||||
await _focusSidebar(tester);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse);
|
||||
|
||||
expect(await _slash(tester), isTrue);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
|
||||
expect(_editable(tester, 'a').controller.text, isEmpty);
|
||||
|
||||
// Inside the composer a slash is an ordinary character for the field.
|
||||
expect(await _slash(tester), isFalse);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
|
||||
|
||||
// Shift+/ (a question mark) and Alt+/ are not the shortcut; Ctrl+/ is
|
||||
// the shell's own Search chord.
|
||||
await _focusSidebar(tester);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.slash, character: '?');
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.slash);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
testWidgets('slash leaves a dialog text field and a popup alone', (
|
||||
tester,
|
||||
) async {
|
||||
await _setup(tester);
|
||||
await _openRow(tester, 'a');
|
||||
await tester.tap(_actions('a'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(await _slash(tester), isFalse);
|
||||
expect(find.text('Rename…'), findsOneWidget);
|
||||
await tester.tap(find.text('Rename…'));
|
||||
await tester.pumpAndSettle();
|
||||
final dialogField = find.descendant(
|
||||
of: find.byType(Dialog),
|
||||
matching: find.byType(EditableText),
|
||||
);
|
||||
expect(dialogField, findsOneWidget);
|
||||
await tester.tap(dialogField);
|
||||
await tester.pumpAndSettle();
|
||||
expect(await _slash(tester), isFalse);
|
||||
expect(find.byType(Dialog), findsOneWidget);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
testWidgets('Control Tab over one pane returns to the previous chat', (
|
||||
tester,
|
||||
) async {
|
||||
await _setup(tester);
|
||||
await _openRow(tester, 'a');
|
||||
final workspace = _workspace(tester);
|
||||
// Nothing shown before: the chord only focuses the composer.
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'a');
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
|
||||
|
||||
await _openRow(tester, 'b');
|
||||
await tester.enterText(_input('b'), 'Draft B');
|
||||
await _focusSidebar(tester);
|
||||
for (final id in ['a', 'b', 'a']) {
|
||||
await _controlTab(tester);
|
||||
expect(workspace.paneCount, 1);
|
||||
expect(workspace.activePane?.sessionId, id);
|
||||
expect(_editable(tester, id).focusNode.hasPrimaryFocus, isTrue);
|
||||
}
|
||||
await _controlTab(tester, shift: true);
|
||||
expect(workspace.activePane?.sessionId, 'b');
|
||||
expect(_editable(tester, 'b').controller.text, 'Draft B');
|
||||
|
||||
// A third chat makes the pair c and b; a is no longer one step away.
|
||||
await _openRow(tester, 'c');
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'b');
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'c');
|
||||
|
||||
// Two panes cycle the panes as before, not the history.
|
||||
await tester.tap(_actions('a'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Open to the right'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(workspace.paneCount, 2);
|
||||
expect(workspace.activePane?.sessionId, 'a');
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'c');
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'a');
|
||||
expect(workspace.paneCount, 2);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
|
||||
|
||||
import 'chat_composer_bar_fixtures.dart';
|
||||
|
||||
/// The phones: Fuchsia counts as a keyboard host (Enter sends), like desktop.
|
||||
final _phones = TargetPlatformVariant({
|
||||
TargetPlatform.android,
|
||||
TargetPlatform.iOS,
|
||||
});
|
||||
|
||||
double _bottomMargin(WidgetTester tester) {
|
||||
final padding = tester.widget<Padding>(
|
||||
find.byKey(const Key('chat-composer')),
|
||||
);
|
||||
return (padding.padding as EdgeInsetsDirectional).bottom;
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('phones keep the close bottom margin, desktops a wider one', () {
|
||||
expect(
|
||||
chatComposerBottomMargin(TargetPlatform.android),
|
||||
kChatComposerBottomMargin,
|
||||
);
|
||||
expect(
|
||||
chatComposerBottomMargin(TargetPlatform.iOS),
|
||||
kChatComposerBottomMargin,
|
||||
);
|
||||
for (final desktop in [
|
||||
TargetPlatform.macOS,
|
||||
TargetPlatform.windows,
|
||||
TargetPlatform.linux,
|
||||
]) {
|
||||
expect(
|
||||
chatComposerBottomMargin(desktop),
|
||||
kChatComposerDesktopBottomMargin,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
kChatComposerDesktopBottomMargin,
|
||||
greaterThan(kChatComposerBottomMargin),
|
||||
);
|
||||
});
|
||||
|
||||
group('rendered composer', () {
|
||||
late ComposerBarGateway gateway;
|
||||
|
||||
setUp(() => gateway = ComposerBarGateway()..page = fixtureTurn());
|
||||
tearDown(() => gateway.close());
|
||||
|
||||
testWidgets(
|
||||
'keeps more room from a desktop window bottom',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(composerThread(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_bottomMargin(tester), kChatComposerDesktopBottomMargin);
|
||||
},
|
||||
variant: TargetPlatformVariant.desktop(),
|
||||
);
|
||||
|
||||
testWidgets('stays close to a phone bottom', (tester) async {
|
||||
await tester.pumpWidget(composerThread(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_bottomMargin(tester), kChatComposerBottomMargin);
|
||||
}, variant: _phones);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/composer_focus_ring.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/sessions/chat_color_palette.dart';
|
||||
|
||||
import 'chat_composer_bar_fixtures.dart';
|
||||
|
||||
/// The focus ring wrapping the composer pill: its outer glow and inner ring.
|
||||
({Color glow, BorderSide side}) _ring(WidgetTester tester) {
|
||||
final container = tester.widget<AnimatedContainer>(
|
||||
find.byKey(const Key('chat-composer-focus-ring')),
|
||||
);
|
||||
final glow = (container.decoration! as ShapeDecoration).shadows!.single;
|
||||
final shape = (container.foregroundDecoration! as ShapeDecoration).shape;
|
||||
return (glow: glow.color, side: (shape as RoundedRectangleBorder).side);
|
||||
}
|
||||
|
||||
Future<void> _focusField(WidgetTester tester) async {
|
||||
await tester.tap(find.byKey(const Key('chat-composer-field')));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void main() {
|
||||
late ComposerBarGateway gateway;
|
||||
|
||||
setUp(() => gateway = ComposerBarGateway()..page = fixtureTurn());
|
||||
tearDown(() => gateway.close());
|
||||
|
||||
testWidgets('unfocused composer draws no ring or glow', (tester) async {
|
||||
await tester.pumpWidget(composerThread(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final ring = _ring(tester);
|
||||
expect(ring.side.color.a, 0);
|
||||
expect(ring.glow.a, 0);
|
||||
expect(ring.side.width, ComposerFocusRing.ringWidth);
|
||||
});
|
||||
|
||||
testWidgets('focused composer takes the primary colour as its ring', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(composerThread(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
await _focusField(tester);
|
||||
|
||||
final primary = Theme.of(
|
||||
tester.element(find.byKey(const Key('chat-composer-field'))),
|
||||
).colorScheme.primary;
|
||||
final ring = _ring(tester);
|
||||
expect(
|
||||
ring.side.color,
|
||||
primary.withValues(alpha: ComposerFocusRing.ringOpacity),
|
||||
);
|
||||
expect(ring.glow, primary.withValues(alpha: ComposerFocusRing.glowOpacity));
|
||||
expect(ring.side.width, ComposerFocusRing.ringWidth);
|
||||
});
|
||||
|
||||
testWidgets('a coloured chat lends its own shade to the ring', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
composerThread(gateway, session: {'id': 's', 'color': 'teal'}),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await _focusField(tester);
|
||||
|
||||
final teal = chatColorShade(
|
||||
tester.element(find.byKey(const Key('chat-composer-field'))),
|
||||
'teal',
|
||||
)!;
|
||||
expect(
|
||||
_ring(tester).side.color,
|
||||
teal.withValues(alpha: ComposerFocusRing.ringOpacity),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('the ring fades out again when focus leaves', (tester) async {
|
||||
await tester.pumpWidget(composerThread(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
await _focusField(tester);
|
||||
expect(_ring(tester).side.color.a, greaterThan(0));
|
||||
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
// One frame applies the focus change, the next rebuilds the ring towards
|
||||
// its unfocused decoration, which the container then animates into.
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(_ring(tester).side.color.a, 0);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_ring(tester).glow.a, 0);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino composer rings in the theme primary colour', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(composerThread(gateway, cupertino: true));
|
||||
await tester.pumpAndSettle();
|
||||
await _focusField(tester);
|
||||
|
||||
final primary = CupertinoTheme.of(
|
||||
tester.element(find.byKey(const Key('chat-composer-field'))),
|
||||
).primaryColor;
|
||||
expect(
|
||||
_ring(tester).side.color,
|
||||
primary.withValues(alpha: ComposerFocusRing.ringOpacity),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
# Files panel
|
||||
|
||||
The chat Files panel lists and navigates the active session's server working
|
||||
directory, with filtering, hidden files, sorting, and list/grid presentation.
|
||||
The follow-up slice will add file opening, viewing, downloading, and image
|
||||
thumbnails.
|
||||
directory, with filtering, hidden files, sorting, and list/grid presentation
|
||||
(`app/lib/features/chat/files/`). The follow-up slice adds file opening, viewing,
|
||||
downloading and image thumbnails.
|
||||
|
||||
Server side:
|
||||
|
||||
- Directory listings (`list_directory`) include file `size` (bytes) and RFC3339 UTC
|
||||
`modified` metadata for files; directories carry neither.
|
||||
- `GET /files?path=...` serves one regular file for the client files panel. Paths may be
|
||||
absolute or `~`-prefixed and are resolved through the operator home directory; cleaned
|
||||
paths and symlinks must stay inside that home subtree. Directories, special files and
|
||||
escape paths are refused. Add `download=1` for attachment disposition.
|
||||
|
||||
@@ -3,8 +3,9 @@ package protocol
|
||||
// Directory browsing for the chat folder picker. A client sends
|
||||
// Message{Type: ListDirectory, ID: <opaque>, ListDirectory: &DirectoryListRequest{Path: ...}}
|
||||
// and the server echoes the ID on a DirectoryListing reply. Listing is
|
||||
// restricted to the server user's home directory subtree, returns names and
|
||||
// kinds only (never file contents) and is bounded by DirectoryListingMaxEntries.
|
||||
// restricted to the server user's home directory subtree, returns names, kinds,
|
||||
// and file metadata (never file contents), and is bounded by
|
||||
// DirectoryListingMaxEntries.
|
||||
const (
|
||||
ListDirectory = "list_directory"
|
||||
DirectoryListing = "directory_listing"
|
||||
@@ -23,8 +24,8 @@ type DirectoryListRequest struct {
|
||||
// DirectoryListingResult is the directory_listing reply. Path is the absolute,
|
||||
// cleaned directory listed (expressed under Home), Parent is null at the home
|
||||
// root, and Entries are directories first, then files, each group sorted
|
||||
// case-insensitively. Files are listed by name only so a picker can show
|
||||
// context; they are not selectable.
|
||||
// case-insensitively. Entries include file size and modification time when
|
||||
// available; file contents are never returned, and files are not selectable.
|
||||
type DirectoryListingResult struct {
|
||||
Path string `json:"path"`
|
||||
Home string `json:"home"`
|
||||
@@ -35,11 +36,14 @@ type DirectoryListingResult struct {
|
||||
|
||||
// DirectoryEntry is one listed name. IsDir is true only for a directory (or a
|
||||
// symlink to one) that stays inside the home subtree; IsGitRepo marks a
|
||||
// directory containing .git; Hidden marks a dot-name.
|
||||
// directory containing .git; Hidden marks a dot-name. Size and Modified are
|
||||
// populated for files; directories have no file metadata.
|
||||
type DirectoryEntry struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
IsGitRepo bool `json:"is_git_repo"`
|
||||
Hidden bool `json:"hidden"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Modified string `json:"modified,omitempty"`
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
|
||||
|
||||
- `internal/server/websocket.go` — the `/connect` transport and the request dispatch. Envelope
|
||||
validation lives here; every command returns its own typed reply.
|
||||
- `internal/server/home_files.go` — the contained `/files` endpoint for regular files under the operator home.
|
||||
- `internal/server/runner.go` — run execution: the stage loop, stage outcomes, budgets, retries,
|
||||
ownership and settlement. This is where a run's state changes.
|
||||
- `internal/server/runevents.go` — the push hub: subscriptions scoped per workspace, per-run frames,
|
||||
|
||||
@@ -442,7 +442,7 @@ func resolveChatDirectory(directory string) (string, error) {
|
||||
// location. It is resolved through the standard library so it never falls back
|
||||
// to the process working directory.
|
||||
func OperatorHomeDirectory() (string, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
home, err := operatorHomeDirectory()
|
||||
if err != nil {
|
||||
return "", errors.New("resolve operator home directory: " + err.Error())
|
||||
}
|
||||
@@ -451,3 +451,7 @@ func OperatorHomeDirectory() (string, error) {
|
||||
}
|
||||
return home, nil
|
||||
}
|
||||
|
||||
// operatorHomeDirectory is a seam for tests of filesystem endpoints that are
|
||||
// rooted at the operator's home directory.
|
||||
var operatorHomeDirectory = os.UserHomeDir
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
@@ -131,8 +132,8 @@ func describePathError(path string, err error) error {
|
||||
}
|
||||
|
||||
// readDirectoryEntries reads at most directoryListingScanLimit names, sorts
|
||||
// directories first then case-insensitively, and caps the result. Only names
|
||||
// and kinds are read; no file is opened.
|
||||
// directories first then case-insensitively, and caps the result. No file is
|
||||
// opened.
|
||||
func readDirectoryEntries(realHome, realDir, shown string, maxEntries int) ([]protocol.DirectoryEntry, bool, error) {
|
||||
dir, err := os.Open(realDir)
|
||||
if err != nil {
|
||||
@@ -191,6 +192,12 @@ func describeEntry(realHome, realDir, shown string, item fs.DirEntry) protocol.D
|
||||
entry.IsDir = true
|
||||
}
|
||||
}
|
||||
if !entry.IsDir {
|
||||
if info, err := item.Info(); err == nil {
|
||||
entry.Size = info.Size()
|
||||
entry.Modified = info.ModTime().UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
if entry.IsDir {
|
||||
if _, err := os.Lstat(filepath.Join(full, ".git")); err == nil {
|
||||
entry.IsGitRepo = true
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
@@ -95,6 +96,35 @@ func TestListDirectorySubdirectoryHasParent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirectoryFileMetadata(t *testing.T) {
|
||||
home, _ := newListingHome(t)
|
||||
file := filepath.Join(home, "Notes.txt")
|
||||
modified := time.Date(2024, time.March, 14, 15, 9, 26, 0, time.UTC)
|
||||
if err := os.Chtimes(file, modified, modified); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
listing, err := listHomeDirectory(home, "~", protocol.DirectoryListingMaxEntries)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var gotFile, gotDir protocol.DirectoryEntry
|
||||
for _, entry := range listing.Entries {
|
||||
switch entry.Name {
|
||||
case "Notes.txt":
|
||||
gotFile = entry
|
||||
case "repo":
|
||||
gotDir = entry
|
||||
}
|
||||
}
|
||||
if gotFile.Size != int64(len("secret contents")) || gotFile.Modified != modified.Format(time.RFC3339) {
|
||||
t.Fatalf("file metadata = %+v", gotFile)
|
||||
}
|
||||
if gotDir.Size != 0 || gotDir.Modified != "" {
|
||||
t.Fatalf("directory metadata = %+v", gotDir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirectoryRefusesPathsOutsideHome(t *testing.T) {
|
||||
home, outside := newListingHome(t)
|
||||
if err := os.Symlink(outside, filepath.Join(home, "escape")); err != nil {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func serveHomeFile(w http.ResponseWriter, r *http.Request) {
|
||||
home, err := OperatorHomeDirectory()
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
serveHomeFileFrom(w, r, home)
|
||||
}
|
||||
|
||||
func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
|
||||
home = filepath.Clean(home)
|
||||
realHome, err := filepath.EvalSymlinks(home)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
target, err := expandHomePath(home, r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
http.Error(w, "file not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, realTarget, err := resolveInsideHome(realHome, target)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "outside the home directory") {
|
||||
http.Error(w, "file access denied", http.StatusForbidden)
|
||||
} else {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
info, err := os.Stat(realTarget)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if info.IsDir() || !info.Mode().IsRegular() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if specialFilesystem(realTarget) {
|
||||
http.Error(w, "file access denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
file, err := os.Open(realTarget)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrPermission) {
|
||||
http.Error(w, "file access denied", http.StatusForbidden)
|
||||
} else {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
w.Header().Set("Cache-Control", "private, no-cache")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
contentType := mime.TypeByExtension(filepath.Ext(realTarget))
|
||||
if contentType == "" {
|
||||
var sample [512]byte
|
||||
n, readErr := file.Read(sample[:])
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
contentType = http.DetectContentType(sample[:n])
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
disposition := "inline"
|
||||
if r.URL.Query().Get("download") == "1" {
|
||||
disposition = "attachment"
|
||||
}
|
||||
w.Header().Set("Content-Disposition", contentDisposition(disposition, filepath.Base(realTarget)))
|
||||
http.ServeContent(w, r, filepath.Base(realTarget), info.ModTime(), file)
|
||||
}
|
||||
|
||||
func contentDisposition(kind, filename string) string {
|
||||
// The ASCII fallback keeps older clients useful; filename* preserves the
|
||||
// actual name for clients that implement RFC 6266/RFC 5987.
|
||||
fallback := strings.Map(func(r rune) rune {
|
||||
if r < 0x20 || r > 0x7e || r == '"' || r == '\\' {
|
||||
return '_'
|
||||
}
|
||||
return r
|
||||
}, filename)
|
||||
if fallback == "" {
|
||||
fallback = "file"
|
||||
}
|
||||
return kind + `; filename="` + fallback + `"; filename*=UTF-8''` + rfc5987(filename)
|
||||
}
|
||||
|
||||
func rfc5987(value string) string {
|
||||
const hex = "0123456789ABCDEF"
|
||||
var b strings.Builder
|
||||
for _, c := range []byte(value) {
|
||||
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strings.ContainsRune("!#$&+-.^_`|~", rune(c)) {
|
||||
b.WriteByte(c)
|
||||
} else {
|
||||
b.WriteByte('%')
|
||||
b.WriteByte(hex[c>>4])
|
||||
b.WriteByte(hex[c&15])
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestServeHomeFile(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
home := filepath.Join(root, "home")
|
||||
outside := filepath.Join(root, "outside.txt")
|
||||
if err := os.Mkdir(home, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(home, "hello.txt"), []byte("hello file contents"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(home, "résumé"), []byte("plain"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(home, "escape")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
originalHomeDirectory := operatorHomeDirectory
|
||||
operatorHomeDirectory = func() (string, error) { return home, nil }
|
||||
t.Cleanup(func() { operatorHomeDirectory = originalHomeDirectory })
|
||||
t.Run("operator home seam", func(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
serveHomeFile(recorder, httptest.NewRequest(http.MethodGet, "/files?path=~/hello.txt", nil))
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "hello file contents" {
|
||||
t.Fatalf("response = %d %q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"happy path", "~/hello.txt", http.StatusOK},
|
||||
{"directory refused", "~", http.StatusNotFound},
|
||||
{"dot dot refused", filepath.Join(home, "..", "outside.txt"), http.StatusForbidden},
|
||||
{"symlink refused", "~/escape", http.StatusForbidden},
|
||||
{"missing file", "~/missing", http.StatusNotFound},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/files?path="+tc.path, nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
serveHomeFileFrom(recorder, req, home)
|
||||
if recorder.Code != tc.want {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("download disposition and range", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/files?path=~/hello.txt&download=1", nil)
|
||||
req.Header.Set("Range", "bytes=0-4")
|
||||
recorder := httptest.NewRecorder()
|
||||
serveHomeFileFrom(recorder, req, home)
|
||||
if recorder.Code != http.StatusPartialContent || recorder.Body.String() != "hello" {
|
||||
t.Fatalf("response = %d %q, want 206 hello", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if got := recorder.Header().Get("Content-Disposition"); got != `attachment; filename="hello.txt"; filename*=UTF-8''hello.txt` {
|
||||
t.Fatalf("disposition = %q", got)
|
||||
}
|
||||
if recorder.Header().Get("Content-Type") != "text/plain; charset=utf-8" {
|
||||
t.Fatalf("content type = %q", recorder.Header().Get("Content-Type"))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("non ASCII disposition", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/files?path=~/r%C3%A9sum%C3%A9", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
serveHomeFileFrom(recorder, req, home)
|
||||
if !strings.Contains(recorder.Header().Get("Content-Disposition"), "filename*=UTF-8''r%C3%A9sum%C3%A9") {
|
||||
t.Fatal(recorder.Header().Get("Content-Disposition"))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -154,6 +154,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
}
|
||||
runs.serveArtifact(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /files", serveHomeFile)
|
||||
mux.HandleFunc("POST /chat-uploads", serveChatUpload)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
Reference in New Issue
Block a user