diff --git a/README.md b/README.md index 057e4f55..4137d756 100644 --- a/README.md +++ b/README.md @@ -1,198 +1,40 @@ # Pipelines -Small, reusable AI workflows for coding, research and everyday project work, -plus chats with the coding agents you already use. - -Pipelines is one per-user server with two clients: - -- **The app** (Flutter): served as a web app behind a sign-in, and as an - **Android APK**. -- **CLI and TUI** (`pipelines`) for scripting, inspection and authoring. - -A **pipeline** is a versioned Markdown definition of stages (model, human -decision, notification). A **run** executes it in a project directory on the -server machine. A **chat** is a conversation with an agent harness (OpenCode, -Claude Code or Codex) that the server keeps going while you are away. - -**Alpha:** single-user, supervised work. Models make mistakes and editing -stages change files and run commands. Start in a disposable project, review -results, and expect provider charges. - -![Workflow](docs/images/workflow.png) +Pipelines is a per-user server and CLI for running reusable AI workflows and chatting with coding agents. ## Install -```sh -git clone https://git.a-wan.net/alan/pipelines.git -cd pipelines -./install # server + CLI + web app, login autostart -./install --web # rebuild only the web app after app changes -./install --apk # optional: Android app, offered to phones for update -./install --linux # Linux x64 client archive, built in Docker -./install --macos --flutter /path/to/flutter # native macOS client archive -``` - -Needs Go (version in `go.mod`), Node.js 18+, Python 3.9+, git, curl, a C -compiler, a **running Docker** (the web app is built in Docker; the install -refuses without it) and an existing OpenCode on `PATH`. The installer never -installs these for you. See [Installation](docs/install.md). - -Then open the URL the installer prints (default `http://localhost:8082/`) -and sign in with the password you chose. Put the CLI on your `PATH` as in the -[terminal quick start](#terminal-quick-start). - -### Linux quick start (Debian/Ubuntu) +From this checkout, run: ```sh -# Prerequisites: git, curl, a C compiler, Python 3, Node.js 18+ and Docker. -sudo apt update -sudo apt install -y git curl build-essential python3 nodejs npm docker.io -sudo usermod -aG docker "$USER" # then log out and back in (or: newgrp docker) - -# Go: the version in go.mod is newer than most distro packages; use go.dev. -curl -fsSL "https://go.dev/dl/$(curl -fsSL 'https://go.dev/VERSION?m=text' | head -1).linux-amd64.tar.gz" \ - | sudo tar -C /usr/local -xz -export PATH="/usr/local/go/bin:$PATH" - -# OpenCode (required: it runs pipeline stages and chat by default). -curl -fsSL https://opencode.ai/install | bash - -git clone https://git.a-wan.net/alan/pipelines.git && cd pipelines ./install - -# Keep the server running after you log out (systemd --user service). -sudo loginctl enable-linger "$USER" ``` -Check `node --version` is 18 or newer (older distros: install Node from -nodejs.org or NodeSource). On ARM machines use `linux-arm64` in the Go URL. - -### Set up harnesses - -One command per harness (native or Docker install). Each checks the CLI is -installed (printing the install command if not), signs in with the harness's -own login when needed, picks default models for OpenCode/Pi, and verifies it -the way the server does. No restart needed. +If `pipelines` is not already on your `PATH`, add it: ```sh -pipelines harness setup opencode # stages + chat (required; ./install configured it) -pipelines harness setup pi # pipeline stages -pipelines harness setup claude # chat -pipelines harness setup codex # chat -pipelines harness list # status of all four +export PATH="$HOME/.local/share/pipelines/bin:$PATH" ``` -## What you can do +## Set up harnesses -**Runs** -- Runs list with filters, sorting (including largest on disk and most tokens) - and multi-select delete. Each row shows the run's size and reported token - total (`≥` when some stages did not report). -- Run detail: Summary (with size, tokens split fresh versus cached, and the - reported cost), Timeline, and Artifacts and Changes when the run has any. -- Artifacts viewer for files a stage produced, including the recorded session - export (`session.html`), with a full-screen view where HTML pages scroll, - zoom and open their links. -- Changes: the file diffs each stage made in the workspace. -- Human decision stages: a run waits for you; decide in the app or with - `pipelines decide`. -- Retry from the failed stage, cancel, rename, per-run model overrides. - -**Pipelines** -- A new install starts with four [example pipelines](examples/README.md), - from one stage to a review loop and a human decision; they are also the - template set. -- Draft-first authoring with a harness, versioned publishing, import/export - as ZIP. -- [Schedules](docs/schedules.md): recurring runs of an existing pipeline. -- Search across pipelines, versions, runs, steps, fields and artifacts. - -**Chat** -- Chat with **OpenCode**, **Claude Code** or **Codex** in any folder on the - server, picked with the folder picker. -- Send messages while the agent is working: Claude Code and Codex receive them - mid-turn; otherwise the server queues them durably and delivers them in order - when the turn ends, even with no client attached. -- Approvals, questions, uploads, model choice and interrupt in the app. -- Adopt an existing harness session with `pipelines chat-adopt`. - -**Notifications** -- The Android app keeps its own connection and shows notifications in the - background (no ntfy app needed). -- Settings: any run ended, chat needs you, chat reply finished, and - **Also send to ntfy** for devices that still use ntfy. - -Pi runs pipeline stages (`harness=pi`) but is not offered as a chat harness. -Claude Code runs chats and pipeline stages (`harness=claude`). -See [Harnesses](docs/harnesses.md). - -## Architecture - -``` - browser / Android app ──HTTPS (tailscale serve) or HTTP──┐ - ▼ - web proxy (node, 0.0.0.0:8082) ── sign-in, web app, /updates/ - │ same-origin /connect, /artifacts/ - ▼ - pipelines CLI/TUI ──ws://127.0.0.1:8080/connect──► pipelines-server (SQLite) - │ - ┌────────────────────┬───────────────┼───────────────┐ - ▼ ▼ ▼ ▼ - opencode serve pi (RPC) claude (stdio) Codex App Server - stages + chat stages chat chat (socket) - │ - ▼ - ntfy (8090, optional fallback) -``` - -- **One server process** (`pipelines-server`) owns the database, runs, chats - and notifications. Its API has no authentication and binds to - `127.0.0.1:8080` by default. -- **One web app.** The authenticated Node proxy (`web/serve.mjs`) serves the - installed web build and proxies to the server. Every address (localhost, - LAN, tailnet) reaches this same proxy. -- **Tailnet HTTPS.** When `PIPELINES_WEB_PUBLIC_URL` is an `https://*.ts.net` - address, `./install` runs `tailscale serve` to point it at the proxy. -- **ntfy** is built from source and runs alongside, for optional fallback - delivery and stage notification hooks. -- A login service (launchd on macOS, `systemd --user` on Linux) supervises the - server, web proxy and ntfy together. - -## Terminal quick start +Run the command for each harness you want to use: ```sh -export PATH="$HOME/.local/share/pipelines/bin:$PATH" # add to ~/.bashrc or ~/.zshrc -pipelines status -cd /path/to/your/project -pipelines # TUI -pipelines run "pipeline name" "Describe a small task" -pipelines runs -pipelines inspect 1 -pipelines doctor +pipelines harness setup claude +pipelines harness setup codex +pipelines harness setup opencode +pipelines harness setup pi ``` -Runs use the directory you start them from, on the server machine. A browser -on another computer does not upload its files. +## Update -## Documentation +```sh +pipelines update +``` -- [Installation and lifecycle](docs/install.md) -- [Harnesses: OpenCode, Claude Code, Codex, Pi](docs/harnesses.md) -- [Notifications](docs/notifications.md) · [ntfy reference](docs/ntfy.md) -- [CLI and authoring](docs/cli.md) -- [Schedules](docs/schedules.md) -- [Pipeline format](internal/author/skill/references/format.md) -- [Reasoning effort and stage limits](docs/harnesses-and-control.md) -- [Chat backend details](docs/chat-backends.md) -- [Artifacts](docs/stage-artifacts.md) · [File diffs](docs/stage-file-diffs.md) -- [Transfer pipeline definitions](docs/pipeline-transfer.md) -- [Docker installation](docs/docker.md) -- [Web proxy](web/README.md) -- [Alpha walkthrough and known limits](docs/first-version-testing.md) +## Uninstall -When reporting a problem, include your OS, install mode, reproduction steps, -`pipelines version --json` and `pipelines ping --json`. Redact credentials and -private content; do not post your database or harness session storage. - -To completely reset Pipelines, including its password and data, run `./uninstall` -from this checkout, then `./install` for a fresh setup. The checkout is retained. +```sh +./uninstall +``` diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 6746219e..f3a52b45 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -689,6 +689,13 @@ class _PipelinesAppState extends State AppRoute? _chatWorkspaceRoute; Set? _availableChatSessionIds; + /// After Ctrl+K or Alt+K shows Chat: the keyboard goes to the open chat's + /// composer, if a chat is open. + void _focusOpenChatComposer() { + final id = _chatWorkspaceRoute?.chatSessionId; + if (id != null) _chatRuntime.composerFocus.request(id); + } + void _selectDestination(AppDestination destination) { final current = tabForRoute(_delegate.route); final last = _tabRoutes[destination]; @@ -825,6 +832,7 @@ class _PipelinesAppState extends State runningRunCount: counts.running, destination: _destinationOf(route.kind), onDestinationSelected: _selectDestination, + onOpenChat: _focusOpenChatComposer, onClosePage: () => _delegate.goTo( _bodyRoutes[AppDestination.pipelines] ?? AppRoute.pipelines, ), diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 5f0d6cc2..b5c2bdb4 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -147,11 +147,14 @@ mixin _ChatScreenWorkspace on State { /// 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. While the app's - /// terminal is shown, Ctrl+Tab moves between its tabs instead. + /// terminal is shown, Ctrl+Tab moves between its tabs instead. While a + /// floating chat window holds the keyboard, Ctrl+Tab cycles those windows + /// (see [ChatWindows]). bool _cycleChatKey(KeyEvent event) { final keyboard = HardwareKeyboard.instance; if (event is! KeyDownEvent || TerminalScope.peek(context)?.claimsTabKeys == true || + keyboardWindow()?.entry.kind == chatWindowKind || event.logicalKey != LogicalKeyboardKey.tab || !keyboard.isControlPressed || keyboard.isMetaPressed || diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 77b66fd5..d3544afa 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,5 +1,6 @@ import 'chat_pane_content.dart'; import 'chat_runtime.dart'; +import 'windows/chat_window_tabs.dart'; import 'windows/chat_windows.dart'; import 'workspace/federated_workspace_store.dart'; import '../../core/servers/chat/federated_chat_gateway.dart'; diff --git a/app/lib/features/chat/windows/chat_window_tabs.dart b/app/lib/features/chat/windows/chat_window_tabs.dart new file mode 100644 index 00000000..4bcc9763 --- /dev/null +++ b/app/lib/features/chat/windows/chat_window_tabs.dart @@ -0,0 +1,39 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../../../shell/windows/window_entry.dart'; +import '../../../shell/windows/window_scope.dart'; + +/// The step Ctrl+Tab (1) or Ctrl+Shift+Tab (-1) moves between floating chat +/// windows, or null for any other key. Command+Tab stays with the system. +int? chatWindowTabStep(KeyEvent event, HardwareKeyboard keyboard) { + if (event is! KeyDownEvent || + event.logicalKey != LogicalKeyboardKey.tab || + !keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isAltPressed) { + return null; + } + return keyboard.isShiftPressed ? -1 : 1; +} + +/// The window [step] away from the window [currentId] in [visible] (bottom +/// to top), wrapping around. Null when [currentId] is not listed or there is +/// no other window to move to. +WindowEntry? chatWindowAfter( + List visible, + String currentId, + int step, +) { + final at = visible.indexWhere((w) => w.id == currentId); + if (at < 0 || visible.length < 2) return null; + return visible[(at + step) % visible.length]; +} + +/// The floating window whose content holds the keyboard, if one does. Read +/// from the focused node's ancestors, so it needs no reference to the host. +WindowScope? keyboardWindow() { + final context = FocusManager.instance.primaryFocus?.context; + if (context == null) return null; + return context.findAncestorWidgetOfExactType(); +} diff --git a/app/lib/features/chat/windows/chat_windows.dart b/app/lib/features/chat/windows/chat_windows.dart index 247dd879..c2c7fb59 100644 --- a/app/lib/features/chat/windows/chat_windows.dart +++ b/app/lib/features/chat/windows/chat_windows.dart @@ -8,11 +8,13 @@ import '../../../shell/list_detail_policy.dart'; import '../../../shell/windows/window_entry.dart'; import '../../../shell/windows/window_kind.dart'; import '../../../shell/windows/window_manager.dart'; +import '../../terminal/terminal_scope.dart'; import '../chat_runtime.dart'; import '../domain/chat_commands.dart'; import '../workspace/chat_float_shortcut.dart'; import '../workspace/chat_float_store.dart'; import 'chat_window_content.dart'; +import 'chat_window_tabs.dart'; const chatWindowKind = 'chat'; @@ -79,7 +81,9 @@ class ChatWindows { if (_started) return; _started = true; manager.kinds.register(kind); - FocusManager.instance.addEarlyKeyEventHandler(_key); + FocusManager.instance + ..addEarlyKeyEventHandler(_key) + ..addEarlyKeyEventHandler(_tabKey); runtime.addSessionReplacedListener(_replacedElsewhere); runtime.sessions.addListener(_rowsChanged); manager.addListener(_rowsChanged); @@ -89,7 +93,9 @@ class ChatWindows { void dispose() { if (!_started) return; _started = false; - FocusManager.instance.removeEarlyKeyEventHandler(_key); + FocusManager.instance + ..removeEarlyKeyEventHandler(_key) + ..removeEarlyKeyEventHandler(_tabKey); runtime.removeSessionReplacedListener(_replacedElsewhere); runtime.sessions.removeListener(_rowsChanged); manager.removeListener(_rowsChanged); @@ -224,6 +230,36 @@ class ChatWindows { if (event is KeyDownEvent) manager.toggleOrRaiseGroup(chatWindowKind); return KeyEventResult.handled; } + + /// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the + /// keyboard: the next (previous) visible chat window, in stacking order and + /// wrapping, comes to the top. The window host then gives it the keyboard, + /// its composer. Left alone when another window or the tiling has the + /// keyboard, when the terminal claims tab keys, or with one window. + KeyEventResult _tabKey(KeyEvent event) { + final step = chatWindowTabStep(event, HardwareKeyboard.instance); + if (step == null || !_wide) return KeyEventResult.ignored; + final scope = keyboardWindow(); + if (scope == null || + scope.entry.kind != chatWindowKind || + _terminalClaimsTabs()) { + return KeyEventResult.ignored; + } + final target = chatWindowAfter( + windows.where(manager.isVisible).toList(), + scope.entry.id, + step, + ); + if (target == null) return KeyEventResult.ignored; + manager.raise(target.id); + return KeyEventResult.handled; + } + + bool _terminalClaimsTabs() { + final context = FocusManager.instance.primaryFocus?.context; + return context != null && + TerminalScope.peek(context)?.claimsTabKeys == true; + } } class _Never implements Listenable { diff --git a/app/lib/features/chat/workspace/chat_center_stage_edges.dart b/app/lib/features/chat/workspace/chat_center_stage_edges.dart new file mode 100644 index 00000000..27f16de1 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_edges.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; + +import 'chat_center_stage_layout.dart'; + +/// Hairline thickness of a center-stage edge. +const double chatCenterStageEdgeThickness = 1; + +/// Where the stage's two hairlines sit: each in the gap beside the stage, or on +/// the workspace edge when the stage reaches it. Returns (left, right). +(Rect, Rect) chatCenterStageEdgeRects(Rect stage, Size size) { + final half = chatCenterStageGap / 2; + const t = chatCenterStageEdgeThickness; + final maxX = size.width - t; + final leftX = stage.left <= 0 + ? 0.0 + : (stage.left - half - t / 2).clamp(0.0, maxX).toDouble(); + final rightX = stage.right >= size.width + ? maxX + : (stage.right + half - t / 2).clamp(0.0, maxX).toDouble(); + return ( + Rect.fromLTWH(leftX, 0, t, size.height), + Rect.fromLTWH(rightX, 0, t, size.height), + ); +} + +/// The stage's left and right hairlines in the workspace's stack, drawn in the +/// theme's outlineVariant so the centred chat column has a visible boundary. +/// Only center stage calls this; the split layout keeps its own dividers. +List chatCenterStageEdges({ + required BuildContext context, + required Rect rect, + required Size size, +}) { + final color = Theme.of(context).colorScheme.outlineVariant; + final (left, right) = chatCenterStageEdgeRects(rect, size); + return [ + Positioned.fromRect( + key: const ValueKey('chat-center-stage-edge-left'), + rect: left, + child: ColoredBox(color: color), + ), + Positioned.fromRect( + key: const ValueKey('chat-center-stage-edge-right'), + rect: right, + child: ColoredBox(color: color), + ), + ]; +} diff --git a/app/lib/features/chat/workspace/chat_workspace_surface.dart b/app/lib/features/chat/workspace/chat_workspace_surface.dart index ea55ea46..d958d5bd 100644 --- a/app/lib/features/chat/workspace/chat_workspace_surface.dart +++ b/app/lib/features/chat/workspace/chat_workspace_surface.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'chat_center_stage_edges.dart'; import 'chat_center_stage_motion.dart'; import 'chat_center_stage_strip.dart'; import 'chat_mobile_panes.dart'; @@ -138,6 +139,12 @@ Widget chatWorkspaceSurface({ for (final pane in livePanes) if (pane.key == ValueKey('chat-workspace-${motion.topPaneId}')) pane, + if (stage.stage case final layout?) + ...chatCenterStageEdges( + context: context, + rect: stage.rectFor(layout.stageId)!, + size: size, + ), if (mobile?.peekId != null && !motion.isAnimating) Positioned( top: mobile!.contentHeight - 12, diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index a4ce79f4..22f12a9d 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -4,6 +4,7 @@ import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; import '../terminal/terminal_shortcuts.dart'; import '../../shell/windows/window_shortcuts.dart'; +import '../../shell/shell_chat_shortcut.dart'; import '../../shell/shell_search_shortcut_labels.dart'; /// A shortcut entry shown in the in-app help. Keeping these entries together @@ -53,6 +54,13 @@ class KeyboardShortcutRegistry { caveat: 'Brings a chat forward from Terminal and focuses its message input.', ), + KeyboardShortcutEntry( + action: 'Open Chat', + keys: shellChatShortcutLabels(platform).join(', '), + caveat: web + ? 'Shows the open chat and focuses its message input. The browser may reserve Ctrl+K.' + : 'Shows the open chat and focuses its message input. In the terminal Ctrl+K stays kill-line; Alt+K still opens Chat.', + ), KeyboardShortcutEntry( action: 'Toggle Center Stage', keys: diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index e74e3266..60a97fa4 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -9,6 +9,7 @@ import 'destination.dart'; import 'list_detail.dart'; import 'list_pane_widths.dart'; import 'shell_bar.dart'; +import 'shell_chat_shortcut.dart'; import 'shell_list_shortcuts.dart'; import 'shell_search_shortcut_labels.dart'; import 'tab_history.dart'; @@ -22,6 +23,7 @@ class AdaptiveShell extends StatefulWidget { this.onDestinationSelected, this.onClosePage, this.onSearch, + this.onOpenChat, this.attentionCount = 0, this.runningRunCount, this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(), @@ -47,6 +49,10 @@ class AdaptiveShell extends StatefulWidget { /// shell tests and compositions without routing keep their tab set only. final VoidCallback? onSearch; + /// Runs after Ctrl+K or Alt+K has shown the Chat destination (also when it + /// was already shown), so the open chat's composer can take the keyboard. + final VoidCallback? onOpenChat; + /// Runs needing the operator today, retained in the tab's accessible label. final int attentionCount; @@ -271,9 +277,16 @@ class _AdaptiveShellState extends State { /// fields. Split-pane navigation belongs to the chat workspace; tab changes /// have no global keyboard chord. bool _handleDestinationKeyEvent(KeyEvent event) { + final keyboard = HardwareKeyboard.instance; + // Ctrl+K is the terminal's kill-line while the terminal has the keyboard; + // Alt+K still opens Chat there. + if (shellChatShortcut(event, keyboard) && + (keyboard.isAltPressed || !primaryFocusIsTypingSurface())) { + if (event is KeyDownEvent) _openChat(); + return true; + } // A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits). if (primaryFocusIsTypingSurface()) return false; - final keyboard = HardwareKeyboard.instance; if (_selected == AppDestination.search && event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape && @@ -299,6 +312,13 @@ class _AdaptiveShellState extends State { return _bar.lists.open(AppDestination.chat, listIndex); } + /// Shows Chat (the tab's own selection, so its open chat returns) and then + /// lets the app focus that chat's composer. + void _openChat() { + if (_selected != AppDestination.chat) _select(AppDestination.chat); + widget.onOpenChat?.call(); + } + /// A popup or nested viewer owns Escape before the underlying Search tab. bool _searchEscape() { final route = ModalRoute.of(context); diff --git a/app/lib/shell/shell_chat_shortcut.dart b/app/lib/shell/shell_chat_shortcut.dart new file mode 100644 index 00000000..52cb1de4 --- /dev/null +++ b/app/lib/shell/shell_chat_shortcut.dart @@ -0,0 +1,29 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// Whether [event] opens the Chat destination from any destination: Ctrl+K, +/// or Alt+K (Option+K on Apple platforms). Alt+K is recognised by key position +/// too, because Option+K yields a dead-key symbol on a Mac. Shift, Cmd and +/// chords with both Ctrl and Alt are not the shortcut. Repeats of a held chord +/// match as well, so the caller can swallow them; only its first press acts. +bool shellChatShortcut(KeyEvent event, HardwareKeyboard keyboard) { + if (event is KeyUpEvent || + keyboard.isShiftPressed || + keyboard.isMetaPressed) { + return false; + } + final control = keyboard.isControlPressed; + final alt = keyboard.isAltPressed; + if (control == alt) return false; + if (event.logicalKey == LogicalKeyboardKey.keyK) return true; + return alt && event.physicalKey == PhysicalKeyboardKey.keyK; +} + +/// The chords that open Chat as they read on this platform, for the help +/// page. Alt (Option on Apple platforms) leads, as it does for the floating +/// chats; Ctrl+K is the other chord everywhere. +List shellChatShortcutLabels([TargetPlatform? platform]) { + final target = platform ?? defaultTargetPlatform; + final apple = target == TargetPlatform.macOS || target == TargetPlatform.iOS; + return [apple ? 'Option+K' : 'Alt+K', 'Ctrl+K']; +} diff --git a/app/notes/center-stage-column-edges.md b/app/notes/center-stage-column-edges.md new file mode 100644 index 00000000..999f8326 --- /dev/null +++ b/app/notes/center-stage-column-edges.md @@ -0,0 +1,40 @@ +# Center stage column edges + +## Change +- In center stage (Alt+E / Option+E), the centred chat column had no visible + boundary: its neighbours are strips or the workspace background, so the + column's end read as unfinished. +- Added two 1px `outlineVariant` hairlines (`ChatCenterStageEdges` in + `app/lib/features/chat/workspace/chat_center_stage_edges.dart`). Each sits + centred in the 12px gap beside the stage, or on the workspace edge when the + stage reaches it. +- Painted from `chat_workspace_surface.dart`, only while a stage layout exists. + The split layout, phone/collapsed layouts and single-chat workspaces draw + nothing new. +- Reading width is unchanged (stage stays `chatCenterStageWidth`, 950 at the + test size). The lines travel with the stage's animated rectangle. + +## Focused results +- `tool/memwatch/full.sh 'test/features/chat/workspace/chat_center_stage_test.dart'` + → PASS: 21 passed, 0 failed, 0 skipped; peak 893 MB; 8s; exit 0. + New tests among them: + - `the stage edges sit in the gaps beside the stage, or on the workspace edge` + - `center stage draws the column edges in the light theme, only on stage` + - `center stage draws the column edges in the dark theme, only on stage` +- `tool/analyze.sh` → clean, exit 0. +- Not run: other `test/features/chat/workspace/*` files use `ChatWorkspace` + without `centerStage` on stage, so the new branch is not reached there. The + land gate runs the suites. + +## Affected states (code-level only) +- Center stage on, 3 panes, light and dark: both hairlines present, colour is + the theme's `outlineVariant`. +- Center stage off: no hairlines (asserted in both themes). +- Stage with a neighbour on each side (gaps) and stage at a workspace edge + (line on the edge) are both covered by the geometry test. + +## Limitations +- No browser or device capture was made; `ui-review` owns visual evidence. + Visual weight of a 1px `outlineVariant` line in light and dark is unverified. +- Hairlines hide at once when leaving center stage (same as the split + dividers); they do not fade. diff --git a/app/notes/chat-floating-pane.md b/app/notes/chat-floating-pane.md index 54407bbc..e17dcb38 100644 --- a/app/notes/chat-floating-pane.md +++ b/app/notes/chat-floating-pane.md @@ -29,6 +29,14 @@ every destination and come back at app start without Chat being opened. terminal). On macOS Ctrl+Y in a terminal always goes to the shell. - **Focus**: a window that shows or comes to the top puts the keyboard in its composer; hiding the last window gives it back to what had it. +- **Cycle**: while a floating chat window's content holds the keyboard (a + composer, a Files page inside it), Ctrl+Tab brings the next visible chat + window to the top and Ctrl+Shift+Tab the previous one, wrapping round. The + order is the stacking order, bottom to top, and the window's composer takes + the keyboard. Command+Tab stays with the system. With the tiling focused, + Ctrl+Tab still cycles its panes; while the terminal claims tab keys (shown) + it switches terminal tabs. Alt+` (`windowCycleShortcut`) still cycles every + kind of window, not only chats. - **Popups**: sheets, dialogs, menus and tooltips opened from a floating chat are above every window. Files opens as a page inside the window, and a file opened from it stays in the window. Because the window's own title bar names @@ -60,6 +68,23 @@ every destination and come back at app start without Chat being opened. ## Checks +- Focused, 2026-11-12, `tool/memwatch/full.sh` with + `test/features/chat/chat_floating_pane_test.dart` and + `test/features/terminal/terminal_chat_tab_test.dart`: 16 passed, 0 failed. + New in the first: Ctrl+Tab and Ctrl+Shift+Tab over three floating chats + (order, wrap, composer focus, Command+Tab ignored); with the tiling focused + Ctrl+Tab moves the active pane and leaves the windows alone, and with one + window focused it does nothing; a terminal that claims tab keys keeps + Ctrl+Tab over a focused chat window. +- `tool/analyze.sh` on the changed paths: clean. +- Affected states: two or more floating chats; one floating chat; tiling + focused; a window focused with the terminal shown (claimed); Command+Tab. +- 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). +- Observed, not changed: in the widget harness, floating from a pane's More + menu does not leave the keyboard in the new window's composer (the window + takes it); the chord and Ctrl+Tab do. + - `test/features/chat/chat_floating_pane_test.dart` (the Chat screen with the window host), `test/features/chat/windows/chat_windows_test.dart`, `test/features/chat/workspace/chat_workspace_float_test.dart`, diff --git a/app/notes/ctrl-k-alt-k-open-chat.md b/app/notes/ctrl-k-alt-k-open-chat.md new file mode 100644 index 00000000..d50457b8 --- /dev/null +++ b/app/notes/ctrl-k-alt-k-open-chat.md @@ -0,0 +1,32 @@ +# Ctrl+K / Alt+K open Chat + +Run 391 (ctrl-k-and-alt-k-open-chat), stage 01-implement. Not committed. + +## Behaviour +- Ctrl+K, or Alt+K (Option+K on Apple platforms, matched by physical key so the dead-key symbol still counts), switches the shell to the Chat destination from any destination, then calls `AdaptiveShell.onOpenChat`. +- The app passes `_focusOpenChatComposer`, which requests the composer of the last workspace chat (`_chatWorkspaceRoute`) through `ChatRuntime.composerFocus`. +- Ctrl+K is left to the terminal while the terminal has the keyboard (`primaryFocusIsTypingSurface`). Alt+K still switches there. +- Shift, Meta, or Ctrl+Alt together do not match. Repeats are swallowed; only the first key-down acts. +- The help page has an "Open Chat" entry: `Option+K, Ctrl+K` on macOS, `Alt+K, Ctrl+K` elsewhere. + +## Changed paths +- `app/lib/shell/shell_chat_shortcut.dart` (new): `shellChatShortcut`, `shellChatShortcutLabels`. +- `app/lib/shell/adaptive_shell.dart`: key handling, `_openChat`, `onOpenChat` parameter. +- `app/lib/application/pipelines_app.dart`: `_focusOpenChatComposer`, wired as `onOpenChat`. +- `app/lib/features/settings/keyboard_shortcuts_registry.dart`: "Open Chat" entry. +- `app/test/shell/shell_chat_shortcut_test.dart` (new): matcher, switch from another destination, controlled shell callback, terminal exception. +- `app/test/application/chat_open_shortcut_test.dart` (new): the full `PipelinesApp` opens `/chat/s1`, moves to Runs, then Alt+K and Ctrl+K each return to `/chat/s1` and put the keyboard in the `s1` composer (primary focus). +- `app/test/features/settings/keyboard_shortcuts_help_test.dart`: "Open Chat" help entry test. + +## Focused results +- Review follow-up (composer focus), `tool/memwatch/full.sh 'test/application/chat_open_shortcut_test.dart test/shell/shell_chat_shortcut_test.dart test/features/settings/keyboard_shortcuts_help_test.dart'`: PASS, 12 passed, 0 failed, peak 1306 MB, 5s, exit 0. Run after `dart format` on the new test. +- Mutation check: with the `_focusOpenChatComposer` request removed from `pipelines_app.dart`, `chat_open_shortcut_test.dart` fails on the composer focus expectation. The source was restored afterwards; `git diff` shows the original wiring. +- Earlier stage run (not repeated here): `test/shell/destination_shortcuts_test.dart`, `test/shell/search_shortcuts_test.dart`, `test/features/chat/workspace/chat_float_shortcut_test.dart` passed with the shell test and help test (21 passed, 0 failed, peak 1062 MB). +- `tool/analyze.sh`: clean. +- Tests that press K chords: none outside the new files. The new shell check returns false for every other key, so the earlier typing-surface and search paths keep their order. + +## Not covered +- The composer-focus test drives the real app with a fake channel; it does not cover a chat opened only through a route with no history yet. +- No UI capture or device run (ui-review owns that). +- Ctrl+Y: the float chord is not left to the terminal. `chatFloatShortcut` matches Ctrl+Y on every platform, and `chat_floating_pane_test.dart` covers Ctrl+Y from the terminal on macOS. Ctrl+K was made the only terminal exception, as the task asked. +- On web, the browser may keep Ctrl+K (address/search focus); the help caveat says so. diff --git a/app/test/application/chat_open_shortcut_test.dart b/app/test/application/chat_open_shortcut_test.dart new file mode 100644 index 00000000..17440c4d --- /dev/null +++ b/app/test/application/chat_open_shortcut_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import 'chat_registration_test.dart' + show replyHistory, replySessions, replySubscribe, webServer; + +bool _composerFocused(WidgetTester tester, String id) => tester + .widget( + find.descendant( + of: find.byKey(ValueKey('chat-composer-$id')), + matching: find.byType(EditableText), + ), + ) + .focusNode + .hasPrimaryFocus; + +Future _chord(WidgetTester tester, LogicalKeyboardKey modifier) async { + await tester.sendKeyDownEvent(modifier); + await tester.sendKeyEvent(LogicalKeyboardKey.keyK); + await tester.sendKeyUpEvent(modifier); + await tester.pump(); + await tester.pump(); +} + +void main() { + testWidgets( + 'Ctrl+K and Alt+K from another destination focus the open chat composer', + (tester) async { + tester.view.physicalSize = const Size(900, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')), + ); + addTearDown(provider.dispose); + + await tester.pumpWidget( + PipelinesApp( + androidSupported: false, + server: webServer(), + client: client, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + await replySessions(tester, channel); + await replySubscribe(tester, channel); + await replyHistory(tester, channel); + await tester.pumpAndSettle(); + + expect(find.byType(ChatThreadView), findsOneWidget); + expect(_composerFocused(tester, 's1'), isFalse); + + // Leave Chat for another destination, then clear any focus left over. + await tester.tap(find.byKey(const ValueKey('shell.destination.runs'))); + await tester.pump(const Duration(milliseconds: 600)); + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + expect(provider.value.uri.path, '/runs'); + + await _chord(tester, LogicalKeyboardKey.altLeft); + expect(provider.value.uri.path, '/chat/s1'); + expect(find.byType(ChatThreadView), findsOneWidget); + expect(_composerFocused(tester, 's1'), isTrue); + expect(tester.takeException(), isNull); + + // Ctrl+K does the same from another destination. + await tester.tap(find.byKey(const ValueKey('shell.destination.runs'))); + await tester.pump(const Duration(milliseconds: 600)); + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + expect(_composerFocused(tester, 's1'), isFalse); + + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(provider.value.uri.path, '/chat/s1'); + expect(find.byType(ChatThreadView), findsOneWidget); + expect(_composerFocused(tester, 's1'), isTrue); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); +} diff --git a/app/test/features/chat/chat_floating_pane_test.dart b/app/test/features/chat/chat_floating_pane_test.dart index d5b13fea..9ae25bda 100644 --- a/app/test/features/chat/chat_floating_pane_test.dart +++ b/app/test/features/chat/chat_floating_pane_test.dart @@ -11,6 +11,7 @@ import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; +import 'package:pipelines_app/features/terminal/terminal_scope.dart'; import 'package:pipelines_app/shell/windows/window_frame.dart'; import 'package:pipelines_app/shell/windows/window_host.dart'; import 'package:pipelines_app/shell/windows/window_kind.dart'; @@ -48,6 +49,16 @@ class _Store implements WindowStore { } } +class _ClaimingTerminal implements TerminalActions { + const _ClaimingTerminal(); + @override + void toggle() {} + @override + bool get claimsTabKeys => true; + @override + Future openAt(ApiGateway gateway, String cwd) async => null; +} + class _TerminalKind extends WindowKind { @override String get key => 'terminal'; @@ -105,6 +116,7 @@ class _App { WidgetTester tester, { Size size = const Size(1800, 1000), bool terminalSurface = false, + bool terminalClaimsTabs = false, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -124,6 +136,13 @@ class _App { ); await tester.pumpWidget( MaterialApp( + // A terminal that shows its tabs: it claims Ctrl+Tab. + builder: terminalClaimsTabs + ? (context, child) => TerminalScope( + actions: const _ClaimingTerminal(), + child: child!, + ) + : null, home: Scaffold( body: Stack( fit: StackFit.expand, @@ -218,6 +237,19 @@ Future _chord(WidgetTester tester) async { await tester.pumpAndSettle(); } +/// Ctrl+Tab, or Ctrl+Shift+Tab with [shift]. +Future _tab(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(); +} + +bool _composerFocused(WidgetTester tester, String id) => + tester.widget(_input(id)).focusNode.hasPrimaryFocus; + Future _controlChord(WidgetTester tester) async { await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyEvent(LogicalKeyboardKey.keyY); @@ -452,6 +484,91 @@ void main() { await app.stop(tester); }); + testWidgets('Ctrl+Tab and Ctrl+Shift+Tab cycle the floating chat windows, ' + 'each composer taking the keyboard', (tester) async { + await _saved('a', 'b', 'c'); + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); + await _menu(tester, 'c', 'Float (Alt+Y)'); + await _menu(tester, 'a', 'Float (Alt+Y)'); + expect(app.floating, ['b', 'c', 'a']); + + // Command+Tab belongs to the system. + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pumpAndSettle(); + expect(app.floating, ['b', 'c', 'a']); + + await _tab(tester); + expect(app.floating, ['c', 'a', 'b']); + expect(_composerFocused(tester, 'b'), isTrue); + // Past the top, the bottom window comes up again. + await _tab(tester); + expect(app.floating, ['a', 'b', 'c']); + expect(_composerFocused(tester, 'c'), isTrue); + await _tab(tester, shift: true); + expect(app.floating, ['a', 'c', 'b']); + expect(_composerFocused(tester, 'b'), isTrue); + await _tab(tester, shift: true); + expect(app.floating, ['a', 'b', 'c']); + expect(_composerFocused(tester, 'c'), isTrue); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('with the tiling focused Ctrl+Tab cycles its panes and leaves ' + 'the windows alone', (tester) async { + await _saved('a', 'b', 'c'); + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'c', 'Float (Alt+Y)'); + expect(app.floating, ['c']); + final controller = _workspace(tester); + + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pump(); + expect(controller.activePane?.sessionId, 'a'); + await _tab(tester); + expect(controller.activePane?.sessionId, 'b'); + expect(_composerFocused(tester, 'b'), isTrue); + expect(app.floating, ['c']); + + // With a window focused, the panes stay where they are; a single window + // has nothing to cycle to. + await tester.tapAt(tester.getCenter(_input('c'))); + await tester.pump(); + expect(_composerFocused(tester, 'c'), isTrue); + await _tab(tester); + expect(controller.activePane?.sessionId, 'b'); + expect(app.floating, ['c']); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('a terminal that claims tab keys keeps Ctrl+Tab over a focused ' + 'floating chat', (tester) async { + await _saved('a', 'b', 'c'); + final app = _App(_Store()); + await app.start(tester, terminalClaimsTabs: true); + await _menu(tester, 'b', 'Float (Alt+Y)'); + await _menu(tester, 'c', 'Float (Alt+Y)'); + expect(app.floating, ['b', 'c']); + await tester.tapAt(tester.getCenter(_input('c'))); + await tester.pump(); + expect(_composerFocused(tester, 'c'), isTrue); + + // The terminal's tabs get the key (its own handler is not in this app); + // neither the windows nor the panes move. + await _tab(tester); + expect(app.floating, ['b', 'c']); + expect(_composerFocused(tester, 'c'), isTrue); + expect(_workspace(tester).activePane?.sessionId, 'a'); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + testWidgets('a floating chat types, runs its tickers, hides and shows over ' 'another destination', (tester) async { await _saved('a', 'b'); diff --git a/app/test/features/chat/workspace/chat_center_stage_test.dart b/app/test/features/chat/workspace/chat_center_stage_test.dart index 52bc959f..1c637ef2 100644 --- a/app/test/features/chat/workspace/chat_center_stage_test.dart +++ b/app/test/features/chat/workspace/chat_center_stage_test.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/chat/workspace/chat_center_stage_controller.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_center_stage_edges.dart'; import 'package:pipelines_app/features/chat/workspace/chat_center_stage_keys.dart'; import 'package:pipelines_app/features/chat/workspace/chat_center_stage_layout.dart'; import 'package:pipelines_app/features/chat/workspace/chat_center_stage_strip.dart'; @@ -82,7 +83,10 @@ Widget host( List? fieldKeys, bool actionBars = false, bool filesProbe = false, + ThemeMode themeMode = ThemeMode.light, }) => MaterialApp( + themeMode: themeMode, + darkTheme: ThemeData.dark(), home: MediaQuery( data: MediaQueryData(disableAnimations: reduceMotion), child: Scaffold( @@ -410,6 +414,71 @@ void main() { }, ); + test( + 'the stage edges sit in the gaps beside the stage, or on the workspace edge', + () { + final (left, right) = chatCenterStageEdgeRects( + const Rect.fromLTWH(418, 0, 950, 800), + const Size(1368, 800), + ); + expect(left, const Rect.fromLTWH(411.5, 0, 1, 800)); + expect(right, const Rect.fromLTWH(1367, 0, 1, 800)); + + // A stage that reaches the workspace's right edge keeps its hairline inside. + final (edgeLeft, edgeRight) = chatCenterStageEdgeRects( + const Rect.fromLTWH(650, 0, 950, 800), + const Size(1600, 800), + ); + expect(edgeLeft, const Rect.fromLTWH(643.5, 0, 1, 800)); + expect(edgeRight, const Rect.fromLTWH(1599, 0, 1, 800)); + }, + ); + + for (final mode in [ThemeMode.light, ThemeMode.dark]) { + testWidgets( + 'center stage draws the column edges in the ${mode.name} theme, only on stage', + (tester) async { + wide(tester); + final workspace = threePanes(); + final stage = ChatCenterStageController(store: _MemoryStore()); + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + await tester.pumpWidget(host(workspace, stage, themeMode: mode)); + await tester.pumpAndSettle(); + const leftKey = ValueKey('chat-center-stage-edge-left'); + const rightKey = ValueKey('chat-center-stage-edge-right'); + expect(find.byKey(leftKey), findsNothing); + expect(find.byKey(rightKey), findsNothing); + + stage.value = true; + await tester.pumpAndSettle(); + final outline = Theme.of( + tester.element(find.byType(ChatWorkspace)), + ).colorScheme.outlineVariant; + for (final key in [leftKey, rightKey]) { + expect( + tester + .widget( + find.descendant( + of: find.byKey(key), + matching: find.byType(ColoredBox), + ), + ) + .color, + outline, + ); + } + // The hairlines frame the stage; the reading width is unchanged. + expect(widthOf(tester, 'three'), 950); + + stage.value = false; + await tester.pumpAndSettle(); + expect(find.byKey(leftKey), findsNothing); + expect(find.byKey(rightKey), findsNothing); + }, + ); + } + testWidgets('reduced motion stages at once', (tester) async { wide(tester); final workspace = threePanes(); diff --git a/app/test/features/settings/keyboard_shortcuts_help_test.dart b/app/test/features/settings/keyboard_shortcuts_help_test.dart index 80fa97e1..f070d2e7 100644 --- a/app/test/features/settings/keyboard_shortcuts_help_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_help_test.dart @@ -23,6 +23,23 @@ void main() { expect(search.caveat, contains('browser')); }); + test( + 'Open Chat lists Option+K or Alt+K with Ctrl+K and the terminal rule', + () { + KeyboardShortcutEntry openChat(TargetPlatform platform) => + KeyboardShortcutRegistry( + platform: platform, + web: false, + ).entries.firstWhere((entry) => entry.action == 'Open Chat'); + + expect(openChat(TargetPlatform.macOS).keys, 'Option+K, Ctrl+K'); + final linux = openChat(TargetPlatform.linux); + expect(linux.keys, 'Alt+K, Ctrl+K'); + expect(linux.caveat, contains('kill-line')); + expect(openChat(TargetPlatform.windows).keys, 'Alt+K, Ctrl+K'); + }, + ); + test('uses the shell primary modifier rule on iOS', () { final entries = const KeyboardShortcutRegistry( platform: TargetPlatform.iOS, diff --git a/app/test/shell/shell_chat_shortcut_test.dart b/app/test/shell/shell_chat_shortcut_test.dart new file mode 100644 index 00000000..69a873d4 --- /dev/null +++ b/app/test/shell/shell_chat_shortcut_test.dart @@ -0,0 +1,181 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/shell_chat_shortcut.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +const _k = KeyDownEvent( + physicalKey: PhysicalKeyboardKey.keyK, + logicalKey: LogicalKeyboardKey.keyK, + timeStamp: Duration.zero, +); + +void main() { + test('Ctrl+K and Alt+K open Chat; other modifiers and plain K do not', () { + bool chord(Set held, [KeyEvent event = _k]) => + shellChatShortcut(event, _FakeKeyboard(held)); + expect(chord({}), isFalse); + expect(chord({LogicalKeyboardKey.controlLeft}), isTrue); + expect(chord({LogicalKeyboardKey.altLeft}), isTrue); + expect( + chord({LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.altLeft}), + isFalse, + ); + expect( + chord({LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.shiftLeft}), + isFalse, + ); + expect(chord({LogicalKeyboardKey.metaLeft}), isFalse); + expect( + chord({LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.metaLeft}), + isFalse, + ); + expect( + shellChatShortcut( + const KeyUpEvent( + physicalKey: PhysicalKeyboardKey.keyK, + logicalKey: LogicalKeyboardKey.keyK, + timeStamp: Duration.zero, + ), + _FakeKeyboard({LogicalKeyboardKey.controlLeft}), + ), + isFalse, + ); + }); + + test('Option+K matches by key position though it types a symbol', () { + // On a Mac, Option+K produces ˚: the logical key is not K. + const ring = KeyDownEvent( + physicalKey: PhysicalKeyboardKey.keyK, + logicalKey: LogicalKeyboardKey(0x02da), + character: '˚', + timeStamp: Duration.zero, + ); + expect( + shellChatShortcut(ring, _FakeKeyboard({LogicalKeyboardKey.altLeft})), + isTrue, + ); + // Without Alt the same symbol is ordinary typing. + expect(shellChatShortcut(ring, _FakeKeyboard({})), isFalse); + }); + + test('labels name the Option chord on Apple platforms', () { + expect(shellChatShortcutLabels(TargetPlatform.linux), ['Alt+K', 'Ctrl+K']); + expect(shellChatShortcutLabels(TargetPlatform.macOS), [ + 'Option+K', + 'Ctrl+K', + ]); + }); + + testWidgets('Ctrl+K and Alt+K show Chat from another destination', ( + tester, + ) async { + var opened = 0; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destinationBodies: { + for (final destination in shellTabDestinations) + destination: (_) => Text('${destination.name} body'), + }, + onOpenChat: () => opened++, + ), + ), + ); + expect(find.text('pipelines body'), isOnstage); + // Chat is built on its first visit only. + expect(find.text('chat body'), findsNothing); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyK); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + // The outgoing tab fades out while still mounted, so Chat being built + // and onstage is the switch. + expect(find.text('chat body'), isOnstage); + expect(opened, 1); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyK); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expect(find.text('chat body'), isOnstage); + // Already in Chat, the chord still hands the keyboard to the composer. + expect(opened, 2); + expect(tester.takeException(), isNull); + }); + + testWidgets('a controlled shell reports the switch to Chat', (tester) async { + final selected = []; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.runs, + onDestinationSelected: selected.add, + destinationBodies: { + for (final destination in shellTabDestinations) + destination: (_) => Text('${destination.name} body'), + }, + ), + ), + ); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyK); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expect(selected, [AppDestination.chat]); + }); + + testWidgets( + 'terminal keeps Ctrl+K for kill-line but Alt+K still opens Chat', + (tester) async { + final terminal = FocusNode(); + addTearDown(terminal.dispose); + var opened = 0; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + onOpenChat: () => opened++, + destinationBodies: { + AppDestination.pipelines: (_) => TypingSurface( + child: Focus( + focusNode: terminal, + child: const Text('terminal'), + ), + ), + AppDestination.chat: (_) => const Text('chat body'), + }, + ), + ), + ); + terminal.requestFocus(); + await tester.pump(); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyK); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect(find.text('chat body'), findsNothing); + expect(find.text('terminal'), isOnstage); + expect(opened, 0); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyK); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expect(find.text('chat body'), isOnstage); + expect(opened, 1); + expect(tester.takeException(), isNull); + }, + ); +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this.pressed); + final Set pressed; + @override + bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key); +} diff --git a/docs/images/workflow.png b/docs/images/workflow.png deleted file mode 100644 index 5b6d4833..00000000 Binary files a/docs/images/workflow.png and /dev/null differ diff --git a/scripts/app_build.py b/scripts/app_build.py index b0c0a05a..e51250a3 100644 --- a/scripts/app_build.py +++ b/scripts/app_build.py @@ -48,6 +48,7 @@ SKIPPED = {"build", ".dart_tool", ".gradle", ".cxx", "local.properties", ".DS_St # generated cannot be mistaken for complete web releases. WEB_CACHE_SCHEMA = "web-release-metadata-v1" WEB_RELEASE_SCHEMA = 1 +VERBOSE = False def flutter_version(app=APP): @@ -103,6 +104,7 @@ def web_cache_complete(entry): def docker(runner, *args, quiet=False): + quiet = quiet or not VERBOSE result = runner(["docker", *args], capture_output=quiet, text=True) if result.returncode: detail = (result.stderr or "").strip().splitlines()[-1:] if quiet else [] @@ -410,12 +412,15 @@ def main(argv=None): parser.add_argument("--publish", action="store_true", help="Publish desktop archive and update feed to this installation") parser.add_argument("--output", type=Path, help="Desktop archive output directory (default: build cache)") parser.add_argument("--flutter", help="Native Flutter executable for macOS and Android (or PIPELINES_FLUTTER/PATH)") + parser.add_argument("--verbose", action="store_true", help="Show full build and tool output") build_mode = parser.add_mutually_exclusive_group() build_mode.add_argument("--native", dest="native", action="store_true", default=None, help="APK: build on this machine with the host Flutter and Android SDK") build_mode.add_argument("--docker", dest="native", action="store_false", help="APK: build in Docker even when a host toolchain exists") args = parser.parse_args(argv) + global VERBOSE + VERBOSE = args.verbose if args.kind in ("linux", "macos"): spec = importlib.util.spec_from_file_location("pipelines_desktop_build", Path(__file__).with_name("app_desktop_build.py")) desktop = importlib.util.module_from_spec(spec) diff --git a/scripts/setup-native.py b/scripts/setup-native.py index 6a3a6b16..7c343d28 100644 --- a/scripts/setup-native.py +++ b/scripts/setup-native.py @@ -72,6 +72,29 @@ class Setup: self.popen = popen self.resolver = resolver or release_lookup.resolve_ntfy self.environ = environ if environ is not None else os.environ + self.verbose = False + self.install_log = None + + def command(self, arguments, **kwargs): + """Run an installer command, keeping tool output out of normal output.""" + if self.verbose: + return self.runner(arguments, **kwargs) + kwargs = dict(kwargs) + kwargs.update(capture_output=True, text=True) + result = self.runner(arguments, **kwargs) + if self.install_log: + self.install_log.parent.mkdir(parents=True, exist_ok=True) + with self.install_log.open("a") as log: + log.write(f"$ {shlex.join(map(str, arguments))}\n") + if result.stdout: + log.write(result.stdout) + if result.stderr: + log.write(result.stderr) + log.write(f"[exit {result.returncode}]\n") + return result + + def step(self, text): + print(f"• {text}") # --- detection ------------------------------------------------------- @@ -261,7 +284,7 @@ class Setup: for field, flag in (("model", "--model"), ("pipeline_model", "--pipeline-model")): if self._valid_model(current.get(field)): command.extend([flag, current[field]]) - result = self.runner(command, cwd=str(Path.home()), env=dict(self.environ)) + result = self.command(command, cwd=str(Path.home()), env=dict(self.environ)) if result.returncode: raise ValueError("Model selection did not complete; native setup is not ready. Rerun ./install or supply --model PROVIDER/MODEL.") return self.configure_harnesses(harness, model, allow_picker=False) @@ -340,7 +363,7 @@ class Setup: # Tool-manager shims dispatch by their invoked name (for example Volta). # Resolving the symlink would run volta-shim instead of node. node = str(Path(shutil.which("node")).absolute()) - version = self.runner([node, "--version"], capture_output=True, text=True) + version = self.command([node, "--version"], capture_output=True, text=True) try: major = int(version.stdout.strip().removeprefix("v").split(".")[0]) except (ValueError, AttributeError): @@ -425,7 +448,7 @@ class Setup: raise ValueError("Docker is not running, so the web app cannot be built. The server is never " "installed without it; start Docker and rerun ./install.") try: - built = app_build.build("web", runner=self.runner, + built = app_build.build("web", runner=self.command, arguments=app_build.update_signing.dart_defines(self.environ)) except RuntimeError as error: raise ValueError(f"The web app build failed ({error}); nothing was installed") from None @@ -453,7 +476,7 @@ class Setup: plist = Path.home() / f"Library/LaunchAgents/{self.LEGACY_WEB_LABEL}.plist" if not plist.is_file(): return - self.runner(["launchctl", "bootout", f"gui/{os.getuid()}/{self.LEGACY_WEB_LABEL}"], + self.command(["launchctl", "bootout", f"gui/{os.getuid()}/{self.LEGACY_WEB_LABEL}"], capture_output=True, text=True) plist.rename(plist.with_name(plist.name + ".disabled")) print(f"Retired the old standalone web agent {self.LEGACY_WEB_LABEL} (kept as {plist.name}.disabled).") @@ -468,7 +491,7 @@ class Setup: if not tailscale: raise ValueError(f"The public web URL {public_url} is a tailnet address but tailscale is not on PATH") port = parsed.port or 443 - result = self.runner([tailscale, "serve", "--bg", f"--https={port}", f"http://127.0.0.1:{web_port}"], + result = self.command([tailscale, "serve", "--bg", f"--https={port}", f"http://127.0.0.1:{web_port}"], capture_output=True, text=True) if result.returncode: raise ValueError(f"tailscale serve could not point {public_url} at the web app: " @@ -488,7 +511,7 @@ class Setup: shutil.rmtree(staging, ignore_errors=True) staging.mkdir(parents=True) for command in self.COMMANDS: - result = self.runner( + result = self.command( ["go", "build", "-trimpath", "-o", str(staging / command), "./cmd/" + command], cwd=str(self.directory)) if result.returncode: @@ -557,7 +580,7 @@ class Setup: return f"{version} (commit {commit})" if commit else str(version) def install_skill(self, prefix): - result = self.runner([str(prefix / "bin/pipelines"), "skill", "install"], cwd=str(self.directory)) + result = self.command([str(prefix / "bin/pipelines"), "skill", "install"], cwd=str(self.directory)) if result.returncode: raise ValueError("pipelines skill install failed; the native install is incomplete") @@ -588,10 +611,10 @@ class Setup: return path self.require_compiler() pinned = f"{module}@{version}" - result = self.runner(["go", "mod", "download", pinned], cwd=str(self.directory)) + result = self.command(["go", "mod", "download", pinned], cwd=str(self.directory)) if result.returncode: raise ValueError(f"go mod download {pinned} failed; the native install is incomplete") - cache = self.runner(["go", "env", "GOMODCACHE"], cwd=str(self.directory), + cache = self.command(["go", "env", "GOMODCACHE"], cwd=str(self.directory), capture_output=True, text=True) if cache.returncode or not (cache.stdout or "").strip(): raise ValueError("Could not locate the Go module cache to build ntfy from") @@ -606,7 +629,7 @@ class Setup: shutil.copytree(source, checkout, symlinks=True) # The module cache is read-only and carries no built web assets; the # upstream Makefile creates the same placeholders for local builds. - self.runner(["chmod", "-R", "u+w", str(checkout)]) + self.command(["chmod", "-R", "u+w", str(checkout)]) (checkout / "server/docs").mkdir(parents=True, exist_ok=True) (checkout / "server/site").mkdir(parents=True, exist_ok=True) (checkout / "server/docs/index.html").touch() @@ -614,7 +637,7 @@ class Setup: built = Path(staging) / "ntfy" env = dict(self.environ) env["CGO_ENABLED"] = "1" - build = self.runner( + build = self.command( ["go", "build", "-trimpath", "-tags", NTFY_BUILD_TAGS, "-ldflags", f"-s -w -X main.version={version}", "-o", str(built), "."], cwd=str(checkout), env=env) @@ -670,7 +693,7 @@ class Setup: if password is not None: # `ntfy user add` takes the password from here instead of a prompt. env["NTFY_PASSWORD"] = password - result = self.runner([str(prefix / "bin/ntfy"), *args], capture_output=capture, text=True, env=env) + result = self.command([str(prefix / "bin/ntfy"), *args], capture_output=capture, text=True, env=env) if result.returncode: step = " ".join(args[:2]) raise ValueError(f"ntfy {step} failed; the native install is incomplete") @@ -726,7 +749,7 @@ class Setup: def docker_volumes(self): try: - result = self.runner(["docker", "volume", "ls", "--format", "{{.Name}}"], + result = self.command(["docker", "volume", "ls", "--format", "{{.Name}}"], capture_output=True, text=True) except FileNotFoundError: # No Docker CLI at all: there is no Docker installation to migrate. @@ -743,7 +766,7 @@ class Setup: return tuple(name for name in ("pipelines_pipelines-data", "pipelines_ntfy-data") if name in names) def _migration_image(self): - result = self.runner(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"], + result = self.command(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"], capture_output=True, text=True) if result.returncode: return None @@ -759,12 +782,12 @@ class Setup: print(f"Keeping existing native {destination.name}; not overwriting it during migration.") return False name = f"pipelines-migrate-{os.getpid()}" - created = self.runner(["docker", "create", "--name", name, "--volume", f"{volume}:/mnt:ro", image], + created = self.command(["docker", "create", "--name", name, "--volume", f"{volume}:/mnt:ro", image], capture_output=True, text=True) if created.returncode: raise ValueError(f"Could not open Docker volume {volume} for migration; install aborted") try: - result = self.runner(["docker", "cp", f"{name}:/mnt/{inner}", str(destination)], + result = self.command(["docker", "cp", f"{name}:/mnt/{inner}", str(destination)], capture_output=True, text=True) if result.returncode: raise ValueError(f"Could not copy {inner} from Docker volume {volume}; install aborted") @@ -774,12 +797,12 @@ class Setup: for suffix in ("-wal",): sidecar = Path(str(destination) + suffix) sidecar.unlink(missing_ok=True) - copy = self.runner(["docker", "cp", f"{name}:/mnt/{inner}{suffix}", str(sidecar)], + copy = self.command(["docker", "cp", f"{name}:/mnt/{inner}{suffix}", str(sidecar)], capture_output=True, text=True) if copy.returncode or not sidecar.exists() or sidecar.stat().st_size == 0: sidecar.unlink(missing_ok=True) finally: - self.runner(["docker", "rm", "-f", name], capture_output=True, text=True, check=False) + self.command(["docker", "rm", "-f", name], capture_output=True, text=True, check=False) return True def migrate_docker(self, prefix, replace=False): @@ -871,9 +894,12 @@ class Setup: resolution = self.resolve_ntfy() # All or nothing: the web app and the server are both built before # either is installed, and a failed build leaves the old pair running. + self.step("Building the web app") web_build = self.build_app_web() self.prepare_layout(prefix) + self.step("Building Pipelines") self.build(prefix) + self.step("Configuring the installation") web = self.configure_web(prefix, args, web_build) self.install_binaries(prefix) self.check_path_shadow(prefix) @@ -909,7 +935,7 @@ class Setup: if self.environ.get(key): opencode_env[key] = self.environ[key] opencode_env["PIPELINES_DEFAULT_MODEL"] = args.model or pipeline_model - web_url = f"http://{web_access.default_url_host(web, lan_ip, web_access.tailnet_ipv4(self.runner))}:{args.web_port}" + web_url = f"http://{web_access.default_url_host(web, lan_ip, web_access.tailnet_ipv4(self.command))}:{args.web_port}" opencode_env["PIPELINES_WEB_PUBLIC_URL"] = web_public_url or web_url path_value = str(prefix / "bin") + os.pathsep + self.environ.get("PATH", "") manifest = { @@ -949,14 +975,9 @@ class Setup: # Docker address. endpoint = f"ws://127.0.0.1:{args.port}/connect" client_path = configure.configure_client(endpoint, self.environ) - print(f"Saved native client default: {endpoint} ({client_path}). Restart the TUI.") - override = self.environ.get("PIPELINES_URL", "") - if override and override != endpoint: - print("WARNING: PIPELINES_URL overrides the saved native address; unset it or pass --url explicitly.") - print(f"Native Pipelines installed at {prefix}." - f" ntfy {resolution.get('tag') or resolution.get('version')} was built from source.") + self.step("Starting the services") # Parity with the Docker installer: leave the server and ntfy running. - started = self.runner([python, str(prefix / "lib/manage.py"), "start", "--prefix", str(prefix)]) + started = self.command([python, str(prefix / "lib/manage.py"), "start", "--prefix", str(prefix)]) if started.returncode: raise ValueError( "The native services were installed but could not be started; run " @@ -965,29 +986,18 @@ class Setup: f"{args.port}, {args.ntfy_port} and {args.web_port} are free (a running Docker installation may use them).") self.retire_legacy_web() self.serve_on_tailnet(opencode_env["PIPELINES_WEB_PUBLIC_URL"], args.web_port) - print(f"ntfy is configured for {base_url}; server, web proxy and ntfy have login autostart ({service_path}).") - print("Phone notifications: subscribe to the 'pipelines' topic as phone-reader with the web password.") - print(f"Web: {web_url}/ (sign-in password in {web['auth_file']}; existing credentials retained).") - print("Web proxy access: " + ("loopback + tailnet" + (" + LAN" if args.web_lan else "") - if args.web_host == web_access.TAILNET else f"bound to {args.web_host}")) - for note in (*web_warnings, web_access.public_url_warning(opencode_env["PIPELINES_WEB_PUBLIC_URL"], web), - web_access.firewall_note(self.runner)): - if note: - print(note) - print("Login autostart is already enabled. To enable/start it again, run:\n " - + shlex.join([str(prefix / "bin/pipelines"), "service", "enable"])) - print("Android app (optional, slower): ./install --apk builds it in Docker and offers it at " - f"{opencode_env['PIPELINES_WEB_PUBLIC_URL']}/updates/.") - print("Configured server role: " + ("single-user authoring enabled (web pipeline creation/publication allowed)." - if allow_authoring else "execution-only (pipeline publication disabled).")) - if args.bind_address == "0.0.0.0": - print(f"Phone client server URL: ws://{lan_ip}:{args.port}/connect " - "(use a workspace path that exists on this server).") - else: - print(f"Unauthenticated API bound to {args.bind_address}:{args.port}; use the authenticated web URL.") + print("\nPipelines installed") + print(f"Install location: {prefix}") app_build.print_web_urls(manifest, lan_host=lan_ip) - print("OpenCode is required (default stage and chat harness) and is set up by ./install.") - print("Next: set up your agent harnesses: pipelines harness setup claude|codex|opencode|pi") + bin_dir = prefix / "bin" + path_entries = self.environ.get("PATH", "").split(os.pathsep) + if str(bin_dir) not in path_entries: + shell = Path(self.environ.get("SHELL", "")).name + rc = "~/.bashrc" if shell == "bash" else "~/.zshrc" if shell == "zsh" else "~/.profile" + displayed_bin = "$HOME/.local/share/pipelines/bin" if bin_dir == Path.home() / ".local/share/pipelines/bin" else str(bin_dir) + print(f"Add commands to PATH: echo 'export PATH=\"{displayed_bin}:$PATH\"' >> {rc}") + print(f"Update later: {prefix / 'bin/pipelines'} update") + print(f"Set up harnesses: {prefix / 'bin/pipelines'} harness setup claude|codex|opencode|pi") def arguments(argv=None): @@ -1020,17 +1030,29 @@ def arguments(argv=None): help="Start with empty data even when an earlier Docker installation's volumes exist") parser.add_argument("--replace-data", action="store_true", help="Allow Docker migration to replace an existing native database/auth store") + parser.add_argument("--verbose", action="store_true", help="Show full build and tool output") parsed = parser.parse_args(argv) parsed.argv = list(sys.argv[1:] if argv is None else argv) return parsed if __name__ == "__main__": + installer = Setup(Path(__file__).resolve().parents[1]) try: - Setup(Path(__file__).resolve().parents[1]).run(arguments()) + parsed = arguments() + installer.verbose = parsed.verbose + app_build.VERBOSE = parsed.verbose + prefix = parsed.prefix or Path(os.environ.get("PIPELINES_PREFIX") or DEFAULT_PREFIX).expanduser().resolve() + (prefix / "logs").mkdir(parents=True, exist_ok=True) + installer.install_log = prefix / "logs/install.log" + installer.run(parsed) except KeyboardInterrupt: print("\nNative setup canceled; existing configuration and data were retained.", file=sys.stderr) sys.exit(130) except (ValueError, OSError, json.JSONDecodeError, subprocess.SubprocessError, ZoneInfoNotFoundError) as error: + if installer.install_log and installer.install_log.is_file() and not installer.verbose: + tail = installer.install_log.read_text(errors="replace").splitlines()[-8:] + detail = "\n".join(tail) + sys.exit(f"Native setup incomplete: {error}\nBuild/tool log: {installer.install_log}\n{detail}") sys.exit(f"Native setup incomplete: {error}") diff --git a/scripts/test_manage_native.py b/scripts/test_manage_native.py index af699494..0463977f 100644 --- a/scripts/test_manage_native.py +++ b/scripts/test_manage_native.py @@ -26,6 +26,27 @@ class FakeProcess: class ManageNativeTests(unittest.TestCase): + def test_native_command_logs_tool_output_when_not_verbose(self): + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "logs/install.log" + calls = [] + + def runner(command, **kwargs): + calls.append((command, kwargs)) + return subprocess.CompletedProcess(command, 1, stdout="build output\n", stderr="failure\n") + + installer = setup_native.Setup(directory, runner=runner) + installer.install_log = log + result = installer.command(["go", "build", "./cmd/pipelines"]) + self.assertEqual(result.returncode, 1) + self.assertIn("build output", log.read_text()) + self.assertIn("failure", log.read_text()) + self.assertTrue(calls[0][1]["capture_output"]) + + def test_native_arguments_accept_verbose(self): + parsed = setup_native.arguments(["--verbose"]) + self.assertTrue(parsed.verbose) + def service_config(self, home, system): config = self.config(home / "prefix") config["opencode_env"] = {"XDG_CONFIG_HOME": str(home / ".config")}