Compare commits

...
18 Commits
Author SHA1 Message Date
blumia 8f6fd99103 feat: scan the pairing QR code with the camera
The pairing dialog gained a "扫码" button: a full-screen scanner points the
back camera at the QR that OpenChamber's connect-a-device dialog shows, and a
decoded pairing link connects straight away.

Frames are decoded with zxing2 (pure Dart, no ML Kit or Play services): the
YUV420 Y plane is already luminance, BGRA frames are converted green-weighted,
and each frame is decoded in a background isolate so camera frames never block
the UI. Only an openchamber://connect payload ends the scan; any other QR code
shows a short hint and scanning continues. A torch button, a denied-permission
message with retry, and camera-less devices are handled.

The recorder audio permission the camera plugin declares for video is removed
from the merged manifest: the scanner reads frames only.

0.4.5 (405).
2026-11-22 17:52:47 +08:00
blumia 902f1e18bb feat: connect through the OpenChamber private relay
A server can now be added by pasting an openchamber://connect pairing link.
The one-time secret is redeemed over the first reachable candidate (direct
addresses first, then the relay), and the device token is stored with the
connection, so later launches reconnect without the link.

The relay candidate carries the relay WebSocket URL, the host's routing id
and its P-256 public key. The new transport opens one encrypted tunnel to the
relay: P-256 ECDH + HKDF-SHA256 derive one AES-256-GCM key per direction;
frames carry a version, a 12-byte IV and the GCM tag; a small mux carries
HTTP, SSE and WebSocket sub-streams with fragmentation and ping/pong. Every
request and the terminal socket ride it; WebSocket upgrades first mint the
short-lived oc_url_token over the tunnel, since upgrades cannot send headers.

Only the host's legacy path is negotiated (no batching, downstream flow
control or body gzip). Pairing while connected switches servers like picking
one in the list, which exposed and fixes a ChatScreen crash when app.chat is
cleared during the switch.

0.4.4 (404).
2026-11-22 16:51:44 +08:00
blumia a7bc380ac0 feat: several terminal tabs per project, with a dropdown
A directory now has a TerminalWorkspace holding a list of tabs instead of a
single session. The status bar's left side became a dropdown: it shows the
active tab and its state ("终端 2 · 运行中") and lists the other tabs (the
active one checked) plus "新建终端". New tabs take the smallest free number,
so closing one frees its name.

Only the active tab keeps a socket: switching detaches the old tab and
attaches the new one, whose screen is replayed from the server snapshot; the
shell itself keeps running. The tab's model stays in memory, so switching
back is immediate.

The tab list (ids, labels, active one) is saved per connection and directory.
On the first open the server's sessions for the directory are reconciled with
it: saved labels and order are kept for sessions that still exist, sessions
opened elsewhere (web UI) are appended in creation order, and tabs whose
session is gone are dropped. Project-action command runners are not shown as
tabs. The 0.4.2 single-session value is read as one tab.

0.4.3 (403).
2026-11-22 15:23:21 +08:00
blumia 675d19d563 fix: reattach the terminal after an app restart
The terminal session id lived only in memory, so the first time the panel
opened after a launch it always created another PTY. The old shell stayed on
the server (unattached shells live for half an hour) but the client could no
longer find it.

The id is now remembered per connection and directory. On first open the
panel lists /api/terminal/sessions?cwd=<dir> and attaches to the remembered
session while the server still has it, showing its replayed history. Without
that id it adopts the newest running session of the directory, and only when
the directory has nothing does it create one. An explicit "close terminal"
forgets the id and forces a fresh shell, and a fatal SESSION_NOT_FOUND clears
it and recovers, so a server restart cannot leave a dead panel.

The panel is still one terminal per project, not a tab strip.

0.4.2 (402).
2026-11-22 14:53:33 +08:00
blumia d25167de58 fix: float the pet over the messages and let it be dragged
The pet used to sit in the column above the composer, reserving a strip of
its own: the message list ended there, which read as an opaque band cutting
off the last row. It is now a layer over the message area, so the list keeps
its full height and shows through around the sprite. Only the body of the
sheet takes touches (contentBox, 4dp out); taps and drags on the transparent
canvas still reach the messages underneath.

Dragging the body moves the pet along the composer's top edge (or the
activity cap's) with a small lift while held and the pack's drag reaction.
The spot is stored as a fraction of the width in pet.x.v1, so a restart or a
change in width puts it back in the same place. Taps now react on tap-up so a
drag does not fire a left/right reaction.

0.4.1 (401).
2026-11-22 14:30:30 +08:00
blumia d72af036a1 feat: imported input-box pets, with dsh-Go's sprite packs
Nothing is built in: Settings → 宠物 shows "尚未导入宠物" until a zip is
picked. The zip holds a dsh-Go pack.json and PNG sheets; it is validated
(pack.json, every named sheet) and unpacked under the app's private files
directory, with enable, size (40/52/64) and remove kept on the device.

A pack's canvas, anchor, per-animation box and frame list drive rendering:
PetSlot reserves the area above the baseline and stands the sprite on the
composer's top edge (or on the activity cap while a turn runs). Idle,
thinking, working and error follow the chat's state, and a tap plays the
pack's react-left/react-right. Only one sheet is decoded at a time.

path_provider's JNI binding does not load on this engine, so MainActivity
exposes the files directory over a tiny method channel instead.

dist/deepy-whale-pet.zip is the Deepy whale for testing. Tests cover the
real pack manifest, frame/state mapping and zip import.

0.4.0 (400).
2026-11-22 13:39:49 +08:00
blumia ff0dbf1b37 ui: make the sidebar rows compact again
Both the project band and the session rows are dense 56px list tiles now
(measured 54), down from 72. Session titles are 14 and project names 14.5,
so the list stays readable while the hierarchy keeps its tinted band. The
project + and the session ⋮ still share one vertical line.

0.3.21 (321).
2026-11-22 12:53:45 +08:00
blumia 73af9d851b ui: one row height and one trailing line in the sidebar, and a dsh-Go activity cap
- The project header is a ListTile now, like a session row: both are 72 high
  (title + subtitle). A Material 3 list tile ends at 24, so the band's 8px
  inset gets 16 more, putting the project + and the session ⋮ on one line
  (a widget test asserts both the heights and the x centres).
- The running status is a full-width stadium like dsh-Go's activity strip:
  title and current-step summary on the left, a tabular m:ss clock on the
  right, translucent surface, 36 minimum height. The spinner inside is gone;
  the cap's top edge is where the future input-box pet will perch.
- 0.3.20 (320).
2026-11-22 12:32:59 +08:00
blumia 6ced914757 fix: centre the context ring, show a live status while running, and settle project rows
- The folded composer aligns to its bottom edge, so the 16px usage ring sat
  below the 36px keys; a 10px bottom padding puts it on their centre line (the
  two-row layout was already centred).
- A running turn no longer shows the finished turn's footer (model · mode ·
  time, with its copy/fork menu). Above the input there is now an activity
  strip like dsh-Go's: "思考中 / 正在回复 / 正在读取 · …" with the current
  step's summary and a clock that ticks each second.
- Project headers in the sidebar are tinted bands at least a session row tall,
  with a folder icon, a bolder name and the path beneath, so the project and
  its sessions read as different levels.
- Project names take the last path segment with either separator, and path
  comparisons unify `\`/`/` (case-insensitively for drive-letter paths); the
  grouping key does too, so a Windows server no longer shows a full path or
  splits one project in two.
- 0.3.19 (319).
2026-11-22 11:59:33 +08:00
blumia d9d5424318 fix: a new server could not be given its password
The form only rendered the password field when editing a saved server
(!_editNew). Adding a password-protected instance therefore failed with
"需要密码或已保存的凭据" and offered nowhere to type it. The field is now
always shown ("密码(如果需要)", empty for a passwordless server); a failed
connect that asks for a password focuses it, and a rejected password reads
as "密码错误,请重试".

Adds test/servers_form_test.dart. 0.3.18 (318).
2026-11-22 11:38:24 +08:00
blumia e646130d1f feat: a settings page, a server footer in the sidebar, and follow-up behaviour
- The sidebar's server switch moves to a footer bar: the connected server's
  name on the left (tap for the server sheet) and a settings key on the
  right, matching the first-party phone layout.
- Settings has three groups: 外观 (theme mode and seed colour, stored on the
  device only in shared_preferences), 聊天 (the server's followUpBehavior:
  steer or queue) and a 宠物 placeholder. The app theme now reads the seed
  and mode.
- The chat's short send while a turn runs uses the configured follow-up
  behaviour; the long-press sheet offers both and marks the default. The
  value is read from GET /api/config/settings?surface=mobile on connect, on
  resume and when the page opens, and written back with PUT.
- Tests: settings page groups and choice, sidebar footer naming the server
  and opening settings, follow-up normalization.
- 0.3.17 (317).
2026-11-21 19:17:22 +08:00
blumia 1aa84a53e5 feat: queue a message for the running turn, and fold the composer when the IME closes
- A send while a turn runs joins it (delivery "steer") on a short press; a
  long press offers steer or queue. Queue/steer prompts wait in the server's
  inbox and show as a pending bubble at the end of the transcript, with
  改为排队/转为转向 and 撤回 (which puts the text back into the composer).
  The inbox is read on open and resume and kept current by the
  session.inbox.* events; delivery reloads the tail.
- The send key is stop only while running with an empty draft; with text it
  sends (as dsh-Go does), leaving the long press for the delivery choice.
- The composer also folds to one line when the phone's back gesture closes
  the keyboard while the field keeps focus: the page passes the keyboard
  height (a Scaffold strips the bottom inset from its body) and the composer
  treats a fall below half the peak as a dismissal.
- The Build/Plan chip now opens a bottom sheet with icons, hints and a check,
  instead of a popup menu.
- Tests: composer_box_test (focus opens, IME dismissal folds, typing reopens)
  and inbox_item_test (list items, enqueued events, delivery changes).
- 0.3.16 (316).
2026-11-21 18:32:57 +08:00
blumia ea3b1f0f5e ui: fold the composer to one line until it has focus
dsh-Go opens the input into two rows only while focused: the text above, the
model / mode / keys below, folding back when focus leaves. ComposerBox keeps
the field across the two layouts with a GlobalKey and animates the swap.

Model and thinking level are now one control (ModelPill shows "model · effort"
and the sheet offers the level after choosing a model); Build/Plan is a
separate ModeChip. The draft page uses the same box, with its project chip
above it. 0.3.15 (315).
2026-11-21 17:47:04 +08:00
blumia 7f2f454539 fix: switching a session's model, and put the model row in the composer
- POST /api/session/:id/model takes the reference under `model`; sending it
  at the top level was rejected with "Missing key at [model]".
- The chat now shows the model/agent row above the input (revealed while
  typing or running, as dsh-Go does) instead of in the app bar; the draft
  keeps the same row, with its project chip first.
- Thinking levels: /api/model's variants become a 思考 chip and sheet; the
  choice travels as ModelRef.variant on the switch or the create, and the
  last level per model is remembered on the device.
- The model picker groups providers, adds 收藏 and 最近 (device-local), shows
  each model's context size and reasoning mark, and collapses sections.
- The `/` palette is shared by the chat and the draft (new slash_palette
  widget); the draft lists commands and skills but not the client-local
  /compact, which needs an existing session.
- 0.3.14 (314).
2026-11-21 17:03:22 +08:00
blumia fff6562cbc feat: a new-session draft and a sidebar grouped by project
- Starting a session opens NewSessionScreen instead of a title sheet: a
  project chip (GET /api/project, one row per canonical), a model/agent
  chip, attachments and the composer. Nothing is created on the server
  until the first send, which posts the session with its directory, model
  and agent and then sends that message.
- The draft lives in AppState (memory only): leaving it keeps it; the
  sidebar shows a draft row with its first line and a discard button; a
  failed create stays on the draft with its text.
- The session list groups by project (chat folders under 聊天), dates the
  rows (今天/昨天/本周早些时候/更早), pins through
  session.metadata.openchamber.pinned, archives on demand, pages with
  "载入更多", and swipes to pin/archive/delete (flutter_slidable).
- Child sessions are hidden; a parent's row shows its children's activity.
- The chat app bar follows the live session list, so the title the server
  generates from the first message appears at once.
- Attachments and the model picker move to shared widgets, used by the
  chat and the draft.
- 0.3.13 (313).
2026-11-21 14:29:52 +08:00
blumia 5a371e4faf feat: tabs own the panel header, a Termux key bar, and agent memory
- The panel's top row is now the tab group plus the close button; each tab
  keeps its own header: the files tab has the breadcrumb with new/more (or
  the name and edit/download while previewing), knowledge its search and
  refresh, the terminal its status.
- The key bar is Termux's two rows of seven: ESC / — HOME ↑ END PGUP, then
  TAB CTRL ALT ← ↓ → PGDN; the modifiers still apply to what the phone
  keyboard types.
- The panel is a dialog, so it gives the IME's height back itself
  (viewInsets.bottom). The key bar and the terminal stay above the
  keyboard, and the PTY reflows to the smaller terminal.
- Project knowledge gains the memory tab: both scopes from
  /api/agent-memory/all, absent when the server has memory switched off,
  with type, edit and delete.
- File preview editing passes minLines: null alongside expands.
- 0.3.12 (312).
2026-11-21 11:09:44 +08:00
blumia 5f95e2da97 feat: the terminal, project knowledge, and downloads that can be cancelled
- lib/api/terminal.dart: the PTY protocol (create/resize/restart/close, and
  the /api/terminal/ws binary control frames) with a reconnecting socket
  that replays the server snapshot at the size it was drawn for.
- lib/terminal_state.dart: an xterm model plus that socket, kept per
  workspace on AppState, so closing the panel or switching tabs keeps the
  shell; the app reattaches when it returns from the background.
- lib/screens/terminal_panel.dart: TerminalView, a status bar (keyboard,
  restart, clear, close) and a Termux-style key bar whose CTRL/ALT/SHIFT
  modifiers also apply to what the phone keyboard types.
- lib/screens/knowledge_panel.dart: notes, todos and plans from
  /api/project-context, searchable, with a full page for a plan's Markdown
  and its raw editor.
- Downloads stream with a progress dialog (bytes, total, percent) and a
  cancel that aborts the request; the save dialog only opens on success.
  The request asks for `accept-encoding: identity` so Content-Length exists.
- MarkdownView renders task lists as ✅/⬜ instead of material_ui's
  Checkbox, which wants a material_ui Material ancestor the app lacks.
- Dialogs own their TextEditingControllers, so closing one no longer
  trips a framework assertion in debug builds.
- 0.3.11 (311).
2026-11-21 02:49:07 +08:00
blumia 60d02083d3 feat: a transport seam, image previews, native forms, a phone drawer
- lib/api/transport.dart: TransportRequest/TransportResponse/Transport, with
  DirectTransport holding the old behaviour (HTTP CONNECT, SOCKS5/socks5h,
  self-signed and pinned certificates). Client goes through it, so a relay
  tunnel only adds an implementation.
- User rows decode the server's inline attachment data and open the shared
  image preview on tap; the local path stays the fallback.
- The agent's native forms: models from @opencode/client, the form list,
  replies and cancels, form.* events, and a dock above the composer with
  when-rules and required-field validation (a switch must be on).
- HomeScreen: the session list is the phone's left drawer and a persistent
  column from 840 px, the chat beside it; the newest session opens on start.
- 0.3.10 (310).
2026-11-21 01:16:10 +08:00
58 changed files with 13458 additions and 1280 deletions

No files matched your search

+222
View File
@@ -5,6 +5,228 @@
---
## 0.4.5 扫码配对(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 扫码入口 | 「配对链接」对话框新增「扫码」:全屏相机 + 取景框 + 手电筒;扫到配对链接直接开始配对,不再要求按第二个按钮 |
| 解码 | 用 `camera` 0.12 + `zxing2` 0.2(纯 Dart,不依赖 ML Kit / Google Play 服务)。Android 取 YUV420 的 Y 平面直接作为亮度;BGRA(iOS/部分相机)按绿加权转亮度。解码放在 `compute` isolate,每帧不阻塞 UI,同一时间只解一帧 |
| 取景 | 后置相机优先、480p 预览、覆盖率/圆角遮罩 + 四角标记;非配对二维码提示「这不是 OpenChamber 配对二维码」并继续扫;无相机/权限被拒给出说明与重试 |
| 权限 | AndroidManifest 增加 CAMERA 权限;camera 硬件声明为非必需,没相机的设备仍可安装 |
| 测试 | `test/qr_scan_test.dart`:用 `qr` 生成配对链接二维码,渲染成 Y 平面(含 rowStride 内边距)后由 `decodeQrLuminance` 解出原文;空白帧、过短/非法尺寸返回 null |
| 版本 | **0.4.5(code 405)** |
---
## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 配对链接 | 服务器列表新增「配对链接」:粘贴 `openchamber://connect?v=2&p=…`,解析一次性密钥与候选地址(lan / tunnel / relay,按 priority 先直连后 Relay),用第一个能连上的候选兑换设备 token 并保存 |
| 端到端加密 | 新增 `relay_crypto.dart`:P-256 ECDH + HKDF-SHA256(salt = 握手 nonce,info = `openchamber-relay-v1`)派生两条 AES-256-GCM 方向密钥;帧 = 版本 + 12 字节 IV(4 随机前缀 + 8 字节计数器)+ 密文 + GCM tag,计数器严格递增,失败即关闭。与官方 `packages/ui/src/lib/relay/crypto.ts` 字节兼容 |
| 隧道 | 新增 `relay_tunnel.dart`:连 `wss://…/ws?v=1&role=client&serverId=…`,明文 hello/ready 握手,之后是加密的 mux 帧(HttpRequest/Body/Response/StreamEnd/Abort、WsOpen/Opened/Text/Binary/Close、Ping/Pong)。大消息按 64 KiB 分片与重组,断线不自动重拉(下一次请求重连,SSE 自己的重试循环会恢复) |
| Transport | `Transport.webSocket` 改为返回 `TransportSocket`(直连包装 WebSocket,Relay 用子流);新增 `RelayTransport` 实现同一接口,所有 HTTP/SSE 走隧道。Relay 下的终端 WebSocket 先经隧道 `POST /auth/url-token` 换取短时 token,附到 `oc_url_token` 查询参数 |
| 连接模型 | `Connection` 增加 `relayUrl/serverId/hostKey/grant` 与 `isRelay`;直连字段不变。配对成功的连接与设备 token 一起保存,之后启动/重连直接用 token,不再需要配对链接 |
| 未协商 | 不声明 batch、下行 flow control 与响应 gzip,走宿主端的 legacy 路径(一帧一条消息、明文响应体),先保证正确性 |
| 切换 | 已连接时配对会先断开旧服务器(关闭旧 shell、事件流),再切到新连接;`ChatScreen` 现在持有自己的 `ChatState`,不再在 dispose/计时器里读已清空的 `app.chat!`(修掉切换服务器时的一个空指针崩溃) |
| 测试 | `test/relay_crypto_test.dart`(JWK 往返、双方派生一致、方向密钥、重放/篡改失败、base64url)、`test/pairing_test.dart`(直连优先、relay-only、grant、过期/非法/裸 payload);`tool/relay_probe.dart` 对真实 relay 做了握手、兑换、/api/version、会话列表、SSE 与终端快照的端到端验证;模拟器上从「配对链接」粘贴 relay-only 链接、重启后自动重连、终端命令输入输出都通过 |
| 版本 | **0.4.4(code 404)** |
---
## 0.4.3 终端多标签:下拉切换、新建、按标签恢复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 多标签 | 每个目录一个 `TerminalWorkspace`,持有多个 `TerminalTab`(各自的 xterm 模型与 socket)。切换标签时旧标签 detach、新标签 attach,不同时占用多条 WebSocket;后台输出由服务端 snapshot 在切回时重放 |
| 下拉 | 状态条左侧变成标签下拉:显示「终端 N · 运行中」,菜单列出所有标签(当前项打勾)与「新建终端」。新建的标签自动用最小的空闲编号(终端 1、终端 2…) |
| 关闭/重启 | ⋮ 菜单改为「关闭此终端」,关掉当前标签并 DELETE;关掉最后一个会自动留一个新标签。重启只作用于当前标签,死会话在原标签内换成新会话 |
| 恢复 | 本机按连接 + 目录保存标签列表(id + 名称 + 活动标签)。启动后首次打开:`GET /api/terminal/sessions?cwd=` 与服务端对账,仍存在的会话按保存的顺序和名称还原,服务端新出现的会话(网页端开的)按创建时间追加成标签,服务端已没有的标签丢弃;一个都没有才新建。兼容 0.4.2 的单会话存档 |
| 过滤 | 只把 interactive 会话算作标签,project-action 的命令运行器不显示 |
| 测试 | `test/terminal_restore_test.dart`:标签对账(顺序、名称、丢弃、列表失败的兜底、过滤 action)、编号复用、按连接+目录保存标签与活动项、0.4.2 存档迁移 |
| 版本 | **0.4.3(code 403)** |
---
## 0.4.2 终端恢复:重启后接回原来的 shell(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 之前 `sessionId` 只在内存里:每次启动 App 后第一次打开终端都走 `POST /api/terminal/create`,旧 shell 还留在服务器上(无连接时 30 分钟空闲回收),只是再也接不回去 |
| 恢复 | 按连接 + 目录记住最后一次的终端 id(`openchamber.terminalSessions.<connId>`)。首次打开终端先 `GET /api/terminal/sessions?cwd=`:记得的 id 还在就直接 attach(服务端 snapshot 重放历史);不在了就采用该目录最新的运行中会话;一个都没有才新建 |
| 关闭 | 「关闭终端」先 DELETE 并忘掉记录,再用 `fresh` 新建,避免又接回刚关掉的会话;断开连接/切换服务器时照旧关闭 shell |
| 失效 | attach 收到 fatal `SESSION_NOT_FOUND`(例如服务端在中间重启过)时清掉记录并自动新建,不留死面板 |
| 单终端 | 仍是每个目录一个终端视图,不是多标签;同目录的其它会话保留给网页端,不会被删除 |
| 测试 | `test/terminal_restore_test.dart`:恢复优先级(记得的 > 最新运行中 > 最新)、按连接+目录保存与清除 |
| 版本 | **0.4.2(code 402)** |
---
## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 不再占位 | `PetSlot` 换成 `PetLayer`:宠物画在消息列表的 Stack 上层,列表恢复完整高度,字会从宠物四周透出来,不再有一条空白带把最后一行截掉 |
| 透明 | 只有精灵本身作画;画布其余部分不填充。命中测试只认 `contentBox`(外扩 4px),点空白处仍然滚动/点消息 |
| 拖动 | 按住身体左右拖,脚沿输入框上沿移动;松手保存在本机(`pet.x.v1`,0–1 的比例),重启后回到同一位置,窄屏/旋转按比例换算并夹在两端内 |
| 拖动反馈 | 拖动时抬升 6px,并播放包里的 `drag`(`react-drag`)动画;没有该动画就保持当前状态,松手回到聊天状态 |
| 点击 | 从 `onTapDown` 改为 `onTapUp`,拖动不再误触发左右半区的 `tapLeft/tapRight` |
| 测试 | `test/pet_layer_test.dart`:空白处点击穿透、身体吃掉点击、拖动改位置并写入 prefs、无宠物时不画 |
| 版本 | **0.4.1(code 401)** |
---
## 0.4.0 输入框宠物:导入宠物包、精灵动画与状态(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 默认无宠物 | 不内置任何宠物;设置 → 宠物 显示「尚未导入宠物」和导入按钮,导入后才启用 |
| 宠物包 | 兼容 dsh-Go 的 PNG 精灵包:zip 内 `pack.json` + 各动画的 sprite sheet。解析 canvas / anchor / contentBox / animations(frames, cols, box) / states / reactions;导入时校验 `pack.json` 与每张精灵图,解压到应用文档目录 `pets/<id>/`,支持更换、启用/关闭、大小(40 / 52 / 64)与移除 |
| 渲染 | 新增 `PetSlot` / `PetSprite`:按 `anchor` 让宠物站在输入框上方(运行时有活动条则站在活动条顶边);按状态播放 `idle / thinking / working / error`;点击左右半区播放 `react-left / react-right`。图片一次只解码当前动画,切换时释放上一张 |
| 状态 | 活动条是「思考中」→ thinking,其余运行状态(回复中、调用工具)→ working,最后一轮失败 → error,空闲 → idle;草稿页显示 idle |
| 示例包 | `dist/deepy-whale-pet.zip`(dsh-Go 的 Deepy 小鲸鱼,保留包内 name/author/license) |
| 测试 | `test/pet_pack_test.dart`(真实 deepy pack 解析、帧与状态映射)、`test/pet_import_test.dart`(zip 解包、嵌套目录、缺少 pack.json 拒绝) |
| 版本 | **0.4.0(code 400)** |
---
## 0.3.21 侧栏行更紧凑(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 行高 | 项目条和会话行都改为 `dense: true` + `minTileHeight: 56`,实测都是 54(此前是 72);标题 14 / 项目名 14.5,路径与副标题保持较小字号 |
| 对齐 | 仍然等高等宽;`+` 与会话 `⋮` 的 x 中心保持对齐(测试断言) |
| 版本 | **0.3.21(code 321)** |
---
## 0.3.20 侧栏项目/会话行等高与右对齐、活动条改为 dsh-Go 胶囊(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏等高 | 项目分组头改用与会话行相同的 `ListTile`(标题 + 副标题),两者高度都是 72;分组的 8px 外边距由 ListTile 的内边距补偿,`+` 与会话的 `⋮` 落在同一竖线上 |
| 活动条 | 改为 dsh-Go 风格的全宽胶囊:左侧「标题 + 步骤摘要」,右侧等宽数字计时 `m:ss`(不足一分钟也显示 `0:03`),半透明 surface 背景,最小高度 36;去掉条内的转圈。胶囊顶边就是之后输入框宠物的栖息位置 |
| 版本 | **0.3.20(code 320)** |
---
## 0.3.19 输入框环居中、运行状态条、侧栏项目层级与 Windows 路径(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 上下文环 | 单行输入框用 `CrossAxisAlignment.end`,16px 的环贴着底部而按键是 36px;给环加 10px 底边距,与按键同一中轴(有焦点时的两行布局本来就是居中,未改) |
| 运行中的尾部 | 运行中不再显示上一轮的 footer(模型 · 模式 · 用时,以及“复制回答 / 从这里分叉”菜单):`_turnRows` 在 `chat.running` 为真时不加 footer。改为在输入框上方显示 dsh-Go 风格的活动条:「思考中 / 正在回复 / 正在读取 · …」加当前步骤摘要和秒表,每秒刷新 |
| 侧栏项目 | 项目分组头改成带底色的圆角条,最小高度 56,加文件夹图标;标题 13.5 粗体、路径作副标题,与会话行的层级更清楚 |
| Windows 路径 | 项目名只取路径最后一段,`/` 与 `\` 都识别;同一项目的比较统一分隔符(盘符路径忽略大小写),分组键也统一分隔符,避免一个项目被拆成两组 |
| 版本 | **0.3.19(code 319)** |
---
## 0.3.18 需要密码的服务器无法输入密码(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 「添加服务器」表单的密码框只在编辑已保存服务器时显示(`!_editNew`)。新服务器首次连接被 401 拒绝后只提示「需要密码或已保存的凭据」,却没有输入密码的地方 |
| 修复 | 密码框始终显示,文案为「密码(如果需要)」,提示服务器未设置可留空;连接失败且错误提示需要密码时自动聚焦密码框;服务端返回 `Invalid credentials` 时显示为「密码错误,请重试」。新增 `test/servers_form_test.dart` 覆盖新服务器表单含密码框 |
| 版本 | **0.3.18(code 318)** |
---
## 0.3.17 设置页、侧栏底部服务器栏与追问处理行为(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 设置页 | 新增 `lib/screens/settings_screen.dart`,分「外观 / 聊天 / 宠物」三组 |
| 侧栏 | 服务器切换从顶部移到底部:左侧是当前服务器名(点击打开服务器面板),右侧齿轮进入设置页,和原版手机端侧栏一致 |
| 外观 | 主题模式(跟随系统 / 浅色 / 深色)与主题色(8 个种子色);`lib/appearance_prefs.dart` 存本机 `shared_preferences`,明确不同步服务端;`main.dart` 的 `ThemeData` 读取它 |
| 聊天 | 「追问处理行为」:转向 / 排队。读写服务端 `GET/PUT /api/config/settings?surface=mobile` 的 `followUpBehavior`(profile 级、跨 surface 共享,默认 queue)。运行中短按发送按该设置执行,长按「发送方式」可临时选另一种并标出默认项。连接成功、设置页打开、应用回到前台时重新读取 |
| 宠物 | 仅占位,显示「暂未提供设置」 |
| 版本 | **0.3.17(code 317)** |
---
## 0.3.16 输入法收起、模式面板与排队消息(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框收起 | 手机返回手势关闭输入法(焦点仍在)时,输入框也收回单行:dsh-Go 用键盘高度判断;`Scaffold` 会从 body 去掉底部 viewInsets,所以由 `HomeScreen`(Scaffold 之上)读取键盘高度,经 `ChatScreen` / `NewSessionScreen` 传给 `ComposerBox`。键盘升到过的峰值一半以下即视为收起,再次唤起时展开。新增 `test/composer_box_test.dart` 覆盖 |
| 模式面板 | 「模式」(Build / Plan)chip 由下拉框改为底部面板:标题、图标、说明、当前项打勾;仍与模型/思考强度分开 |
| 排队消息 | 运行中短按发送默认「转向」(`delivery: steer`),长按发送键弹出「转向当前回合 / 排队」,只用服务端支持的 steer/queue。排队或转向的消息不乐观写入对话,而是显示为末尾的待发气泡(半透明 + 状态:正在转入 / 已排队 / 未发送),可「改为排队 / 转为转向」与「撤回」(`DELETE /api/session/:id/inbox/:id`,文本放回输入框)。打开会话与前台恢复时 `GET /api/session/:id/inbox`;订阅 `session.inbox.enqueued / delivered / cancelled / delivery.changed`,送达时刷新尾部。运行且输入框有文字时发送键显示为发送(dsh-Go 行为),空输入时才显示停止 |
| 版本 | **0.3.16(code 316)** |
---
## 0.3.15 输入框两行折叠、模型与思考成组、模式独立(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框折叠动画 | 新增 `lib/widgets/composer_box.dart`:未获焦点时是单行(附件键在左、输入框、上下文环、发送键在右),获得焦点时平滑展开为两行(上为输入框,下为附件键/模型/模式/环/发送键),失焦后收回单行;输入框用 `GlobalKey` 在两种布局间搬移,保留焦点与输入连接。参照 dsh-Go `Composer` 的 `footer` + `_ComposerRows` + `AnimationController` 做法 |
| 模型与思考强度成组 | 模型 chip 直接显示 `模型 · 思考档位`(如 `deepseek-flash · 高`),点开同一个面板:选模型后若该模型有 variants,底部出现思考强度选择,选完一次提交;最近使用的档位记在本机。草稿页与聊天页共用 `ModelPill` |
| 模式独立 | 原「智能体」chip 改为独立的 `ModeChip`(Build / Plan),与模型 chip 并列,不再把智能体与模型放在同一行组里;仍通过 `switchAgent` / 草稿的 `agent` 提交 |
| 草稿页 | 同样使用两行折叠 `ComposerBox`;项目 chip 单独在输入框上方始终可见(草稿页没有会话,模型/模式放在折叠的第二行);斜杠面板、快捷键保持不变 |
| 版本 | **0.3.15(code 315)** |
---
## 0.3.14 模型切换修复、输入框模型行、思考强度与模型面板(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 切换模型报错 | `POST /api/session/:id/model` 的 body 应为 `{model: {id, providerID, variant?}}`,之前把模型对象直接放在顶层,服务端报 `Missing key at ["model"]`;已修正并实测切换成功 |
| 输入框模型行 | 参照 dsh-Go:聊天页把模型/智能体从顶栏移到输入框上方,输入框获得焦点、有草稿文字或正在生成时显示;草稿页始终显示同一行(左侧多一个项目 chip)。聊天顶栏只留文件按钮 |
| 思考强度 | `/api/model` 的每个模型带 `variants`(v2 的 `{id, settings.reasoningEffort}`)。输入框行在模型有档位时显示「思考·默认/低/中/高/极高」,点开选档;选择以 `ModelRef.variant` 随 `POST /session/:id/model` 或建会话时提交,实测会话的 `model.variant` 变为 `high`。每个模型上次的档位记在本机 |
| 模型面板 | 重做 `lib/widgets/model_picker.dart`:按 provider 分组(可折叠)、「收藏」「最近」分组(本机 `shared_preferences`,收藏用星标切换)、每个模型标注上下文大小(如 `200K 上下文`)、推理能力标记、搜索、当前项打勾;智能体分段保留 |
| 草稿斜杠 | 斜杠面板抽成共享的 `lib/widgets/slash_palette.dart`(匹配、排序、面板、快捷键),草稿页与聊天页共用;草稿只列 `/api/command` 与 `/api/skill` 的结果,不含需要已有会话的客户端内置 `/compact`;无参命令选中即发送(先建会话再执行命令),带参命令补全名称 |
| 版本 | **0.3.14(code 314)** |
---
## 0.3.13 草稿会话与分组侧栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 新会话 = 草稿 | 左侧栏 `+` 不再弹「标题」底部框,而是进入 `NewSessionScreen`:大标题「我们今天要做什么?」、项目 chip(`GET /api/project`,按 canonical 去重)、模型/智能体 chip(与聊天共用新的 `lib/widgets/model_picker.dart`)、附件与输入框。**发送前不创建会话**:第一次发送才 `POST /api/session`(带 `location.directory`、`model`、`agent`),随后 `openChat` 并发出这条消息 |
| 草稿生命周期 | 草稿只存内存(`AppState.draft` + `draftOpen`):未发送就离开时保留,侧栏顶部出现「草稿 · 项目名」一行(笔图标、首行、× 丢弃),点它回到草稿;发送成功即清空,创建失败留在草稿并显示错误。第二期接服务端 `/api/session-drafts`(已记入项目待办) |
| 侧栏分组 | 会话按 `location.directory` 分组(`.openchamber/chats` 归为「聊天」),组头是项目名 + 路径 + 折叠 + 「在此项目新会话」;组内按 `updated` 倒序并插「今天 / 昨天 / 本周早些时候 / 更早」小标题;默认过滤子会话(`parentID`),父会话的运行点会带上子会话的活动 |
| 置顶 | 写进 `session.metadata.openchamber.pinned`(`PATCH /api/session/:id {metadata}`,合并原有 metadata),跨客户端可见;置顶的会话收进顶部「已置顶」区,不再重复出现在项目组里 |
| 归档 | 主列表请求 `archived=false`;底部「显示已归档」按需拉 `archived=true`,展开后可取消归档(事件 `session.archived/unarchived` 同步) |
| 行操作 | 左滑(`flutter_slidable`,DrawerMotion)露出置顶 / 归档 / 删除;`⋮` 菜单有重命名、置顶、归档、删除、复制会话 ID;选中行有底色与加粗 |
| 其它 | 会话列表支持「载入更多」(cursor 分页);聊天页标题改为跟随 `AppState.sessions`,服务端根据首条消息生成的标题会即时显示;附件选择与缩略图抽到 `lib/widgets/composer_attachment.dart`,与草稿页共用 |
| 版本 | **0.3.13(code 313)** |
---
## 0.3.12 侧栏头部、Termux 按键栏、键盘避让与记忆(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏头部 | 顶部一行改成「标签组 + 关闭按钮」,标题/目录副标题去掉(目录本来就在面包屑里);文件/项目知识/终端各自的功能按钮下沉到标签自己的头部行——文件页是面包屑右侧的「+ / ⋯」(预览时是「编辑 / 下载」),项目知识页是搜索框 + 刷新,终端页是状态 + 键盘/重启/菜单 |
| 按键栏 | 按 Termux 改成两行七列等宽:`ESC / — HOME ↑ END PGUP`、`TAB CTRL ALT ← ↓ → PGDN`(左下角是 **TAB**,不是收起按钮);CTRL/ALT 修饰对手机输入法的字符仍然生效 |
| 键盘避让 | 侧栏是对话框,不会自己随输入法缩小;现在给底部加上 `MediaQuery.viewInsets.bottom` 的内边距,终端连同按键栏一起抬到键盘上方,`TerminalView` 随之减少行数并把新尺寸回传给 PTY |
| 记忆 | 项目知识新增「记忆」标签:`GET /api/agent-memory/all` 一次取全局与项目两份,服务端把功能关掉时(404)整个标签不出现;卡片显示标题、类型(事实/偏好/参考)、内容,可编辑(标题/类型/正文)与删除,搜索也覆盖记忆 |
| 顺带修复 | 文件预览的编辑框 `expands: true` 缺 `minLines: null`,进编辑会触发断言 |
| 版本 | **0.3.12(code 312)** |
---
## 0.3.11 终端、项目知识与下载进度(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 终端 | 右侧栏「终端」页:`POST /api/terminal/create` 建 PTY(cwd = 会话目录),`/api/terminal/ws` 走二进制控制帧(`0x01` + JSON:hello/attach/write/ping,snapshot/output/restart/exit/error)。渲染用 **xterm 4.0.0**(`Terminal` 模型 + `TerminalView`),断线按 500ms 起指数退避重连、重连后按服务端快照重放(先 `resize` 到快照尺寸再写历史);`/api/terminal/:id/resize` 做 250ms 去抖;App 回前台时自动重连 |
| 底栏 | 仿 Termux 的按键条(横向滚动):CTRL / ALT / SHIFT 修饰键,ESC、TAB、方向键、HOME/END/PGUP/PGDN/DEL,以及 `/ - \| ~ * $ # _ = + : ; " ' ( ) [ ] { } < > ? ! & \ ^ % @`;修饰键对**手机输入法**输入的字符同样生效(在 `onOutput` 里把下一个可打印字符映射成控制字符/ESC 前缀),按一次即清除 |
| 状态 | 状态条显示「运行中 / 正在连接 / 已退出(退出码)/ 连接失败」,并提供键盘、重启、清屏、关闭终端;终端会话按目录保存在 `AppState.terminals`,关面板不断 shell,切换服务器时显式关闭 |
| 项目知识 | 右侧栏「项目知识」页:`/api/project-context/:projectId`(projectId = `path_` + 目录 base64url);笔记(新建/编辑/置顶/删除)、待办(勾选、新建、删除,完成项沉底)、计划(新建、置顶、删除、打开全文);搜索框跨三种记录即时过滤;计划详情是全屏页(Markdown 渲染 + 编辑原文 + 保存) |
| 下载进度 | `/api/fs/raw` 改为流式:`downloadFile` 带 `onProgress` 与 `CancelToken`,请求头 `accept-encoding: identity` 以拿到 `Content-Length`(gzip 会让响应变成 chunked,进度只能是不确定态);下载中弹「正在下载」对话框显示已下载/总量/百分比,取消即中止连接并丢弃结果;完成后才弹保存对话框 |
| 修复 | `MarkdownView` 里的任务列表不再用 `material_ui` 的 Checkbox(它会找 `material_ui` 的 Material 祖先,应用里没有),改为 `✅`/`⬜` 文本;对话框里的 `TextEditingController` 改由对话框自身持有,避免关闭动画期间 dispose 触发框架断言 |
| 版本 | **0.3.11(code 311)** |
---
## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| Transport | 新增 `lib/api/transport.dart`:`TransportRequest`(method/path/query/rawQuery/headers/body)、`TransportResponse`(状态码/头/`Stream<List<int>>`,SSE 与文件下载仍可流式读)、`abstract Transport`;`DirectTransport` 就是原来的直连实现(HTTP CONNECT、SOCKS5/socks5h、自签与指纹固定、SHA-256 内置实现),`Client` 只保留业务方法,构造时可注入别的 Transport。行为与之前逐字节一致,后续 Private Relay 只需再加一个 `RelayTransport` |
| 历史图片 | 用户消息里的 `files` 现在从服务端读 `data`(base64)并缓存解码结果;气泡内显示缩略图,点按打开图片预览(与工具行读图共用同一个对话框)。无内联图片时仍回退到刚发送时的本地路径 |
| 原生表单 | `FormInfo`/`AgentFormField`/`FormOption`/`FormWhen` 按 `@opencode/client` 2.2.7 的 schema 建模;`GET /api/session/:id/form` 拉取待答问题,`POST …/form/:fid/reply` 提交、`DELETE …/form/:fid` 取消;订阅 `form.created/replied/cancelled`。输入框上方是表单卡片:string(带 options 时用 chip + 「其他…」)、multiselect、boolean(开关)、number/integer、external(链接确认);`when` 控制字段显隐,必填项(含「必须打开」的开关)不满足时提示并阻止发送,最多 360 px 内部滚动 |
| 左右分栏 | 新增 `lib/screens/home_screen.dart`:手机(< 840 px)把会话列表放进左侧 Drawer、聊天占满屏幕、顶栏是菜单键;宽屏(平板/桌面)左侧常驻 320 px 会话列 + 聊天。两者共用同一个 `SessionListPane`(会话选中高亮、搜索、新建、服务器、重命名/归档/删除)。启动时若还没有打开的会话,自动打开最新一条(与官方手机端一致) |
| 版本 | **0.3.10(code 310)** |
---
## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
**背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo;
+40 -8
View File
@@ -5,23 +5,55 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity.
Status: 0.3.9 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
Status: 0.4.5 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a
context usage ring with a detail sheet, model/agent switching (Build/Plan only,
current one checked), copy / fork / revert, attachments (photos/files),
permissions. Android 7.0 (API 24)+, plus a Linux desktop target used for local
testing.
current one checked), copy / fork / revert, attachments (photos/files, kept
after a reload), the agent's native forms, permissions. The files sidebar also
carries the project knowledge (notes, todos, plans, and agent memory when the
server enables it) and a full terminal with a Termux-style key bar; downloads
show their progress and can be cancelled. The terminal holds several tabs per
project, switched from a dropdown next to the status (new tab included), and
remembers them per connection and directory: reopening after an app restart
attaches to the shells the server still holds instead of starting new ones. The panel is a tab row with its own
close button, and each tab has its own header row. Starting a session opens a
draft that only creates the session on the first send; the session list is
grouped by project with date captions, pins, archive and swipe actions. The
composer folds to one line when unfocused (or when the keyboard is dismissed)
and opens into two rows on focus, as in dsh-Go: the model and its thinking level
form one pill, the Build/Plan mode a separate chip (picked from a sheet). A
message sent while a turn runs can steer it or queue for its end, and waits as a
pending bubble that can be withdrawn; while a turn runs, an activity strip above
the input names the current step and its clock instead of the finished turn's
footer. Pets are opt-in: nothing is built in, and a dsh-Go sprite pack (a zip
with pack.json) is imported from Settings → 宠物 to stand above the input and
react to the turn's mood. The pet floats over the messages (only its body
takes touches) and can be dragged along the input's top edge; the spot is
remembered on the device. The picker groups providers, favourites,
recents and context size. The sidebar footer names the connected server (tap to
switch) beside a settings key; settings holds appearance (theme mode and seed
colour, device-local), the server's follow-up behavior (steer or queue on a send
while a turn runs) and a pet placeholder. A
phone opens the session list as the left drawer and a wide window (tablet,
desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop
target used for local testing.
## What is here
| Path | What |
| --- | --- |
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback` |
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, forms, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; every request goes through `Transport` (today `DirectTransport`: HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback`), so a relay tunnel only adds an implementation |
| `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) |
| `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding |
| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets); the message list is reversed so older pages grow above without moving the viewport |
| `lib/state.dart` | The app state: connections, live sessions, the open chat, the server's follow-up behavior, and SSE event folding |
| `lib/appearance_prefs.dart` | Device-local theme mode and seed colour (`shared_preferences`) |
| `lib/pets/` | Imported pet packs: the dsh-Go `pack.json` sprite format, unpacked into the app's documents, plus the one-sheet image cache |
| `lib/widgets/pet_sprite.dart` | The pet strip above the composer and its sprite player (frames, moods, tap reactions) |
| `lib/terminal_state.dart` | Terminal workspaces and tabs: each tab is an xterm model plus its `/api/terminal/ws` socket; switching detaches the old tab, the saved tab list lets a restart reattach |
| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar with the knowledge and terminal tabs); the message list is reversed so older pages grow above without moving the viewport |
| `lib/widgets/` | The context usage ring |
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
+8 -1
View File
@@ -1,5 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<!-- The camera plugin declares audio for video; the scanner only reads
frames, so the app must not end up asking for the microphone. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<application
android:label="OpenChamber"
android:name="${applicationName}"
@@ -1,5 +1,21 @@
package net.blumia.openchamber.flutter
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// The app's private files directory, for imported pet packs. A small
// channel instead of path_provider, whose JNI binding does not load
// on this engine.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/appdir")
.setMethodCallHandler { call, result ->
when (call.method) {
"documents" -> result.success(filesDir.absolutePath)
else -> result.notImplemented()
}
}
}
}
+511 -245
View File
@@ -4,11 +4,12 @@ library;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:socks5_proxy/socks_client.dart';
import 'dart:typed_data';
import '../version.dart';
import 'models.dart';
import 'terminal.dart';
import 'transport.dart';
class ApiError implements Exception {
final int status;
@@ -18,114 +19,57 @@ class ApiError implements Exception {
String toString() => message.isEmpty ? 'HTTP $status' : message;
}
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
class _ProxyConfig {
final String scheme; // http | https | socks5 | socks5h
final String host;
final int port;
final String? username;
final String? password;
_ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]);
bool get socks => scheme.startsWith('socks');
}
_ProxyConfig? _parseProxy(String? raw) {
final s = raw?.trim() ?? '';
if (s.isEmpty) return null;
var normalized = s;
if (!normalized.contains('://')) normalized = 'http://$normalized';
final uri = Uri.tryParse(normalized);
if (uri == null || uri.host.isEmpty) {
throw ArgumentError('代理地址无效:$raw');
}
final scheme = uri.scheme.toLowerCase();
final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h';
final http = scheme == 'http' || scheme == 'https';
if (!socks && !http) {
throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)');
}
String? user;
String? pass;
if (uri.userInfo.isNotEmpty) {
final i = uri.userInfo.indexOf(':');
if (i >= 0) {
user = Uri.decodeComponent(uri.userInfo.substring(0, i));
pass = Uri.decodeComponent(uri.userInfo.substring(i + 1));
} else {
user = Uri.decodeComponent(uri.userInfo);
}
}
final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080);
return _ProxyConfig(scheme, uri.host, port, user, pass);
}
class Client {
final Uri base;
final String? proxy; // http://host:port or socks5://host:port
final bool insecure;
final String? fingerprint;
String? token;
late HttpClient _http;
_ProxyConfig? _proxyConfig;
InternetAddress? _proxyAddress;
/// Every request and the event stream go through here; today a direct
/// connection, later one that can also be a relay tunnel.
final Transport transport;
String? _token;
/// The bearer this client authenticates with. A relay transport is told too,
/// because it must mint URL-scoped tokens for WebSocket upgrades.
String? get token => _token;
set token(String? value) {
_token = value;
transport.setBearerToken(value);
}
Client(
this.base, {
this.proxy,
this.insecure = false,
this.fingerprint,
}) {
_http = HttpClient();
_http.connectionTimeout = const Duration(seconds: 20);
_proxyConfig = _parseProxy(proxy);
if (_proxyConfig != null && _proxyConfig!.socks) {
// Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy
// package tunnels the socket and hands a Socket back to the client.
_http.connectionFactory = (uri, _, __) async {
final address = await _resolveProxyAddress();
final settings = ProxySettings(address, _proxyConfig!.port,
username: _proxyConfig!.username, password: _proxyConfig!.password);
final tunnel = SocksTCPClient.connect(
[settings],
// A unix-type address carries the host name, so the proxy resolves
// it (socks5h semantics) instead of resolving it here.
InternetAddress(uri.host, type: InternetAddressType.unix),
uri.port,
);
if (uri.scheme == 'https') {
final secure = tunnel.then(
(s) => s.secure(uri.host, onBadCertificate: _badCertificate));
return ConnectionTask.fromSocket(secure, () {});
}
return ConnectionTask.fromSocket(tunnel, () {});
};
} else if (_proxyConfig != null) {
_http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}';
}
_http.badCertificateCallback = (cert, host, port) => _badCertificate(cert);
}
Future<InternetAddress> _resolveProxyAddress() async {
if (_proxyAddress != null) return _proxyAddress!;
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
if (addresses.isEmpty) {
throw const SocketException('无法解析代理主机');
}
return _proxyAddress = addresses.first;
}
/// True for a certificate the app was told to accept: the user trusts any
/// (insecure), or its SHA-256 matches the pinned fingerprint.
bool _badCertificate(X509Certificate cert) {
if (insecure) return true;
final pinned = fingerprint?.replaceAll(':', '').toLowerCase();
if (pinned == null || pinned.isEmpty) return false;
return _sha256(cert.der) == pinned;
}
String? proxy,
bool insecure = false,
String? fingerprint,
Transport? transport,
}) : transport = transport ??
DirectTransport(base,
proxy: proxy, insecure: insecure, fingerprint: fingerprint);
String get baseUrl => base.toString();
/// Redeems a pairing link's one-time secret over whichever transport this
/// client uses, and returns the device token.
Future<({String token, Map<String, dynamic> response})> redeemPairing({
required String pairingId,
required String secret,
required String installId,
String clientLabel = 'OpenChamber Native',
String clientKind = 'mobile',
String? deviceName,
}) async {
final r = await _json('POST', '/api/client-auth/pairing/redeem', body: {
'pairingId': pairingId,
'secret': secret,
'clientLabel': clientLabel,
'clientKind': clientKind,
'deviceName': deviceName ?? clientLabel,
'devicePlatform': 'android',
'dedupeKey': installId,
'appVersion': appVersion,
});
return (token: r['clientToken'] as String? ?? '', response: r);
}
Future<Map<String, dynamic>> sessionStatus() async {
final r = await _json('GET', '/auth/session');
return r;
@@ -150,6 +94,7 @@ class Client {
String order = 'desc',
String? search,
String? directory,
bool? archived,
}) async {
final query = <String, String>{
'limit': '$limit',
@@ -157,6 +102,7 @@ class Client {
if (cursor != null) 'cursor': cursor,
if (search != null && search.isNotEmpty) 'search': search,
if (directory != null && directory.isNotEmpty) 'directory': directory,
if (archived != null) 'archived': '$archived',
};
final r = await _json('GET', '/api/session', query: query, directory: directory);
final data = (r['data'] as List? ?? [])
@@ -173,22 +119,40 @@ class Client {
return data.keys.toSet();
}
Future<Session> createSession({String? title, String? directory}) async {
Future<Session> createSession(
{String? title,
String? directory,
ModelRef? model,
String? agent}) async {
final r = await _json('POST', '/api/session', body: {
if (title != null && title.isNotEmpty) 'title': title,
if (directory != null && directory.isNotEmpty)
'location': {'directory': directory},
// The first turn runs on the draft's selection; no switch after create.
if (model != null) 'model': model.toJson(),
if (agent != null && agent.isNotEmpty) 'agent': agent,
});
return Session.fromJson(r['data'] as Map<String, dynamic>);
}
Future<void> updateSession(String id, {String? title, bool? archived}) async {
Future<void> updateSession(String id,
{String? title, bool? archived, Map<String, dynamic>? metadata}) async {
await _json('PATCH', '/api/session/${Uri.encodeComponent(id)}', body: {
if (title != null) 'title': title,
if (archived != null) 'archived': archived,
if (metadata != null) 'metadata': metadata,
});
}
/// The projects (checkouts and chat folders) an agent can open a session in.
Future<List<ProjectInfo>> listProjects() async {
final list = await _jsonList('GET', '/api/project');
return [
for (final p in list)
if (p is Map<String, dynamic>) ProjectInfo.fromJson(p),
];
}
Future<void> deleteSession(String id) async {
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
}
@@ -249,22 +213,54 @@ class Client {
body: {'decision': decision, if (message.isNotEmpty) 'message': message});
}
Future<void> prompt(String sessionId,
/// Sends a prompt. [delivery] is 'steer' or 'queue' on a running turn; with
/// none the server starts a turn when idle. Returns the inbox item id.
Future<String?> prompt(String sessionId,
{String text = '',
String? messageId,
String? directory,
String? delivery,
List<Map<String, String>>? files,
List<String>? skillIds}) async {
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory,
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory,
body: {
if (text.isNotEmpty) 'text': text,
if (messageId != null) 'id': messageId,
if (delivery != null) 'delivery': delivery,
if (files != null && files.isNotEmpty) 'files': files,
if (skillIds != null && skillIds.isNotEmpty)
'skills': [
for (final id in skillIds) {'id': id},
],
});
final data = r['data'];
return data is Map ? data['id'] as String? : null;
}
/// Prompts waiting in the session's inbox (queued or about to steer).
Future<List<InboxItem>> inbox(String sessionId, {String? directory}) async {
final r = await _json('GET', '/api/session/${Uri.encodeComponent(sessionId)}/inbox',
directory: directory);
return [
for (final e in (r['data'] as List? ?? []))
if (e is Map<String, dynamic> && e['type'] == 'user')
InboxItem.fromJson(e),
];
}
/// Takes a waiting prompt out of the inbox.
Future<void> cancelInbox(String sessionId, String inboxId, {String? directory}) async {
await _json('DELETE',
'/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}',
directory: directory);
}
/// Moves a waiting prompt between `steer` and `queue`.
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
{String? directory}) async {
await _json('PATCH',
'/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}',
directory: directory, body: {'delivery': delivery});
}
/// Runs a registered slash command (`/initialize`, `/review`, …). The
@@ -290,6 +286,39 @@ class Client {
return data is Map ? data['id'] as String? : null;
}
// -------------------------------------------------------------- forms
/// The agent's pending questions in this session.
Future<List<FormInfo>> forms(String sessionId, {String? directory}) async {
final r = await _json(
'GET', '/api/session/${Uri.encodeComponent(sessionId)}/form',
directory: directory);
return [
for (final f in (r['data'] as List? ?? []))
if (f is Map<String, dynamic>) FormInfo.fromJson(f),
];
}
Future<void> replyForm(String sessionId, String formId,
Map<String, Object?> answer, {String? directory}) async {
await _json(
'POST',
'/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}/reply',
body: {'answer': answer},
directory: directory);
}
Future<void> cancelForm(String sessionId, String formId,
{String? message, String? directory}) async {
await _json(
'DELETE',
'/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}',
query: {
if (message != null && message.isNotEmpty) 'message': message,
},
directory: directory);
}
/// The commands this directory registers (`/api/command`).
Future<List<Map<String, String>>> commands({String? directory}) async {
final r = await _json('GET', '/api/command', directory: directory);
@@ -340,8 +369,23 @@ class Client {
}
Future<void> switchModel(String sessionId, ModelRef model, {String? directory}) async {
// The route takes the reference under `model`; sending it at the top level
// is rejected with "Missing key at [model]".
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/model',
directory: directory, body: model.toJson());
directory: directory, body: {'model': model.toJson()});
}
/// The instance settings. `surface` selects a per-surface profile (a phone
/// still shares every key that is not marked per-surface).
Future<Map<String, dynamic>> settings({String surface = 'mobile'}) async {
return _json('GET', '/api/config/settings', query: {'surface': surface});
}
/// Persists a partial settings patch and returns the updated settings.
Future<Map<String, dynamic>> saveSettings(Map<String, dynamic> patch,
{String surface = 'mobile'}) async {
return _json('PUT', '/api/config/settings',
query: {'surface': surface}, body: patch);
}
Future<void> switchAgent(String sessionId, String agent, {String? directory}) async {
@@ -349,18 +393,51 @@ class Client {
directory: directory, body: {'agent': agent});
}
Future<List<int>> rawFile(String path, {String? directory}) async {
Future<List<int>> rawFile(String path, {String? directory}) =>
downloadFile(path, directory: directory);
/// Downloads a file, reporting bytes as they arrive and letting the caller
/// cancel. A cancelled download throws [DownloadCancelled] and drops the
/// connection instead of reading it to the end.
Future<Uint8List> downloadFile(String path,
{String? directory,
void Function(int received, int? total)? onProgress,
CancelToken? cancel}) async {
final res = await _request('GET', '/api/fs/raw',
query: {
'path': path,
'allowOutsideWorkspace': 'true',
},
directory: directory,
rawDirectory: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true));
rawDirectory: true,
// Gzip would leave the response chunked (no total to show) and count
// compressed bytes; a download wants the file as it is.
noCompression: true);
final total = int.tryParse(res.headers['content-length'] ?? '');
cancel?.attach(() => res.abort?.call());
try {
final bytes = BytesBuilder(copy: false);
try {
await for (final chunk in res.body) {
if (cancel?.isCancelled ?? false) throw const DownloadCancelled();
bytes.add(chunk);
onProgress?.call(bytes.length, total);
}
} catch (error) {
// Aborting the request surfaces as a socket error; the caller only
// asked to stop.
if (cancel?.isCancelled ?? false) throw const DownloadCancelled();
rethrow;
}
if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(
res.statusCode,
utf8.decode(bytes.takeBytes(), allowMalformed: true));
}
return bytes.takeBytes();
} finally {
cancel?.detach();
}
return res.body;
}
// ------------------------------------------------------------ files
@@ -383,7 +460,7 @@ class Client {
Future<String> fsRead(String path, {String? directory}) async {
final res = await _request('GET', '/api/fs/read',
query: {'path': path}, directory: directory, rawDirectory: true);
final text = utf8.decode(res.body, allowMalformed: true);
final text = utf8.decode(await res.collect(), allowMalformed: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(res.statusCode, text.trim());
}
@@ -419,27 +496,29 @@ class Client {
/// when the connection drops; the caller restarts it with backoff.
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
// `types` repeats: a Map would keep only the last one.
var uri = base.resolve('/api/event');
if (types != null && types.isNotEmpty) {
final q = types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&');
uri = Uri.parse('$uri?$q');
}
final req = await _http.openUrl('GET', uri);
req.headers.set('Accept', 'text/event-stream');
req.headers.set('Cache-Control', 'no-cache');
if (token != null && token!.isNotEmpty) {
req.headers.set('Authorization', 'Bearer $token');
}
final res = await req.close();
if (res.statusCode != 200) {
throw ApiError(res.statusCode, 'event stream failed');
final query = types == null || types.isEmpty
? null
: types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&');
final res = await transport.send(TransportRequest(
method: 'GET',
path: '/api/event',
rawQuery: query,
headers: {
'accept': 'text/event-stream',
'cache-control': 'no-cache',
'user-agent': 'openchamber-native/0.3',
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
},
));
if (res.status != 200) {
throw ApiError(res.status, 'event stream failed');
}
String data = '';
// The server sends a `: heartbeat` comment every few seconds; if nothing
// at all arrives for a while the connection is dead and the caller should
// reconnect rather than wait on a half-open socket.
final lines = utf8.decoder
.bind(res)
.bind(res.body)
.transform(const LineSplitter())
.timeout(const Duration(seconds: 30));
await for (final line in lines) {
@@ -457,21 +536,291 @@ class Client {
}
}
// ------------------------------------------------------ project knowledge
/// The project id the server derives from a checkout path: `path_` + the
/// path base64url-encoded, both ends agreeing on the encoding.
static String projectIdFor(String directory) {
final normalized = directory
.replaceAll('\\', '/')
.replaceAll(RegExp(r'/+$'), '')
.trim();
if (normalized.isEmpty) return '';
final encoded = base64Url
.encode(utf8.encode(normalized))
.replaceAll('=', '');
return 'path_$encoded';
}
Future<ProjectContext> projectContext(String projectId,
{String? directory}) async {
final r = await _json(
'GET', '/api/project-context/${Uri.encodeComponent(projectId)}',
directory: directory);
return ProjectContext.fromJson(r);
}
/// Every mutation answers with the whole context beside the record it
/// changed, so the panel refreshes from one reply.
static ProjectContext _contextOf(Map<String, dynamic> r) {
final context = r['context'];
return ProjectContext.fromJson(
context is Map<String, dynamic> ? context : r);
}
Future<ProjectContext> createNote(String projectId, String body,
{String? planId, String? directory}) async {
final r = await _json(
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/notes',
body: {
'body': body,
if (planId != null) 'planId': planId,
},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> updateNote(
String projectId, String noteId,
{String? body, bool? pinned, String? directory}) async {
final r = await _json(
'PATCH',
'/api/project-context/${Uri.encodeComponent(projectId)}/notes/${Uri.encodeComponent(noteId)}',
body: {
if (body != null) 'body': body,
if (pinned != null) 'pinned': pinned,
},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> deleteNote(String projectId, String noteId,
{String? directory}) async {
final r = await _json(
'DELETE',
'/api/project-context/${Uri.encodeComponent(projectId)}/notes/${Uri.encodeComponent(noteId)}',
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> createTodo(String projectId, String text,
{String? planId, String? directory}) async {
final r = await _json(
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/todos',
body: {
'text': text,
if (planId != null) 'planId': planId,
},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> updateTodo(String projectId, String todoId,
{String? text, bool? completed, String? directory}) async {
final r = await _json(
'PATCH',
'/api/project-context/${Uri.encodeComponent(projectId)}/todos/${Uri.encodeComponent(todoId)}',
body: {
if (text != null) 'text': text,
if (completed != null) 'completed': completed,
},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> deleteTodo(String projectId, String todoId,
{String? directory}) async {
final r = await _json(
'DELETE',
'/api/project-context/${Uri.encodeComponent(projectId)}/todos/${Uri.encodeComponent(todoId)}',
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> createPlan(String projectId,
{required String title, required String body, String? directory}) async {
final r = await _json(
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/plans',
body: {'title': title, 'body': body},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> savePlan(String projectId, String planId, String raw,
{String? directory}) async {
final r = await _json(
'PUT',
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
body: {'raw': raw},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> setPlanPinned(
String projectId, String planId, bool pinned,
{String? directory}) async {
final r = await _json(
'PATCH',
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
body: {'pinned': pinned},
directory: directory);
return _contextOf(r);
}
Future<ProjectContext> deletePlan(String projectId, String planId,
{String? directory}) async {
final r = await _json(
'DELETE',
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
directory: directory);
return _contextOf(r);
}
Future<ProjectPlanContent> planContent(String projectId, String planId,
{String? directory}) async {
final r = await _json(
'GET',
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
directory: directory);
return ProjectPlanContent.fromJson(r);
}
// ----------------------------------------------------------------- memory
/// Both memory scopes at once; null when the server has the feature switched
/// off (the route answers 404, which it also uses for a missing entry, but
/// this read has no entry id to miss).
Future<AgentMemorySnapshot?> agentMemory(String projectId,
{String? directory}) async {
try {
final r = await _json('GET', '/api/agent-memory/all',
query: {
if (projectId.isNotEmpty) 'projectId': projectId,
},
directory: directory);
return AgentMemorySnapshot.fromJson(r);
} on ApiError catch (error) {
if (error.status == 404) return null;
rethrow;
}
}
Future<void> updateMemory(String memoryId,
{required String scope,
String? projectId,
String? title,
String? body,
String? type,
String? directory}) async {
await _json(
'PATCH', '/api/agent-memory/${Uri.encodeComponent(memoryId)}',
query: {
'scope': scope,
if (scope == 'project' && projectId != null && projectId.isNotEmpty)
'projectId': projectId,
},
body: {
if (title != null) 'title': title,
if (body != null) 'body': body,
if (type != null) 'type': type,
},
directory: directory);
}
Future<void> deleteMemory(String memoryId,
{required String scope,
String? projectId,
String? directory}) async {
await _json(
'DELETE', '/api/agent-memory/${Uri.encodeComponent(memoryId)}',
query: {
'scope': scope,
if (scope == 'project' && projectId != null && projectId.isNotEmpty)
'projectId': projectId,
},
directory: directory);
}
// --------------------------------------------------------------- terminal
Future<TerminalSessionInfo> createTerminal(
{required String cwd, int cols = 80, int rows = 24}) async {
final r = await _json('POST', '/api/terminal/create',
body: {'cwd': cwd, 'cols': cols, 'rows': rows}, directory: cwd);
return TerminalSessionInfo.fromJson(r);
}
Future<void> resizeTerminal(String sessionId, int cols, int rows,
{String? directory}) async {
await _json('POST',
'/api/terminal/${Uri.encodeComponent(sessionId)}/resize',
body: {'cols': cols, 'rows': rows}, directory: directory);
}
Future<TerminalSessionInfo> restartTerminal(String sessionId,
{required String cwd, int cols = 80, int rows = 24}) async {
final r = await _json('POST',
'/api/terminal/${Uri.encodeComponent(sessionId)}/restart',
body: {'cwd': cwd, 'cols': cols, 'rows': rows}, directory: cwd);
return TerminalSessionInfo.fromJson(r);
}
Future<void> closeTerminal(String sessionId, {String? directory}) async {
await _json(
'DELETE', '/api/terminal/${Uri.encodeComponent(sessionId)}',
directory: directory);
}
/// The terminals the server still holds for [cwd] (or all of them when it is
/// empty). The server keeps an unattached shell for half an hour, so a
/// client that remembers its session id can reattach after a restart.
Future<List<ServerTerminal>> listTerminals({String? cwd}) async {
final r = await _json('GET', '/api/terminal/sessions',
query: {if (cwd != null && cwd.isNotEmpty) 'cwd': cwd},
directory: cwd);
final raw = r['sessions'];
if (raw is! List) return const [];
return [
for (final entry in raw)
if (entry is Map<String, dynamic>) ServerTerminal.fromJson(entry),
];
}
/// The headers the terminal socket needs (auth, and the workspace the
/// server routes the upgrade by).
Map<String, String> get eventHeaders => {
'user-agent': 'openchamber-native/0.3',
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
};
// --------------------------------------------------------------- transport
Future<List<dynamic>> _jsonList(String method, String path,
{Map<String, String>? query}) async {
final res = await _request(method, path, query: query);
final text = utf8.decode(await res.collect(), allowMalformed: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(res.statusCode, text.trim());
}
final decoded = jsonDecode(text);
return decoded is List ? decoded : const [];
}
Future<Map<String, dynamic>> _json(String method, String path,
{Map<String, String>? query,
Map<String, dynamic>? body,
String? directory,
bool partShells = false,
bool rawDirectory = false}) async {
bool rawDirectory = false,
bool noCompression = false}) async {
final res = await _request(method, path,
query: query,
body: body,
directory: directory,
partShells: partShells,
rawDirectory: rawDirectory);
final text = utf8.decode(res.body, allowMalformed: true);
rawDirectory: rawDirectory,
noCompression: noCompression);
final text = utf8.decode(await res.collect(), allowMalformed: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
String msg = text;
try {
@@ -493,128 +842,45 @@ class Client {
Map<String, dynamic>? body,
String? directory,
bool partShells = false,
bool rawDirectory = false}) async {
final q = Uri(queryParameters: query ?? {});
final uri = base.resolve(path).replace(queryParameters: q.queryParameters.isEmpty ? null : q.queryParameters);
final req = await _http.openUrl(method, uri);
// Every header must be set before the body, which finalizes them.
req.headers.set('Accept', path == '/api/event' ? 'text/event-stream' : 'application/json');
req.headers.set('User-Agent', 'openchamber-native/0.3');
if (token != null && token!.isNotEmpty) {
req.headers.set('Authorization', 'Bearer $token');
}
bool rawDirectory = false,
bool noCompression = false}) async {
final headers = <String, String>{
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
'user-agent': 'openchamber-native/0.3',
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
};
if (directory != null && directory.isNotEmpty) {
// The file routes compare this header with the workspace path, so they
// need it as written; the rest of the API wants it URI-encoded.
req.headers.set('x-opencode-directory',
rawDirectory ? directory : Uri.encodeComponent(directory));
if (!rawDirectory) {
req.headers.set('x-opencode-directory-encoding', 'uri');
}
headers['x-opencode-directory'] =
rawDirectory ? directory : Uri.encodeComponent(directory);
if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
}
if (partShells) {
req.headers.set('x-openchamber-part-shells', 'v1');
}
if (path == '/api/event') {
req.headers.set('Cache-Control', 'no-cache');
}
if (body != null) {
req.headers.contentType = ContentType.json;
req.write(jsonEncode(body));
}
final res = await req.close();
final bodyBytes = await res.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
return _Response(res.statusCode, bodyBytes);
if (partShells) headers['x-openchamber-part-shells'] = 'v1';
if (noCompression) headers['accept-encoding'] = 'identity';
if (path == '/api/event') headers['cache-control'] = 'no-cache';
final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body));
if (bodyBytes != null) headers['content-type'] = 'application/json';
final res = await transport.send(TransportRequest(
method: method,
path: path,
query: query ?? const {},
headers: headers,
body: bodyBytes,
));
return _Response(res.status, res.headers, res.body, res.abort);
}
void close() => _http.close();
void close() => transport.close();
}
class _Response {
final int statusCode;
final List<int> body;
_Response(this.statusCode, this.body);
}
final Map<String, String> headers;
final Stream<List<int>> body;
final void Function()? abort;
_Response(this.statusCode, this.headers, this.body, [this.abort]);
String _sha256(List<int> bytes) {
return _Digest.sha256Hex(bytes);
}
// Minimal SHA-256, so the client has no native dependencies for pinning.
class _Digest {
static String sha256Hex(List<int> bytes) {
final h = List<int>.from(const [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
final k = <int>[
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
final m = List<int>.from(bytes);
final bitLen = m.length * 8;
m.add(0x80);
while (m.length % 64 != 56) {
m.add(0);
}
for (var i = 7; i >= 0; i--) {
m.add((bitLen >> (8 * i)) & 0xff);
}
final words = List<int>.generate(m.length ~/ 4, (i) =>
(m[i * 4] << 24) | (m[i * 4 + 1] << 16) | (m[i * 4 + 2] << 8) | m[i * 4 + 3]);
var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
for (var i = 0; i < words.length; i += 16) {
final w = List<int>.filled(64, 0);
for (var j = 0; j < 16; j++) {
w[j] = words[i + j];
}
for (var j = 16; j < 64; j++) {
final s0 = _rotr(w[j - 15], 7) ^ _rotr(w[j - 15], 18) ^ (w[j - 15] >> 3);
final s1 = _rotr(w[j - 2], 17) ^ _rotr(w[j - 2], 19) ^ (w[j - 2] >> 10);
w[j] = (w[j - 16] + s0 + w[j - 7] + s1) & 0xffffffff;
}
var ta = a, tb = b, tc = c, td = d, te = e, tf = f, tg = g, th = hh;
for (var j = 0; j < 64; j++) {
final S1 = _rotr(te, 6) ^ _rotr(te, 11) ^ _rotr(te, 25);
final ch = (te & tf) ^ ((~te) & tg);
final t1 = (th + S1 + ch + k[j] + w[j]) & 0xffffffff;
final S0 = _rotr(ta, 2) ^ _rotr(ta, 13) ^ _rotr(ta, 22);
final maj = (ta & tb) ^ (ta & tc) ^ (tb & tc);
final t2 = (S0 + maj) & 0xffffffff;
th = tg;
tg = tf;
tf = te;
te = (td + t1) & 0xffffffff;
td = tc;
tc = tb;
tb = ta;
ta = (t1 + t2) & 0xffffffff;
}
a = (a + ta) & 0xffffffff;
b = (b + tb) & 0xffffffff;
c = (c + tc) & 0xffffffff;
d = (d + td) & 0xffffffff;
e = (e + te) & 0xffffffff;
f = (f + tf) & 0xffffffff;
g = (g + tg) & 0xffffffff;
hh = (hh + th) & 0xffffffff;
}
final out = List<int>.filled(32, 0);
final vals = [a, b, c, d, e, f, g, hh];
for (var i = 0; i < 8; i++) {
out[i * 4] = (vals[i] >> 24) & 0xff;
out[i * 4 + 1] = (vals[i] >> 16) & 0xff;
out[i * 4 + 2] = (vals[i] >> 8) & 0xff;
out[i * 4 + 3] = vals[i] & 0xff;
}
return out.map((e) => e.toRadixString(16).padLeft(2, '0')).join();
}
static int _rotr(int x, int n) => (x >> n) | ((x << (32 - n)) & 0xffffffff);
Future<List<int>> collect() =>
body.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
}
+593 -4
View File
@@ -52,34 +52,147 @@ class Location {
class Session {
final String id;
final String? parentID;
final String projectID;
final String title;
final String agent;
final ModelRef? model;
final Location? location;
final Map<String, dynamic> metadata;
final int created;
final int updated;
final int viewed;
final int archived;
Session({
required this.id,
required this.title,
this.parentID,
this.projectID = '',
this.agent = '',
this.model,
this.location,
this.metadata = const {},
this.created = 0,
this.updated = 0,
this.viewed = 0,
this.archived = 0,
});
factory Session.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
return Session(
id: j['id'] as String,
parentID: j['parentID'] as String?,
projectID: j['projectID'] as String? ?? '',
title: j['title'] as String? ?? '',
agent: j['agent'] as String? ?? '',
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
location: j['location'] == null ? null : Location.fromJson(j['location'] as Map<String, dynamic>),
metadata: j['metadata'] is Map<String, dynamic>
? Map<String, dynamic>.from(j['metadata'] as Map<String, dynamic>)
: const {},
created: (t['created'] as num?)?.toInt() ?? 0,
updated: (t['updated'] as num?)?.toInt() ?? 0,
viewed: (t['viewed'] as num?)?.toInt() ?? 0,
archived: (t['archived'] as num?)?.toInt() ?? 0,
);
}
String get directory => location?.directory ?? '';
bool get isChild => parentID != null && parentID!.isNotEmpty;
bool get isArchived => archived > 0;
/// Pins live in the session's metadata (`openchamber.pinned`), so every
/// client of the server sees them.
bool get isPinned {
final openchamber = metadata['openchamber'];
return openchamber is Map && openchamber['pinned'] is Map;
}
int get pinnedAt {
final openchamber = metadata['openchamber'];
if (openchamber is! Map) return 0;
final pinned = openchamber['pinned'];
return pinned is Map && pinned['at'] is num ? (pinned['at'] as num).toInt() : 0;
}
Session copyWith({
String? title,
ModelRef? model,
String? agent,
Map<String, dynamic>? metadata,
int? viewed,
int? archived,
int? updated,
}) =>
Session(
id: id,
parentID: parentID,
projectID: projectID,
title: title ?? this.title,
agent: agent ?? this.agent,
model: model ?? this.model,
location: location,
metadata: metadata ?? this.metadata,
created: created,
updated: updated ?? this.updated,
viewed: viewed ?? this.viewed,
archived: archived ?? this.archived,
);
}
/// A project the server knows: a checkout (or chat folder) an agent can work
/// in. [canonical] is the directory a session there carries.
class ProjectInfo {
final String id;
final String canonical;
final String name;
final String vcs;
const ProjectInfo({
required this.id,
required this.canonical,
this.name = '',
this.vcs = '',
});
factory ProjectInfo.fromJson(Map<String, dynamic> j) => ProjectInfo(
id: j['id'] as String? ?? '',
canonical: j['canonical'] as String? ?? '',
name: j['name'] as String? ?? '',
vcs: j['vcs'] as String? ?? '',
);
String get label {
if (name.trim().isNotEmpty) return name.trim();
return pathLeaf(canonical);
}
}
/// The last segment of a path, treating `\` and `/` alike: a Windows server
/// sends `C:\...` and a project has to read as its folder name, not the path.
String pathLeaf(String path) {
final trimmed = path.replaceAll(RegExp(r'[/\\]+$'), '');
final index = trimmed.lastIndexOf(RegExp(r'[/\\]'));
return index >= 0 ? trimmed.substring(index + 1) : trimmed;
}
/// A path with `\` written as `/` and no trailing slash, for comparing and
/// grouping directory names from a Windows or a POSIX server.
String slashPath(String path) =>
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), '');
/// Whether two directory paths name the same place. Separators are unified;
/// a drive-letter path compares case-insensitively, as Windows does.
bool samePath(String a, String b) {
final x = slashPath(a);
final y = slashPath(b);
if (x == y) return true;
final windows = RegExp(r'^[A-Za-z]:').hasMatch(x) ||
RegExp(r'^[A-Za-z]:').hasMatch(y);
return windows && x.toLowerCase() == y.toLowerCase();
}
class ContentPart {
@@ -291,9 +404,466 @@ class Message {
class FileAttachment {
final String name;
final String mime;
FileAttachment(this.name, this.mime);
factory FileAttachment.fromJson(Map<String, dynamic> j) =>
FileAttachment(j['name'] as String? ?? '', j['mime'] as String? ?? '');
/// Base64 of the file the user attached, as the server stores it.
final String data;
/// 'inline' | 'path' — where the bytes came from, when the server says.
final String source;
FileAttachment(this.name, this.mime, {this.data = '', this.source = ''});
bool get isImage => mime.startsWith('image/') && data.isNotEmpty;
factory FileAttachment.fromJson(Map<String, dynamic> j) => FileAttachment(
j['name'] as String? ?? '',
j['mime'] as String? ?? '',
data: j['data'] as String? ?? '',
// Stored messages carry `{type: 'inline'}` here; keep only text.
source: j['source'] is String ? j['source'] as String : '',
);
}
/// A prompt the server holds in the session's inbox until it is delivered:
/// `queue` waits for the running turn to end, `steer` joins it at its next
/// step. The message only enters the transcript when it is delivered.
class InboxItem {
final String id;
final String text;
/// 'steer' | 'queue'.
final String delivery;
final int created;
final List<FileAttachment> files;
const InboxItem({
required this.id,
required this.text,
required this.delivery,
this.created = 0,
this.files = const [],
});
/// Non-user inbox entries (compaction, moves, synthetic context) are the
/// server's own; only what the person typed is shown.
factory InboxItem.fromJson(Map<String, dynamic> j) {
final time = j['time'] as Map<String, dynamic>? ?? {};
final payload = j['payload'] as Map<String, dynamic>? ?? {};
return InboxItem(
id: j['id'] as String,
text: payload['text'] as String? ?? '',
delivery: j['delivery'] as String? ?? 'queue',
created: (time['created'] as num?)?.toInt() ?? 0,
files: (payload['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
}
/// An `enqueued` event carries the payload under `item` and the id beside
/// it, rather than in the item.
factory InboxItem.fromEvent(String id, Map<String, dynamic> j, int created) {
final payload = j['payload'] as Map<String, dynamic>? ?? {};
return InboxItem(
id: id,
text: payload['text'] as String? ?? '',
delivery: j['delivery'] as String? ?? 'queue',
created: created,
files: (payload['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
}
InboxItem withDelivery(String value) => InboxItem(
id: id,
text: text,
delivery: value,
created: created,
files: files,
);
}
/// One row of a native form's choice control.
class FormOption {
final String value;
final String label;
final String? description;
const FormOption(this.value, this.label, [this.description]);
factory FormOption.fromJson(Map<String, dynamic> j) => FormOption(
j['value'] as String? ?? '',
j['label'] as String? ?? j['value'] as String? ?? '',
j['description'] as String?,
);
}
/// `when` makes a field visible only while another field holds a value.
class FormWhen {
final String key;
final String op; // eq | neq
final Object? value;
const FormWhen(this.key, this.op, this.value);
factory FormWhen.fromJson(Map<String, dynamic> j) => FormWhen(
j['key'] as String? ?? '',
j['op'] as String? ?? 'eq',
j['value'],
);
}
/// A field of a form request: string, number, integer, boolean, multiselect
/// or external (a link the user acknowledges).
class AgentFormField {
final String key;
final String type;
final String? title;
final String? description;
final String? placeholder;
final String? format;
final String? url;
final bool required;
final bool hidden;
final bool custom;
final Object? defaultValue;
final num? minimum;
final num? maximum;
final int? minLength;
final int? maxLength;
final int? minItems;
final int? maxItems;
final List<FormOption> options;
final List<FormWhen> when;
const AgentFormField({
required this.key,
required this.type,
this.title,
this.description,
this.placeholder,
this.format,
this.url,
this.required = false,
this.hidden = false,
this.custom = false,
this.defaultValue,
this.minimum,
this.maximum,
this.minLength,
this.maxLength,
this.minItems,
this.maxItems,
this.options = const [],
this.when = const [],
});
factory AgentFormField.fromJson(Map<String, dynamic> j) {
num? numOf(Object? v) => v is num ? v : null;
return AgentFormField(
key: j['key'] as String? ?? '',
type: j['type'] as String? ?? 'string',
title: j['title'] as String?,
description: j['description'] as String?,
placeholder: j['placeholder'] as String?,
format: j['format'] as String?,
url: j['url'] as String?,
required: j['required'] as bool? ?? false,
hidden: j['hidden'] as bool? ?? false,
custom: j['custom'] as bool? ?? false,
defaultValue: j['default'],
minimum: numOf(j['minimum']),
maximum: numOf(j['maximum']),
minLength: (j['minLength'] as num?)?.toInt(),
maxLength: (j['maxLength'] as num?)?.toInt(),
minItems: (j['minItems'] as num?)?.toInt(),
maxItems: (j['maxItems'] as num?)?.toInt(),
options: [
for (final o in (j['options'] as List? ?? []))
if (o is Map<String, dynamic>) FormOption.fromJson(o),
],
when: [
for (final w in (j['when'] as List? ?? []))
if (w is Map<String, dynamic>) FormWhen.fromJson(w),
],
);
}
String get label => (title == null || title!.isEmpty) ? key : title!;
}
/// A blocking question from the agent. The client answers every visible field
/// at once; the answer map is keyed by field key.
class FormInfo {
final String id;
final String sessionID;
final String title;
final List<AgentFormField> fields;
const FormInfo({
required this.id,
required this.sessionID,
required this.title,
required this.fields,
});
factory FormInfo.fromJson(Map<String, dynamic> j) => FormInfo(
id: j['id'] as String? ?? '',
sessionID: j['sessionID'] as String? ?? '',
title: j['title'] as String? ?? '',
fields: [
for (final f in (j['fields'] as List? ?? []))
if (f is Map<String, dynamic>) AgentFormField.fromJson(f),
],
);
}
// -------------------------------------------------------- project knowledge
/// A saved note, as `/api/project-context` stores it.
class ProjectNote {
final String id;
final String body;
final int createdAt;
final int updatedAt;
final String source; // manual | selection | agent
final bool pinned;
final String? planId;
const ProjectNote({
required this.id,
required this.body,
this.createdAt = 0,
this.updatedAt = 0,
this.source = 'manual',
this.pinned = false,
this.planId,
});
factory ProjectNote.fromJson(Map<String, dynamic> j) => ProjectNote(
id: j['id'] as String? ?? '',
body: j['body'] as String? ?? '',
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
source: j['source'] as String? ?? 'manual',
pinned: j['pinned'] as bool? ?? false,
planId: j['planId'] as String?,
);
String get firstLine {
final line = body.split('\n').firstWhere((l) => l.trim().isNotEmpty,
orElse: () => '');
return line.trim();
}
}
/// A todo item. [planId] links it to a plan; [dependsOn] lists the todos of
/// the same plan that must be completed first.
class ProjectTodo {
final String id;
final String text;
final bool completed;
final int createdAt;
final String? planId;
final List<String> dependsOn;
const ProjectTodo({
required this.id,
required this.text,
this.completed = false,
this.createdAt = 0,
this.planId,
this.dependsOn = const [],
});
factory ProjectTodo.fromJson(Map<String, dynamic> j) => ProjectTodo(
id: j['id'] as String? ?? '',
text: j['text'] as String? ?? '',
completed: j['completed'] as bool? ?? false,
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
planId: j['planId'] as String?,
dependsOn: [
for (final d in (j['dependsOn'] as List? ?? []))
if (d is String) d,
],
);
}
/// A plan the project lists: a manifest entry (personal) or a file from the
/// team's shared folder.
class ProjectPlanLink {
final String id;
final String file;
final String title;
final int createdAt;
final bool pinned;
final String source; // personal | shared
final int progressDone;
final int progressTotal;
final String? sessionId;
const ProjectPlanLink({
required this.id,
required this.file,
required this.title,
this.createdAt = 0,
this.pinned = false,
this.source = 'personal',
this.progressDone = 0,
this.progressTotal = 0,
this.sessionId,
});
factory ProjectPlanLink.fromJson(Map<String, dynamic> j) {
final progress = j['progress'];
final session = j['session'];
return ProjectPlanLink(
id: j['id'] as String? ?? '',
file: j['file'] as String? ?? '',
title: j['title'] as String? ?? '',
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
pinned: j['pinned'] as bool? ?? false,
source: j['source'] as String? ?? 'personal',
progressDone:
progress is Map ? (progress['done'] as num?)?.toInt() ?? 0 : 0,
progressTotal:
progress is Map ? (progress['total'] as num?)?.toInt() ?? 0 : 0,
sessionId: session is Map ? session['sessionId'] as String? : null,
);
}
bool get hasProgress => progressTotal > 0;
}
/// Everything the project knowledge panel shows for one directory.
class ProjectContext {
final List<ProjectNote> notes;
final List<ProjectTodo> todos;
final List<ProjectPlanLink> plans;
final String? sharedPlansDir;
const ProjectContext({
this.notes = const [],
this.todos = const [],
this.plans = const [],
this.sharedPlansDir,
});
factory ProjectContext.fromJson(Map<String, dynamic> j) => ProjectContext(
notes: [
for (final n in (j['notes'] as List? ?? []))
if (n is Map<String, dynamic>) ProjectNote.fromJson(n),
],
todos: [
for (final t in (j['todos'] as List? ?? []))
if (t is Map<String, dynamic>) ProjectTodo.fromJson(t),
],
plans: [
for (final p in (j['plans'] as List? ?? []))
if (p is Map<String, dynamic>) ProjectPlanLink.fromJson(p),
],
sharedPlansDir: j['sharedPlansDir'] as String?,
);
bool get isEmpty => notes.isEmpty && todos.isEmpty && plans.isEmpty;
}
/// One remembered fact, preference or reference. The agent writes these
/// through its memory tool; the panel reads, corrects and deletes them.
class AgentMemoryEntry {
final String id;
final String title;
final String body;
final String type; // fact | preference | reference
final int createdAt;
final int updatedAt;
final bool flagged;
final String? sessionId;
const AgentMemoryEntry({
required this.id,
required this.title,
required this.body,
this.type = 'fact',
this.createdAt = 0,
this.updatedAt = 0,
this.flagged = false,
this.sessionId,
});
factory AgentMemoryEntry.fromJson(Map<String, dynamic> j) => AgentMemoryEntry(
id: j['id'] as String? ?? '',
title: j['title'] as String? ?? '',
body: j['body'] as String? ?? '',
type: j['type'] as String? ?? 'fact',
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
flagged: j['flagged'] == true,
sessionId: j['sessionId'] as String?,
);
String get typeLabel => switch (type) {
'preference' => '偏好',
'reference' => '参考',
_ => '事实',
};
}
/// Both memory scopes in one read, as `/api/agent-memory/all` answers.
class AgentMemorySnapshot {
final List<AgentMemoryEntry> global;
final List<AgentMemoryEntry> project;
final bool globalFailed;
final bool projectFailed;
const AgentMemorySnapshot({
this.global = const [],
this.project = const [],
this.globalFailed = false,
this.projectFailed = false,
});
factory AgentMemorySnapshot.fromJson(Map<String, dynamic> j) =>
AgentMemorySnapshot(
global: [
for (final m in (j['global'] as List? ?? []))
if (m is Map<String, dynamic>) AgentMemoryEntry.fromJson(m),
],
project: [
for (final m in (j['project'] as List? ?? []))
if (m is Map<String, dynamic>) AgentMemoryEntry.fromJson(m),
],
globalFailed: j['globalFailed'] == true,
projectFailed: j['projectFailed'] == true,
);
bool get isEmpty => global.isEmpty && project.isEmpty;
}
/// A plan as the server reads it back: the link plus its Markdown.
class ProjectPlanContent {
final String id;
final String title;
final String body;
final String raw;
final String? path;
final String source;
const ProjectPlanContent({
required this.id,
required this.title,
required this.body,
this.raw = '',
this.path,
this.source = 'personal',
});
factory ProjectPlanContent.fromJson(Map<String, dynamic> j) =>
ProjectPlanContent(
id: j['id'] as String? ?? '',
title: j['title'] as String? ?? '',
body: j['body'] as String? ?? '',
raw: j['raw'] as String? ?? '',
path: j['path'] as String?,
source: j['source'] as String? ?? 'personal',
);
}
class Page<T> {
@@ -316,17 +886,36 @@ class ModelInfo {
final String name;
final int context;
final int output;
ModelInfo(this.id, this.providerId, this.name, this.context, this.output);
/// Thinking levels this model offers (`minimal`, `low`, `medium`, …), as
/// v2's model variants. Empty means the model has no effort choice.
final List<String> variants;
/// The provider says the model reasons; worth a mark in the picker.
final bool reasoning;
ModelInfo(this.id, this.providerId, this.name, this.context, this.output,
{this.variants = const [], this.reasoning = false});
factory ModelInfo.fromJson(Map<String, dynamic> j) {
final lim = j['limit'] as Map<String, dynamic>? ?? {};
final capabilities = j['capabilities'];
return ModelInfo(
j['id'] as String,
j['providerID'] as String? ?? '',
j['name'] as String? ?? (j['id'] as String? ?? ''),
(lim['context'] as num?)?.toInt() ?? 0,
(lim['output'] as num?)?.toInt() ?? 0,
variants: [
for (final v in (j['variants'] as List? ?? []))
if (v is Map && v['id'] is String) v['id'] as String,
],
reasoning:
capabilities is Map && capabilities['reasoning'] == true,
);
}
bool get hasEffort => variants.isNotEmpty;
}
class AgentInfo {
+193
View File
@@ -0,0 +1,193 @@
// The pairing link the desktop shows as a QR code: `openchamber://connect?v=2`
// with a base64url JSON payload. It carries the one-time secret and the ways
// to reach the server — direct URLs and, when enabled, the private relay with
// the host's encryption key (the E2EE trust anchor).
import 'dart:convert';
const _maxPayloadLength = 16384;
class PairingCandidate {
final String type; // lan | tunnel | relay
final String url; // direct candidates
final String relayUrl; // relay candidates
final String serverId;
final Map<String, dynamic>? hostKey;
final String? grant;
final int priority;
const PairingCandidate.direct({
required this.type,
required this.url,
this.priority = 100,
}) : relayUrl = '',
serverId = '',
hostKey = null,
grant = null;
const PairingCandidate.relay({
required String this.relayUrl,
required this.serverId,
required Map<String, dynamic> this.hostKey,
this.grant,
this.priority = 100,
}) : type = 'relay',
url = '';
bool get isRelay => type == 'relay';
}
class PairingPayload {
final String pairingId;
final String secret;
final String? label;
final String? fingerprint;
final DateTime? expiresAt;
final List<PairingCandidate> candidates;
const PairingPayload({
required this.pairingId,
required this.secret,
this.label,
this.fingerprint,
this.expiresAt,
required this.candidates,
});
}
/// Parses a link or payload. Returns null when it is not a valid, unexpired
/// pairing link. Direct candidates come before relay, each by priority, so a
/// reachable LAN address is tried before the tunnel.
PairingPayload? parsePairingLink(String raw) {
final text = raw.trim();
if (text.isEmpty || text.length > _maxPayloadLength) return null;
String? encoded;
final start = text.indexOf('?');
if (start >= 0) {
final head = text.substring(0, start);
if (RegExp(r'^openchamber://connect/?$', caseSensitive: false)
.hasMatch(head)) {
for (final part in text.substring(start + 1).split('&')) {
final eq = part.indexOf('=');
if (eq < 0) continue;
final key = part.substring(0, eq);
final value = part.substring(eq + 1);
if (key == 'p') encoded = value;
if (key == 'v' && value != '2') return null;
}
}
}
encoded ??= text;
if (encoded.length > _maxPayloadLength) return null;
final Object? decoded;
try {
decoded = jsonDecode(utf8.decode(_base64UrlDecode(encoded)));
} catch (_) {
return null;
}
if (decoded is! Map) return null;
final pairingId = decoded['pairingId'];
final secret = decoded['secret'];
if (decoded['v'] != 2 || pairingId is! String || secret is! String) {
return null;
}
if (pairingId.trim().isEmpty || secret.trim().isEmpty) return null;
DateTime? expiresAt;
final rawExpiry = decoded['expiresAt'];
if (rawExpiry is String && rawExpiry.isNotEmpty) {
expiresAt = DateTime.tryParse(rawExpiry);
if (expiresAt != null && !expiresAt.isAfter(DateTime.now())) return null;
}
final rawCandidates = decoded['candidates'];
final candidates = <PairingCandidate>[];
if (rawCandidates is List) {
for (final raw in rawCandidates) {
final candidate = _candidate(raw);
if (candidate != null) candidates.add(candidate);
}
}
if (candidates.isEmpty) return null;
candidates.sort((a, b) {
if (a.isRelay != b.isRelay) return a.isRelay ? 1 : -1;
return a.priority.compareTo(b.priority);
});
final label = decoded['label'];
final fingerprint = decoded['fingerprint'];
return PairingPayload(
pairingId: pairingId.trim(),
secret: secret.trim(),
label: label is String && label.trim().isNotEmpty ? label.trim() : null,
fingerprint: fingerprint is String && fingerprint.trim().isNotEmpty
? fingerprint.trim()
: null,
expiresAt: expiresAt,
candidates: candidates,
);
}
PairingCandidate? _candidate(Object? raw) {
if (raw is! Map) return null;
final priority = raw['priority'] is num
? (raw['priority'] as num).toInt()
: 100;
final type = raw['type'];
if (type == 'lan' || type == 'tunnel') {
final url = _httpUrl(raw['url']);
if (url == null) return null;
return PairingCandidate.direct(type: type as String, url: url, priority: priority);
}
if (type == 'relay') {
final relayUrl = _wsUrl(raw['relayUrl']);
final serverId = raw['serverId'];
final key = _ecPublicJwk(raw['hostEncPubJwk']);
if (relayUrl == null ||
serverId is! String ||
serverId.trim().isEmpty ||
key == null) {
return null;
}
final grant = raw['grant'];
return PairingCandidate.relay(
relayUrl: relayUrl,
serverId: serverId.trim(),
hostKey: key,
grant: grant is String && grant.trim().isNotEmpty ? grant.trim() : null,
priority: priority,
);
}
return null;
}
String? _httpUrl(Object? raw) {
if (raw is! String) return null;
final uri = Uri.tryParse(raw.trim());
if (uri == null || (uri.scheme != 'http' && uri.scheme != 'https')) {
return null;
}
if (uri.host.isEmpty) return null;
return uri.removeFragment().toString().replaceAll(RegExp(r'/+$'), '');
}
String? _wsUrl(Object? raw) {
if (raw is! String) return null;
final uri = Uri.tryParse(raw.trim());
if (uri == null || (uri.scheme != 'ws' && uri.scheme != 'wss')) return null;
if (uri.host.isEmpty) return null;
return uri.removeFragment().toString();
}
Map<String, dynamic>? _ecPublicJwk(Object? raw) {
if (raw is! Map) return null;
if (raw['kty'] != 'EC' || raw['crv'] != 'P-256') return null;
final x = raw['x'];
final y = raw['y'];
if (x is! String || y is! String || x.isEmpty || y.isEmpty) return null;
return {'kty': 'EC', 'crv': 'P-256', 'x': x, 'y': y};
}
List<int> _base64UrlDecode(String value) {
final padded = value.padRight((value.length + 3) ~/ 4 * 4, '=');
return base64Url.decode(padded);
}
+98
View File
@@ -0,0 +1,98 @@
// QR decoding for the pairing scanner. The camera hands us a Y plane (YUV420
// on Android) that is already luminance; zxing2's QR reader does the rest. Kept
// free of Flutter so a frame can be decoded in a background isolate and a unit
// test can feed it a generated QR image.
import 'dart:typed_data';
import 'package:zxing2/qrcode.dart';
import 'package:zxing2/zxing2.dart';
/// One grayscale frame: [rowStride] may exceed [width] (camera padding).
class QrFrame {
final Uint8List luminance;
final int width;
final int height;
final int rowStride;
const QrFrame({
required this.luminance,
required this.width,
required this.height,
required this.rowStride,
});
}
/// The payload of the QR code in [frame], or null when there is none.
String? decodeQrFrame(QrFrame frame) => decodeQrLuminance(
frame.luminance,
frame.width,
frame.height,
frame.rowStride,
);
String? decodeQrLuminance(
Uint8List luminance, int width, int height, int rowStride) {
if (width <= 0 || height <= 0 || rowStride < width) return null;
if (luminance.length < rowStride * height) return null;
try {
final source = _PlaneLuminanceSource(luminance, width, height, rowStride);
final bitmap = BinaryBitmap(HybridBinarizer(source));
return QRCodeReader().decode(bitmap).text;
} on ReaderException {
return null;
} catch (_) {
// A torn or malformed frame must not stop the scanner.
return null;
}
}
/// BGRA8888 (iOS and some cameras): green-weighted luminance, as zxing2's
/// RGBLuminanceSource computes it.
Uint8List bgraToLuminance(
Uint8List bytes, int width, int height, int rowStride) {
final out = Uint8List(width * height);
for (var y = 0; y < height; y++) {
final row = y * rowStride;
final target = y * width;
for (var x = 0; x < width; x++) {
final i = row + x * 4;
if (i + 2 >= bytes.length) break;
final b = bytes[i];
final g = bytes[i + 1];
final r = bytes[i + 2];
out[target + x] = (r + 2 * g + b) >> 2;
}
}
return out;
}
class _PlaneLuminanceSource extends LuminanceSource {
final Uint8List data;
final int rowStride;
_PlaneLuminanceSource(this.data, int width, int height, this.rowStride)
: super(width, height);
@override
Int8List getRow(int y, Int8List? row) {
final out = (row != null && row.length >= width) ? row : Int8List(width);
final base = y * rowStride;
for (var x = 0; x < width; x++) {
out[x] = data[base + x].toSigned(8);
}
return out;
}
@override
Int8List getMatrix() {
final out = Int8List(width * height);
for (var y = 0; y < height; y++) {
final base = y * rowStride;
final target = y * width;
for (var x = 0; x < width; x++) {
out[target + x] = data[base + x].toSigned(8);
}
}
return out;
}
}
+209
View File
@@ -0,0 +1,209 @@
// E2EE for the OpenChamber private relay (Layer 2). The host holds a
// long-lived P-256 key; its public JWK reaches us in the pairing link and is
// the trust anchor. An ephemeral P-256 key and a 16-byte nonce per connection
// derive two AES-256-GCM keys, one per direction; frames carry a version, a
// 12-byte IV (4-byte random prefix + 8-byte counter) and the GCM tag.
//
// The wire format is the first-party one (packages/ui/src/lib/relay/crypto.ts),
// so this must stay byte-compatible.
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:pointycastle/export.dart';
const relayHkdfInfo = 'openchamber-relay-v1';
const encryptedFrameVersion = 1;
const _ivPrefixBytes = 4;
const _ivCounterBytes = 8;
const _ivBytes = _ivPrefixBytes + _ivCounterBytes;
const _tagBytes = 16;
const _frameHeaderBytes = 1 + _ivBytes;
const _nonceBytes = 16;
const _sessionKeyBytes = 32;
const _maxPlaintextBytes = 64 * 1024;
class RelayCryptoError implements Exception {
final String message;
const RelayCryptoError(this.message);
@override
String toString() => message;
}
ECDomainParameters get _p256 => ECCurve_prime256v1();
class RelayKeyPair {
final ECPrivateKey privateKey;
final ECPublicKey publicKey;
RelayKeyPair(this.privateKey, this.publicKey);
}
final Random _secureRandom = Random.secure();
Uint8List randomBytes(int length) =>
Uint8List.fromList(List<int>.generate(length, (_) => _secureRandom.nextInt(256)));
RelayKeyPair newRelayKeyPair() {
final random = FortunaRandom()
..seed(KeyParameter(randomBytes(32)));
final generator = ECKeyGenerator()
..init(ParametersWithRandom(
ECKeyGeneratorParameters(_p256), random));
final pair = generator.generateKeyPair();
return RelayKeyPair(pair.privateKey, pair.publicKey);
}
/// The four public members only, as the protocol's JWK.
Map<String, String> publicJwk(ECPublicKey key) {
final point = key.Q;
if (point == null || point.isInfinity) {
throw const RelayCryptoError('invalid public key');
}
return {
'kty': 'EC',
'crv': 'P-256',
'x': _base64Url(_bigIntBytes(point.x!.toBigInteger()!, 32)),
'y': _base64Url(_bigIntBytes(point.y!.toBigInteger()!, 32)),
};
}
ECPublicKey importPublicJwk(Map<String, dynamic> jwk) {
if (jwk['kty'] != 'EC' || jwk['crv'] != 'P-256') {
throw const RelayCryptoError('invalid ECDH public key JWK');
}
final x = jwk['x'];
final y = jwk['y'];
if (x is! String || y is! String) {
throw const RelayCryptoError('invalid ECDH public key JWK');
}
try {
final point = _p256.curve.createPoint(
_bytesBigInt(_base64UrlDecode(x)),
_bytesBigInt(_base64UrlDecode(y)),
);
return ECPublicKey(point, _p256);
} catch (_) {
throw const RelayCryptoError('invalid ECDH public key JWK');
}
}
String jwkFingerprint(Map<String, dynamic> jwk) =>
jsonEncode({'crv': jwk['crv'], 'kty': jwk['kty'], 'x': jwk['x'], 'y': jwk['y']});
/// The two 32-byte AES keys. The nonce is the handshake salt; the info string
/// is fixed, so the host derives the same pair.
({Uint8List clientToHost, Uint8List hostToClient}) deriveSessionKeys(
ECPrivateKey ownPrivate, ECPublicKey peer, Uint8List nonce) {
if (nonce.length != _nonceBytes) {
throw const RelayCryptoError('invalid handshake nonce length');
}
final agreement = ECDHBasicAgreement()..init(ownPrivate);
final shared = _bigIntBytes(agreement.calculateAgreement(peer), 32);
final hkdf = HKDFKeyDerivator(SHA256Digest())
..init(HkdfParameters(
shared,
_sessionKeyBytes * 2,
nonce,
Uint8List.fromList(utf8.encode(relayHkdfInfo)),
));
final material = hkdf.process(Uint8List(0));
return (
clientToHost: Uint8List.sublistView(material, 0, _sessionKeyBytes),
hostToClient: Uint8List.sublistView(material, _sessionKeyBytes),
);
}
class RelayEncryptor {
final Uint8List _key;
final Uint8List _prefix;
int _counter = 0;
RelayEncryptor(this._key) : _prefix = randomBytes(_ivPrefixBytes);
Uint8List encrypt(Uint8List plaintext) {
if (plaintext.length > _maxPlaintextBytes) {
throw const RelayCryptoError('plaintext frame exceeds maximum size');
}
_counter += 1;
final iv = Uint8List(_ivBytes)..setAll(0, _prefix);
var counter = _counter;
for (var i = _ivCounterBytes - 1; i >= 0; i--) {
iv[_ivPrefixBytes + i] = counter & 0xff;
counter >>= 8;
}
final cipher = GCMBlockCipher(AESEngine())
..init(true, AEADParameters(KeyParameter(_key), _tagBytes * 8, iv, Uint8List(0)));
final ciphertext = cipher.process(plaintext);
final frame = Uint8List(_frameHeaderBytes + ciphertext.length)
..[0] = encryptedFrameVersion
..setAll(1, iv)
..setAll(_frameHeaderBytes, ciphertext);
return frame;
}
}
class RelayDecryptor {
final Uint8List _key;
int _lastCounter = 0;
RelayDecryptor(this._key);
Uint8List decrypt(Uint8List frame) {
if (frame.length < _frameHeaderBytes + _tagBytes) {
throw const RelayCryptoError('encrypted frame too short');
}
if (frame[0] != encryptedFrameVersion) {
throw const RelayCryptoError('unsupported encrypted frame version');
}
final iv = Uint8List.sublistView(frame, 1, _frameHeaderBytes);
var counter = 0;
for (var i = 0; i < _ivCounterBytes; i++) {
counter = (counter << 8) | iv[_ivPrefixBytes + i];
}
if (counter <= _lastCounter) {
throw const RelayCryptoError('frame counter regression');
}
try {
final cipher = GCMBlockCipher(AESEngine())
..init(false,
AEADParameters(KeyParameter(_key), _tagBytes * 8, iv, Uint8List(0)));
final plaintext =
cipher.process(Uint8List.sublistView(frame, _frameHeaderBytes));
_lastCounter = counter;
return plaintext;
} catch (_) {
throw const RelayCryptoError('frame decryption failed');
}
}
}
Uint8List _bigIntBytes(BigInt value, int length) {
final out = Uint8List(length);
var v = value;
for (var i = length - 1; i >= 0; i--) {
out[i] = (v & BigInt.from(0xff)).toInt();
v >>= 8;
}
return out;
}
BigInt _bytesBigInt(Uint8List bytes) {
var value = BigInt.zero;
for (final b in bytes) {
value = (value << 8) | BigInt.from(b);
}
return value;
}
String _base64Url(Uint8List bytes) =>
base64Url.encode(bytes).replaceAll('=', '');
Uint8List _base64UrlDecode(String value) {
if (!RegExp(r'^[A-Za-z0-9_-]*$').hasMatch(value)) {
throw const RelayCryptoError('invalid base64url input');
}
final padded = value.padRight((value.length + 3) ~/ 4 * 4, '=');
return base64Url.decode(padded);
}
String base64UrlEncodeBytes(Uint8List bytes) => _base64Url(bytes);
Uint8List base64UrlDecodeBytes(String value) => _base64UrlDecode(value);
+110
View File
@@ -0,0 +1,110 @@
// The server as reached through the private relay: every request and socket
// rides the E2EE tunnel started from the pairing link's relay candidate.
import 'dart:async';
import 'dart:convert';
import '../version.dart';
import 'relay_tunnel.dart';
import 'transport.dart';
class RelayTransport implements Transport {
final RelayTunnel _tunnel;
String? _bearer;
String? _urlToken;
DateTime _urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
Future<String>? _minting;
RelayTransport({
required String relayUrl,
required String serverId,
required Map<String, dynamic> hostKey,
String? grant,
String version = appVersion,
}) : _tunnel = RelayTunnel(
relayUrl: relayUrl,
serverId: serverId,
hostKey: hostKey,
grant: grant,
appVersion: version,
);
@override
Future<TransportResponse> send(TransportRequest request) =>
_tunnel.send(request);
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async {
final token = await _mintUrlToken();
final query = [
if (rawQuery != null && rawQuery.isNotEmpty) rawQuery,
if (token.isNotEmpty) 'oc_url_token=${Uri.encodeQueryComponent(token)}',
].join('&');
return _tunnel.openWebSocket(path, rawQuery: query, headers: headers);
}
@override
void setBearerToken(String? token) {
if (_bearer != token) {
_bearer = token;
_urlToken = null;
_urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
}
}
/// WebSocket upgrades cannot carry headers, so the host expects a short-lived
/// URL-scoped token minted over the same tunnel with the bearer.
Future<String> _mintUrlToken() async {
final bearer = _bearer;
if (bearer == null || bearer.isEmpty) return '';
if (_urlToken != null && _urlToken!.isNotEmpty &&
DateTime.now().isBefore(_urlTokenExpiresAt)) {
return _urlToken!;
}
final inFlight = _minting;
if (inFlight != null) return inFlight;
final future = _mint(bearer);
_minting = future;
try {
return await future;
} finally {
_minting = null;
}
}
Future<String> _mint(String bearer) async {
final response = await _tunnel.send(TransportRequest(
method: 'POST',
path: '/auth/url-token',
headers: {'authorization': 'Bearer $bearer', 'accept': 'application/json'},
));
final bytes = await response.body
.fold<List<int>>(<int>[], (all, chunk) => all..addAll(chunk));
if (response.status < 200 || response.status >= 300) {
throw RelayTunnelException('无法获取 WebSocket 令牌(${response.status})');
}
try {
final decoded = jsonDecode(utf8.decode(bytes, allowMalformed: true));
if (decoded is! Map) return '';
final token = decoded['token'];
if (token is! String) return '';
final expiresIn = decoded['expiresIn'];
final expiresAt = decoded['expiresAt'];
final lifetime = expiresIn is num
? Duration(seconds: expiresIn.toInt())
: expiresAt is num && expiresAt > 0
? Duration(milliseconds: expiresAt.toInt())
: const Duration(minutes: 4);
_urlToken = token.trim();
_urlTokenExpiresAt = DateTime.now()
.add(lifetime)
.subtract(const Duration(seconds: 20));
return _urlToken!;
} catch (_) {
return '';
}
}
@override
void close() => _tunnel.close();
}
+631
View File
@@ -0,0 +1,631 @@
// The OpenChamber private relay, client side: one outbound WebSocket to the
// relay, an end-to-end encrypted channel to the host (P-256 ECDH + HKDF +
// AES-256-GCM), and a small mux that carries the app's HTTP/SSE requests and
// WebSockets. The relay only forwards ciphertext; the host key from the
// pairing link is the trust anchor.
//
// Wire-compatible with packages/ui/src/lib/relay/ (protocol v1). Batching,
// downstream flow control and response gzip are not negotiated: the host's
// legacy path sends one plain frame per message and plain bodies.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'relay_crypto.dart';
import 'transport.dart';
const _relayProtocolVersion = 1;
const _tunnelFrameHeaderBytes = 5;
const _tunnelFragmentFlag = 0x80;
const _maxPlaintextFrameBytes = 64 * 1024;
const _maxTunnelPayloadBytes = _maxPlaintextFrameBytes - _tunnelFrameHeaderBytes - 5;
const _connectTimeout = Duration(seconds: 20);
const _handshakeTimeout = Duration(seconds: 30);
const _keepAliveEvery = Duration(seconds: 30);
const _keepAliveDeadAfter = Duration(seconds: 70);
class RelayFrameType {
static const httpRequest = 1;
static const httpBody = 2;
static const httpResponse = 3;
static const streamEnd = 4;
static const streamAbort = 5;
static const wsOpen = 6;
static const wsOpened = 7;
static const wsText = 8;
static const wsBinary = 9;
static const wsClose = 10;
static const ping = 11;
static const pong = 12;
static const deliveryAck = 13;
}
class RelayTunnelException implements Exception {
final String message;
const RelayTunnelException(this.message);
@override
String toString() => message;
}
/// One request over the tunnel. [path] is relative to the server root, [query]
/// the encoded query string (without `?`). The reply's body streams.
class RelayTunnel {
final String relayUrl;
final String serverId;
final Map<String, dynamic> hostKey;
final String? grant;
final String appVersion;
final String platform;
final HttpClient _http = HttpClient()
..connectionTimeout = const Duration(seconds: 20);
_RelayChannel? _channel;
Future<_RelayChannel>? _connecting;
bool _closed = false;
int _failures = 0;
DateTime _retryAfter = DateTime.fromMillisecondsSinceEpoch(0);
RelayTunnel({
required this.relayUrl,
required this.serverId,
required this.hostKey,
this.grant,
this.appVersion = '0.4.4',
this.platform = 'android',
});
Future<TransportResponse> send(TransportRequest request) async {
final channel = await _ensureChannel();
final streamId = channel.nextStreamId();
final body = request.body;
final controller = StreamController<List<int>>();
final response = Completer<TransportResponse>();
var finished = false;
void cleanup() {
channel.streams.remove(streamId);
channel.dropFragments(streamId);
}
void finish({Object? error}) {
if (finished) return;
finished = true;
cleanup();
if (error != null) {
if (!response.isCompleted) {
response.completeError(error);
} else {
controller.addError(error);
controller.close();
}
}
}
void deliveredHead(int status, Map<String, String> headers) {
final noBody = status == 204 || status == 205 || status == 304;
if (noBody) {
finished = true;
cleanup();
controller.close();
}
response.complete(TransportResponse(
status,
headers,
controller.stream,
abort: () {
if (finished) return;
finished = true;
cleanup();
channel.sendJson(RelayFrameType.streamAbort, streamId, {'reason': 'aborted'});
controller.close();
},
));
}
channel.streams[streamId] = _TunnelStream(
onFrame: (type, payload) {
switch (type) {
case RelayFrameType.httpResponse:
if (finished || response.isCompleted) return;
final dynamic decoded;
try {
decoded = jsonDecode(utf8.decode(payload));
} catch (_) {
finish(error: const RelayTunnelException('响应头无效'));
return;
}
if (decoded is! Map) {
finish(error: const RelayTunnelException('响应头无效'));
return;
}
final status = (decoded['status'] as num?)?.toInt() ?? 0;
final rawHeaders = decoded['headers'];
final headers = <String, String>{};
if (rawHeaders is Map) {
for (final entry in rawHeaders.entries) {
if (entry.key is String && entry.value is String) {
headers[(entry.key as String).toLowerCase()] = entry.value as String;
}
}
}
deliveredHead(status, headers);
break;
case RelayFrameType.httpBody:
if (!finished) controller.add(Uint8List.fromList(payload));
break;
case RelayFrameType.streamEnd:
if (finished) return;
finished = true;
cleanup();
controller.close();
break;
case RelayFrameType.streamAbort:
var reason = '传输被中断';
try {
final decoded = jsonDecode(utf8.decode(payload));
if (decoded is Map && decoded['reason'] is String) {
reason = decoded['reason'] as String;
}
} catch (_) {}
finish(error: RelayTunnelException(reason));
break;
}
},
onFail: (error) => finish(error: error),
);
final query = request.rawQuery ??
Uri(queryParameters: request.query.isEmpty ? null : request.query).query;
channel.sendJson(RelayFrameType.httpRequest, streamId, {
'method': request.method,
'path': request.path,
'query': query,
'headers': request.headers,
'hasBody': body != null,
});
if (body != null) {
if (body.isEmpty) {
channel.send(RelayFrameType.httpBody, streamId, Uint8List(0));
} else {
for (var offset = 0; offset < body.length; offset += _maxTunnelPayloadBytes) {
final end = (offset + _maxTunnelPayloadBytes).clamp(0, body.length);
channel.send(RelayFrameType.httpBody, streamId,
Uint8List.fromList(body.sublist(offset, end)));
}
}
}
channel.send(RelayFrameType.streamEnd, streamId, Uint8List(0));
return response.future;
}
/// Opens a server WebSocket over the tunnel. [path] carries no query;
/// [rawQuery] is sent as-is. Outgoing frames are held until the host reports
/// the loopback socket open.
Future<TransportSocket> openWebSocket(
String path, {
String rawQuery = '',
Map<String, String> headers = const {},
}) async {
final channel = await _ensureChannel();
final streamId = channel.nextStreamId();
final socket = _RelaySocket(
channel: channel,
streamId: streamId,
path: path,
query: rawQuery,
);
channel.streams[streamId] = _TunnelStream(
onFrame: socket.onFrame,
onFail: socket.onFail,
);
channel.sendJson(RelayFrameType.wsOpen, streamId, {
'path': path,
'query': rawQuery,
});
return socket;
}
Future<_RelayChannel> _ensureChannel() async {
if (_closed) throw const RelayTunnelException('relay tunnel closed');
final current = _channel;
if (current != null && !current.dead) return current;
final connecting = _connecting;
if (connecting != null) return connecting;
final wait = _retryAfter.difference(DateTime.now());
if (wait > Duration.zero) await Future<void>.delayed(wait);
final future = _connect();
_connecting = future;
try {
final channel = await future;
_channel = channel;
_failures = 0;
return channel;
} catch (error) {
_failures += 1;
final delay = Duration(
milliseconds: (500 * (1 << (_failures.clamp(0, 4)))).clamp(500, 8000));
_retryAfter = DateTime.now().add(delay);
rethrow;
} finally {
_connecting = null;
}
}
Future<_RelayChannel> _connect() async {
final keyPair = newRelayKeyPair();
final nonce = randomBytes(16);
final hello = jsonEncode({
't': 'hello',
'v': _relayProtocolVersion,
'clientPubJwk': publicJwk(keyPair.publicKey),
'nonce': base64UrlEncodeBytes(nonce),
});
final uri = _relayUri();
final WebSocket ws;
try {
ws = await WebSocket.connect(uri.toString(), customClient: _http)
.timeout(_connectTimeout);
} catch (error) {
throw RelayTunnelException('无法连接 Relay:$error');
}
final channel = _RelayChannel(ws);
final ready = Completer<void>();
var finished = false;
Timer? helloTimer;
Timer? deadline;
StreamSubscription<dynamic>? subscription;
void closeWith(Object error) {
if (finished) return;
finished = true;
helloTimer?.cancel();
deadline?.cancel();
channel.dead = true;
channel.failAll(error);
subscription?.cancel();
try {
ws.close();
} catch (_) {}
if (!ready.isCompleted) ready.completeError(error);
_channel = null;
}
void onData(dynamic raw) {
if (finished) return;
if (raw is String) {
if (raw.contains('relay-retire')) {
// The relay asks the peer to close instead of closing its side.
var code = 1011;
try {
final decoded = jsonDecode(raw);
if (decoded is Map) {
final parsed = decoded['code'];
if (parsed is num) code = parsed.toInt();
}
} catch (_) {}
closeWith(RelayTunnelException('relay closed the tunnel ($code)'));
return;
}
if (!ready.isCompleted) {
dynamic decoded;
try {
decoded = jsonDecode(raw);
} catch (_) {
return;
}
if (decoded is Map && decoded['t'] == 'ready') {
try {
final keys = deriveSessionKeys(
keyPair.privateKey, importPublicJwk(hostKey), nonce);
channel.encryptor = RelayEncryptor(keys.clientToHost);
channel.decryptor = RelayDecryptor(keys.hostToClient);
helloTimer?.cancel();
deadline?.cancel();
ready.complete();
} catch (error) {
closeWith(RelayTunnelException('密钥协商失败:$error'));
}
}
return;
}
// After the channel is up the host may repeat `ready` for a retried
// hello; anything else plaintext is a protocol violation.
if (raw.contains('"ready"')) return;
closeWith(const RelayTunnelException('握手后收到明文帧'));
return;
}
if (raw is! List<int>) return;
channel.lastReceived = DateTime.now();
if (!ready.isCompleted) return;
try {
final plaintext = channel.decryptor.decrypt(Uint8List.fromList(raw));
channel.handlePlaintext(plaintext);
} catch (error) {
closeWith(RelayTunnelException('解密失败:$error'));
}
}
subscription = ws.listen(
onData,
onError: (Object error) => closeWith(RelayTunnelException('Relay 连接出错:$error')),
onDone: () {
if (!finished) {
closeWith(RelayTunnelException(
'Relay 连接已关闭(${ws.closeCode ?? '-'} ${ws.closeReason ?? ''})'));
}
},
cancelOnError: true,
);
channel.onClosed = () =>
closeWith(const RelayTunnelException('Relay 连接已关闭'));
void sendHello() {
if (finished) return;
try {
ws.add(hello);
} catch (_) {}
}
sendHello();
helloTimer = Timer.periodic(const Duration(seconds: 1), (_) => sendHello());
deadline = Timer(_handshakeTimeout, () {
closeWith(const RelayTunnelException('Relay 握手超时'));
});
await ready.future;
if (channel.dead) {
throw RelayTunnelException(
'Relay 连接已关闭(${ws.closeCode ?? '-'} ${ws.closeReason ?? ''})');
}
channel.startKeepAlive();
return channel;
}
Uri _relayUri() {
final base = Uri.parse(relayUrl);
final params = <String, String>{
...base.queryParameters,
'v': '$_relayProtocolVersion',
'role': 'client',
'serverId': serverId,
'appId': 'openchamber',
'appVersion': appVersion,
'platform': platform,
};
final relayGrant = grant;
if (relayGrant != null && relayGrant.isNotEmpty) {
params['grant'] = relayGrant;
}
return base.replace(queryParameters: params);
}
void close() {
if (_closed) return;
_closed = true;
final channel = _channel;
_channel = null;
if (channel != null) {
channel.dead = true;
channel.failAll(const RelayTunnelException('relay tunnel closed'));
channel.close();
}
_http.close(force: true);
}
}
class _TunnelStream {
final void Function(int type, Uint8List payload) onFrame;
final void Function(Object error) onFail;
_TunnelStream({required this.onFrame, required this.onFail});
}
class _RelayChannel {
final WebSocket ws;
late final RelayEncryptor encryptor;
late final RelayDecryptor decryptor;
final Map<int, _TunnelStream> streams = {};
final Map<String, BytesBuilder> _fragments = {};
Timer? _keepAlive;
DateTime lastReceived = DateTime.now();
int _nextStreamId = -1;
bool dead = false;
void Function()? onClosed;
_RelayChannel(this.ws);
int nextStreamId() {
_nextStreamId += 2;
return _nextStreamId;
}
void startKeepAlive() {
_keepAlive?.cancel();
_keepAlive = Timer.periodic(_keepAliveEvery, (_) {
if (dead) return;
if (DateTime.now().difference(lastReceived) > _keepAliveDeadAfter) {
dead = true;
_keepAlive?.cancel();
onClosed?.call();
return;
}
send(RelayFrameType.ping, 0, Uint8List(0));
});
}
void send(int type, int streamId, Uint8List payload, {bool more = false}) {
if (dead) return;
final frame = Uint8List(_tunnelFrameHeaderBytes + payload.length);
frame[0] = more ? type | _tunnelFragmentFlag : type;
frame[1] = (streamId >> 24) & 0xff;
frame[2] = (streamId >> 16) & 0xff;
frame[3] = (streamId >> 8) & 0xff;
frame[4] = streamId & 0xff;
frame.setAll(_tunnelFrameHeaderBytes, payload);
try {
ws.add(encryptor.encrypt(frame));
} catch (_) {
dead = true;
onClosed?.call();
}
}
void sendJson(int type, int streamId, Object value) =>
send(type, streamId, Uint8List.fromList(utf8.encode(jsonEncode(value))));
void sendFragmented(int type, int streamId, Uint8List payload) {
if (payload.isEmpty) {
send(type, streamId, Uint8List(0));
return;
}
for (var offset = 0; offset < payload.length; offset += _maxTunnelPayloadBytes) {
final end = (offset + _maxTunnelPayloadBytes).clamp(0, payload.length);
send(type, streamId, Uint8List.sublistView(payload, offset, end),
more: end < payload.length);
}
}
void dropFragments(int streamId) {
_fragments.removeWhere((key, _) => key.startsWith('$streamId:'));
}
void handlePlaintext(Uint8List plaintext) {
if (dead || plaintext.length < _tunnelFrameHeaderBytes) return;
final rawType = plaintext[0];
final more = (rawType & _tunnelFragmentFlag) != 0;
final type = rawType & ~_tunnelFragmentFlag;
final streamId = (plaintext[1] << 24) |
(plaintext[2] << 16) |
(plaintext[3] << 8) |
plaintext[4];
var payload = Uint8List.sublistView(plaintext, _tunnelFrameHeaderBytes);
lastReceived = DateTime.now();
if (type == RelayFrameType.ping) {
send(RelayFrameType.pong, streamId, Uint8List(0));
return;
}
if (type == RelayFrameType.pong) return;
if (type == RelayFrameType.deliveryAck) return;
if (type == RelayFrameType.wsText || type == RelayFrameType.wsBinary) {
if (more || _fragments.containsKey('$streamId:$type')) {
final key = '$streamId:$type';
final builder = _fragments.putIfAbsent(key, BytesBuilder.new);
builder.add(payload);
if (builder.length > 16 * 1024 * 1024) {
dead = true;
onClosed?.call();
return;
}
if (more) return;
payload = builder.takeBytes();
_fragments.remove(key);
}
} else if (more) {
return;
}
final stream = streams[streamId];
if (stream == null) return;
stream.onFrame(type, payload);
}
void failAll(Object error) {
final all = List.of(streams.values);
streams.clear();
for (final stream in all) {
try {
stream.onFail(error);
} catch (_) {}
}
}
void close() {
_keepAlive?.cancel();
try {
ws.close();
} catch (_) {}
}
}
class _RelaySocket implements TransportSocket {
final _RelayChannel channel;
final int streamId;
final String path;
final String query;
final StreamController<List<int>> _messages = StreamController<List<int>>();
final List<Uint8List> _pending = [];
bool _open = false;
bool _closed = false;
_RelaySocket({
required this.channel,
required this.streamId,
required this.path,
required this.query,
});
@override
Stream<List<int>> get messages => _messages.stream;
@override
void add(List<int> data) {
if (_closed) return;
final bytes = Uint8List.fromList(data);
if (!_open) {
_pending.add(bytes);
return;
}
channel.sendFragmented(RelayFrameType.wsBinary, streamId, bytes);
}
void onFrame(int type, Uint8List payload) {
switch (type) {
case RelayFrameType.wsOpened:
if (_open) return;
_open = true;
for (final frame in _pending) {
channel.sendFragmented(RelayFrameType.wsBinary, streamId, frame);
}
_pending.clear();
break;
case RelayFrameType.wsText:
if (!_closed) _messages.add(payload);
break;
case RelayFrameType.wsBinary:
if (!_closed) _messages.add(payload);
break;
case RelayFrameType.wsClose:
_finish();
break;
case RelayFrameType.streamAbort:
_finish(error: const RelayTunnelException('WebSocket 子流被中断'));
break;
}
}
void onFail(Object error) => _finish(error: error);
void _finish({Object? error}) {
if (_closed) return;
_closed = true;
channel.streams.remove(streamId);
channel.dropFragments(streamId);
if (error != null) {
_messages.addError(error);
}
_messages.close();
}
@override
Future<void> close([int code = 1000, String reason = '']) async {
if (_closed) return;
// Even before `wsOpened`: the host may be dialing the loopback socket
// already, and this frame tells it to abandon that sub-stream.
channel.sendJson(
RelayFrameType.wsClose, streamId, {'code': code, 'reason': reason});
_finish();
}
}
+300
View File
@@ -0,0 +1,300 @@
// The OpenChamber terminal protocol: HTTP commands (create, resize, restart,
// close) plus one WebSocket per host carrying binary control frames (a 0x01
// tag, then JSON). A socket can attach to several terminals; we attach to one.
import 'dart:async';
import 'dart:convert';
import 'transport.dart';
/// What `POST /api/terminal/create` (and restart) answers.
class TerminalSessionInfo {
final String sessionId;
final int cols;
final int rows;
final String status;
const TerminalSessionInfo({
required this.sessionId,
this.cols = 80,
this.rows = 24,
this.status = 'running',
});
factory TerminalSessionInfo.fromJson(Map<String, dynamic> j) =>
TerminalSessionInfo(
sessionId: j['sessionId'] as String? ?? '',
cols: (j['cols'] as num?)?.toInt() ?? 80,
rows: (j['rows'] as num?)?.toInt() ?? 24,
status: j['status'] as String? ?? 'running',
);
}
/// A terminal the server still holds, from `GET /api/terminal/sessions`.
/// The id outlives this app process, so a restart can attach to the same
/// shell instead of making another one.
class ServerTerminal {
final String sessionId;
final String cwd;
final String status; // running | exited
final int? createdAt;
final String mode; // interactive | command
final String purpose; // terminal | project-action (or empty)
const ServerTerminal({
required this.sessionId,
this.cwd = '',
this.status = 'running',
this.createdAt,
this.mode = 'interactive',
this.purpose = '',
});
/// A terminal a person opened. A project action's command runner is also a
/// PTY, but it is not one of the user's tabs.
bool get interactive => mode != 'command' && purpose != 'project-action';
factory ServerTerminal.fromJson(Map<String, dynamic> j) {
final purposeJson = j['purpose'];
return ServerTerminal(
sessionId: j['sessionId'] as String? ?? '',
cwd: j['cwd'] as String? ?? '',
status: j['status'] as String? ?? 'running',
createdAt: (j['createdAt'] as num?)?.toInt(),
mode: j['mode'] as String? ?? 'interactive',
purpose: purposeJson is Map
? purposeJson['type'] as String? ?? ''
: '',
);
}
}
/// One frame from the server: a snapshot (the authoritative screen), output,
/// an exit notice, or an error.
class TerminalEvent {
final String type; // snapshot | output | restarted | exit | error
final String data; // snapshot history / output text
final int sequence;
final int? cols;
final int? rows;
final String? status;
final int? exitCode;
final int? signal;
final String? code;
final String? message;
final bool fatal;
const TerminalEvent(
this.type, {
this.data = '',
this.sequence = 0,
this.cols,
this.rows,
this.status,
this.exitCode,
this.signal,
this.code,
this.message,
this.fatal = false,
});
}
/// The socket's life, for the status bar.
enum TerminalLinkState { idle, creating, connecting, open, reconnecting, exited, error }
/// One attached terminal. Writes made while the socket is down wait in a
/// buffer; a dropped socket reconnects with backoff and reattaches, which
/// begins with a fresh snapshot.
class TerminalSocket {
final Transport transport;
final Map<String, String> headers;
final String sessionId;
final void Function(TerminalEvent event) onEvent;
final void Function(TerminalLinkState state, {String? detail}) onState;
TransportSocket? _socket;
Timer? _keepAlive;
Timer? _reconnect;
final StringBuffer _pending = StringBuffer();
int _failures = 0;
int _generation = 0;
bool _disposed = false;
bool _opened = false;
TerminalSocket({
required this.transport,
required this.headers,
required this.sessionId,
required this.onEvent,
required this.onState,
});
Future<void> connect() async {
if (_disposed) return;
final generation = ++_generation;
onState(_opened ? TerminalLinkState.reconnecting : TerminalLinkState.connecting);
try {
final socket = await transport.webSocket(
'/api/terminal/ws',
headers: headers,
);
if (_disposed || generation != _generation) {
await socket.close();
return;
}
_socket = socket;
_failures = 0;
socket.messages.listen(
_handle,
onError: (_) => _drop(generation),
onDone: () => _drop(generation),
);
_send({'t': 'hello', 'v': 3});
_send({'t': 'attach', 'v': 3, 's': sessionId});
_opened = true;
_keepAlive?.cancel();
_keepAlive = Timer.periodic(
const Duration(seconds: 45), (_) => _send({'t': 'ping', 'v': 3}));
onState(TerminalLinkState.open);
_flushPending();
} catch (error) {
if (_disposed) return;
onState(TerminalLinkState.error, detail: '$error');
_scheduleReconnect();
}
}
void write(String data) {
if (data.isEmpty) return;
if (_socket == null) {
_pending.write(data);
return;
}
_send({'t': 'write', 'v': 3, 's': sessionId, 'd': data});
}
Future<void> dispose() async {
_disposed = true;
_generation++;
_reconnect?.cancel();
_keepAlive?.cancel();
final socket = _socket;
_socket = null;
// Detaching leaves the session running on the server; closing the socket
// is enough for a panel that is going away.
try {
await socket?.close();
} catch (_) {}
}
// ------------------------------------------------------------- internals
void _send(Map<String, Object?> message) {
final socket = _socket;
if (socket == null) return;
final bytes = <int>[1, ...utf8.encode(jsonEncode(message))];
try {
socket.add(bytes);
} catch (_) {
_drop(_generation);
}
}
void _flushPending() {
if (_pending.isEmpty) return;
final data = _pending.toString();
_pending.clear();
write(data);
}
void _drop(int generation) {
if (_disposed || generation != _generation) return;
_generation++;
_keepAlive?.cancel();
_keepAlive = null;
final socket = _socket;
_socket = null;
try {
socket?.close();
} catch (_) {}
onState(TerminalLinkState.reconnecting);
_scheduleReconnect();
}
void _scheduleReconnect() {
if (_disposed || _reconnect != null) return;
_failures += 1;
final delay = Duration(
milliseconds: 500 * (1 << (_failures - 1).clamp(0, 4)));
_reconnect = Timer(delay, () {
_reconnect = null;
if (!_disposed) connect();
});
}
void _handle(dynamic raw) {
if (_disposed || raw is! List<int> || raw.isEmpty) return;
final Map<String, dynamic> message;
try {
final tag = raw.first;
final bytes = tag == 1 ? raw.sublist(1) : raw;
final decoded = jsonDecode(utf8.decode(bytes));
if (decoded is! Map<String, dynamic>) return;
message = decoded;
} catch (_) {
return;
}
final type = message['t'] as String? ?? '';
final sequence = (message['q'] as num?)?.toInt() ?? 0;
switch (type) {
case 'snapshot':
onEvent(TerminalEvent(
'snapshot',
data: message['history'] as String? ?? '',
sequence: sequence,
cols: (message['cols'] as num?)?.toInt(),
rows: (message['rows'] as num?)?.toInt(),
status: message['status'] as String?,
exitCode: (message['exitCode'] as num?)?.toInt(),
signal: (message['signal'] as num?)?.toInt(),
));
break;
case 'output':
// `r` is the replay-safe text (terminal queries removed); `d` the raw
// bytes. Replay text is what the official client renders.
onEvent(TerminalEvent(
'output',
data: (message['r'] ?? message['d'] ?? '') as String,
sequence: sequence,
));
break;
case 'restarted':
onEvent(TerminalEvent(
'restarted',
data: message['history'] as String? ?? '',
sequence: sequence,
));
break;
case 'exit':
onState(TerminalLinkState.exited,
detail: '${(message['exitCode'] as num?)?.toInt() ?? ''}');
onEvent(TerminalEvent(
'exit',
sequence: sequence,
exitCode: (message['exitCode'] as num?)?.toInt(),
signal: (message['signal'] as num?)?.toInt(),
));
break;
case 'error':
onEvent(TerminalEvent(
'error',
sequence: sequence,
code: message['code'] as String?,
message: message['message'] as String?,
fatal: message['fatal'] as bool? ?? false,
));
break;
default:
break;
}
}
}
+343
View File
@@ -0,0 +1,343 @@
// How the client reaches the server. Today that is a direct HttpClient with
// the configured proxy and certificate rules; a relay transport can implement
// the same interface over its encrypted tunnel without any caller changing.
import 'dart:async';
import 'dart:io';
import 'package:socks5_proxy/socks_client.dart';
/// One request: a method, a path relative to the server root, its query, the
/// headers already decided by [Client] (auth, directory, accept, …) and an
/// optional complete body.
class TransportRequest {
final String method;
final String path;
final Map<String, String> query;
final Map<String, String> headers;
final List<int>? body;
/// When set, used verbatim as the query string (the event stream repeats
/// `types`, which a Map cannot express).
final String? rawQuery;
const TransportRequest({
required this.method,
required this.path,
this.query = const {},
this.headers = const {},
this.body,
this.rawQuery,
});
}
/// A reply whose head is in hand and whose body still streams (SSE and file
/// downloads rely on that).
class TransportResponse {
final int status;
final Map<String, String> headers;
final Stream<List<int>> body;
/// Drops the connection while the body is still being read (a download the
/// user cancelled); null when the reply already finished.
final void Function()? abort;
const TransportResponse(this.status, this.headers, this.body, {this.abort});
}
/// A binary socket: a direct WebSocket, or one sub-stream of the relay tunnel.
/// The terminal speaks binary control frames, so text frames are not surfaced.
abstract class TransportSocket {
Stream<List<int>> get messages;
void add(List<int> data);
Future<void> close([int code = 1000, String reason = '']);
}
/// The one seam every request goes through.
abstract class Transport {
/// Sends [request], completing when the reply head arrives.
Future<TransportResponse> send(TransportRequest request);
/// Opens a WebSocket on [path] (the terminal stream). Through the same
/// sockets as [send], so proxies and certificates keep working.
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}});
/// The bearer the client authenticates with. A direct transport ignores it;
/// a relay must mint URL-scoped tokens from it for WebSocket upgrades, which
/// cannot carry headers.
void setBearerToken(String? token) {}
/// Releases whatever sockets the transport holds.
void close();
}
/// Lets a caller abandon a download: [cancel] aborts the request and makes the
/// reader stop at its next chunk.
class CancelToken {
bool _cancelled = false;
void Function()? _abort;
bool get isCancelled => _cancelled;
/// Called by the downloader once the request is in flight.
void attach(void Function() abort) {
_abort = abort;
if (_cancelled) abort();
}
void detach() => _abort = null;
void cancel() {
if (_cancelled) return;
_cancelled = true;
_abort?.call();
}
}
/// Thrown by a download the user cancelled.
class DownloadCancelled implements Exception {
const DownloadCancelled();
@override
String toString() => '下载已取消';
}
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
class ProxyConfig {
final String scheme; // http | https | socks5 | socks5h
final String host;
final int port;
final String? username;
final String? password;
ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]);
bool get socks => scheme.startsWith('socks');
}
ProxyConfig? parseProxy(String? raw) {
final s = raw?.trim() ?? '';
if (s.isEmpty) return null;
var normalized = s;
if (!normalized.contains('://')) normalized = 'http://$normalized';
final uri = Uri.tryParse(normalized);
if (uri == null || uri.host.isEmpty) {
throw ArgumentError('代理地址无效:$raw');
}
final scheme = uri.scheme.toLowerCase();
final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h';
final http = scheme == 'http' || scheme == 'https';
if (!socks && !http) {
throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)');
}
String? user;
String? pass;
if (uri.userInfo.isNotEmpty) {
final i = uri.userInfo.indexOf(':');
if (i >= 0) {
user = Uri.decodeComponent(uri.userInfo.substring(0, i));
pass = Uri.decodeComponent(uri.userInfo.substring(i + 1));
} else {
user = Uri.decodeComponent(uri.userInfo);
}
}
final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080);
return ProxyConfig(scheme, uri.host, port, user, pass);
}
/// Direct HTTP: the server's own URL, optionally through an HTTP or SOCKS5
/// proxy, with the self-signed certificate rules.
class DirectTransport implements Transport {
final Uri base;
final bool insecure;
final String? fingerprint;
late final HttpClient _http;
ProxyConfig? _proxyConfig;
InternetAddress? _proxyAddress;
DirectTransport(
this.base, {
String? proxy,
this.insecure = false,
this.fingerprint,
}) {
_http = HttpClient()..connectionTimeout = const Duration(seconds: 20);
_proxyConfig = parseProxy(proxy);
if (_proxyConfig != null && _proxyConfig!.socks) {
// Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy
// package tunnels the socket and hands a Socket back to the client.
_http.connectionFactory = (uri, _, __) async {
final address = await _resolveProxyAddress();
final settings = ProxySettings(address, _proxyConfig!.port,
username: _proxyConfig!.username, password: _proxyConfig!.password);
final tunnel = SocksTCPClient.connect(
[settings],
// A unix-type address carries the host name, so the proxy resolves
// it (socks5h semantics) instead of resolving it here.
InternetAddress(uri.host, type: InternetAddressType.unix),
uri.port,
);
if (uri.scheme == 'https') {
final secure = tunnel.then(
(s) => s.secure(uri.host, onBadCertificate: _badCertificate));
return ConnectionTask.fromSocket(secure, () {});
}
return ConnectionTask.fromSocket(tunnel, () {});
};
} else if (_proxyConfig != null) {
_http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}';
}
_http.badCertificateCallback = (cert, host, port) => _badCertificate(cert);
}
Future<InternetAddress> _resolveProxyAddress() async {
if (_proxyAddress != null) return _proxyAddress!;
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
if (addresses.isEmpty) {
throw const SocketException('无法解析代理主机');
}
return _proxyAddress = addresses.first;
}
/// True for a certificate the app was told to accept: the user trusts any
/// (insecure), or its SHA-256 matches the pinned fingerprint.
bool _badCertificate(X509Certificate cert) {
if (insecure) return true;
final pinned = fingerprint?.replaceAll(':', '').toLowerCase();
if (pinned == null || pinned.isEmpty) return false;
return sha256Hex(cert.der) == pinned;
}
@override
Future<TransportResponse> send(TransportRequest r) async {
final query = r.rawQuery ??
Uri(queryParameters: r.query.isEmpty ? null : r.query).query;
final uri = base.resolve(r.path).replace(query: query.isEmpty ? null : query);
final req = await _http.openUrl(r.method, uri);
// Every header must be set before the body, which finalizes them.
r.headers.forEach(req.headers.set);
if (r.body != null) req.add(r.body!);
final res = await req.close();
final headers = <String, String>{};
res.headers.forEach((name, values) {
headers[name.toLowerCase()] = values.join(', ');
});
return TransportResponse(res.statusCode, headers, res,
abort: req.abort);
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async {
// ws:// is http:// with the upgrade; wss:// checks the same certificates,
// so the configured client is reused as it stands.
final base = this.base.replace(
scheme: this.base.scheme == 'https' ? 'wss' : 'ws');
final query = rawQuery ?? '';
final uri = base.resolve(path).replace(query: query.isEmpty ? null : query);
final socket = await WebSocket.connect(uri.toString(),
headers: headers, customClient: _http);
return _DirectSocket(socket);
}
@override
void setBearerToken(String? token) {}
@override
void close() => _http.close();
}
/// Wraps a direct WebSocket in the transport-agnostic socket shape. The
/// terminal only speaks binary frames; text frames are ignored.
class _DirectSocket implements TransportSocket {
final WebSocket _socket;
_DirectSocket(this._socket);
@override
Stream<List<int>> get messages =>
_socket.where((event) => event is List<int>).cast<List<int>>();
@override
void add(List<int> data) => _socket.add(data);
@override
Future<void> close([int code = 1000, String reason = '']) =>
_socket.close(code, reason);
}
String sha256Hex(List<int> bytes) => _Digest.sha256Hex(bytes);
// Minimal SHA-256, so the client has no native dependencies for pinning.
class _Digest {
static String sha256Hex(List<int> bytes) {
final h = List<int>.from(const [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
const k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
final m = List<int>.from(bytes);
final bitLen = m.length * 8;
m.add(0x80);
while (m.length % 64 != 56) {
m.add(0);
}
for (var i = 7; i >= 0; i--) {
m.add((bitLen >> (8 * i)) & 0xff);
}
final words = List<int>.generate(m.length ~/ 4, (i) =>
(m[i * 4] << 24) | (m[i * 4 + 1] << 16) | (m[i * 4 + 2] << 8) | m[i * 4 + 3]);
var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
for (var i = 0; i < words.length; i += 16) {
final w = List<int>.filled(64, 0);
for (var j = 0; j < 16; j++) {
w[j] = words[i + j];
}
for (var j = 16; j < 64; j++) {
final s0 = _rotr(w[j - 15], 7) ^ _rotr(w[j - 15], 18) ^ (w[j - 15] >> 3);
final s1 = _rotr(w[j - 2], 17) ^ _rotr(w[j - 2], 19) ^ (w[j - 2] >> 10);
w[j] = (w[j - 16] + s0 + w[j - 7] + s1) & 0xffffffff;
}
var ta = a, tb = b, tc = c, td = d, te = e, tf = f, tg = g, th = hh;
for (var j = 0; j < 64; j++) {
final s1 = _rotr(te, 6) ^ _rotr(te, 11) ^ _rotr(te, 25);
final ch = (te & tf) ^ ((~te) & tg);
final t1 = (th + s1 + ch + k[j] + w[j]) & 0xffffffff;
final s0 = _rotr(ta, 2) ^ _rotr(ta, 13) ^ _rotr(ta, 22);
final maj = (ta & tb) ^ (ta & tc) ^ (tb & tc);
final t2 = (s0 + maj) & 0xffffffff;
th = tg;
tg = tf;
tf = te;
te = (td + t1) & 0xffffffff;
td = tc;
tc = tb;
tb = ta;
ta = (t1 + t2) & 0xffffffff;
}
a = (a + ta) & 0xffffffff;
b = (b + tb) & 0xffffffff;
c = (c + tc) & 0xffffffff;
d = (d + td) & 0xffffffff;
e = (e + te) & 0xffffffff;
f = (f + tf) & 0xffffffff;
g = (g + tg) & 0xffffffff;
hh = (hh + th) & 0xffffffff;
}
final out = List<int>.filled(32, 0);
final vals = [a, b, c, d, e, f, g, hh];
for (var i = 0; i < 8; i++) {
out[i * 4] = (vals[i] >> 24) & 0xff;
out[i * 4 + 1] = (vals[i] >> 16) & 0xff;
out[i * 4 + 2] = (vals[i] >> 8) & 0xff;
out[i * 4 + 3] = vals[i] & 0xff;
}
return out.map((e) => e.toRadixString(16).padLeft(2, '0')).join();
}
static int _rotr(int x, int n) => (x >> n) | ((x << (32 - n)) & 0xffffffff);
}
+69
View File
@@ -0,0 +1,69 @@
// Appearance preferences: theme mode and seed colour. Device-local — the
// phone draws its own Material theme, so none of this is sent to the server.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AppearancePrefs extends ChangeNotifier {
AppearancePrefs._();
static final AppearancePrefs instance = AppearancePrefs._();
static const _modeKey = 'appearance.themeMode.v1';
static const _seedKey = 'appearance.seedColor.v1';
/// The first-party client's colour; a fresh install starts here.
static const defaultSeed = 0xFF6C5CE7;
ThemeMode _themeMode = ThemeMode.system;
int _seed = defaultSeed;
bool _loaded = false;
ThemeMode get themeMode => _themeMode;
Color get seedColor => Color(_seed);
Future<void> ensureLoaded() async {
if (_loaded) return;
_loaded = true;
try {
final prefs = await SharedPreferences.getInstance();
_themeMode = switch (prefs.getString(_modeKey)) {
'light' => ThemeMode.light,
'dark' => ThemeMode.dark,
_ => ThemeMode.system,
};
_seed = prefs.getInt(_seedKey) ?? defaultSeed;
notifyListeners();
} catch (_) {}
}
Future<void> setThemeMode(ThemeMode mode) async {
if (mode == _themeMode) return;
_themeMode = mode;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_modeKey, mode.name);
} catch (_) {}
}
Future<void> setSeedColor(int value) async {
if (value == _seed) return;
_seed = value;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(_seedKey, value);
} catch (_) {}
}
}
/// The colours the appearance section offers; the first is the default.
const appearanceSeeds = <int>[
0xFF6C5CE7,
0xFF2F80ED,
0xFF00A884,
0xFF0FA3B1,
0xFFF2994A,
0xFFEB5757,
0xFFE84393,
0xFF6B7280,
];
+11 -5
View File
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'appearance_prefs.dart';
import 'pets/pet_library.dart';
import 'screens/home_screen.dart';
import 'screens/servers_screen.dart';
import 'screens/sessions_screen.dart';
import 'state.dart';
void main() {
@@ -23,6 +25,8 @@ class _OpenChamberAppState extends State<OpenChamberApp>
super.initState();
WidgetsBinding.instance.addObserver(this);
app.init();
AppearancePrefs.instance.ensureLoaded();
PetLibrary.instance.ensureLoaded();
}
@override
@@ -40,24 +44,26 @@ class _OpenChamberAppState extends State<OpenChamberApp>
@override
Widget build(BuildContext context) {
final look = AppearancePrefs.instance;
return ListenableBuilder(
listenable: app,
listenable: Listenable.merge([app, look]),
builder: (context, _) {
final home = app.client == null
? ServersScreen(app: app)
: SessionsScreen(app: app);
: HomeScreen(app: app);
return MaterialApp(
title: 'OpenChamber',
themeMode: look.themeMode,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF6C5CE7),
seedColor: look.seedColor,
brightness: Brightness.light,
),
useMaterial3: true,
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF6C5CE7),
seedColor: look.seedColor,
brightness: Brightness.dark,
),
useMaterial3: true,
+106
View File
@@ -0,0 +1,106 @@
// Model picker preferences: favorites, recently used models, and the effort
// last chosen for each. Device-local; the server has no say in them.
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class ModelPrefs {
ModelPrefs._();
static final ModelPrefs instance = ModelPrefs._();
static const _favoritesKey = 'model.favorites.v1';
static const _recentsKey = 'model.recents.v1';
static const _effortsKey = 'model.efforts.v1';
static const _maxRecents = 6;
final Set<String> favorites = {};
final List<String> recents = [];
final Map<String, String> efforts = {};
bool _loaded = false;
static String keyFor(String providerId, String id) => '$providerId/$id';
Future<void> ensureLoaded() async {
if (_loaded) return;
_loaded = true;
try {
final prefs = await SharedPreferences.getInstance();
favorites
..clear()
..addAll(prefs.getStringList(_favoritesKey) ?? const []);
recents
..clear()
..addAll(prefs.getStringList(_recentsKey) ?? const []);
final raw = prefs.getString(_effortsKey);
if (raw != null && raw.isNotEmpty) {
final decoded = jsonDecode(raw);
if (decoded is Map) {
efforts
..clear()
..addAll({
for (final entry in decoded.entries)
if (entry.value is String)
'${entry.key}': entry.value as String,
});
}
}
} catch (_) {}
}
bool isFavorite(String key) => favorites.contains(key);
Future<void> toggleFavorite(String key) async {
if (!favorites.remove(key)) favorites.add(key);
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(_favoritesKey, favorites.toList());
}
Future<void> rememberModel(String key) async {
recents.remove(key);
recents.insert(0, key);
if (recents.length > _maxRecents) recents.removeRange(_maxRecents, recents.length);
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(_recentsKey, recents);
}
String? effortFor(String key) => efforts[key];
Future<void> rememberEffort(String key, String? variant) async {
if (variant == null || variant.isEmpty) {
efforts.remove(key);
} else {
efforts[key] = variant;
}
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_effortsKey, jsonEncode(efforts));
}
}
/// `200000` reads as `200K`, `1000000` as `1M`.
String formatTokenCount(int tokens) {
if (tokens <= 0) return '';
String trim(String value) =>
value.endsWith('.0') ? value.substring(0, value.length - 2) : value;
if (tokens >= 1000000) {
return '${trim((tokens / 1000000).toStringAsFixed(1))}M';
}
if (tokens >= 1000) {
return '${(tokens / 1000).round()}K';
}
return '$tokens';
}
/// The Chinese label for an effort variant; unknown ids keep their own name.
String effortLabel(String? variant) {
if (variant == null || variant.isEmpty) return '默认';
return switch (variant.toLowerCase()) {
'default' => '默认',
'none' => '无',
'minimal' => '极低',
'low' => '低',
'medium' || 'mid' => '中',
'high' => '高',
'xhigh' || 'max' => '极高',
_ => variant,
};
}
+320
View File
@@ -0,0 +1,320 @@
// Imported pets live on the device: a zip's `pack.json` and sprite sheets are
// unpacked under the app's documents, and only this client reads them. There
// is no built-in pet; nothing shows until the person imports one.
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:archive/archive.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'pet_pack.dart';
class PetImportException implements Exception {
final String message;
const PetImportException(this.message);
@override
String toString() => message;
}
class PetLibrary extends ChangeNotifier {
PetLibrary._();
static final PetLibrary instance = PetLibrary._();
static const _activeKey = 'pet.active.v1';
static const _enabledKey = 'pet.enabled.v1';
static const _sizeKey = 'pet.size.v1';
static const _positionKey = 'pet.x.v1';
/// The canvas width a pet is drawn at; the list offers these.
static const sizes = <double>[40, 52, 64];
PetPack? pack;
bool enabled = false;
double size = 52;
/// Where the pet stands along its edge, 0 = left end, 1 = right end.
double position = 0.5;
String? _packDir;
bool _loaded = false;
// One decoded sheet at a time: a full sheet can be several megabytes, and
// only the current mood is on screen.
String? _imagePath;
ui.Image? _image;
Future<ui.Image?>? _loading;
bool get hasPet => pack != null;
bool get ready => pack != null && enabled;
Future<void> ensureLoaded() async {
if (_loaded) return;
_loaded = true;
try {
final prefs = await SharedPreferences.getInstance();
enabled = prefs.getBool(_enabledKey) ?? false;
size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80);
position = (prefs.getDouble(_positionKey) ?? 0.5).clamp(0.0, 1.0);
final active = prefs.getString(_activeKey);
if (active != null && active.isNotEmpty) {
final root = await _petsRoot();
final dir = Directory('${root.path}/$active');
final manifest = File('${dir.path}/pack.json');
if (await manifest.exists()) {
final json = jsonDecode(await manifest.readAsString());
if (json is Map<String, dynamic>) {
final parsed = PetPack.fromJson(json);
if (parsed.isValid) {
pack = parsed;
_packDir = dir.path;
}
}
}
}
} catch (_) {
// A corrupt or half-written pet must not keep the app from starting.
}
notifyListeners();
}
Future<void> setEnabled(bool value) async {
enabled = value;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_enabledKey, value);
} catch (_) {}
}
Future<void> setSize(double value) async {
size = value.clamp(32, 80);
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_sizeKey, size);
} catch (_) {}
}
Future<void> setPosition(double value) async {
position = value.clamp(0.0, 1.0);
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_positionKey, position);
} catch (_) {}
}
/// Unpacks and activates a pet package. [root] is for tests; the app uses
/// the documents directory.
Future<PetPack> importZip(List<int> bytes, {Directory? root}) async {
if (bytes.isEmpty) throw const PetImportException('文件为空');
if (bytes.length > 40 * 1024 * 1024) {
throw const PetImportException('宠物包不能超过 40MB');
}
final Archive archive;
try {
archive = ZipDecoder().decodeBytes(bytes, verify: true);
} catch (_) {
throw const PetImportException('不是有效的 zip 文件');
}
ArchiveFile? manifest;
for (final file in archive.files) {
if (!file.isFile) continue;
final name = file.name.replaceAll('\\', '/');
if (name == 'pack.json' || name.endsWith('/pack.json')) {
if (manifest == null || name.length < manifest.name.length) {
manifest = file;
}
}
}
if (manifest == null) {
throw const PetImportException('压缩包里没有 pack.json');
}
final manifestName = manifest.name.replaceAll('\\', '/');
final base = manifestName == 'pack.json'
? ''
: manifestName.substring(0, manifestName.length - '/pack.json'.length);
final PetPack parsed;
try {
final text = utf8.decode(_content(manifest));
final json = jsonDecode(text);
if (json is! Map<String, dynamic>) throw const FormatException();
parsed = PetPack.fromJson(json);
} catch (_) {
throw const PetImportException('pack.json 不是有效的宠物包');
}
if (!parsed.isValid) {
throw const PetImportException('pack.json 缺少动画或状态');
}
final id = _safeId(parsed.id.isNotEmpty ? parsed.id : parsed.name);
final rootDir = root ?? await _petsRoot();
await rootDir.create(recursive: true);
final staging = Directory('${rootDir.path}/.$id.importing');
if (await staging.exists()) await staging.delete(recursive: true);
await staging.create(recursive: true);
try {
var extracted = 0;
for (final file in archive.files) {
if (!file.isFile) continue;
final name = file.name.replaceAll('\\', '/');
if (base.isNotEmpty && !name.startsWith('$base/')) continue;
final rel = base.isEmpty ? name : name.substring(base.length + 1);
if (rel.isEmpty || rel.startsWith('/')) continue;
final segments = rel.split('/');
if (segments.any((s) => s.isEmpty || s == '..' || s == '.')) continue;
final content = _content(file);
extracted += content.length;
if (extracted > 60 * 1024 * 1024) {
throw const PetImportException('解压后超过 60MB');
}
final target = File('${staging.path}/$rel');
await target.parent.create(recursive: true);
await target.writeAsBytes(content, flush: true);
}
for (final animation in parsed.animations.values) {
if (animation.sheet.isEmpty) {
throw PetImportException('动画 ${animation.name} 没有精灵图');
}
final sheet = File('${staging.path}/${animation.sheet}');
if (!await sheet.exists()) {
throw PetImportException('缺少精灵图 ${animation.sheet}');
}
}
final destination = Directory('${rootDir.path}/$id');
if (await destination.exists()) await destination.delete(recursive: true);
await staging.rename(destination.path);
_clearImages();
pack = parsed;
_packDir = destination.path;
enabled = true;
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_activeKey, id);
await prefs.setBool(_enabledKey, true);
} catch (_) {}
notifyListeners();
return parsed;
} catch (_) {
if (await staging.exists()) {
try {
await staging.delete(recursive: true);
} catch (_) {}
}
rethrow;
}
}
Future<void> remove() async {
final dir = _packDir;
pack = null;
_packDir = null;
enabled = false;
_clearImages();
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_activeKey);
await prefs.setBool(_enabledKey, false);
} catch (_) {}
if (dir != null) {
try {
await Directory(dir).delete(recursive: true);
} catch (_) {}
}
}
/// The decoded sheet for [animation], held one at a time.
Future<ui.Image?> imageFor(PetAnimation animation) {
final dir = _packDir;
if (dir == null || animation.sheet.isEmpty) return Future.value(null);
final path = '$dir/${animation.sheet}';
if (_imagePath == path) {
if (_image != null) return Future.value(_image);
if (_loading != null) return _loading!;
}
_imagePath = path;
_image?.dispose();
_image = null;
final loading = _decode(path);
_loading = loading;
return loading;
}
Future<ui.Image?> _decode(String path) async {
try {
final bytes = await File(path).readAsBytes();
final codec = await ui.instantiateImageCodec(bytes);
final frame = await codec.getNextFrame();
final image = frame.image;
if (_imagePath != path) {
image.dispose();
return null;
}
_image = image;
return image;
} catch (_) {
return null;
} finally {
if (_imagePath == path) _loading = null;
}
}
void _clearImages() {
_image?.dispose();
_image = null;
_imagePath = null;
_loading = null;
}
static const _appDirChannel = MethodChannel('openchamber/appdir');
Future<Directory> _petsRoot() async {
String? base;
if (Platform.isAndroid) {
// A tiny channel in MainActivity: enough to find the app's files dir
// without the JNI-based path_provider, which this engine cannot load.
try {
base = await _appDirChannel.invokeMethod<String>('documents');
} catch (_) {
// Fall through to the StateError below.
}
} else {
final env = Platform.environment;
final data = env['XDG_DATA_HOME'];
base = data != null && data.isNotEmpty
? '$data/openchamber'
: '${env['HOME'] ?? '.'}/.local/share/openchamber';
}
if (base == null || base.isEmpty) {
throw StateError('no writable directory for pets');
}
final root = Directory('$base/pets');
if (!await root.exists()) await root.create(recursive: true);
return root;
}
static List<int> _content(ArchiveFile file) {
final content = file.content;
return content is List<int> ? content : List<int>.from(content as List);
}
static String _safeId(String raw) {
final id = raw
.toLowerCase()
.replaceAll(RegExp(r'[^a-z0-9._-]+'), '-')
.replaceAll(RegExp(r'^[-._]+|[-._]+$'), '');
return id.isEmpty ? 'pet' : id;
}
}
+213
View File
@@ -0,0 +1,213 @@
// A pet package, in the shape dsh-Go's packs already use: `pack.json` points
// at PNG sprite sheets, each frame cropped from a canvas of a few logical
// pixels, and names the animations for each mood.
import 'dart:ui';
/// One sheet frame in the play order, with how long it stays up.
class PetFrame {
final int index;
final int ms;
const PetFrame(this.index, this.ms);
}
class PetAnimation {
final String name;
final String sheet;
final int frameW;
final int frameH;
final int cols;
final bool loop;
/// Where this animation sits on the pack's logical canvas.
final Rect box;
final List<PetFrame> frames;
const PetAnimation({
required this.name,
required this.sheet,
required this.frameW,
required this.frameH,
required this.cols,
required this.loop,
required this.box,
required this.frames,
});
int get totalMs => frames.fold(0, (sum, f) => sum + f.ms);
factory PetAnimation.fromJson(String name, Map<String, dynamic> j) {
final box = _rect(j['box'], const Rect.fromLTWH(0, 0, 1, 1));
final cols = _int(j['cols'], 1).clamp(1, 4096);
final total = _int(j['ms'], 50 * cols);
final frames = <PetFrame>[];
final raw = j['frames'];
if (raw is List) {
for (final e in raw) {
if (e is! Map) continue;
final ms = _int(e['ms'], 50);
frames.add(PetFrame(_int(e['i'], 0), ms <= 0 ? 50 : ms));
}
}
if (frames.isEmpty) {
final each = (total / cols).round().clamp(16, 2000);
for (var i = 0; i < cols; i++) {
frames.add(PetFrame(i, each));
}
}
return PetAnimation(
name: name,
sheet: j['sheet'] as String? ?? '',
frameW: _int(j['frameW'], (box.width * 5).round()),
frameH: _int(j['frameH'], (box.height * 5).round()),
cols: cols,
loop: j['loop'] != false,
box: box,
frames: frames,
);
}
}
/// What a pack says. Only the parts this client draws are kept; reactions
/// and idle pools are read as far as they can be played.
class PetPack {
final String id;
final String name;
final String author;
final String license;
final String source;
final bool pixelArt;
/// The logical canvas the frames are placed on.
final Size canvas;
/// Where the pet's feet rest on that canvas.
final Offset anchor;
final Rect contentBox;
final Map<String, PetAnimation> animations;
final Map<String, List<String>> states;
/// tapLeft / tapRight / tickle / drag -> animation name.
final Map<String, String> reactions;
const PetPack({
required this.id,
required this.name,
required this.author,
required this.license,
required this.source,
required this.pixelArt,
required this.canvas,
required this.anchor,
required this.contentBox,
required this.animations,
required this.states,
required this.reactions,
});
bool get isValid =>
animations.isNotEmpty && states.values.any((list) => list.any(animations.containsKey));
String? get idleName {
for (final name in states['idle'] ?? const <String>[]) {
if (animations.containsKey(name)) return name;
}
return animations.keys.isEmpty ? null : animations.keys.first;
}
/// The first animation of [state] the pack actually has, then idle.
String? animationForState(String state) {
for (final name in states[state] ?? const <String>[]) {
if (animations.containsKey(name)) return name;
}
return idleName;
}
PetAnimation? animation(String? name) =>
name == null ? null : animations[name];
factory PetPack.fromJson(Map<String, dynamic> j) {
final canvasJson = j['canvas'];
final cw = _double(canvasJson is Map ? canvasJson['w'] : null, 52);
final ch = _double(canvasJson is Map ? canvasJson['h'] : null, cw);
final anchorJson = j['anchor'];
final ax = _double(anchorJson is Map ? anchorJson['x'] : null, cw / 2);
final ay = _double(anchorJson is Map ? anchorJson['baseline'] : null, ch);
final animations = <String, PetAnimation>{};
final rawAnims = j['animations'];
if (rawAnims is Map) {
for (final e in rawAnims.entries) {
final value = e.value;
if (e.key is String && value is Map) {
animations[e.key as String] =
PetAnimation.fromJson(e.key as String, Map<String, dynamic>.from(value));
}
}
}
final states = <String, List<String>>{};
final rawStates = j['states'];
if (rawStates is Map) {
for (final e in rawStates.entries) {
final list = e.value;
if (e.key is String && list is List) {
states[e.key as String] = [
for (final v in list)
if (v is String) v,
];
}
}
}
final reactions = <String, String>{};
final rawReactions = j['reactions'];
if (rawReactions is Map) {
for (final key in const ['tapLeft', 'tapRight', 'tickle', 'drag']) {
final v = rawReactions[key];
if (v is String) {
reactions[key] = v;
} else if (v is Map) {
final file = v['file'];
final files = v['files'];
if (file is String) {
reactions[key] = file;
} else if (files is List && files.isNotEmpty && files.first is String) {
reactions[key] = files.first as String;
}
}
}
}
return PetPack(
id: j['id'] as String? ?? '',
name: j['name'] as String? ?? '',
author: j['author'] as String? ?? '',
license: j['license'] as String? ?? '',
source: j['source'] as String? ?? '',
pixelArt: j['pixelArt'] != false,
canvas: Size(cw, ch),
anchor: Offset(ax, ay),
contentBox: _rect(j['contentBox'], Rect.fromLTWH(0, 0, cw, ch)),
animations: animations,
states: states,
reactions: reactions,
);
}
}
int _int(Object? v, int fallback) =>
v is num ? v.toInt() : (v is String ? int.tryParse(v) ?? fallback : fallback);
double _double(Object? v, double fallback) =>
v is num ? v.toDouble() : (v is String ? double.tryParse(v) ?? fallback : fallback);
Rect _rect(Object? v, Rect fallback) {
if (v is! Map) return fallback;
return Rect.fromLTWH(
_double(v['x'], fallback.left),
_double(v['y'], fallback.top),
_double(v['w'], fallback.width),
_double(v['h'], fallback.height),
);
}
File diff suppressed because it is too large. Load diff
+318 -207
View File
@@ -9,11 +9,14 @@ import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/transport.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
import 'knowledge_panel.dart';
import 'terminal_panel.dart';
Future<void> showFilesPanel(
BuildContext context, AppState app, Session session) {
BuildContext context, AppState app, String directory) {
return showGeneralDialog<void>(
context: context,
barrierDismissible: true,
@@ -29,7 +32,7 @@ Future<void> showFilesPanel(
child: SizedBox(
width: width * 0.92,
height: double.infinity,
child: FilesPanel(app: app, session: session),
child: FilesPanel(app: app, directory: directory),
),
),
);
@@ -44,8 +47,11 @@ Future<void> showFilesPanel(
class FilesPanel extends StatefulWidget {
final AppState app;
final Session session;
const FilesPanel({super.key, required this.app, required this.session});
/// The workspace directory this panel browses. A draft has one before it
/// has a session, so the panel never needs a session.
final String directory;
const FilesPanel({super.key, required this.app, required this.directory});
@override
State<FilesPanel> createState() => _FilesPanelState();
@@ -64,7 +70,7 @@ const _skipDirs = {
};
class _FilesPanelState extends State<FilesPanel> {
String get _root => widget.session.directory;
String get _root => widget.directory;
Client? get _client => widget.app.client;
String _path = '';
@@ -289,16 +295,28 @@ class _FilesPanelState extends State<FilesPanel> {
final client = _client;
final path = _previewPath;
if (client == null || path == null) return;
// A file already in memory needs no progress; the rest stream with one.
var bytes = _previewBytes;
if (bytes == null) {
bytes = await showDialog<Uint8List>(
context: context,
barrierDismissible: false,
builder: (_) => _DownloadDialog(
name: _previewName,
start: (onProgress, cancel) => client.downloadFile(path,
directory: _root, onProgress: onProgress, cancel: cancel),
),
);
}
if (bytes == null || !mounted) return;
try {
final bytes = _previewBytes ??
Uint8List.fromList(await client.rawFile(path, directory: _root));
final uri = await FilePicker.saveFile(
fileName: _previewName,
bytes: bytes,
);
if (uri != null) _toast('已保存');
} catch (e) {
_toast('下载失败:$e');
_toast('保存失败:$e');
}
}
@@ -372,57 +390,198 @@ class _FilesPanelState extends State<FilesPanel> {
Widget build(BuildContext context) {
final theme = Theme.of(context);
return SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
child: Padding(
// The panel is a dialog, so it does not shrink for the keyboard on its
// own: give the IME's height back here, or it covers the terminal's
// key bar and its last lines.
padding:
EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_tabs(theme),
const Divider(height: 1),
Expanded(child: _body(theme)),
],
),
),
);
}
/// The tab row is the panel's title now; the only global action left is
/// closing the panel. Everything else belongs to the tab's own header.
Widget _tabs(ThemeData theme) {
const labels = ['文件', '项目知识', '终端'];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 2, 6),
child: Row(
children: [
_header(theme),
_tabs(theme),
const Divider(height: 1),
Expanded(child: _body(theme)),
Expanded(
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < labels.length; i++)
ButtonSegment(value: i, label: Text(labels[i])),
],
selected: {_tab},
onSelectionChanged: (v) => setState(() => _tab = v.first),
),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭侧栏',
onPressed: () => Navigator.of(context).maybePop(),
),
],
),
);
}
Widget _header(ThemeData theme) {
return Padding(
padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
child: Row(
children: [
if (_previewPath != null)
IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: '返回',
onPressed: () => setState(() => _previewPath = null),
)
else
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
Widget _body(ThemeData theme) {
if (_root.isEmpty) {
return const Center(child: Text('这个会话没有关联目录'));
}
switch (_tab) {
case 1:
return KnowledgePanel(app: widget.app, directory: _root);
case 2:
return TerminalPanel(app: widget.app, directory: _root);
default:
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pathBar(theme),
Expanded(
child: _previewPath != null
? _previewBody(theme)
: _browserBody(theme),
),
],
);
}
}
Widget _browserBody(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
child: Row(
children: [
Expanded(
child: TextField(
controller: _search,
onChanged: (v) => setState(() {
_query = v;
_deepResults = [];
_deepDone = false;
}),
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search, size: 20),
hintText: '搜索当前目录…',
suffixIcon: _query.trim().isEmpty
? null
: IconButton(
icon: const Icon(Icons.travel_explore, size: 20),
tooltip: '搜索子目录',
onPressed: _searching ? null : _deepSearch,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12)),
contentPadding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
),
),
),
],
),
),
if (_searching)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
Text(_previewPath != null ? _previewName : '文件',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600)),
if (_previewPath == null && _root.isNotEmpty)
Text(_rootName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: theme.hintColor)),
const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2)),
const SizedBox(width: 8),
Text('正在搜索子目录…(${_deepResults.length})',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
),
if (_previewPath != null) ...[
Expanded(child: _list(theme)),
],
);
}
/// The tab's own header: where you are, plus what you can do here. The
/// panel's global actions (close) sit in the tab row above.
Widget _pathBar(ThemeData theme) {
final crumbs = _crumbs;
final preview = _previewPath != null;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 0, 4, 4),
child: Row(
children: [
IconButton(
icon: Icon(preview ? Icons.arrow_back : Icons.arrow_upward,
size: 20),
tooltip: preview ? '返回' : '上一级',
onPressed: preview
? () => setState(() => _previewPath = null)
: (_path == _root ? null : _up),
),
Expanded(
child: preview
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_previewName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13.5, fontWeight: FontWeight.w600)),
Text(_previewPath!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11, color: theme.hintColor)),
],
)
: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_crumb(theme, _rootName, () => _load(_root),
last: crumbs.isEmpty),
for (var i = 0; i < crumbs.length; i++) ...[
Text(' / ', style: TextStyle(color: theme.hintColor)),
_crumb(theme, crumbs[i], () => _goToCrumb(i),
last: i == crumbs.length - 1),
],
],
),
),
),
if (preview) ...[
if (_previewText != null)
IconButton(
icon: Icon(_editing ? Icons.visibility_outlined : Icons.edit_outlined),
icon: Icon(_editing
? Icons.visibility_outlined
: Icons.edit_outlined),
tooltip: _editing ? '预览' : '编辑',
onPressed: _saving
? null
: () => setState(() => _editing = !_editing),
onPressed:
_saving ? null : () => setState(() => _editing = !_editing),
),
if (_editing)
IconButton(
@@ -480,167 +639,6 @@ class _FilesPanelState extends State<FilesPanel> {
],
),
],
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭',
onPressed: () => Navigator.of(context).maybePop(),
),
],
),
);
}
Widget _tabs(ThemeData theme) {
const labels = ['文件', '项目知识', '终端'];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < labels.length; i++)
ButtonSegment(value: i, label: Text(labels[i])),
],
selected: {_tab},
onSelectionChanged: (v) => setState(() => _tab = v.first),
),
);
}
Widget _body(ThemeData theme) {
if (_root.isEmpty) {
return const Center(child: Text('这个会话没有关联目录'));
}
switch (_tab) {
case 1:
return _placeholder(theme, Icons.menu_book_outlined, '项目知识',
'笔记、待办与计划会在这里。');
case 2:
return _placeholder(
theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。');
default:
if (_previewPath != null) return _previewBody(theme);
return _browser(theme);
}
}
Widget _placeholder(
ThemeData theme, IconData icon, String title, String note) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 40, color: theme.hintColor),
const SizedBox(height: 12),
Text(title,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 6),
Text(note,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
const SizedBox(height: 10),
Chip(
label: const Text('即将支持'),
visualDensity: VisualDensity.compact,
side: BorderSide(color: theme.dividerColor),
),
],
),
),
);
}
Widget _browser(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pathBar(theme),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
child: Row(
children: [
Expanded(
child: TextField(
controller: _search,
onChanged: (v) => setState(() {
_query = v;
_deepResults = [];
_deepDone = false;
}),
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search, size: 20),
hintText: '搜索当前目录…',
suffixIcon: _query.trim().isEmpty
? null
: IconButton(
icon: const Icon(Icons.travel_explore, size: 20),
tooltip: '搜索子目录',
onPressed: _searching ? null : _deepSearch,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12)),
contentPadding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
),
),
),
],
),
),
if (_searching)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2)),
const SizedBox(width: 8),
Text('正在搜索子目录…(${_deepResults.length})',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
),
Expanded(child: _list(theme)),
],
);
}
Widget _pathBar(ThemeData theme) {
final crumbs = _crumbs;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 0, 8, 4),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_upward, size: 20),
tooltip: '上一级',
onPressed: _path == _root ? null : _up,
),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_crumb(theme, _rootName, () => _load(_root), last: crumbs.isEmpty),
for (var i = 0; i < crumbs.length; i++) ...[
Text(' / ', style: TextStyle(color: theme.hintColor)),
_crumb(theme, crumbs[i], () => _goToCrumb(i),
last: i == crumbs.length - 1),
],
],
),
),
),
],
),
);
@@ -816,6 +814,7 @@ class _FilesPanelState extends State<FilesPanel> {
child: TextField(
controller: _editor,
maxLines: null,
minLines: null,
expands: true,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace', height: 1.4),
textAlignVertical: TextAlignVertical.top,
@@ -935,3 +934,115 @@ class _FilesPanelState extends State<FilesPanel> {
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
}
/// Streams one download and shows its progress; 取消 aborts the request and
/// the dialog closes with no bytes, so nothing is saved.
class _DownloadDialog extends StatefulWidget {
final String name;
final Future<Uint8List> Function(
void Function(int received, int? total) onProgress,
CancelToken cancel) start;
const _DownloadDialog({required this.name, required this.start});
@override
State<_DownloadDialog> createState() => _DownloadDialogState();
}
class _DownloadDialogState extends State<_DownloadDialog> {
final CancelToken _cancel = CancelToken();
int _received = 0;
int? _total;
bool _cancelling = false;
String? _error;
int _lastPaint = 0;
@override
void initState() {
super.initState();
_run();
}
Future<void> _run() async {
try {
final bytes = await widget.start((received, total) {
if (!mounted) return;
// Chunks arrive every few dozen KB; repaint a few times a second at
// most, and always on the last one.
final now = DateTime.now().millisecondsSinceEpoch;
if (total != null && received < total && now - _lastPaint < 80) return;
_lastPaint = now;
setState(() {
_received = received;
_total = total;
});
}, _cancel);
if (mounted) Navigator.of(context).pop(bytes);
} on DownloadCancelled {
if (mounted) Navigator.of(context).pop();
} catch (error) {
if (!mounted) return;
setState(() => _error = error is ApiError ? error.message : '$error');
}
}
String _size(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final total = _total;
final fraction = total != null && total > 0
? (_received / total).clamp(0.0, 1.0)
: null;
return AlertDialog(
title: const Text('正在下载'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13)),
const SizedBox(height: 12),
if (_error == null) ...[
LinearProgressIndicator(value: fraction),
const SizedBox(height: 8),
Text(
total != null
? '${_size(_received)} / ${_size(total)}'
'(${(fraction! * 100).toStringAsFixed(0)}%)'
: '已下载 ${_size(_received)}',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
] else
Text(_error!,
style:
TextStyle(fontSize: 12.5, color: theme.colorScheme.error)),
],
),
actions: [
if (_error == null)
TextButton(
onPressed: _cancelling
? null
: () {
setState(() => _cancelling = true);
_cancel.cancel();
},
child: Text(_cancelling ? '正在取消…' : '取消'),
)
else
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('关闭'),
),
],
);
}
}
+143
View File
@@ -0,0 +1,143 @@
// The connected shell. A phone treats the session list as the left drawer and
// the chat as the screen; a wide layout shows both side by side, which is
// where a tablet or a desktop window lands.
import 'package:flutter/material.dart';
import '../state.dart';
import 'chat_screen.dart';
import 'new_session_screen.dart';
import 'sessions_screen.dart';
class HomeScreen extends StatefulWidget {
final AppState app;
const HomeScreen({super.key, required this.app});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final GlobalKey<ScaffoldState> _scaffold = GlobalKey();
bool _opening = false;
static const _wideBreakpoint = 840.0;
@override
void initState() {
super.initState();
widget.app.addListener(_maybeOpenFirst);
WidgetsBinding.instance.addPostFrameCallback((_) => _maybeOpenFirst());
}
@override
void dispose() {
widget.app.removeListener(_maybeOpenFirst);
super.dispose();
}
/// Like the first-party client, a phone lands in a conversation rather than
/// on an empty pane: open the newest one when nothing is open yet.
void _maybeOpenFirst() {
final app = widget.app;
if (!mounted || _opening) return;
if (app.draftOpen) return;
if (app.chat != null || app.sessions.isEmpty) return;
_opening = true;
app.openChat(app.sessions.first).whenComplete(() => _opening = false);
}
void _closeDrawer() {
_scaffold.currentState?.closeDrawer();
}
@override
Widget build(BuildContext context) {
// Read above the shell's Scaffold: its body has the bottom inset removed.
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
return ListenableBuilder(
listenable: widget.app,
builder: (context, _) {
return LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= _wideBreakpoint;
final app = widget.app;
final chat = app.chat;
final draftOpen = app.draftOpen && app.draft != null;
final content = draftOpen
? NewSessionScreen(
key: const ValueKey('draft'),
app: app,
keyboardInset: keyboardInset,
onOpenSessions: wide
? null
: () => _scaffold.currentState?.openDrawer(),
)
: chat == null
? _empty(wide)
: ChatScreen(
key: ValueKey(chat.session.id),
app: app,
session: chat.session,
keyboardInset: keyboardInset,
onOpenSessions: wide
? null
: () => _scaffold.currentState?.openDrawer(),
);
if (wide) {
return Scaffold(
body: Row(
children: [
SizedBox(
width: 320,
child: SessionListPane(app: widget.app),
),
const VerticalDivider(width: 1),
Expanded(child: content),
],
),
);
}
return Scaffold(
key: _scaffold,
drawer: Drawer(
width: constraints.maxWidth * 0.86 > 380
? 380
: constraints.maxWidth * 0.86,
child: SessionListPane(
app: widget.app,
onOpened: _closeDrawer,
),
),
body: content,
);
},
);
},
);
}
Widget _empty(bool wide) {
final scheme = Theme.of(context).colorScheme;
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.forum_outlined, size: 40, color: scheme.onSurfaceVariant),
const SizedBox(height: 12),
Text('选择一个会话',
style: TextStyle(fontSize: 16, color: scheme.onSurfaceVariant)),
if (!wide) ...[
const SizedBox(height: 12),
FilledButton(
onPressed: () => _scaffold.currentState?.openDrawer(),
child: const Text('打开会话列表'),
),
],
],
),
),
);
}
}
File diff suppressed because it is too large. Load diff
+537
View File
@@ -0,0 +1,537 @@
// The new-session draft. Nothing exists on the server until the first message
// creates the session; this screen only holds the project, the model and what
// has been typed.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/composer_box.dart';
import '../widgets/model_controls.dart';
import '../widgets/pet_sprite.dart';
import '../widgets/slash_palette.dart';
import 'files_panel.dart';
class NewSessionScreen extends StatefulWidget {
final AppState app;
/// Opens the session drawer; null where the list is always on screen.
final VoidCallback? onOpenSessions;
/// The soft keyboard's height, from above the shell's Scaffold.
final double keyboardInset;
const NewSessionScreen({
super.key,
required this.app,
this.onOpenSessions,
this.keyboardInset = 0,
});
@override
State<NewSessionScreen> createState() => _NewSessionScreenState();
}
class _NewSessionScreenState extends State<NewSessionScreen> {
SessionDraft get _draft => widget.app.draft!;
final TextEditingController _text = TextEditingController();
final FocusNode _inputFocus = FocusNode();
List<ComposerAttachment> _attachments = [];
bool _attaching = false;
/// The `/` palette for the draft's directory. It carries commands and
/// skills, not the client-local `compact` that needs an existing session.
List<SlashItem> _slashItems = [];
bool _slashLoading = false;
bool _slashLoaded = false;
int _slashIndex = 0;
String? _slashDismissed;
@override
void initState() {
super.initState();
_text.text = _draft.text;
_text.addListener(_syncText);
_attachments = [];
_draft.attachments = 0;
}
@override
void dispose() {
_text.removeListener(_syncText);
_text.dispose();
_inputFocus.dispose();
super.dispose();
}
void _syncText() {
if (_draft.text == _text.text) return;
widget.app.updateDraftText(_text.text);
}
bool get _canSend =>
_text.text.trim().isNotEmpty || _attachments.isNotEmpty;
List<SlashItem>? _slashMatches() => matchSlashItems(
items: _slashItems,
text: _text.text,
dismissed: _slashDismissed,
);
Future<void> _ensureSlash() async {
if (_slashLoaded || _slashLoading) return;
_slashLoading = true;
if (mounted) setState(() {});
try {
_slashItems = await widget.app.slashItemsFor(_draft.directory,
includeLocal: false);
_slashLoaded = true;
} catch (_) {
// An empty palette; a send falls back to a plain prompt.
}
_slashLoading = false;
if (mounted) setState(() {});
}
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
setState(() {
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
});
}
void _dismissSlash() => setState(() => _slashDismissed = _text.text);
/// A row was picked: no-argument commands run at once (creating the session
/// on the spot), the rest complete the name and wait for arguments.
void _pickSlash(SlashItem item) {
HapticFeedback.selectionClick();
final text = _text.text;
final lead = text.length - text.trimLeft().length;
final rest = text.trimLeft();
final match = RegExp(r'\s').firstMatch(rest);
final suffix = match == null ? '' : rest.substring(match.start);
final completes = item.skill || item.takesArgs;
if (!completes) {
final command = '/${item.name}';
_text.value = TextEditingValue(
text: command,
selection: TextSelection.collapsed(offset: command.length),
);
widget.app.updateDraftText(command);
setState(() {});
_send();
return;
}
final prefix = '${text.substring(0, lead)}/${item.name}';
final separator =
suffix.isEmpty || !RegExp(r'^\s').hasMatch(suffix) ? ' ' : '';
final next = '$prefix$separator$suffix';
_text.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: prefix.length + 1),
);
widget.app.updateDraftText(next);
_inputFocus.requestFocus();
setState(() {});
}
Future<void> _send() async {
if (!_canSend || widget.app.sendingDraft) return;
final text = _text.text.trim();
final files = [
for (final a in _attachments) {'uri': a.dataUrl, 'name': a.name}
];
final images = [
for (final a in _attachments)
if (a.isImage && a.path != null) a.path!
];
FocusScope.of(context).unfocus();
await widget.app.sendDraft(text: text, files: files, images: images);
if (!mounted) return;
final draft = widget.app.draft;
if (draft != null) {
// The create failed: the draft is still here, keep what was typed.
_text.text = draft.text;
} else {
HapticFeedback.lightImpact();
}
}
Future<void> _pickFiles() async {
setState(() => _attaching = true);
try {
final picked = await pickComposerAttachments(context);
if (picked.isEmpty) return;
setState(() {
for (final file in picked) {
if (_attachments.length >= 5) break;
_attachments.add(file);
}
_draft.attachments = _attachments.length;
});
widget.app.touch();
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('选择失败:$e')));
}
} finally {
if (mounted) setState(() => _attaching = false);
}
}
void _removeAttachment(int index) {
setState(() {
_attachments.removeAt(index);
_draft.attachments = _attachments.length;
});
widget.app.touch();
}
@override
Widget build(BuildContext context) {
final app = widget.app;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return ListenableBuilder(
listenable: app,
builder: (context, _) {
final draft = app.draft;
if (draft == null) return const SizedBox.shrink();
return Scaffold(
appBar: AppBar(
leading: widget.onOpenSessions == null
? null
: IconButton(
icon: const Icon(Icons.menu),
tooltip: '会话',
onPressed: widget.onOpenSessions,
),
title: const Text('新会话'),
actions: [
IconButton(
icon: const Icon(Icons.folder_open_outlined),
tooltip: '文件',
onPressed: () => showFilesPanel(context, app, draft.directory),
),
],
),
body: Column(
children: [
Expanded(
child: Stack(
children: [
Positioned.fill(
child: Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Text(
'我们今天要做什么?',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
),
),
),
const Positioned.fill(child: PetLayer(state: 'idle')),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (draft.error != null)
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Text(
draft.error!,
style: TextStyle(
fontSize: 12.5, color: scheme.error),
),
),
Align(
alignment: Alignment.centerLeft,
child: _projectChip(draft),
),
const SizedBox(height: 4),
if (_attachments.isNotEmpty)
AttachmentTray(
items: _attachments,
onRemove: _removeAttachment,
),
_composer(theme, widget.keyboardInset),
],
),
),
],
),
);
},
);
}
Widget _projectChip(SessionDraft draft) {
final theme = Theme.of(context);
final label = widget.app.projectLabelFor(draft.directory);
return InkWell(
borderRadius: BorderRadius.circular(18),
onTap: _pickProject,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.folder_outlined,
size: 15, color: theme.hintColor),
const SizedBox(width: 5),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 170),
child: Text(
label.isEmpty ? '选择项目' : label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
),
),
Icon(Icons.expand_more, size: 16, color: theme.hintColor),
],
),
),
);
}
Widget _composer(ThemeData theme, double keyboardInset) {
final scheme = theme.colorScheme;
final sending = widget.app.sendingDraft;
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = ComposerBox(
controller: _text,
focusNode: _inputFocus,
hint: '规划、构建或提问',
maxLines: 5,
keyboardInset: keyboardInset,
textInputAction:
slash != null ? TextInputAction.send : TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty
? null
: (_) => _pickSlash(
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
onChanged: (v) {
widget.app.updateDraftText(v);
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) _ensureSlash();
setState(() {});
if (slash != null && v.endsWith('\n')) {
final trimmed = v.trimRight();
_text.value = TextEditingValue(
text: trimmed,
selection: TextSelection.collapsed(offset: trimmed.length),
);
widget.app.updateDraftText(trimmed);
final rows = _slashMatches() ?? const <SlashItem>[];
if (rows.isNotEmpty) {
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
}
}
},
leading: _roundKey(
icon: Icons.attach_file,
label: '添加附件',
onTap: _pickFiles,
busy: _attaching,
),
model: ModelPill(
app: widget.app,
model: _draft.model,
onModel: (m) => widget.app.updateDraftModel(m),
),
mode: ModeChip(
app: widget.app,
agent: _draft.agent,
onAgent: (a) => widget.app.updateDraftModel(null, agent: a),
),
trailing: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: sending || !_canSend ? null : _send,
child: Container(
width: 36,
height: 36,
alignment: Alignment.center,
decoration: BoxDecoration(
color: _canSend || sending ? scheme.primary : scheme.surface,
shape: BoxShape.circle,
),
child: sending
? SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2, color: scheme.onPrimary))
: Icon(Icons.arrow_upward,
size: 20,
color: _canSend ? scheme.onPrimary : theme.hintColor),
),
),
);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('draft-slash-palette'),
child: SlashPalette(
items: slashRows,
index: _slashIndex,
loading: _slashLoading,
onPick: _pickSlash,
),
),
const SizedBox(height: 6),
],
CallbackShortcuts(
bindings: slash == null
? const {}
: {
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSlash(slashRows, 1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSlash(slashRows, -1),
const SingleActivator(LogicalKeyboardKey.enter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.escape):
_dismissSlash,
},
child: body,
),
],
);
}
Widget _roundKey(
{required IconData icon,
required String label,
required VoidCallback onTap,
bool busy = false}) {
final theme = Theme.of(context);
return Tooltip(
message: label,
child: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: busy ? null : onTap,
child: Container(
width: 36,
height: 36,
alignment: Alignment.center,
decoration: BoxDecoration(
color: theme.colorScheme.surface,
shape: BoxShape.circle,
),
child: busy
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: Icon(icon, size: 19, color: theme.hintColor),
),
),
);
}
Future<void> _pickProject() async {
final app = widget.app;
await app.refreshProjects();
if (!mounted) return;
final draft = app.draft;
if (draft == null) return;
final projects = _selectableProjects(app.projects);
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.6,
maxChildSize: 0.9,
builder: (context, controller) => Column(
children: [
const Padding(
padding: EdgeInsets.fromLTRB(16, 14, 16, 6),
child: Text('选择项目',
style:
TextStyle(fontSize: 17, fontWeight: FontWeight.w600)),
),
Expanded(
child: ListView(
controller: controller,
children: [
for (final project in projects)
ListTile(
dense: true,
leading: Icon(
project.vcs.isNotEmpty
? Icons.account_tree_outlined
: Icons.folder_outlined,
size: 20),
title: Text(project.label,
maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(project.canonical,
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: project.canonical == draft.directory
? Icon(Icons.check,
size: 18,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () {
app.updateDraftTarget(project.canonical);
_slashLoaded = false;
_slashItems = [];
Navigator.pop(context);
},
),
if (projects.isEmpty)
const Padding(
padding: EdgeInsets.all(24),
child: Text('没有可用的项目', textAlign: TextAlign.center),
),
],
),
),
],
),
),
);
}
/// The picker shows checkouts, not the server's chat folders (those are
/// reached by just starting a chat, not by choosing a project). The server
/// can list the same path twice (a project record and a sandbox), so one
/// path is one row, preferring the one that knows its VCS.
List<ProjectInfo> _selectableProjects(List<ProjectInfo> projects) {
final byPath = <String, ProjectInfo>{};
for (final project in projects) {
if (project.canonical.isEmpty) continue;
if (project.canonical.contains('/.config/openchamber/')) continue;
final existing = byPath[project.canonical];
if (existing == null ||
(existing.vcs.isEmpty && project.vcs.isNotEmpty)) {
byPath[project.canonical] = project;
}
}
return byPath.values.toList();
}
}
+301
View File
@@ -0,0 +1,301 @@
// Scans the QR code a pairing link is shown as in OpenChamber's "connect a
// device" dialog. The camera stream's Y plane goes to zxing2 in a background
// isolate; only a decoded `openchamber://connect` link ends the scan.
import 'dart:async';
import 'dart:math' as math;
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/qr_scan.dart';
/// Opens the scanner and returns the pairing link, or null when cancelled.
Future<String?> scanPairingQr(BuildContext context) {
return Navigator.of(context).push<String>(MaterialPageRoute(
fullscreenDialog: true,
builder: (_) => const ScanQrScreen(),
));
}
class ScanQrScreen extends StatefulWidget {
const ScanQrScreen({super.key});
@override
State<ScanQrScreen> createState() => _ScanQrScreenState();
}
class _ScanQrScreenState extends State<ScanQrScreen> {
CameraController? _controller;
String? _error;
String? _hint;
bool _decoding = false;
bool _found = false;
bool _torch = false;
Timer? _hintTimer;
@override
void initState() {
super.initState();
_start();
}
@override
void dispose() {
_hintTimer?.cancel();
_closeCamera();
super.dispose();
}
void _closeCamera() {
final controller = _controller;
_controller = null;
if (controller == null) return;
controller.stopImageStream().catchError((_) {});
controller.dispose();
}
Future<void> _start() async {
setState(() {
_error = null;
_found = false;
});
try {
final cameras = await availableCameras();
if (cameras.isEmpty) {
if (mounted) setState(() => _error = '没有可用的相机');
return;
}
CameraDescription pick = cameras.first;
for (final camera in cameras) {
if (camera.lensDirection == CameraLensDirection.back) {
pick = camera;
break;
}
}
final controller = CameraController(
pick,
ResolutionPreset.medium,
enableAudio: false,
imageFormatGroup: ImageFormatGroup.yuv420,
);
await controller.initialize();
if (!mounted) {
await controller.dispose();
return;
}
setState(() => _controller = controller);
await controller.startImageStream(_onFrame);
} on CameraException catch (error) {
if (!mounted) return;
setState(() {
_error = error.code == 'CameraAccessDenied'
? '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。'
: '无法打开相机:${error.description ?? error.code}';
});
} catch (error) {
if (mounted) setState(() => _error = '无法打开相机:$error');
}
}
void _onFrame(CameraImage image) {
if (_decoding || _found || !mounted) return;
final frame = _frameOf(image);
if (frame == null) return;
_decoding = true;
// Decoding off the UI thread: a 480p frame is cheap, but not free, and
// camera frames arrive at 30/s.
compute(decodeQrFrame, frame).then((text) {
_decoding = false;
if (!mounted || text == null || _found) return;
if (text.trim().startsWith('openchamber://connect')) {
_accept(text.trim());
} else {
_showHint('这不是 OpenChamber 配对二维码');
}
}).catchError((_) {
_decoding = false;
});
}
QrFrame? _frameOf(CameraImage image) {
if (image.planes.isEmpty) return null;
final plane = image.planes.first;
final group = image.format.group;
if (group == ImageFormatGroup.bgra8888) {
// The packed BGRA plane is not luminance yet.
final luminance = bgraToLuminance(
plane.bytes, image.width, image.height, plane.bytesPerRow);
return QrFrame(
luminance: luminance,
width: image.width,
height: image.height,
rowStride: image.width,
);
}
return QrFrame(
luminance: plane.bytes,
width: image.width,
height: image.height,
rowStride: plane.bytesPerRow,
);
}
void _showHint(String text) {
_hintTimer?.cancel();
if (mounted) setState(() => _hint = text);
_hintTimer = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _hint = null);
});
}
Future<void> _accept(String text) async {
_found = true;
HapticFeedback.mediumImpact();
try {
await _controller?.stopImageStream();
} catch (_) {}
if (mounted) Navigator.of(context).pop(text);
}
Future<void> _toggleTorch() async {
final controller = _controller;
if (controller == null) return;
try {
await controller.setFlashMode(_torch ? FlashMode.off : FlashMode.torch);
if (mounted) setState(() => _torch = !_torch);
} catch (_) {
if (mounted) _showHint('这个相机不支持手电筒');
}
}
@override
Widget build(BuildContext context) {
final controller = _controller;
final ready = controller != null && controller.value.isInitialized;
return Scaffold(
backgroundColor: Colors.black,
body: Stack(
fit: StackFit.expand,
children: [
if (ready)
Center(child: CameraPreview(controller))
else if (_error != null)
Center(
child: Padding(
padding: const EdgeInsets.all(28),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.no_photography_outlined,
size: 36, color: Colors.white70),
const SizedBox(height: 12),
Text(_error!,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70)),
const SizedBox(height: 16),
FilledButton.tonal(
onPressed: _start,
child: const Text('重试'),
),
],
),
),
)
else
const Center(child: CircularProgressIndicator()),
if (ready) const IgnorePointer(child: CustomPaint(painter: _ScanOverlay())),
SafeArea(
child: Column(
children: [
Row(
children: [
IconButton(
tooltip: '关闭',
icon: const Icon(Icons.close),
color: Colors.white,
onPressed: () => Navigator.of(context).pop(),
),
const Spacer(),
IconButton(
tooltip: '手电筒',
icon: Icon(_torch ? Icons.flash_on : Icons.flash_off),
color: Colors.white,
onPressed: _toggleTorch,
),
],
),
const Spacer(),
Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 32),
child: Column(
children: [
Text(
_hint ?? '把配对二维码放进框内',
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white, fontSize: 14),
),
const SizedBox(height: 6),
const Text(
'在 OpenChamber 网页端打开「连接设备」,选择二维码',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white60, fontSize: 12),
),
],
),
),
],
),
),
],
),
);
}
}
/// Dims everything but the scan square and marks its corners.
class _ScanOverlay extends CustomPainter {
const _ScanOverlay();
@override
void paint(Canvas canvas, Size size) {
final side = math.min(size.width, size.height) * 0.68;
final square = Rect.fromCenter(
center: Offset(size.width / 2, size.height / 2),
width: side,
height: side,
);
final radius = Radius.circular(side * 0.05);
final shade = Path()
..fillType = PathFillType.evenOdd
..addRect(Offset.zero & size)
..addRRect(RRect.fromRectAndRadius(square, radius));
canvas.drawPath(shade, Paint()..color = const Color(0x99000000));
final border = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2
..color = Colors.white.withValues(alpha: 0.85);
canvas.drawRRect(RRect.fromRectAndRadius(square, radius), border);
final corner = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round
..color = const Color(0xFFC6BFFF);
const arm = 28.0;
for (final (dx, dy, sx, sy) in [
(square.left, square.top, 1.0, 1.0),
(square.right, square.top, -1.0, 1.0),
(square.left, square.bottom, 1.0, -1.0),
(square.right, square.bottom, -1.0, -1.0),
]) {
canvas.drawLine(Offset(dx, dy), Offset(dx + arm * sx, dy), corner);
canvas.drawLine(Offset(dx, dy), Offset(dx, dy + arm * sy), corner);
}
}
@override
bool shouldRepaint(_ScanOverlay oldDelegate) => false;
}
+244 -50
View File
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../state.dart';
import '../storage.dart';
import 'scan_qr_screen.dart';
/// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget {
@@ -28,6 +30,9 @@ class _ServersScreenState extends State<ServersScreen> {
String _password = '';
bool _connecting = false;
String? _formError;
// A server may ask for a password only after the first attempt; the field
// is always there, but this one takes the focus when it is what is missing.
final FocusNode _passwordFocus = FocusNode();
@override
void initState() {
@@ -35,6 +40,12 @@ class _ServersScreenState extends State<ServersScreen> {
if (widget.startEditing) _editing = true;
}
@override
void dispose() {
_passwordFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
@@ -81,10 +92,24 @@ class _ServersScreenState extends State<ServersScreen> {
children: [
for (final c in conns) _serverCard(c),
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: () => _startEdit(null),
icon: const Icon(Icons.add),
label: const Text('添加服务器'),
Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () => _startEdit(null),
icon: const Icon(Icons.add),
label: const Text('添加服务器'),
),
),
const SizedBox(width: 8),
Expanded(
child: FilledButton.tonalIcon(
onPressed: _pair,
icon: const Icon(Icons.qr_code_2, size: 18),
label: const Text('配对链接'),
),
),
],
),
],
),
@@ -105,8 +130,9 @@ class _ServersScreenState extends State<ServersScreen> {
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
if (c.proxy.isNotEmpty)
Text(c.isRelay ? '经由 Relay · ${c.serverId}' : c.url,
maxLines: 1, overflow: TextOverflow.ellipsis),
if (!c.isRelay && c.proxy.isNotEmpty)
Text('经由 ${c.proxy}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -159,6 +185,7 @@ class _ServersScreenState extends State<ServersScreen> {
_password = '';
_formError = widget.app.lastError;
});
_focusPasswordIfNeeded(_formError);
widget.app.clearLastError();
} else if (mounted) {
setState(() => _connecting = false);
@@ -206,44 +233,55 @@ class _ServersScreenState extends State<ServersScreen> {
decoration: const InputDecoration(hintText: '如 我的电脑', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('服务器地址'),
TextField(
controller: TextEditingController(text: _url),
onChanged: (v) => _url = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('代理(可选)'),
TextField(
controller: TextEditingController(text: _proxy),
onChanged: (v) => _proxy = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('自签证书指纹(可选)'),
TextField(
controller: TextEditingController(text: _fingerprint),
onChanged: (v) => _fingerprint = v,
decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()),
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('信任自签名证书'),
value: _insecure,
onChanged: (v) => setState(() => _insecure = v),
),
if (!_editNew) ...[
_labelText('密码'),
if (_edit?.isRelay == true) ...[
const ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(Icons.lock_outline, size: 20),
title: Text('通过 Relay 连接'),
subtitle: Text('端到端加密;服务器与设备令牌保持不变'),
),
] else ...[
_labelText('服务器地址'),
TextField(
controller: TextEditingController(text: _url),
onChanged: (v) => _url = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('代理(可选)'),
TextField(
controller: TextEditingController(text: _proxy),
onChanged: (v) => _proxy = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('自签证书指纹(可选)'),
TextField(
controller: TextEditingController(text: _fingerprint),
onChanged: (v) => _fingerprint = v,
decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()),
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('信任自签名证书'),
value: _insecure,
onChanged: (v) => setState(() => _insecure = v),
),
// Shown for new servers too: a password-protected instance rejects
// the first attempt, and this is where the password goes.
_labelText('密码(如果需要)'),
TextField(
controller: TextEditingController(text: _password),
focusNode: _passwordFocus,
onChanged: (v) => _password = v,
obscureText: true,
decoration: const InputDecoration(
hintText: '服务器密码', border: OutlineInputBorder()),
hintText: '服务器密码;服务器未设置可留空',
border: OutlineInputBorder()),
),
],
if (_formError != null)
@@ -275,14 +313,20 @@ class _ServersScreenState extends State<ServersScreen> {
_connecting = true;
_formError = null;
});
final c = Connection(
id: _edit?.id ?? _newId(),
label: _label.isEmpty ? _hostOf(_url) : _label,
url: _url,
proxy: _proxy,
insecure: _insecure,
fingerprint: _fingerprint,
);
final relay = _edit?.isRelay == true ? _edit : null;
final c = relay != null
? relay.copyWith(
label: _label.isEmpty ? relay.label : _label,
lastUsedAt: DateTime.now().millisecondsSinceEpoch,
)
: Connection(
id: _edit?.id ?? Storage.newId(),
label: _label.isEmpty ? _hostOf(_url) : _label,
url: _url,
proxy: _proxy,
insecure: _insecure,
fingerprint: _fingerprint,
);
// Only a connection that works is saved (AppState saves it on success),
// so failed attempts do not pile up in the server list.
await widget.app.connect(c, password: _password);
@@ -296,11 +340,26 @@ class _ServersScreenState extends State<ServersScreen> {
_connecting = false;
_formError = widget.app.lastError;
});
_focusPasswordIfNeeded(_formError);
widget.app.clearLastError();
}
}
}
/// The server asked for a password: put the caret where it is typed.
void _focusPasswordIfNeeded(String? message) {
if (message == null || !message.contains('需要密码')) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _passwordFocus.requestFocus();
});
}
void _pair() {
widget.app.error = null;
widget.app.clearLastError();
showPairingDialog(context, widget.app);
}
void _confirmDelete(Connection c) {
showDialog(
context: context,
@@ -321,9 +380,6 @@ class _ServersScreenState extends State<ServersScreen> {
);
}
static String _newId() =>
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}';
static String _hostOf(String raw) {
try {
return Uri.parse(raw).host;
@@ -332,3 +388,141 @@ class _ServersScreenState extends State<ServersScreen> {
}
}
}
/// Opens the paste-a-pairing-link dialog (also reachable from the connected
/// sidebar's server sheet).
Future<void> showPairingDialog(BuildContext context, AppState app) {
app.error = null;
app.clearLastError();
return showDialog<void>(
context: context,
builder: (_) => _PairingDialog(app: app),
);
}
/// Paste an `openchamber://connect` link and pair. The relay candidate in the
/// link is used when no direct address answers.
class _PairingDialog extends StatefulWidget {
final AppState app;
const _PairingDialog({required this.app});
@override
State<_PairingDialog> createState() => _PairingDialogState();
}
class _PairingDialogState extends State<_PairingDialog> {
final TextEditingController _text = TextEditingController();
bool _busy = false;
String? _error;
@override
void dispose() {
_text.dispose();
super.dispose();
}
Future<void> _scan() async {
final text = await scanPairingQr(context);
if (!mounted || text == null) return;
setState(() => _text.text = text);
// A scan is an explicit "connect these": do not make the person press
// another button after pointing the camera at the code.
await _connect();
}
Future<void> _paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text?.trim() ?? '';
if (text.isEmpty || !mounted) return;
setState(() => _text.text = text);
}
Future<void> _connect() async {
final link = _text.text.trim();
if (link.isEmpty || _busy) return;
setState(() {
_busy = true;
_error = null;
});
final paired = await widget.app.connectWithPairing(link);
if (!mounted) return;
if (paired && widget.app.client != null) {
Navigator.of(context).pop();
return;
}
setState(() {
_busy = false;
_error = widget.app.lastError ?? '配对失败';
});
widget.app.clearLastError();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
title: const Text('配对链接'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'在 OpenChamber 网页端打开「连接设备」,粘贴链接或直接扫描二维码。'
'链接里带一次性密钥,以及直连地址或私有 Relay。',
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
),
const SizedBox(height: 12),
TextField(
controller: _text,
autofocus: true,
minLines: 2,
maxLines: 4,
keyboardType: TextInputType.multiline,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
decoration: const InputDecoration(
hintText: 'openchamber://connect?v=2&p=…',
border: OutlineInputBorder(),
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(_error!,
style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)),
),
Row(
children: [
TextButton.icon(
onPressed: _busy ? null : _scan,
icon: const Icon(Icons.qr_code_scanner, size: 18),
label: const Text('扫码'),
),
const SizedBox(width: 4),
TextButton.icon(
onPressed: _busy ? null : _paste,
icon: const Icon(Icons.content_paste, size: 18),
label: const Text('粘贴'),
),
],
),
],
),
),
actions: [
TextButton(
onPressed: _busy ? null : () => Navigator.of(context).pop(),
child: const Text('取消'),
),
FilledButton(
onPressed: _busy ? null : _connect,
child: _busy
? const SizedBox(
width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('配对并连接'),
),
],
);
}
}
+638 -157
View File
@@ -1,25 +1,35 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import '../api/models.dart';
import '../state.dart';
import 'servers_screen.dart';
import 'chat_screen.dart';
import 'settings_screen.dart';
/// The connected screen: the live session list.
class SessionsScreen extends StatefulWidget {
/// The session list: a drawer on a phone, a persistent column on a wide
/// layout. Sessions are grouped by project, dated within it, and a row swipes
/// to pin, archive or delete.
class SessionListPane extends StatefulWidget {
final AppState app;
const SessionsScreen({super.key, required this.app});
/// Called after a session (or the draft) was opened, so the drawer closes.
final VoidCallback? onOpened;
const SessionListPane({super.key, required this.app, this.onOpened});
@override
State<SessionsScreen> createState() => _SessionsScreenState();
State<SessionListPane> createState() => _SessionListPaneState();
}
class _SessionsScreenState extends State<SessionsScreen> {
class _SessionListPaneState extends State<SessionListPane> {
bool _searchOpen = false;
Timer? _timer;
late final TextEditingController _searchCtrl;
final Set<String> _collapsed = {};
bool _showArchived = false;
@override
void initState() {
@@ -34,57 +44,62 @@ class _SessionsScreenState extends State<SessionsScreen> {
super.dispose();
}
AppState get _app => widget.app;
void _onSearchChanged(String v) {
_timer?.cancel();
_timer = Timer(const Duration(milliseconds: 350), () {
if (v.isEmpty) {
widget.app.refreshSessions();
_app.refreshSessions();
} else {
widget.app.searchSessions(v);
_app.searchSessions(v);
}
});
}
@override
Widget build(BuildContext context) {
final app = widget.app;
return ListenableBuilder(
listenable: app,
listenable: _app,
builder: (context, _) {
return Scaffold(
appBar: AppBar(
title: const Text('会话'),
leading: IconButton(
icon: const Icon(Icons.dns_outlined),
tooltip: '服务器',
onPressed: _instancesSheet,
),
actions: [
IconButton(
icon: Icon(_searchOpen ? Icons.close : Icons.search),
tooltip: '搜索',
onPressed: () {
setState(() {
_searchOpen = !_searchOpen;
if (!_searchOpen) {
_searchCtrl.clear();
app.refreshSessions();
}
});
},
),
IconButton(
icon: const Icon(Icons.add),
tooltip: '新建会话',
onPressed: _newSessionSheet,
),
],
),
body: Column(
final scheme = Theme.of(context).colorScheme;
return SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(4, 6, 4, 0),
child: Row(
children: [
const SizedBox(width: 12),
const Expanded(
child: Text('会话',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w600)),
),
IconButton(
icon: Icon(_searchOpen ? Icons.close : Icons.search),
tooltip: '搜索',
onPressed: () {
setState(() {
_searchOpen = !_searchOpen;
if (!_searchOpen) {
_searchCtrl.clear();
_app.refreshSessions();
}
});
},
),
IconButton(
icon: const Icon(Icons.add),
tooltip: '新会话',
onPressed: () => _newSession(),
),
],
),
),
if (_searchOpen)
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 4),
padding: const EdgeInsets.fromLTRB(12, 2, 12, 4),
child: TextField(
controller: _searchCtrl,
autofocus: true,
@@ -97,20 +112,24 @@ class _SessionsScreenState extends State<SessionsScreen> {
),
),
),
if (app.error != null)
if (_app.error != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
Expanded(
child: Text(app.error!,
style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 13)),
child: Text(_app.error!,
style: TextStyle(
color: scheme.error, fontSize: 13)),
),
TextButton(onPressed: app.refreshSessions, child: const Text('重试')),
TextButton(
onPressed: _app.refreshSessions,
child: const Text('重试')),
],
),
),
Expanded(child: _body()),
Expanded(child: _body(scheme)),
_serverFooter(scheme),
],
),
);
@@ -118,90 +137,563 @@ class _SessionsScreenState extends State<SessionsScreen> {
);
}
Widget _body() {
final app = widget.app;
/// The bottom bar: the connected server on the left (tap to switch), the
/// settings key on the right, as the first-party phone sidebar has it.
Widget _serverFooter(ColorScheme scheme) {
return DecoratedBox(
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: scheme.outlineVariant.withValues(alpha: 0.6)),
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 4, 4),
child: Row(
children: [
Expanded(
child: InkWell(
borderRadius: BorderRadius.circular(10),
onTap: _instancesSheet,
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
child: Row(
children: [
Icon(Icons.dns_outlined,
size: 18, color: scheme.onSurfaceVariant),
const SizedBox(width: 8),
Expanded(
child: Text(
_app.connectionName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: scheme.onSurfaceVariant,
),
),
),
],
),
),
),
),
IconButton(
icon: const Icon(Icons.settings_outlined),
tooltip: '设置',
onPressed: _openSettings,
),
],
),
),
);
}
void _openSettings() {
// A phone's list is a drawer: close it before the settings page covers
// the shell.
widget.onOpened?.call();
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => SettingsScreen(app: _app),
));
}
Widget _body(ColorScheme scheme) {
final app = _app;
if (app.sessionsLoading && app.sessions.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (app.sessions.isEmpty) {
final draft = app.draft;
final topLevel = [
for (final s in app.sessions)
if (!s.isChild) s
];
final pinned = [
for (final s in topLevel)
if (s.isPinned) s
]..sort((a, b) => b.pinnedAt.compareTo(a.pinnedAt));
final unpinned = [
for (final s in topLevel)
if (!s.isPinned) s
];
if (topLevel.isEmpty && draft == null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('暂无会话'),
Text(_searchCtrl.text.isEmpty ? '暂无会话' : '没有匹配的会话'),
const SizedBox(height: 8),
FilledButton(onPressed: _newSessionSheet, child: const Text('新建会话')),
FilledButton(
onPressed: () => _newSession(), child: const Text('新会话')),
],
),
);
}
return RefreshIndicator(
onRefresh: app.refreshSessions,
child: ListView.builder(
itemCount: app.sessions.length,
itemBuilder: (context, i) {
final s = app.sessions[i];
final running = app.active.contains(s.id);
return ListTile(
title: Text(s.title.isEmpty ? '(无标题会话)' : s.title,
maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(_subtitle(s),
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (running)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Icon(Icons.circle, size: 10, color: Theme.of(context).colorScheme.primary),
),
PopupMenuButton<String>(
onSelected: (v) => _sessionAction(s, v),
itemBuilder: (_) => const [
PopupMenuItem(value: 'rename', child: Text('重命名')),
PopupMenuItem(value: 'archive', child: Text('归档')),
PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
],
onRefresh: () async {
await app.refreshSessions();
if (app.archivedLoaded) await app.refreshArchived();
},
child: ListView(
padding: const EdgeInsets.only(bottom: 16),
children: [
if (draft != null) _draftRow(draft),
if (pinned.isNotEmpty) ..._pinnedSection(pinned),
for (final group in _groups(unpinned)) ..._groupSection(group),
_footer(scheme),
],
),
);
}
// --------------------------------------------------------------- groups
bool _isChatDirectory(String directory) =>
directory.contains('/.config/openchamber/chats');
String _groupLabel(String key) =>
key == '\u0000chats' ? '聊天' : _app.projectLabelFor(key);
List<_SessionGroup> _groups(List<Session> sessions) {
final map = <String, List<Session>>{};
for (final session in sessions) {
// Group on a separator-normalised key so a Windows server's mix of
// `\` and `/` does not split one project into two.
final key = _isChatDirectory(session.directory)
? '\u0000chats'
: slashPath(session.directory);
map.putIfAbsent(key, () => []).add(session);
}
final groups = [
for (final entry in map.entries)
_SessionGroup(
key: entry.key,
label: _groupLabel(entry.value.first.directory),
// The first session's own path: the server knows that spelling.
path: entry.key == '\u0000chats' ? '' : entry.value.first.directory,
sessions: entry.value
..sort((a, b) => b.updated.compareTo(a.updated)),
),
];
groups.sort((a, b) {
final aTime = a.sessions.isEmpty ? 0 : a.sessions.first.updated;
final bTime = b.sessions.isEmpty ? 0 : b.sessions.first.updated;
return bTime.compareTo(aTime);
});
return groups;
}
List<Widget> _groupSection(_SessionGroup group) {
final collapsed = _collapsed.contains(group.key);
return [
_groupHeader(group, collapsed: collapsed),
if (!collapsed)
for (final entry in _dated(group.sessions)) ...[
_caption(entry.key),
for (final session in entry.value) _row(session),
],
];
}
Widget _groupHeader(_SessionGroup group, {required bool collapsed}) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
// A ListTile with a title and a subtitle has the session rows' height and
// trailing slot; only the tinted band and the folder mark it as a project.
return Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 2),
child: Material(
color: scheme.surfaceContainerHighest.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(10),
clipBehavior: Clip.antiAlias,
child: ListTile(
// Compact like a session row: two dense lines in a 56px band.
dense: true,
minTileHeight: 56,
// The band already insets by 8. A Material 3 list tile ends at 24
// (start 16), so 16 here makes the + line up with the session
// rows' ⋮.
contentPadding: const EdgeInsets.only(left: 8, right: 16),
leading: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(collapsed ? Icons.chevron_right : Icons.expand_more,
size: 18, color: scheme.onSurfaceVariant),
const SizedBox(width: 2),
Icon(Icons.folder_outlined, size: 16, color: scheme.primary),
],
),
title: Text(
group.label.isEmpty ? '未命名项目' : group.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.w700,
color: scheme.onSurface,
),
onTap: () {
app.openChat(s);
Navigator.push(
context,
MaterialPageRoute(builder: (_) => ChatScreen(app: app, session: s)),
);
},
);
),
subtitle: group.path.isEmpty
? null
: Text(
group.path,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
// A fixed 48 slot, like the session rows' menu: both keys then sit
// on the same vertical line.
trailing: SizedBox(
width: 48,
height: 48,
child: IconButton(
icon: const Icon(Icons.add, size: 20),
padding: EdgeInsets.zero,
tooltip: '在此项目新会话',
onPressed: () => _newSession(directory: group.path),
),
),
onTap: () => setState(() {
if (collapsed) {
_collapsed.remove(group.key);
} else {
_collapsed.add(group.key);
}
}),
),
),
);
}
Widget _caption(String label) {
return Padding(
padding: const EdgeInsets.fromLTRB(28, 6, 12, 2),
child: Text(label,
style: TextStyle(
fontSize: 11, color: Theme.of(context).hintColor)),
);
}
/// 今天 / 昨天 / 本周早些时候 / 更早, in that order.
List<MapEntry<String, List<Session>>> _dated(List<Session> sessions) {
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final yesterday = today.subtract(const Duration(days: 1));
final weekAgo = today.subtract(const Duration(days: 7));
final buckets = <String, List<Session>>{
'今天': [],
'昨天': [],
'本周早些时候': [],
'更早': [],
};
for (final session in sessions) {
final time = session.updated > 0
? DateTime.fromMillisecondsSinceEpoch(session.updated)
: DateTime.fromMillisecondsSinceEpoch(session.created);
final day = DateTime(time.year, time.month, time.day);
final key = day == today
? '今天'
: day == yesterday
? '昨天'
: day.isAfter(weekAgo)
? '本周早些时候'
: '更早';
buckets[key]!.add(session);
}
return [
for (final entry in buckets.entries)
if (entry.value.isNotEmpty) entry,
];
}
// ----------------------------------------------------------------- rows
List<Widget> _pinnedSection(List<Session> pinned) {
final collapsed = _collapsed.contains('pinned');
return [
InkWell(
onTap: () => setState(() {
if (collapsed) {
_collapsed.remove('pinned');
} else {
_collapsed.add('pinned');
}
}),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 4, 4),
child: Row(
children: [
Icon(Icons.push_pin,
size: 13, color: Theme.of(context).hintColor),
const SizedBox(width: 5),
Expanded(
child: Text('已置顶',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: Theme.of(context).hintColor)),
),
Icon(collapsed ? Icons.chevron_right : Icons.expand_more,
size: 16, color: Theme.of(context).hintColor),
],
),
),
),
if (!collapsed)
for (final session in pinned) _row(session),
];
}
Widget _draftRow(SessionDraft draft) {
final theme = Theme.of(context);
final label = draft.firstLine.isEmpty ? '新会话' : draft.firstLine;
final project = _app.projectLabelFor(draft.directory);
return ListTile(
selected: _app.draftOpen,
leading: Icon(Icons.edit_outlined, size: 18, color: theme.hintColor),
title: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontStyle: FontStyle.italic),
),
subtitle: Text(
project.isEmpty ? '草稿' : '草稿 · $project',
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: IconButton(
icon: const Icon(Icons.close, size: 18),
tooltip: '丢弃草稿',
onPressed: () => _app.discardDraft(),
),
onTap: () {
_app.showDraft();
widget.onOpened?.call();
},
);
}
bool _isActive(Session session) {
if (_app.active.contains(session.id)) return true;
return _app.sessions
.any((s) => s.parentID == session.id && _app.active.contains(s.id));
}
Widget _row(Session session, {bool archived = false}) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final running = _isActive(session);
final selected =
!_app.draftOpen && _app.chat?.session.id == session.id;
return Slidable(
key: ValueKey('${archived ? 'a' : 's'}-${session.id}'),
endActionPane: ActionPane(
motion: const DrawerMotion(),
extentRatio: 0.62,
children: [
if (!archived)
SlidableAction(
onPressed: (_) => _app.togglePin(session),
icon: Icons.push_pin_outlined,
label: session.isPinned ? '取消置顶' : '置顶',
backgroundColor: scheme.secondaryContainer,
foregroundColor: scheme.onSecondaryContainer,
),
SlidableAction(
onPressed: (_) => _archive(session, archived),
icon: archived ? Icons.unarchive_outlined : Icons.archive_outlined,
label: archived ? '取消归档' : '归档',
backgroundColor: scheme.surfaceContainerHighest,
foregroundColor: scheme.onSurface,
),
SlidableAction(
onPressed: (_) => _confirmDelete(session),
icon: Icons.delete_outline,
label: '删除',
backgroundColor: scheme.errorContainer,
foregroundColor: scheme.onErrorContainer,
),
],
),
child: ListTile(
// Compact: both the project band and a session row are 56 high.
dense: true,
minTileHeight: 56,
selected: selected,
selectedTileColor: scheme.primary.withValues(alpha: 0.10),
title: Text(
session.title.isEmpty ? '(无标题会话)' : session.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
),
),
subtitle: Text(_subtitle(session),
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (session.isPinned)
Padding(
padding: const EdgeInsets.only(right: 6),
child: Icon(Icons.push_pin,
size: 13, color: scheme.primary),
),
if (running)
Padding(
padding: const EdgeInsets.only(right: 6),
child: SizedBox(
width: 12,
height: 12,
child: CircularProgressIndicator(
strokeWidth: 1.8, color: scheme.primary),
),
),
_menu(session, archived: archived),
],
),
onTap: () {
_app.openChat(session);
widget.onOpened?.call();
},
),
);
}
Widget _menu(Session session, {required bool archived}) {
// The same 48 slot as the project header's +, so the keys line up.
return SizedBox(
width: 48,
height: 48,
child: PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
case 'rename':
_rename(session);
break;
case 'pin':
_app.togglePin(session);
break;
case 'archive':
_archive(session, archived);
break;
case 'delete':
_confirmDelete(session);
break;
case 'copy':
Clipboard.setData(ClipboardData(text: session.id));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('已复制会话 ID')));
break;
}
},
itemBuilder: (_) => [
if (!archived) ...[
const PopupMenuItem(value: 'rename', child: Text('重命名')),
PopupMenuItem(
value: 'pin',
child: Text(session.isPinned ? '取消置顶' : '置顶')),
],
PopupMenuItem(
value: 'archive',
child: Text(archived ? '取消归档' : '归档')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
const PopupMenuItem(value: 'copy', child: Text('复制会话 ID')),
],
),
);
}
Widget _footer(ColorScheme scheme) {
final app = _app;
final archivedCount =
app.archivedLoaded ? app.archivedSessions.length : null;
return Column(
children: [
if (app.hasMoreSessions)
TextButton(
onPressed: app.loadingMoreSessions ? null : app.loadMoreSessions,
child: app.loadingMoreSessions
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: const Text('载入更多'),
),
TextButton.icon(
icon: Icon(
_showArchived
? Icons.expand_less
: Icons.archive_outlined,
size: 16),
label: Text(
_showArchived
? '隐藏已归档'
: archivedCount == null
? '显示已归档'
: '显示已归档 ($archivedCount)',
style: const TextStyle(fontSize: 12.5),
),
onPressed: app.archivedLoading ? null : _toggleArchived,
),
if (app.archivedLoading)
const Padding(
padding: EdgeInsets.only(bottom: 8),
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2)),
),
if (_showArchived)
for (final session in app.archivedSessions)
_row(session, archived: true),
if (_showArchived &&
app.archivedLoaded &&
app.archivedSessions.isEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text('没有已归档的会话',
style: TextStyle(fontSize: 12, color: scheme.outline)),
),
],
);
}
Future<void> _toggleArchived() async {
if (_showArchived) {
setState(() => _showArchived = false);
return;
}
if (!_app.archivedLoaded) await _app.refreshArchived();
if (mounted) setState(() => _showArchived = true);
}
String _subtitle(Session s) {
final parts = <String>[];
if (s.agent.isNotEmpty) parts.add(s.agent);
if (s.model != null) parts.add(widget.app.modelName(s.model));
if (s.model != null) parts.add(_app.modelName(s.model));
if (s.updated > 0) {
final t = DateTime.fromMillisecondsSinceEpoch(s.updated);
parts.add('${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')} '
parts.add(
'${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')} '
'${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}');
}
return parts.join(' · ');
}
void _sessionAction(Session s, String v) {
switch (v) {
case 'rename':
_rename(s);
break;
case 'archive':
widget.app.client?.updateSession(s.id, archived: true);
break;
case 'delete':
_confirmDelete(s);
break;
}
// -------------------------------------------------------------- actions
void _newSession({String? directory}) {
_app.openDraft(directory: directory ?? _app.chat?.session.directory);
widget.onOpened?.call();
}
Future<void> _archive(Session session, bool archived) async {
await _app.setArchived(session, !archived);
}
void _rename(Session s) {
@@ -212,11 +704,13 @@ class _SessionsScreenState extends State<SessionsScreen> {
title: const Text('重命名'),
content: TextField(controller: ctrl, autofocus: true),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton(
onPressed: () {
Navigator.pop(context);
widget.app.client?.updateSession(s.id, title: ctrl.text);
_app.client?.updateSession(s.id, title: ctrl.text);
},
child: const Text('保存'),
),
@@ -232,13 +726,16 @@ class _SessionsScreenState extends State<SessionsScreen> {
title: const Text('删除会话?'),
content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton(
onPressed: () {
Navigator.pop(context);
widget.app.client?.deleteSession(s.id);
widget.app.sessions.removeWhere((x) => x.id == s.id);
widget.app.touch();
_app.client?.deleteSession(s.id);
_app.sessions.removeWhere((x) => x.id == s.id);
_app.archivedSessions.removeWhere((x) => x.id == s.id);
_app.touch();
},
child: const Text('删除'),
),
@@ -247,51 +744,8 @@ class _SessionsScreenState extends State<SessionsScreen> {
);
}
void _newSessionSheet() {
final ctrl = TextEditingController();
showModalBottomSheet(
context: context,
builder: (context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('新建会话', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
const SizedBox(height: 12),
TextField(
controller: ctrl,
autofocus: true,
decoration: const InputDecoration(hintText: '标题(可选)', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
FilledButton(
onPressed: () async {
Navigator.pop(context);
final s = await widget.app.client?.createSession(
title: ctrl.text, directory: widget.app.directory);
if (s != null) {
widget.app.sessions.insert(0, s);
widget.app.touch();
widget.app.openChat(s);
if (mounted) {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => ChatScreen(app: widget.app, session: s)),
);
}
}
},
child: const Text('创建'),
),
],
),
),
);
}
void _instancesSheet() {
final app = widget.app;
final app = _app;
showModalBottomSheet(
context: context,
builder: (context) => SafeArea(
@@ -300,14 +754,20 @@ class _SessionsScreenState extends State<SessionsScreen> {
children: [
const Padding(
padding: EdgeInsets.all(12),
child: Text('服务器', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
child: Text('服务器',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
for (final c in app.connections) ...[
ListTile(
title: Text(c.label),
subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'),
subtitle: Text(c.isRelay
? '经由 Relay · ${c.serverId}'
: (c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}')),
trailing: app.conn?.id == c.id
? Text('已连接', style: TextStyle(color: Theme.of(context).colorScheme.primary))
? Text('已连接',
style: TextStyle(
color: Theme.of(context).colorScheme.primary))
: null,
onTap: () {
Navigator.pop(context);
@@ -321,11 +781,19 @@ class _SessionsScreenState extends State<SessionsScreen> {
onTap: () {
Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute(
builder: (_) =>
ServersScreen(app: app, startEditing: true),
builder: (_) => ServersScreen(app: app, startEditing: true),
));
},
),
ListTile(
leading: const Icon(Icons.qr_code_2),
title: const Text('配对链接'),
subtitle: const Text('直连地址或 OpenChamber Relay'),
onTap: () {
Navigator.pop(context);
showPairingDialog(context, app);
},
),
if (app.client != null)
ListTile(
leading: const Icon(Icons.link_off),
@@ -342,3 +810,16 @@ class _SessionsScreenState extends State<SessionsScreen> {
);
}
}
class _SessionGroup {
final String key;
final String label;
final String path;
final List<Session> sessions;
const _SessionGroup({
required this.key,
required this.label,
required this.path,
required this.sessions,
});
}
+347
View File
@@ -0,0 +1,347 @@
// Settings. Three groups for now: appearance (device-local theme), chat (the
// server's follow-up behavior) and a pet placeholder.
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../appearance_prefs.dart';
import '../pets/pet_library.dart';
import '../state.dart';
class SettingsScreen extends StatefulWidget {
final AppState app;
const SettingsScreen({super.key, required this.app});
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
@override
void initState() {
super.initState();
// Pick up a change made on another client while this page opens.
widget.app.refreshFollowUpBehavior();
PetLibrary.instance.ensureLoaded();
}
@override
Widget build(BuildContext context) {
final look = AppearancePrefs.instance;
return Scaffold(
appBar: AppBar(title: const Text('设置')),
body: ListenableBuilder(
listenable: Listenable.merge(
[widget.app, look, PetLibrary.instance]),
builder: (context, _) {
final theme = Theme.of(context);
return ListView(
padding: const EdgeInsets.only(top: 4, bottom: 32),
children: [
const _SectionHeader('外观', note: '仅当前设备生效,不同步到服务器'),
_appearance(theme, look),
const _SectionHeader('聊天'),
_chat(theme),
const _SectionHeader('宠物',
note: '默认不提供;宠物包只存放在本机'),
_pet(theme),
],
);
},
),
);
}
// ------------------------------------------------------------- appearance
Widget _appearance(ThemeData theme, AppearancePrefs look) {
const modes = [
(ThemeMode.system, '跟随系统'),
(ThemeMode.light, '浅色'),
(ThemeMode.dark, '深色'),
];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const _Label('主题模式'),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 12),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final (mode, label) in modes)
ChoiceChip(
label: Text(label),
selected: look.themeMode == mode,
onSelected: (_) => look.setThemeMode(mode),
),
],
),
),
const _Label('主题色'),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Wrap(
spacing: 12,
runSpacing: 12,
children: [
for (final seed in appearanceSeeds) _swatch(theme, look, seed),
],
),
),
],
);
}
Widget _swatch(ThemeData theme, AppearancePrefs look, int seed) {
final color = Color(seed);
final selected = look.seedColor.toARGB32() == seed;
return Semantics(
button: true,
selected: selected,
label: '主题色 ${seed.toRadixString(16)}',
child: InkWell(
borderRadius: BorderRadius.circular(22),
onTap: () => look.setSeedColor(seed),
child: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(
color: selected
? theme.colorScheme.onSurface
: theme.colorScheme.outlineVariant,
width: selected ? 2.5 : 1,
),
),
child: selected
? const Icon(Icons.check, size: 20, color: Colors.white)
: null,
),
),
);
}
// ------------------------------------------------------------------- chat
Widget _chat(ThemeData theme) {
final steer = widget.app.followUpBehavior == 'steer';
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const ListTile(
title: Text('追问处理行为'),
subtitle: Text('运行中按发送时,消息默认怎么处理。与网页端设置同步。'),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 6),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: const Text('转向'),
selected: steer,
onSelected: (_) => _setFollowUp('steer'),
),
ChoiceChip(
label: const Text('排队'),
selected: !steer,
onSelected: (_) => _setFollowUp('queue'),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Text(
steer ? '转向:在下一步加入当前回合,工作继续。' : '排队:等当前回合结束后再发送。',
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
),
),
],
);
}
Future<void> _setFollowUp(String value) async {
final ok = await widget.app.setFollowUpBehavior(value);
if (!ok && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(widget.app.lastError ?? '保存失败')),
);
widget.app.clearLastError();
}
}
// -------------------------------------------------------------------- pet
Widget _pet(ThemeData theme) {
final library = PetLibrary.instance;
final pack = library.pack;
if (pack == null) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const ListTile(
title: Text('尚未导入宠物'),
subtitle: Text('默认不提供宠物。导入一个宠物包(.zip)后,它会站在输入框上方。'),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: FilledButton.tonalIcon(
onPressed: _importPet,
icon: const Icon(Icons.file_upload_outlined, size: 18),
label: const Text('导入宠物包'),
),
),
],
);
}
final info = [pack.author, pack.license]
.where((s) => s.trim().isNotEmpty)
.join(' · ');
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
title: Text(pack.name.isEmpty ? pack.id : pack.name),
subtitle: info.isEmpty
? null
: Text(info, maxLines: 2, overflow: TextOverflow.ellipsis),
),
SwitchListTile(
title: const Text('启用宠物'),
subtitle: const Text('站在输入框上方,默认关闭'),
value: library.enabled,
onChanged: (v) => library.setEnabled(v),
),
const _Label('大小'),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Wrap(
spacing: 8,
children: [
for (final (size, label) in const [
(40.0, '小'),
(52.0, '中'),
(64.0, '大'),
])
ChoiceChip(
label: Text(label),
selected: (library.size - size).abs() < 0.5,
onSelected: (_) => library.setSize(size),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 2, 20, 8),
child: Row(
children: [
FilledButton.tonalIcon(
onPressed: _importPet,
icon: const Icon(Icons.swap_horiz, size: 18),
label: const Text('更换宠物包'),
),
const SizedBox(width: 8),
TextButton(
onPressed: _confirmRemovePet,
child: const Text('移除'),
),
],
),
),
],
);
}
Future<void> _importPet() async {
try {
final file = await FilePicker.pickFile(
dialogTitle: '选择宠物包(.zip)',
type: FileType.custom,
allowedExtensions: const ['zip'],
);
if (file == null) return;
final bytes = await file.readAsBytes();
final pack = await PetLibrary.instance.importZip(bytes);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text('已导入 ${pack.name.isEmpty ? pack.id : pack.name}')),
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('导入失败:$e')),
);
}
}
Future<void> _confirmRemovePet() async {
final ok = await showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: const Text('移除宠物?'),
content: const Text('本机保存的宠物包会被删除。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(dialog, true),
child: const Text('移除')),
],
),
);
if (ok == true) await PetLibrary.instance.remove();
}
}
class _SectionHeader extends StatelessWidget {
final String title;
final String? note;
const _SectionHeader(this.title, {this.note});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Padding(
padding: const EdgeInsets.fromLTRB(20, 18, 20, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: theme.colorScheme.primary,
)),
if (note != null)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(note!,
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
),
],
),
);
}
}
class _Label extends StatelessWidget {
final String text;
const _Label(this.text);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(20, 2, 20, 6),
child: Text(text,
style: const TextStyle(fontSize: 13.5, fontWeight: FontWeight.w500)),
);
}
}
+356
View File
@@ -0,0 +1,356 @@
// The terminal tab: xterm renders the PTY, a status bar offers the tab
// dropdown (switch / new), restart and close, and the key bar below sends what
// a phone keyboard cannot (Esc, Tab, Ctrl, arrows, punctuation), the way
// Termux does.
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
import '../api/terminal.dart';
import '../state.dart';
import '../terminal_state.dart';
/// A light palette, so the terminal does not turn into a black hole in the
/// light theme. (xterm ships only dark ones.)
const _lightTheme = TerminalTheme(
cursor: Color(0xFF3A3A3A),
selection: Color(0x553A6EA5),
foreground: Color(0xFF1F1F1F),
background: Color(0xFFFFFFFF),
black: Color(0xFF000000),
red: Color(0xFFCD3131),
green: Color(0xFF0D7A44),
yellow: Color(0xFF7A6200),
blue: Color(0xFF1B5FA6),
magenta: Color(0xFFA626A4),
cyan: Color(0xFF0E7490),
white: Color(0xFFBDBDBD),
brightBlack: Color(0xFF666666),
brightRed: Color(0xFFD73A49),
brightGreen: Color(0xFF1A8A4E),
brightYellow: Color(0xFF8A6D00),
brightBlue: Color(0xFF2E6FBF),
brightMagenta: Color(0xFFB23BB0),
brightCyan: Color(0xFF12859B),
brightWhite: Color(0xFFEEEEEE),
searchHitBackground: Color(0xFFFFF176),
searchHitBackgroundCurrent: Color(0xFFAED581),
searchHitForeground: Color(0xFF000000),
);
class TerminalPanel extends StatefulWidget {
final AppState app;
final String directory;
const TerminalPanel({super.key, required this.app, this.directory = ''});
@override
State<TerminalPanel> createState() => _TerminalPanelState();
}
class _TerminalPanelState extends State<TerminalPanel> {
late final TerminalWorkspace _workspace;
final FocusNode _focus = FocusNode();
/// The dropdown's value for "new terminal"; tab values are their index.
static const _newTab = -1;
@override
void initState() {
super.initState();
_workspace = widget.app.terminalFor(widget.directory);
_workspace.ensureOpen();
}
@override
void dispose() {
_focus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListenableBuilder(
listenable: _workspace,
builder: (context, _) {
final tab = _workspace.activeTab;
if (tab == null) return const SizedBox.shrink();
final state = tab.state;
return ListenableBuilder(
listenable: state,
builder: (context, _) {
return Column(
children: [
_statusBar(theme, tab, state),
Expanded(
child: ColoredBox(
color: theme.brightness == Brightness.dark
? const Color(0xFF1E1E1E)
: Colors.white,
child: TerminalView(
// A fresh view per tab, so scroll position and selection
// do not leak from the one before it.
key: ObjectKey(state),
state.model,
focusNode: _focus,
theme: theme.brightness == Brightness.dark
? TerminalThemes.defaultTheme
: _lightTheme,
textStyle: const TerminalStyle(
fontSize: 13,
height: 1.25,
fontFamily: 'monospace',
),
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
keyboardType: TextInputType.text,
deleteDetection: true,
backgroundOpacity: 1,
),
),
),
_keyBar(theme, state),
],
);
},
);
},
);
}
Widget _statusBar(
ThemeData theme, TerminalTab tab, TerminalSessionState state) {
final scheme = theme.colorScheme;
final (label, color) = switch (state.link) {
TerminalLinkState.idle => ('未启动', theme.hintColor),
TerminalLinkState.creating => ('正在创建…', theme.hintColor),
TerminalLinkState.connecting => ('正在连接…', theme.hintColor),
TerminalLinkState.reconnecting => ('连接中断,正在重连…', scheme.error),
TerminalLinkState.open => ('运行中', scheme.primary),
TerminalLinkState.exited => (state.detail ?? '已退出', theme.hintColor),
TerminalLinkState.error => (state.detail ?? '连接失败', scheme.error),
};
return Row(
children: [
Expanded(
child: PopupMenuButton<int>(
tooltip: '切换终端',
position: PopupMenuPosition.under,
onSelected: _onTabMenu,
itemBuilder: (_) => [
for (var i = 0; i < _workspace.tabs.length; i++)
PopupMenuItem<int>(
value: i,
child: Row(
children: [
Icon(
i == _workspace.activeIndex
? Icons.check
: Icons.terminal_outlined,
size: 18,
color: i == _workspace.activeIndex
? scheme.primary
: theme.hintColor,
),
const SizedBox(width: 10),
Expanded(
child: Text(
_workspace.tabs[i].label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
const PopupMenuDivider(),
const PopupMenuItem<int>(
value: _newTab,
child: Row(
children: [
Icon(Icons.add, size: 18),
SizedBox(width: 10),
Text('新建终端'),
],
),
),
],
child: Container(
height: 40,
padding: const EdgeInsets.fromLTRB(12, 2, 4, 2),
child: Row(
children: [
Icon(Icons.circle, size: 8, color: color),
const SizedBox(width: 6),
Flexible(
child: Text(
tab.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5, fontWeight: FontWeight.w600),
),
),
const SizedBox(width: 4),
Flexible(
child: Text(
'· $label',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: color),
),
),
Icon(Icons.arrow_drop_down, size: 20, color: theme.hintColor),
],
),
),
),
),
IconButton(
tooltip: '键盘',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.keyboard_outlined, size: 18),
onPressed: () => _focus.requestFocus(),
),
IconButton(
tooltip: '重新启动',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.restart_alt, size: 18),
onPressed: state.link == TerminalLinkState.exited ||
state.link == TerminalLinkState.error ||
state.isRunning
? _restart
: null,
),
PopupMenuButton<String>(
tooltip: '更多',
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
case 'clear':
state.model.write('\x1b[2J\x1b[H');
break;
case 'close':
_workspace.closeActive();
break;
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'clear', child: Text('清屏')),
PopupMenuItem(value: 'close', child: Text('关闭此终端')),
],
),
],
);
}
void _onTabMenu(int value) {
if (value == _newTab) {
_workspace.addTab();
} else {
_workspace.select(value);
}
}
Future<void> _restart() async {
final state = _workspace.activeTab?.state;
if (state == null) return;
if (state.link == TerminalLinkState.error) {
// A dead session cannot restart in place; a fresh shell replaces it
// inside the same tab.
await state.closeSession();
await state.ensureOpen();
return;
}
await state.restart();
}
// ------------------------------------------------------------- key bar
/// Two rows of seven, the way Termux lays them out: the keys a phone
/// keyboard cannot produce, all reachable with a thumb.
Widget _keyBar(ThemeData theme, TerminalSessionState state) {
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
border: Border(top: BorderSide(color: theme.dividerColor, width: 0.5)),
),
padding: const EdgeInsets.fromLTRB(3, 3, 3, 3),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_keyRow([
_key('ESC', onTap: () => _sendKey(state, TerminalKey.escape)),
_key('/', onTap: () => _sendText(state, '/')),
_key('—', onTap: () => _sendText(state, '-')),
_key('HOME', onTap: () => _sendKey(state, TerminalKey.home)),
_key('↑',
big: true, onTap: () => _sendKey(state, TerminalKey.arrowUp)),
_key('END', onTap: () => _sendKey(state, TerminalKey.end)),
_key('PGUP', onTap: () => _sendKey(state, TerminalKey.pageUp)),
]),
_keyRow([
_key('TAB', onTap: () => _sendKey(state, TerminalKey.tab)),
_key('CTRL', active: state.ctrl, onTap: state.toggleCtrl),
_key('ALT', active: state.alt, onTap: state.toggleAlt),
_key('←',
big: true,
onTap: () => _sendKey(state, TerminalKey.arrowLeft)),
_key('↓',
big: true,
onTap: () => _sendKey(state, TerminalKey.arrowDown)),
_key('→',
big: true,
onTap: () => _sendKey(state, TerminalKey.arrowRight)),
_key('PGDN', onTap: () => _sendKey(state, TerminalKey.pageDown)),
]),
],
),
);
}
Widget _keyRow(List<Widget> keys) => Padding(
padding: const EdgeInsets.symmetric(vertical: 1.5),
child: Row(
children: [for (final key in keys) Expanded(child: key)],
),
);
/// [big] draws a single glyph (an arrow) larger than a word.
Widget _key(String label,
{bool active = false, bool big = false, required VoidCallback onTap}) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
height: 30,
margin: const EdgeInsets.symmetric(horizontal: 1.5),
alignment: Alignment.center,
decoration: BoxDecoration(
color: active
? scheme.primary.withValues(alpha: 0.22)
: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: active ? scheme.primary : Colors.transparent, width: 1),
),
child: Text(
label,
maxLines: 1,
style: TextStyle(
fontFamily: 'monospace',
fontSize: big ? 16 : 11,
fontWeight: active ? FontWeight.w700 : FontWeight.w500,
color: active ? scheme.primary : scheme.onSurface,
),
),
),
);
}
void _sendKey(TerminalSessionState state, TerminalKey key) => state.model
.keyInput(key, ctrl: state.ctrl, alt: state.alt, shift: state.shift);
void _sendText(TerminalSessionState state, String text) =>
state.model.textInput(text);
}
+841 -60
View File
File diff suppressed because it is too large. Load diff
+124 -2
View File
@@ -15,6 +15,14 @@ class Connection {
final bool insecure;
final String fingerprint;
final int lastUsedAt;
/// Set for a server reached through the private relay. The host's public
/// key (JSON JWK) is the E2EE trust anchor from the pairing link.
final String relayUrl;
final String serverId;
final String hostKey;
final String grant;
Connection({
required this.id,
required this.label,
@@ -23,8 +31,15 @@ class Connection {
this.insecure = false,
this.fingerprint = '',
this.lastUsedAt = 0,
this.relayUrl = '',
this.serverId = '',
this.hostKey = '',
this.grant = '',
});
bool get isRelay =>
relayUrl.isNotEmpty && serverId.isNotEmpty && hostKey.isNotEmpty;
factory Connection.fromJson(Map<String, dynamic> j) => Connection(
id: j['id'] as String? ?? '',
label: j['label'] as String? ?? '',
@@ -33,6 +48,10 @@ class Connection {
insecure: j['insecure'] as bool? ?? false,
fingerprint: j['fingerprint'] as String? ?? '',
lastUsedAt: (j['lastUsedAt'] as num?)?.toInt() ?? 0,
relayUrl: j['relayUrl'] as String? ?? '',
serverId: j['serverId'] as String? ?? '',
hostKey: j['hostKey'] as String? ?? '',
grant: j['grant'] as String? ?? '',
);
Map<String, dynamic> toJson() => {
@@ -43,6 +62,10 @@ class Connection {
'insecure': insecure,
'fingerprint': fingerprint,
'lastUsedAt': lastUsedAt,
if (relayUrl.isNotEmpty) 'relayUrl': relayUrl,
if (serverId.isNotEmpty) 'serverId': serverId,
if (hostKey.isNotEmpty) 'hostKey': hostKey,
if (grant.isNotEmpty) 'grant': grant,
};
Connection copyWith({
@@ -52,6 +75,10 @@ class Connection {
bool? insecure,
String? fingerprint,
int? lastUsedAt,
String? relayUrl,
String? serverId,
String? hostKey,
String? grant,
}) =>
Connection(
id: id,
@@ -61,12 +88,32 @@ class Connection {
insecure: insecure ?? this.insecure,
fingerprint: fingerprint ?? this.fingerprint,
lastUsedAt: lastUsedAt ?? this.lastUsedAt,
relayUrl: relayUrl ?? this.relayUrl,
serverId: serverId ?? this.serverId,
hostKey: hostKey ?? this.hostKey,
grant: grant ?? this.grant,
);
}
/// One remembered terminal tab: the server's session id and the local label.
class SavedTerminalTab {
final String id;
final String label;
const SavedTerminalTab(this.id, this.label);
}
/// The terminal tabs remembered for one directory, with the tab that was
/// showing.
class SavedTerminalTabs {
final List<SavedTerminalTab> tabs;
final String? activeId;
const SavedTerminalTabs(this.tabs, this.activeId);
}
class Storage {
static const _connsKey = 'openchamber.connections';
static const _installKey = 'openchamber.installId';
static const _terminalPrefix = 'openchamber.terminalSessions.';
// v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default.
final _secure = const FlutterSecureStorage();
@@ -92,11 +139,86 @@ class Storage {
await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList()));
}
// ------------------------------------------------------------- terminals
// The terminal tabs per directory, so reopening the terminal after an app
// restart can reattach to the shells the server still holds instead of
// starting new ones. Ids are meaningless across servers, hence one map per
// connection.
static String _terminalKey(String connectionId) =>
'$_terminalPrefix$connectionId';
Future<Map<String, dynamic>> _terminalMap(String connectionId) async {
if (connectionId.isEmpty) return {};
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_terminalKey(connectionId));
if (raw == null || raw.isEmpty) return {};
try {
final decoded = jsonDecode(raw);
if (decoded is Map) return Map<String, dynamic>.from(decoded);
} catch (_) {}
return {};
}
/// The tabs saved for [directory], or null when there are none. A value
/// written by 0.4.2 (a bare session id) is read as a single tab.
Future<SavedTerminalTabs?> terminalTabs(
String connectionId, String directory) async {
final entry = (await _terminalMap(connectionId))[directory];
if (entry is String && entry.isNotEmpty) {
return SavedTerminalTabs(
[SavedTerminalTab(entry, '终端 1')], entry);
}
if (entry is! Map) return null;
final rawTabs = entry['tabs'];
if (rawTabs is! List) return null;
final tabs = <SavedTerminalTab>[];
for (final raw in rawTabs) {
if (raw is! Map) continue;
final id = raw['id'];
final label = raw['label'];
if (id is! String || id.isEmpty) continue;
tabs.add(SavedTerminalTab(
id, label is String && label.trim().isNotEmpty ? label : '终端'));
}
if (tabs.isEmpty) return null;
final active = entry['active'];
return SavedTerminalTabs(tabs, active is String ? active : null);
}
Future<void> saveTerminalTabs(
String connectionId, String directory, SavedTerminalTabs value) async {
if (connectionId.isEmpty || directory.isEmpty) return;
final prefs = await SharedPreferences.getInstance();
final map = await _terminalMap(connectionId);
map[directory] = {
'tabs': [
for (final tab in value.tabs) {'id': tab.id, 'label': tab.label},
],
if (value.activeId != null) 'active': value.activeId,
};
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
}
Future<void> clearTerminalTabs(
String connectionId, String directory) async {
if (connectionId.isEmpty) return;
final prefs = await SharedPreferences.getInstance();
final map = await _terminalMap(connectionId);
if (map.remove(directory) == null) return;
if (map.isEmpty) {
await prefs.remove(_terminalKey(connectionId));
} else {
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
}
}
Future<String> installId() async {
final prefs = await SharedPreferences.getInstance();
var id = prefs.getString(_installKey);
if (id == null || id.isEmpty) {
id = _newId();
id = newId();
await prefs.setString(_installKey, id);
}
return id;
@@ -119,7 +241,7 @@ class Storage {
return 'openchamber.token.$digest';
}
static String _newId() =>
static String newId() =>
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}${(_rand() & 0xffffff).toRadixString(36).padLeft(6, '0')}';
static int _rand() => DateTime.now().microsecondsSinceEpoch % 0xffffffff;
+570
View File
@@ -0,0 +1,570 @@
// The live terminal: the xterm model the view renders, and the socket that
// carries its bytes. A directory can hold several tabs; the workspace keeps
// them and owns which one is attached, so closing the panel (or switching
// tabs) does not end the shells — reattaching replays the server's snapshot.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:xterm/xterm.dart';
import 'api/terminal.dart';
import 'state.dart';
import 'storage.dart';
/// One terminal tab. [state] holds the model and the socket; the label is the
/// local name ("终端 1") the dropdown shows.
class TerminalTab {
final TerminalSessionState state;
String label;
TerminalTab(this.state, this.label);
}
/// A tab before its state exists: [id] is the server session when the tab is
/// restored, null when it is about to be created.
class TerminalTabPlan {
final String? id;
final String label;
const TerminalTabPlan({this.id, required this.label});
}
/// Every terminal tab of one working directory, and which one is showing.
class TerminalWorkspace extends ChangeNotifier {
final AppState app;
final String directory;
final List<TerminalTab> tabs = [];
int activeIndex = 0;
bool _loaded = false;
bool _disposed = false;
TerminalWorkspace(this.app, this.directory);
TerminalTab? get activeTab => tabs.isEmpty
? null
: tabs[activeIndex.clamp(0, tabs.length - 1)];
String get _connectionId => app.conn?.id ?? '';
/// Opens the workspace on first use: the saved tabs and the server's sessions
/// for this directory are reconciled, then the active tab attaches. Later
/// calls just make sure its socket is alive.
Future<void> ensureOpen() async {
if (_disposed) return;
if (_loaded) {
await activeTab?.state.ensureOpen();
return;
}
_loaded = true;
await _load();
}
Future<void> _load() async {
final saved = await _savedTabs();
final server = await _serverTabs();
final plans = planTabs(saved: saved?.tabs ?? const [], server: server);
await _applyPlans(plans, activeId: saved?.activeId);
await activeTab?.state.ensureOpen();
}
/// Tabs to show, given what was saved locally and what the server holds for
/// the directory. A saved tab whose session is gone is dropped; sessions
/// from elsewhere (the web UI, another phone) become tabs of their own.
static List<TerminalTabPlan> planTabs({
required List<SavedTerminalTab> saved,
required List<ServerTerminal>? server,
}) {
final plans = <TerminalTabPlan>[];
String label() => freeLabel(plans.map((p) => p.label));
if (server == null) {
// The listing failed: trust what was saved, and let the attach path
// report a dead id.
for (final tab in saved) {
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
}
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
return plans;
}
// Project-action command runners are PTYs too, but they are not the
// person's terminal tabs.
final sessions = [
for (final s in server)
if (s.interactive) s,
];
final byId = {for (final s in sessions) s.sessionId: s};
final seen = <String>{};
for (final tab in saved) {
if (!byId.containsKey(tab.id) || !seen.add(tab.id)) continue;
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
}
final rest = [
for (final s in sessions)
if (s.sessionId.isNotEmpty && !seen.contains(s.sessionId)) s,
]..sort((a, b) => (a.createdAt ?? 0).compareTo(b.createdAt ?? 0));
for (final session in rest) {
if (!seen.add(session.sessionId)) continue;
plans.add(TerminalTabPlan(id: session.sessionId, label: label()));
}
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
return plans;
}
/// The first free "终端 N" among [labels], so closing a tab makes its number
/// available again.
static String freeLabel(Iterable<String> labels) {
final used = <int>{};
for (final label in labels) {
final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim());
if (match != null) used.add(int.parse(match.group(1)!));
}
var n = 1;
while (used.contains(n)) {
n++;
}
return '终端 $n';
}
Future<SavedTerminalTabs?> _savedTabs() async {
final connection = _connectionId;
if (connection.isEmpty) return null;
return app.storage.terminalTabs(connection, directory);
}
/// The interactive terminals the server holds for this directory, or null
/// when the listing failed (then the saved tabs are kept as they are).
Future<List<ServerTerminal>?> _serverTabs() async {
final client = app.client;
if (client == null) return null;
try {
final all = await client.listTerminals(cwd: directory);
return [
for (final session in all)
if (session.interactive) session,
];
} catch (_) {
return null;
}
}
Future<void> _applyPlans(List<TerminalTabPlan> plans,
{String? activeId}) async {
final reuse = <String, TerminalTab>{};
for (final tab in tabs) {
final id = tab.state.sessionId;
if (id != null) reuse[id] = tab;
}
final next = <TerminalTab>[];
for (final plan in plans) {
final existing = plan.id == null ? null : reuse[plan.id];
final state = existing?.state ??
TerminalSessionState(app, directory,
onSessionIdChanged: _persistLater);
if (plan.id != null) state.sessionId = plan.id;
next.add(TerminalTab(state, plan.label));
}
for (final tab in tabs) {
if (!next.any((entry) => entry.state == tab.state)) tab.state.dispose();
}
tabs
..clear()
..addAll(next);
final match = activeId == null
? -1
: tabs.indexWhere((tab) => tab.state.sessionId == activeId);
activeIndex = match >= 0 ? match : tabs.length - 1;
notifyListeners();
await _persist();
}
void _persistLater() {
unawaited(_persist());
}
Future<void> _persist() async {
final connection = _connectionId;
if (connection.isEmpty || _disposed) return;
final saved = [
for (final tab in tabs)
if (tab.state.sessionId case final id?)
SavedTerminalTab(id, tab.label),
];
if (saved.isEmpty) {
await app.storage.clearTerminalTabs(connection, directory);
return;
}
await app.storage.saveTerminalTabs(connection, directory,
SavedTerminalTabs(saved, activeTab?.state.sessionId));
}
/// Switches tabs: the old one detaches (its shell stays on the server) and
/// the new one attaches or is created.
Future<void> select(int index) async {
if (_disposed || tabs.isEmpty) return;
index = index.clamp(0, tabs.length - 1);
if (index == activeIndex) return;
final previous = activeTab;
activeIndex = index;
notifyListeners();
await previous?.state.detach();
await activeTab?.state.ensureOpen();
await _persist();
}
/// Adds an empty tab and shows it; its shell is created on open.
Future<void> addTab() async {
if (_disposed) return;
final previous = activeTab;
final state = TerminalSessionState(app, directory,
onSessionIdChanged: _persistLater);
tabs.add(TerminalTab(state, freeLabel(tabs.map((tab) => tab.label))));
activeIndex = tabs.length - 1;
notifyListeners();
await previous?.state.detach();
await state.ensureOpen();
await _persist();
}
/// Closes the active tab on the server and in the list; when it was the last
/// one, a fresh tab takes its place so the panel stays usable.
Future<void> closeActive() async {
if (_disposed || tabs.isEmpty) return;
final closing = tabs.removeAt(activeIndex.clamp(0, tabs.length - 1));
if (tabs.isEmpty) {
final state = TerminalSessionState(app, directory,
onSessionIdChanged: _persistLater);
tabs.add(TerminalTab(state, freeLabel(const [])));
activeIndex = 0;
} else {
activeIndex = activeIndex.clamp(0, tabs.length - 1);
}
notifyListeners();
await closing.state.closeSession();
closing.state.dispose();
await activeTab?.state.ensureOpen();
await _persist();
}
/// Ends every shell and forgets the directory's tabs (an explicit
/// disconnect, not the panel closing).
Future<void> closeAll() async {
final connection = _connectionId;
for (final tab in List.of(tabs)) {
await tab.state.closeSession();
tab.state.dispose();
}
tabs.clear();
_loaded = false;
if (connection.isNotEmpty) {
await app.storage.clearTerminalTabs(connection, directory);
}
notifyListeners();
}
/// After the app returns from the background: the socket may be dead
/// without having reported it.
Future<void> reconnectIfNeeded() async {
await activeTab?.state.reconnectIfNeeded();
}
@override
void dispose() {
_disposed = true;
for (final tab in tabs) {
tab.state.dispose();
}
super.dispose();
}
}
class TerminalSessionState extends ChangeNotifier {
final AppState app;
final String directory;
/// Called when [sessionId] changes (created, replaced, cleared), so the
/// workspace can save its tab list.
final VoidCallback? onSessionIdChanged;
final Terminal model = Terminal(maxLines: 5000);
TerminalSocket? _socket;
TerminalLinkState link = TerminalLinkState.idle;
String? detail;
String? sessionId;
/// Key-bar modifiers. They apply to the next character, whichever keyboard
/// produced it: the on-screen bar or the phone's IME (which never sends
/// Ctrl itself).
bool ctrl = false;
bool alt = false;
bool shift = false;
int _cols = 80;
int _rows = 24;
Timer? _resizeTimer;
bool _opened = false;
bool _disposed = false;
bool _recovering = false;
TerminalSessionState(this.app, this.directory, {this.onSessionIdChanged}) {
model.onOutput = _onOutput;
model.onResize = (cols, rows, _, __) {
_cols = cols;
_rows = rows;
_scheduleResize();
};
}
bool get isOpen => link == TerminalLinkState.open;
bool get isRunning =>
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
/// Attaches to the tab's session, or creates one when the tab has none yet.
Future<void> ensureOpen() async {
if (_disposed) return;
if (!_opened) {
_opened = true;
if (sessionId == null) {
await _create();
} else {
await _attach();
}
return;
}
if (_socket == null && link != TerminalLinkState.exited) await _attach();
}
/// Drops the socket without ending the shell; [ensureOpen] attaches again.
Future<void> detach() async {
await _socket?.dispose();
_socket = null;
}
void toggleCtrl() {
ctrl = !ctrl;
notifyListeners();
}
void toggleAlt() {
alt = !alt;
notifyListeners();
}
void toggleShift() {
shift = !shift;
notifyListeners();
}
/// Sends one typed character, with whatever modifiers are pending, then
/// drops them. Escape sequences (arrows, Home, …) arrive already complete
/// and pass through untouched.
void _onOutput(String data) {
var out = data;
if (out.isNotEmpty) {
final code = out.codeUnitAt(0);
final printable = out.length == 1 && code >= 0x20 && code != 0x7f;
if (printable && ctrl) {
if (code >= 0x61 && code <= 0x7a) {
out = String.fromCharCode(code - 0x60);
} else if (code >= 0x41 && code <= 0x5a) {
out = String.fromCharCode(code - 0x40);
} else if (code >= 0x5b && code <= 0x5f) {
out = String.fromCharCode(code - 0x40);
} else if (code == 0x20) {
out = '\x00';
}
}
// Alt is an ESC prefix on the character.
if (printable && alt) out = '\x1b$out';
}
_socket?.write(out);
if ((ctrl || alt || shift) && out.isNotEmpty) {
ctrl = false;
alt = false;
shift = false;
notifyListeners();
}
}
Future<void> _create() async {
final client = app.client;
if (client == null) return;
_set(TerminalLinkState.creating);
try {
final info = await client.createTerminal(
cwd: directory, cols: _cols, rows: _rows);
if (_disposed) return;
sessionId = info.sessionId;
_cols = info.cols;
_rows = info.rows;
onSessionIdChanged?.call();
await _attach();
} catch (error) {
_set(TerminalLinkState.error, detail: _message(error));
}
}
Future<void> _attach() async {
final client = app.client;
final id = sessionId;
if (client == null || id == null || _disposed) return;
await _socket?.dispose();
final socket = TerminalSocket(
transport: client.transport,
headers: client.eventHeaders,
sessionId: id,
onEvent: _onEvent,
onState: (state, {detail}) => _set(state, detail: detail),
);
_socket = socket;
await socket.connect();
}
void _onEvent(TerminalEvent event) {
if (_disposed) return;
switch (event.type) {
case 'snapshot':
// Replay at the size the server drew the history for, then clear what
// this view already had: a reattach must not duplicate the screen.
if (event.cols != null && event.rows != null) {
model.resize(event.cols!, event.rows!);
}
_clear();
if (event.data.isNotEmpty) model.write(event.data);
if (event.status == 'exited') {
_set(TerminalLinkState.exited,
detail: event.exitCode == null
? '已退出'
: '退出码 ${event.exitCode}');
}
break;
case 'restarted':
_clear();
if (event.data.isNotEmpty) model.write(event.data);
_set(TerminalLinkState.open);
break;
case 'output':
model.write(event.data);
break;
case 'exit':
_set(TerminalLinkState.exited,
detail: event.exitCode == null
? '已退出'
: '退出码 ${event.exitCode}');
break;
case 'error':
if (event.fatal) {
if (event.code == 'SESSION_NOT_FOUND') {
// The remembered id outlived the server's session (a server
// restart, or the idle reaper won a race with the attach): open a
// new shell instead of leaving a dead panel.
_recoverMissing();
} else {
_set(TerminalLinkState.error,
detail: event.message ?? event.code ?? '终端连接失败');
}
}
break;
}
}
/// Clears the screen and the scrollback, then homes the cursor.
void _clear() => model.write('\x1b[2J\x1b[3J\x1b[H');
void _set(TerminalLinkState state, {String? detail}) {
link = state;
if (detail != null) this.detail = detail;
if (state == TerminalLinkState.open) this.detail = null;
notifyListeners();
}
void _scheduleResize() {
_resizeTimer?.cancel();
_resizeTimer = Timer(const Duration(milliseconds: 250), () {
final client = app.client;
final id = sessionId;
if (client == null || id == null || _disposed) return;
client
.resizeTerminal(id, _cols, _rows, directory: directory)
.catchError((_) {});
});
}
/// Restarts the shell in place (the server keeps the session id).
Future<void> restart() async {
final client = app.client;
final id = sessionId;
if (client == null || id == null) return;
_set(TerminalLinkState.connecting);
try {
await client.restartTerminal(id,
cwd: directory, cols: _cols, rows: _rows);
if (_disposed) return;
_clear();
_set(TerminalLinkState.open);
} catch (error) {
_set(TerminalLinkState.error, detail: _message(error));
}
}
/// After the app returns from the background: the socket may be dead
/// without having reported it.
Future<void> reconnectIfNeeded() async {
if (_disposed) return;
if (link == TerminalLinkState.exited || link == TerminalLinkState.error) {
return;
}
if (_socket == null) await _attach();
}
/// Ends the shell on the server and drops the socket.
Future<void> closeSession() async {
final client = app.client;
final id = sessionId;
sessionId = null;
_opened = false;
link = TerminalLinkState.idle;
detail = null;
onSessionIdChanged?.call();
await _socket?.dispose();
_socket = null;
if (!_disposed) notifyListeners();
if (client != null && id != null) {
try {
await client.closeTerminal(id, directory: directory);
} catch (_) {}
}
}
/// Drops a session the server no longer has and opens another one in its
/// place, so a stale id does not leave the tab unusable.
Future<void> _recoverMissing() async {
if (_recovering || _disposed) return;
_recovering = true;
try {
sessionId = null;
onSessionIdChanged?.call();
await _socket?.dispose();
_socket = null;
if (_disposed) return;
_opened = true;
await _create();
} finally {
_recovering = false;
}
}
@override
void dispose() {
_disposed = true;
_resizeTimer?.cancel();
_socket?.dispose();
_socket = null;
// The session is left for the server's idle reaper when the app goes
// away; [closeSession] handles an explicit disconnect.
super.dispose();
}
String _message(Object error) {
final text = '$error';
return text.startsWith('ApiError') ? text : text;
}
}
+2
View File
@@ -0,0 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.5';
+135
View File
@@ -0,0 +1,135 @@
// Attachments shared by the chat composer and the new-session draft: what a
// picked file becomes (a data URL the server stores) and the chips that show
// it above the input.
import 'dart:convert';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
class ComposerAttachment {
final String name;
final String mime;
final String dataUrl;
final String? path;
const ComposerAttachment({
required this.name,
required this.mime,
required this.dataUrl,
this.path,
});
bool get isImage => mime.startsWith('image/');
}
/// Opens the system picker and turns each choice into an attachment. Files
/// over 10 MB are refused with a message instead of being dropped silently.
Future<List<ComposerAttachment>> pickComposerAttachments(
BuildContext context) async {
final picked = await FilePicker.pickFiles();
if (picked.isEmpty) return const [];
final out = <ComposerAttachment>[];
for (final file in picked) {
final bytes = await file.readAsBytes();
if (bytes.length > 10 * 1024 * 1024) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('附件不能超过 10MB')));
}
continue;
}
final mime = _mimeOf(file.name);
String? keptPath;
if (mime.startsWith('image/') && file.path != null) {
keptPath = await _keepImage(file.path!, file.name);
}
out.add(ComposerAttachment(
name: file.name,
mime: mime,
dataUrl: 'data:$mime;base64,${base64Encode(bytes)}',
path: keptPath,
));
}
return out;
}
/// Chips with a thumbnail, unfolded above the input bar.
class AttachmentTray extends StatelessWidget {
final List<ComposerAttachment> items;
final ValueChanged<int> onRemove;
const AttachmentTray({
super.key,
required this.items,
required this.onRemove,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 46,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
for (var i = 0; i < items.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: InputChip(
avatar: items[i].path != null
? CircleAvatar(
backgroundImage: FileImage(File(items[i].path!)),
)
: const Icon(Icons.insert_drive_file, size: 16),
label: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 160),
child: Text(items[i].name,
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onDeleted: () => onRemove(i),
),
),
],
),
);
}
}
String _mimeOf(String name) {
final ext = name.split('.').last.toLowerCase();
return switch (ext) {
'png' => 'image/png',
'jpg' || 'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'webp' => 'image/webp',
'bmp' => 'image/bmp',
'avif' => 'image/avif',
'ico' => 'image/x-icon',
'pdf' => 'application/pdf',
'json' => 'application/json',
'md' || 'markdown' => 'text/markdown',
'txt' => 'text/plain',
'csv' => 'text/csv',
'html' => 'text/html',
'xml' => 'text/xml',
'zip' => 'application/zip',
_ => 'application/octet-stream',
};
}
Future<String?> _keepImage(String src, String name) async {
try {
// No plugin needed: a cache copy is enough for the message being sent.
final dir = Directory(
'${Directory.systemTemp.path}/openchamber-attachments');
await dir.create(recursive: true);
final safe =
name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_');
final dst =
'${dir.path}/${DateTime.now().microsecondsSinceEpoch}-$safe';
await File(src).copy(dst);
return dst;
} catch (_) {
return null;
}
}
+248
View File
@@ -0,0 +1,248 @@
// The input capsule. Focus opens it into two rows — the text above, the
// model / mode / keys below — and losing focus folds it back to one line, the
// way dsh-Go's composer behaves. The field keeps its state across the two
// layouts through a GlobalKey.
import 'package:flutter/material.dart';
class ComposerBox extends StatefulWidget {
final TextEditingController controller;
final FocusNode focusNode;
final String hint;
final int maxLines;
/// The soft keyboard's height, from the page (a Scaffold removes the bottom
/// view inset from its body, so the composer cannot read it itself).
final double keyboardInset;
final ValueChanged<String>? onChanged;
final ValueChanged<String>? onSubmitted;
final TextInputAction textInputAction;
/// The attach key; shown on the text's line when folded and on the second
/// row when open.
final Widget leading;
/// Model (and thinking level) pill, second row.
final Widget? model;
/// The mode (Build / Plan), second row and separate from [model].
final Widget? mode;
/// The context ring, right of the keys.
final Widget? accessory;
/// Send or stop.
final Widget trailing;
const ComposerBox({
super.key,
required this.controller,
required this.focusNode,
required this.hint,
required this.leading,
required this.trailing,
this.model,
this.mode,
this.accessory,
this.maxLines = 5,
this.keyboardInset = 0,
this.onChanged,
this.onSubmitted,
this.textInputAction = TextInputAction.newline,
});
@override
State<ComposerBox> createState() => _ComposerBoxState();
}
class _ComposerBoxState extends State<ComposerBox> {
// The editor moves between the one-line row and the two-line column; a
// GlobalKey carries its state (and its input connection) across the swap.
final GlobalKey _fieldKey = GlobalKey();
bool _open = false;
// The keyboard went down with the field still focused (the phone's back
// gesture closes the IME without unfocusing). dsh-Go folds the composer in
// that case too, so the same rule is kept here.
bool _keyboardDown = false;
double _keyboardPeak = 0;
@override
void initState() {
super.initState();
widget.focusNode.addListener(_onFocus);
_open = widget.focusNode.hasFocus;
}
@override
void dispose() {
widget.focusNode.removeListener(_onFocus);
super.dispose();
}
@override
void didUpdateWidget(ComposerBox oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.focusNode != widget.focusNode) {
oldWidget.focusNode.removeListener(_onFocus);
widget.focusNode.addListener(_onFocus);
}
if (oldWidget.keyboardInset != widget.keyboardInset) {
_keyboardMoved(oldWidget.keyboardInset, widget.keyboardInset);
// The build that follows reads this; no second one is needed.
_open = widget.focusNode.hasFocus && !_keyboardDown;
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// A sheet over the page takes the keyboard for a moment; when the page is
// current again, settle on where the composer should be.
WidgetsBinding.instance.addPostFrameCallback((_) => _syncOpen());
}
/// A keyboard rising clears "down"; falling to well under its peak means it
/// was dismissed (a height change alone stays open).
void _keyboardMoved(double before, double inset) {
if (!(ModalRoute.of(context)?.isCurrent ?? true)) return;
if (inset > before) {
_keyboardDown = false;
if (inset > _keyboardPeak) _keyboardPeak = inset;
} else if (inset < _keyboardPeak * 0.5) {
_keyboardDown = true;
_keyboardPeak = 0;
}
}
void _onFocus() {
if (widget.focusNode.hasFocus) _keyboardDown = false;
_syncOpen();
}
void _syncOpen() {
if (!mounted) return;
// The model sheet (or any page over this one) takes focus for a moment:
// leave the composer as it is until it is current again.
if (!(ModalRoute.of(context)?.isCurrent ?? true)) return;
final open = widget.focusNode.hasFocus && !_keyboardDown;
if (open == _open) return;
setState(() => _open = open);
}
Widget _field() {
return TextField(
key: _fieldKey,
controller: widget.controller,
focusNode: widget.focusNode,
minLines: 1,
maxLines: widget.maxLines,
keyboardType: TextInputType.multiline,
textInputAction: widget.textInputAction,
onChanged: widget.onChanged,
onSubmitted: widget.onSubmitted,
style: const TextStyle(fontSize: 15, height: 1.45),
decoration: InputDecoration(
hintText: widget.hint,
hintMaxLines: 1,
isDense: true,
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 6),
),
);
}
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final accessory = widget.accessory;
return AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(_open ? 20 : 26),
),
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutCubic,
alignment: Alignment.bottomCenter,
child: _open
? Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(6, 0, 6, 2),
child: _field(),
),
_secondRow(),
],
)
: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
widget.leading,
const SizedBox(width: 4),
Expanded(child: _field()),
const SizedBox(width: 4),
if (accessory != null) ...[
// The keys are 36 high and the row aligns to its bottom:
// lift the smaller accessory by half the difference so it
// sits on the keys' centre line, not below it.
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: accessory,
),
const SizedBox(width: 2),
],
widget.trailing,
],
),
),
);
}
Widget _secondRow() {
final accessory = widget.accessory;
// The row fades and rises a little as the composer opens.
return TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: 1),
duration: const Duration(milliseconds: 220),
curve: Curves.easeOutCubic,
builder: (context, t, child) => Opacity(
opacity: t,
child: Transform.translate(
offset: Offset(0, (1 - t) * 4),
child: child,
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 2, 0, 0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
widget.leading,
const SizedBox(width: 6),
if (widget.model != null)
Flexible(
fit: FlexFit.loose,
child: Align(
alignment: Alignment.centerLeft,
child: widget.model!,
),
),
const SizedBox(width: 6),
if (widget.mode != null) widget.mode!,
const Spacer(),
if (accessory != null) ...[
accessory,
const SizedBox(width: 4),
],
widget.trailing,
],
),
),
);
}
}
+14 -1
View File
@@ -40,11 +40,24 @@ class MarkdownView extends StatelessWidget {
return mui.Theme(
data: markdownThemeData(Theme.of(context)),
child: GptMarkdown(
text,
_taskMarkers(text),
// The server already streams deltas; show them as they arrive.
isStreaming: false,
style: TextStyle(fontSize: fontSize, height: height, color: color),
),
);
}
/// gpt_markdown draws task lists with `material_ui`'s Checkbox, which wants
/// a `material_ui` Material ancestor the app never provides (its Scaffold is
/// Flutter's). Boxed emoji read the same and cost no widget tree.
static String _taskMarkers(String source) {
var out = source.replaceAllMapped(
RegExp(r'^(\s*)[-*+]\s+\[[xX]\]\s+', multiLine: true),
(match) => '${match[1]}- ✅ ');
out = out.replaceAllMapped(
RegExp(r'^(\s*)[-*+]\s+\[\s?\]\s+', multiLine: true),
(match) => '${match[1]}- ⬜ ');
return out;
}
}
+168
View File
@@ -0,0 +1,168 @@
// The composer's two controls: the model pill (model and thinking level in
// one group) and, separately, the mode (Build / Plan).
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../model_prefs.dart';
import '../state.dart';
import 'model_picker.dart';
/// `deepseek-flash · 高` — model and effort together, as dsh-Go shows them.
class ModelPill extends StatelessWidget {
final AppState app;
final ModelRef? model;
final ValueChanged<ModelRef> onModel;
const ModelPill({
super.key,
required this.app,
required this.model,
required this.onModel,
});
@override
Widget build(BuildContext context) {
final info = app.modelInfo(model);
// The server may name the default level "default"; only a level the
// catalog lists counts as a choice.
final effort = model?.variant != null &&
info != null &&
info.variants.contains(model!.variant)
? model!.variant
: null;
final name = model == null ? '模型' : app.modelName(model!);
final label = effort == null ? name : '$name · ${effortLabel(effort)}';
return _Pill(
icon: Icons.smart_toy_outlined,
label: label,
onTap: () => showModelPickerSheet(
context,
app: app,
model: model,
onModel: onModel,
),
);
}
}
/// The mode is its own control: Build or Plan, not part of the model.
class ModeChip extends StatelessWidget {
final AppState app;
final String agent;
final ValueChanged<String> onAgent;
const ModeChip({
super.key,
required this.app,
required this.agent,
required this.onAgent,
});
static const _modes = ['build', 'plan'];
@override
Widget build(BuildContext context) {
final current = agent.isEmpty ? _modes.first : agent;
return _Pill(
icon: Icons.tune,
label: _label(current),
onTap: () => _open(context, current),
);
}
Future<void> _open(BuildContext context, String current) async {
final known = [
for (final a in app.agentList)
if (a.mode == 'primary' && !a.hidden) a,
];
final ids = <String>{..._modes, for (final a in known) a.id};
final names = {for (final a in known) a.id: a.name};
final scheme = Theme.of(context).colorScheme;
final picked = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheet) => SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text('模式',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
),
for (final id in ids)
ListTile(
leading: Icon(
id == 'plan' ? Icons.map_outlined : Icons.construction_outlined,
color: id == current ? scheme.primary : null,
),
title: Text(
names[id]?.isNotEmpty == true ? names[id]! : _label(id),
style: TextStyle(
fontWeight: id == current ? FontWeight.w700 : FontWeight.w400,
),
),
subtitle: Text(id == 'plan' ? '先规划,不改动文件' : '直接构建',
style: const TextStyle(fontSize: 12)),
trailing: id == current
? Icon(Icons.check, size: 20, color: scheme.primary)
: null,
onTap: () => Navigator.pop(sheet, id),
),
const SizedBox(height: 8),
],
),
),
);
if (picked != null && picked != current) onAgent(picked);
}
static String _label(String id) =>
id.isEmpty ? 'Build' : id[0].toUpperCase() + id.substring(1);
}
class _Pill extends StatelessWidget {
final IconData icon;
final String label;
final VoidCallback? onTap;
const _Pill({required this.icon, required this.label, this.onTap});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return InkWell(
borderRadius: BorderRadius.circular(16),
onTap: onTap,
child: Container(
constraints: const BoxConstraints(minHeight: 30),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: ShapeDecoration(
color: scheme.onSurface.withValues(alpha: 0.07),
shape: const StadiumBorder(),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: theme.hintColor),
const SizedBox(width: 4),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5,
color: scheme.onSurface,
),
),
),
],
),
),
);
}
}
+324
View File
@@ -0,0 +1,324 @@
// The model picker: favourites, recents, models grouped by provider with their
// context size, and — when a model has them — its thinking levels, chosen in
// the same sheet because model and effort are one selection.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../model_prefs.dart';
import '../state.dart';
Future<void> showModelPickerSheet(
BuildContext context, {
required AppState app,
required ModelRef? model,
required ValueChanged<ModelRef> onModel,
}) async {
app.refreshModels();
await ModelPrefs.instance.ensureLoaded();
if (!context.mounted) return;
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.85,
maxChildSize: 0.95,
builder: (context, controller) => _PickerSheet(
app: app,
model: model,
scrollController: controller,
onModel: onModel,
),
),
);
}
class _PickerSheet extends StatefulWidget {
final AppState app;
final ModelRef? model;
final ScrollController scrollController;
final ValueChanged<ModelRef> onModel;
const _PickerSheet({
required this.app,
required this.model,
required this.scrollController,
required this.onModel,
});
@override
State<_PickerSheet> createState() => _PickerSheetState();
}
class _PickerSheetState extends State<_PickerSheet> {
String _filter = '';
final Set<String> _collapsed = {};
/// The model whose thinking level the bottom panel is offering; null hides
/// the panel.
ModelInfo? _effortModel;
String? _effortVariant;
ModelPrefs get _prefs => ModelPrefs.instance;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: widget.app,
builder: (context, _) => Column(
children: [
const Padding(
padding: EdgeInsets.fromLTRB(12, 12, 12, 4),
child: Text('选择模型',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
Padding(
padding: const EdgeInsets.all(12),
child: TextField(
onChanged: (v) => setState(() => _filter = v),
decoration: const InputDecoration(
hintText: '搜索',
border: OutlineInputBorder(),
isDense: true),
),
),
Expanded(child: _models()),
if (_effortModel != null) _effortPanel(_effortModel!),
],
),
);
}
Widget _models() {
final all = widget.app.modelList;
if (all.isEmpty) {
return const Center(child: Text('正在载入模型…'));
}
final filter = _filter.trim().toLowerCase();
final matching = filter.isEmpty
? all
: [
for (final m in all)
if (m.name.toLowerCase().contains(filter) ||
m.id.toLowerCase().contains(filter))
m,
];
if (matching.isEmpty) return const Center(child: Text('没有结果'));
final byKey = {
for (final m in all) ModelPrefs.keyFor(m.providerId, m.id): m,
};
final favorites = [
for (final key in _prefs.favorites)
if (byKey[key] != null) byKey[key]!,
]..sort((a, b) => a.name.compareTo(b.name));
final recents = [
for (final key in _prefs.recents)
if (byKey[key] != null && !_prefs.favorites.contains(key)) byKey[key]!,
];
final providers = <String, List<ModelInfo>>{};
for (final model in matching) {
providers.putIfAbsent(model.providerId, () => []).add(model);
}
final children = <Widget>[];
if (filter.isEmpty) {
if (favorites.isNotEmpty) {
children.add(_sectionHeader('收藏', 'favorites', count: favorites.length));
if (!_collapsed.contains('favorites')) {
for (final model in favorites) {
children.add(_modelRow(model));
}
}
}
if (recents.isNotEmpty) {
children.add(_sectionHeader('最近', 'recents', count: recents.length));
if (!_collapsed.contains('recents')) {
for (final model in recents) {
children.add(_modelRow(model));
}
}
}
}
for (final entry in providers.entries) {
final label = entry.key.isEmpty ? '其它' : entry.key;
children.add(_sectionHeader(label, 'provider:${entry.key}',
count: entry.value.length));
if (!_collapsed.contains('provider:${entry.key}')) {
for (final model in entry.value) {
children.add(_modelRow(model));
}
}
}
return ListView(controller: widget.scrollController, children: children);
}
Widget _sectionHeader(String label, String key, {int? count}) {
final collapsed = _collapsed.contains(key);
return InkWell(
onTap: () => setState(() {
if (collapsed) {
_collapsed.remove(key);
} else {
_collapsed.add(key);
}
}),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 4),
child: Row(
children: [
Icon(collapsed ? Icons.chevron_right : Icons.expand_more,
size: 16, color: Theme.of(context).hintColor),
const SizedBox(width: 4),
Expanded(
child: Text(
count == null ? label : '$label($count)',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Theme.of(context).hintColor),
),
),
],
),
),
);
}
Widget _modelRow(ModelInfo model) {
final theme = Theme.of(context);
final key = ModelPrefs.keyFor(model.providerId, model.id);
final selected = widget.model != null &&
widget.model!.id == model.id &&
widget.model!.providerId == model.providerId;
final favorite = _prefs.isFavorite(key);
return ListTile(
dense: true,
contentPadding: const EdgeInsets.only(left: 20, right: 4),
title: Row(
children: [
Flexible(
child: Text(model.name,
maxLines: 1, overflow: TextOverflow.ellipsis),
),
if (model.reasoning)
Padding(
padding: const EdgeInsets.only(left: 4),
child: Icon(Icons.psychology_outlined,
size: 14, color: theme.hintColor),
),
],
),
subtitle: model.context > 0
? Text('${formatTokenCount(model.context)} 上下文',
style: TextStyle(fontSize: 11, color: theme.hintColor))
: null,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (selected)
Padding(
padding: const EdgeInsets.only(right: 4),
child: Icon(Icons.check,
size: 18, color: theme.colorScheme.primary),
),
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(
favorite ? Icons.star : Icons.star_border,
size: 18,
color: favorite ? theme.colorScheme.primary : theme.hintColor,
),
tooltip: favorite ? '取消收藏' : '收藏',
onPressed: () async {
await _prefs.toggleFavorite(key);
if (mounted) setState(() {});
},
),
],
),
onTap: () => _select(model),
);
}
Future<void> _select(ModelInfo model) async {
final key = ModelPrefs.keyFor(model.providerId, model.id);
final remembered = _prefs.effortFor(key);
final variant = remembered != null && model.variants.contains(remembered)
? remembered
: null;
await _prefs.rememberModel(key);
if (!mounted) return;
// Model and effort are one choice: apply the model with its remembered
// level, then let the level be changed without leaving the sheet.
widget.onModel(ModelRef(model.id, model.providerId, variant));
if (model.hasEffort) {
setState(() {
_effortModel = model;
_effortVariant = variant;
});
} else {
Navigator.pop(context);
}
}
Future<void> _pickEffort(ModelInfo model, String? variant) async {
final key = ModelPrefs.keyFor(model.providerId, model.id);
await _prefs.rememberEffort(key, variant);
widget.onModel(ModelRef(model.id, model.providerId, variant));
if (!mounted) return;
Navigator.pop(context);
}
Widget _effortPanel(ModelInfo model) {
final theme = Theme.of(context);
final options = <String?>[null, ...model.variants];
return Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: theme.dividerColor.withValues(alpha: 0.6))),
),
padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
const Text('思考强度',
style: TextStyle(
fontSize: 13, fontWeight: FontWeight.w700)),
const SizedBox(width: 6),
Expanded(
child: Text(model.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style:
TextStyle(fontSize: 12, color: theme.hintColor)),
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('完成'),
),
],
),
Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (final option in options)
ChoiceChip(
label: Text(effortLabel(option),
style: const TextStyle(fontSize: 12.5)),
selected: (_effortVariant ?? '') == (option ?? ''),
onSelected: (_) => _pickEffort(model, option),
),
],
),
],
),
);
}
}
+391
View File
@@ -0,0 +1,391 @@
// The input-box pet. A PetSprite plays the pack's sheet frames; PetLayer is
// the floating layer it lives in, placed over the chat's message area so the
// messages keep their full height and show through around the pet. Nothing
// renders until a pack is imported and enabled.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../pets/pet_library.dart';
import '../pets/pet_pack.dart';
/// The pet over the chat. It reserves no layout space: the message list runs
/// underneath, and only the sprite's body takes touches. The feet rest on the
/// bottom edge of the layer, which is the composer's top (or the activity
/// cap's while a turn runs). Dragging it sideways moves it along that edge.
class PetLayer extends StatefulWidget {
final String state;
const PetLayer({super.key, required this.state});
@override
State<PetLayer> createState() => _PetLayerState();
}
class _PetLayerState extends State<PetLayer> {
/// Where the feet are, as a fraction of the layer's width. Null: use the
/// saved spot.
double? _fraction;
bool _dragging = false;
double _lift = 0;
/// How far from either end the body keeps, logical px.
static const _edge = 8.0;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: PetLibrary.instance,
builder: (context, _) {
final library = PetLibrary.instance;
final pack = library.pack;
if (!library.enabled || pack == null) return const SizedBox.shrink();
return LayoutBuilder(builder: (context, constraints) {
final width = constraints.maxWidth;
final size = library.size;
final scale = size / pack.canvas.width;
final height = size * pack.canvas.height / pack.canvas.width;
// Body extents left and right of the feet, so dragging keeps the
// whole pet on screen.
final leftExtent = (pack.anchor.dx - pack.contentBox.left) * scale;
final rightExtent = (pack.contentBox.right - pack.anchor.dx) * scale;
final lo = leftExtent + _edge;
final hi = width - rightExtent - _edge;
final minFoot = hi <= lo ? width / 2 : lo;
final maxFoot = hi <= lo ? width / 2 : hi;
final fraction = (_fraction ?? library.position).clamp(0.0, 1.0);
final foot = (fraction * width).clamp(minFoot, maxFoot);
// Stand on the composer's top edge. The sprite's own canvas goes a
// little below the anchor, and the composer keeps a few px of top
// padding above its capsule, so step past both; that overflow is
// fine, the layer does not clip.
final bottom =
-((pack.canvas.height - pack.anchor.dy) * scale + 6) + _lift;
return Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: foot - pack.anchor.dx * scale,
bottom: bottom,
width: size,
height: height,
child: PetSprite(
pack: pack,
state: widget.state,
width: size,
dragging: _dragging,
onDragStart: () => setState(() {
_dragging = true;
_lift = -6;
}),
onDragUpdate: (dx) {
final next = ((_fraction ?? library.position) * width + dx)
.clamp(minFoot, maxFoot);
setState(() => _fraction = next / width);
},
onDragEnd: () {
final spot = _fraction;
setState(() {
_dragging = false;
_lift = 0;
});
if (spot != null) library.setPosition(spot);
},
),
),
],
);
});
},
);
}
}
class PetSprite extends StatefulWidget {
final PetPack pack;
final String state;
/// The pack canvas's on-screen width; the height follows the canvas ratio.
final double width;
/// A drag is in progress: play the pack's drag reaction while held.
final bool dragging;
/// Called when the body is dragged; the layer moves the pet.
final VoidCallback? onDragStart;
final ValueChanged<double>? onDragUpdate;
final VoidCallback? onDragEnd;
const PetSprite({
super.key,
required this.pack,
required this.state,
required this.width,
this.dragging = false,
this.onDragStart,
this.onDragUpdate,
this.onDragEnd,
});
@override
State<PetSprite> createState() => _PetSpriteState();
}
class _PetSpriteState extends State<PetSprite> {
PetAnimation? _animation;
ui.Image? _image;
String? _sheet;
int _frame = 0;
Timer? _timer;
int _loadToken = 0;
/// A reaction being played; the state resumes when it ends.
String? _oneShot;
String? _pendingState;
/// The drag reaction's name while a drag holds it.
String? _dragAnimation;
@override
void initState() {
super.initState();
_begin(widget.state);
}
@override
void didUpdateWidget(PetSprite oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.pack != widget.pack) {
_oneShot = null;
_pendingState = null;
_dragAnimation = null;
_begin(widget.state);
return;
}
if (oldWidget.dragging != widget.dragging) {
_oneShot = null;
if (widget.dragging) {
final drag = widget.pack.reactions['drag'];
_dragAnimation =
drag != null && widget.pack.animations.containsKey(drag) ? drag : null;
final name = _dragAnimation ?? widget.pack.animationForState(widget.state);
if (name != null) _beginNamed(name);
} else {
final next = _pendingState ?? widget.state;
_pendingState = null;
_dragAnimation = null;
_begin(next);
}
return;
}
if (oldWidget.state != widget.state) {
if (_oneShot != null || widget.dragging) {
_pendingState = widget.state;
} else {
_begin(widget.state);
}
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _begin(String state) => _beginNamed(widget.pack.animationForState(state));
void _beginNamed(String? name) {
final animation = widget.pack.animation(name);
if (animation == null) {
_timer?.cancel();
_animation = null;
return;
}
_animation = animation;
_frame = 0;
_showSheet(animation);
_schedule();
}
/// Loads a new sheet; a frame from the old one must not be cropped with the
/// new animation's box, so the image clears while it loads.
void _showSheet(PetAnimation animation) {
if (animation.sheet == _sheet) return;
_sheet = animation.sheet;
_image = null;
final token = ++_loadToken;
PetLibrary.instance.imageFor(animation).then((image) {
if (!mounted || token != _loadToken) return;
setState(() => _image = image);
});
}
void _schedule() {
_timer?.cancel();
final animation = _animation;
if (animation == null || animation.frames.isEmpty) return;
final frame = animation.frames[_frame.clamp(0, animation.frames.length - 1)];
_timer = Timer(Duration(milliseconds: frame.ms), _tick);
}
void _tick() {
final animation = _animation;
if (!mounted || animation == null) return;
if (_frame + 1 < animation.frames.length) {
setState(() => _frame++);
_schedule();
return;
}
final oneShot = _oneShot;
if (oneShot != null) {
_oneShot = null;
final next = _pendingState ?? widget.state;
_pendingState = null;
_begin(next);
setState(() {});
return;
}
// Held by a drag: keep the pose until it is let go, even when the pack's
// drag sheet plays once.
if (widget.dragging &&
_dragAnimation != null &&
animation.name == _dragAnimation &&
!animation.loop) {
setState(() => _frame = 0);
_schedule();
return;
}
if (animation.loop) {
setState(() => _frame = 0);
_schedule();
return;
}
_begin(widget.state);
setState(() {});
}
void _react(TapUpDetails details) {
final left = details.localPosition.dx < widget.width / 2;
final name = widget.pack.reactions[left ? 'tapLeft' : 'tapRight'];
final animation = widget.pack.animation(name);
if (animation == null) return;
_oneShot = name;
_pendingState = widget.state;
_animation = animation;
_frame = 0;
_showSheet(animation);
_schedule();
setState(() {});
}
@override
Widget build(BuildContext context) {
final width = widget.width;
final height = width * widget.pack.canvas.height / widget.pack.canvas.width;
return GestureDetector(
// Only the body takes touches; the rest of the layer lets the message
// list scroll.
behavior: HitTestBehavior.deferToChild,
onTapUp: _react,
onHorizontalDragStart: (_) => widget.onDragStart?.call(),
onHorizontalDragUpdate: (details) =>
widget.onDragUpdate?.call(details.delta.dx),
onHorizontalDragEnd: (_) => widget.onDragEnd?.call(),
onHorizontalDragCancel: () => widget.onDragEnd?.call(),
child: CustomPaint(
size: Size(width, height),
painter: _PetPainter(
pack: widget.pack,
animation: _animation,
image: _image,
frame: _frame,
spriteSize: Size(width, height),
),
),
);
}
}
class _PetPainter extends CustomPainter {
final PetPack pack;
final PetAnimation? animation;
final ui.Image? image;
final int frame;
/// The on-screen size, for hit testing.
final Size spriteSize;
const _PetPainter({
required this.pack,
required this.animation,
required this.image,
required this.frame,
required this.spriteSize,
});
/// The body only: taps and drags on the transparent canvas around it go to
/// whatever is underneath.
@override
bool? hitTest(Offset position) {
if (spriteSize.width <= 0) return false;
final scale = spriteSize.width / pack.canvas.width;
final body = Rect.fromLTRB(
pack.contentBox.left * scale,
pack.contentBox.top * scale,
pack.contentBox.right * scale,
pack.contentBox.bottom * scale,
).inflate(4);
return body.contains(position);
}
@override
void paint(Canvas canvas, Size size) {
final animation = this.animation;
final image = this.image;
if (image == null || animation == null || animation.frames.isEmpty) return;
final cols = animation.cols;
final maxCols = image.width ~/ animation.frameW;
final maxRows = image.height ~/ animation.frameH;
if (maxCols <= 0 || maxRows <= 0) return;
final entry =
animation.frames[frame.clamp(0, animation.frames.length - 1)];
final col = (entry.index % cols).clamp(0, maxCols - 1);
final row = (entry.index ~/ cols).clamp(0, maxRows - 1);
final src = Rect.fromLTWH(
col * animation.frameW.toDouble(),
row * animation.frameH.toDouble(),
animation.frameW.toDouble(),
animation.frameH.toDouble(),
);
final scale = size.width / pack.canvas.width;
final dst = Rect.fromLTWH(
animation.box.left * scale,
animation.box.top * scale,
animation.box.width * scale,
animation.box.height * scale,
);
canvas.drawImageRect(
image,
src,
dst,
Paint()
..filterQuality =
pack.pixelArt ? FilterQuality.none : FilterQuality.medium,
);
}
@override
bool shouldRepaint(_PetPainter oldDelegate) =>
oldDelegate.image != image ||
oldDelegate.animation != animation ||
oldDelegate.frame != frame ||
oldDelegate.pack != pack ||
oldDelegate.spriteSize != spriteSize;
}
+195
View File
@@ -0,0 +1,195 @@
// The `/` palette above a composer, shared by the chat and the new-session
// draft: commands and skills of one directory, filtered as the name is typed.
import 'package:flutter/material.dart';
import '../state.dart';
const _slashLabels = {
'compact': '压缩',
'init': '初始化',
'review': '审查',
'goal': '目标',
'new-extension': '新建扩展',
'permission': '权限',
'plan': '计划',
'feedback': '反馈',
};
String? slashLabel(SlashItem item) =>
item.skill ? null : _slashLabels[item.name];
/// Rows for a draft, or null when the palette should stay closed. It stays
/// up while only the command name is typed and closes once an argument
/// starts, unless the same text was dismissed with Esc.
List<SlashItem>? matchSlashItems({
required List<SlashItem> items,
required String text,
String? dismissed,
}) {
if (dismissed == text) return null;
final trimmed = text.trimLeft();
if (!trimmed.startsWith('/')) return null;
if (trimmed.length > 1 && RegExp(r'\s').hasMatch(trimmed.substring(1))) {
return null;
}
final query = trimmed.substring(1).toLowerCase().trim();
if (query.isEmpty) return items;
bool hit(SlashItem item) {
final label = slashLabel(item) ?? '';
return item.name.toLowerCase().contains(query) ||
label.toLowerCase().contains(query) ||
item.description.toLowerCase().contains(query);
}
return items.where(hit).toList()
..sort((a, b) {
final aPrefix = a.name.toLowerCase().startsWith(query) ? 0 : 1;
final bPrefix = b.name.toLowerCase().startsWith(query) ? 0 : 1;
if (aPrefix != bPrefix) return aPrefix - bPrefix;
if (a.skill != b.skill) return a.skill ? 1 : -1;
return a.name.compareTo(b.name);
});
}
/// The panel itself: rows with an icon, the command and its description.
class SlashPalette extends StatelessWidget {
final List<SlashItem> items;
final int index;
final bool loading;
final ValueChanged<SlashItem> onPick;
const SlashPalette({
super.key,
required this.items,
required this.index,
required this.loading,
required this.onPick,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final selected = items.isEmpty ? 0 : index.clamp(0, items.length - 1);
Widget row(IconData icon, String title, String subtitle) => Padding(
padding: const EdgeInsets.fromLTRB(14, 14, 14, 14),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(icon, size: 20, color: scheme.onSurfaceVariant),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style:
TextStyle(fontSize: 14, color: scheme.onSurface)),
if (subtitle.isNotEmpty)
Text(subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
],
),
);
return Container(
constraints: const BoxConstraints(maxHeight: 56 * 5.5),
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: scheme.outlineVariant.withValues(alpha: 0.6)),
),
child: items.isEmpty
? (loading
? const Padding(
padding: EdgeInsets.all(18),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2)),
),
)
: row(Icons.search_off, '没有可用的指令', '这个目录还没有注册指令或技能'))
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
itemCount: items.length,
itemBuilder: (context, i) {
final item = items[i];
final label = slashLabel(item);
final isSelected = i == selected;
return InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => onPick(item),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: isSelected
? scheme.primary.withValues(alpha: 0.10)
: null,
borderRadius: BorderRadius.circular(14),
),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(
item.skill
? Icons.extension_outlined
: Icons.terminal,
size: 20,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text('/${item.name}',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: scheme.onSurface)),
if (label != null)
Padding(
padding: const EdgeInsets.only(left: 6),
child: Text(label,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
),
],
),
if (item.description.isNotEmpty)
Text(item.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
],
),
),
);
},
),
);
}
}
+152
View File
@@ -9,6 +9,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.2.0"
archive:
dependency: "direct main"
description:
name: archive
sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.6.1"
args:
dependency: transitive
description:
@@ -33,6 +41,46 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.2"
camera:
dependency: "direct main"
description:
name: camera
sha256: "4a0863bc142f6fbfdca19161205574fd8a8f00d4753b48d214c4dfbdcc534c51"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.12.2"
camera_android_camerax:
dependency: transitive
description:
name: camera_android_camerax
sha256: daefacb4c2c575426772a83ac312b93e2c49c003224962cddab904426dc04dbc
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.7.6+2"
camera_avfoundation:
dependency: transitive
description:
name: camera_avfoundation
sha256: "971f7b4938ae761797dd667c078af92f1b6a1bb7760774c0cbcf9c9d4a14bdf1"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.11.1"
camera_platform_interface:
dependency: transitive
description:
name: camera_platform_interface
sha256: c22b8403d7925c6cc6a37fc0cf01f645c1400bdfb0e765f81373a3ac080d93e3
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.15.1"
camera_web:
dependency: transitive
description:
name: camera_web
sha256: "54183db5a296cf29478dd150d7685b761f9e8eeb4a11114bcbc2792adea7cb3b"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.3.6"
characters:
dependency: transitive
description:
@@ -41,6 +89,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.1"
charcode:
dependency: transitive
description:
name: charcode
sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.0"
cli_util:
dependency: transitive
description:
@@ -73,6 +129,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.19.1"
convert:
dependency: transitive
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.1.2"
cross_file:
dependency: transitive
description:
@@ -113,6 +177,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.8.0"
equatable:
dependency: transitive
description:
name: equatable
sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.0"
fake_async:
dependency: transitive
description:
@@ -185,6 +257,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.2.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
@@ -203,6 +283,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.0.35"
flutter_secure_storage:
dependency: "direct main"
description:
@@ -251,6 +339,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.2.2"
flutter_slidable:
dependency: "direct main"
description:
name: flutter_slidable
sha256: "373a94a50169bc4732267539af312b3cc6c5ab5b5b240364163255ff4c9a8adc"
url: "https://pub.flutter-io.cn"
source: hosted
version: "5.2.0"
flutter_svg:
dependency: transitive
description:
@@ -517,6 +613,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.8"
pointycastle:
dependency: "direct main"
description:
name: pointycastle
sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5"
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.0.0"
pub_semver:
dependency: transitive
description:
@@ -525,6 +629,22 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.2.1"
qr:
dependency: "direct dev"
description:
name: qr
sha256: f9461594b257c2ec882159fb8100db28408f6aacdba5b21f109708bce2e482b6
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.0.1"
quiver:
dependency: transitive
description:
name: quiver
sha256: ea0b925899e64ecdfbf9c7becb60d5b50e706ade44a85b2363be2a22d88117d2
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.2.2"
record_use:
dependency: transitive
description:
@@ -626,6 +746,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.4"
stream_transform:
dependency: transitive
description:
name: stream_transform
sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.2"
string_scanner:
dependency: transitive
description:
@@ -770,6 +898,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "7.0.1"
xterm:
dependency: "direct main"
description:
name: xterm
sha256: "168dfedca77cba33fdb6f52e2cd001e9fde216e398e89335c19b524bb22da3a2"
url: "https://pub.flutter-io.cn"
source: hosted
version: "4.0.0"
yaml:
dependency: transitive
description:
@@ -778,6 +914,22 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.1.4"
zmodem:
dependency: transitive
description:
name: zmodem
sha256: "3b7e5b29f3a7d8aee472029b05165a68438eff2f3f7766edf13daba1e297adbf"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.0.6"
zxing2:
dependency: "direct main"
description:
name: zxing2
sha256: "2677c49a3b9ca9457cb1d294fd4bd5041cac6aab8cdb07b216ba4e98945c684f"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.2.4"
sdks:
dart: ">=3.14.0 <4.0.0"
flutter: ">=3.47.0"
+8 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones."
publish_to: 'none'
version: 0.3.9+309
version: 0.4.5+405
environment:
sdk: ^3.14.0
@@ -16,10 +16,17 @@ dependencies:
file_picker: ^13.0.0
gpt_markdown: ^1.4.0
socks5_proxy: ^2.1.2
xterm: ^4.0.0
flutter_slidable: ^5.2.0
archive: ^3.6.1
pointycastle: ^4.0.0
camera: ^0.12.2
zxing2: ^0.2.4
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
qr: ^4.0.1
flutter:
uses-material-design: true
+60
View File
@@ -0,0 +1,60 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/widgets/composer_box.dart';
void main() {
testWidgets('the composer opens on focus and folds when the IME closes',
(tester) async {
final controller = TextEditingController();
final focus = FocusNode();
final keyboard = ValueNotifier<double>(0);
addTearDown(controller.dispose);
addTearDown(focus.dispose);
addTearDown(keyboard.dispose);
// A stand-in for the second row's contents: it only exists while open.
const model = Text('MODEL');
// The page owns the keyboard inset (a Scaffold removes it from the body),
// so the test feeds it in as the screens do.
await tester.pumpWidget(MaterialApp(
home: ValueListenableBuilder<double>(
valueListenable: keyboard,
builder: (context, inset, _) => Scaffold(
body: ComposerBox(
controller: controller,
focusNode: focus,
hint: 'hi',
keyboardInset: inset,
leading: const Icon(Icons.attach_file),
model: model,
trailing: const Icon(Icons.send),
),
),
),
));
// Unfocused: one line, no model pill.
expect(find.text('MODEL'), findsNothing);
// Focus: the composer opens into two rows.
focus.requestFocus();
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsOneWidget);
// The soft keyboard rises, then the back gesture closes it while the
// field keeps focus: the composer folds back to one line.
keyboard.value = 300;
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsOneWidget);
keyboard.value = 0;
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsNothing);
expect(focus.hasFocus, isTrue);
// Typing again brings the keyboard back: the composer opens.
keyboard.value = 300;
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsOneWidget);
});
}
+274
View File
@@ -0,0 +1,274 @@
{
"schema": 1,
"id": "deepy-whale",
"name": "Deepy 小鲸鱼",
"author": "DSH-TUI",
"license": "DSH-TUI 吉祥物,作者授权 dsh-go 使用",
"source": "DSH-TUI(Clawd on Desk 主题包 v1.0.0)",
"pixelArt": true,
"scale": 5,
"canvas": {"w": 52, "h": 52},
"anchor": {"x": 28, "baseline": 48},
"contentBox": {"x": 12, "y": 26, "w": 36, "h": 22},
"hitBoxes": {
"default": {"x": 12, "y": 26, "w": 33, "h": 22},
"wide": {"x": 8, "y": 18, "w": 44, "h": 31},
"sleeping": {"x": 7, "y": 23, "w": 39, "h": 25},
"byAnim": {
"typing": {"x": 0, "y": 26, "w": 52, "h": 23},
"conducting": {"x": 3, "y": 27, "w": 39, "h": 22},
"react-drag": {"x": 12, "y": 6, "w": 37, "h": 26}
},
"wideAnims": ["idle-spout", "building", "music", "error", "happy", "notification", "carrying", "waking", "roam-hop", "react-double"],
"sleepingAnims": ["sleeping"]
},
"animations": {
"idle": {
"sheet": "idle.png",
"frameW": 180,
"frameH": 120,
"cols": 21,
"box": {"x": 12, "y": 26, "w": 36, "h": 24},
"loop": true,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 35, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 30, "ms": 50}, {"i": 29, "ms": 50}, {"i": 28, "ms": 50}, {"i": 27, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}]
},
"idle-look": {
"sheet": "idle-look.png",
"frameW": 185,
"frameH": 195,
"cols": 22,
"box": {"x": 11, "y": 11, "w": 37, "h": 39},
"loop": true,
"ms": 3400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}, {"i": 56, "ms": 50}, {"i": 57, "ms": 50}, {"i": 58, "ms": 50}, {"i": 59, "ms": 50}, {"i": 60, "ms": 50}, {"i": 61, "ms": 50}, {"i": 62, "ms": 50}, {"i": 63, "ms": 50}, {"i": 64, "ms": 50}, {"i": 65, "ms": 50}, {"i": 65, "ms": 50}]
},
"idle-spout": {
"sheet": "idle-spout.png",
"frameW": 195,
"frameH": 165,
"cols": 16,
"box": {"x": 8, "y": 17, "w": 39, "h": 33},
"loop": true,
"ms": 3200,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}, {"i": 56, "ms": 50}, {"i": 57, "ms": 50}, {"i": 58, "ms": 50}, {"i": 59, "ms": 50}, {"i": 60, "ms": 50}, {"i": 61, "ms": 50}, {"i": 62, "ms": 50}, {"i": 63, "ms": 50}]
},
"thinking": {
"sheet": "thinking.png",
"frameW": 235,
"frameH": 220,
"cols": 16,
"box": {"x": 0, "y": 6, "w": 47, "h": 44},
"loop": true,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
},
"typing": {
"sheet": "typing.png",
"frameW": 260,
"frameH": 165,
"cols": 12,
"box": {"x": 0, "y": 17, "w": 52, "h": 33},
"loop": true,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
},
"building": {
"sheet": "building.png",
"frameW": 250,
"frameH": 250,
"cols": 15,
"box": {"x": 2, "y": 0, "w": 50, "h": 50},
"loop": true,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 0, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}]
},
"music": {
"sheet": "music.png",
"frameW": 240,
"frameH": 200,
"cols": 16,
"box": {"x": 2, "y": 10, "w": 48, "h": 40},
"loop": true,
"ms": 1600,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}]
},
"conducting": {
"sheet": "conducting.png",
"frameW": 255,
"frameH": 250,
"cols": 16,
"box": {"x": 1, "y": 0, "w": 51, "h": 50},
"loop": true,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
},
"error": {
"sheet": "error.png",
"frameW": 225,
"frameH": 165,
"cols": 16,
"box": {"x": 4, "y": 17, "w": 45, "h": 33},
"loop": true,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
},
"happy": {
"sheet": "happy.png",
"frameW": 260,
"frameH": 225,
"cols": 13,
"box": {"x": 0, "y": 5, "w": 52, "h": 45},
"loop": true,
"ms": 2600,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}]
},
"notification": {
"sheet": "notification.png",
"frameW": 235,
"frameH": 215,
"cols": 16,
"box": {"x": 3, "y": 7, "w": 47, "h": 43},
"loop": true,
"ms": 1600,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}]
},
"compacting": {
"sheet": "compacting.png",
"frameW": 230,
"frameH": 180,
"cols": 14,
"box": {"x": 2, "y": 14, "w": 46, "h": 36},
"loop": true,
"ms": 2800,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}]
},
"carrying": {
"sheet": "carrying.png",
"frameW": 200,
"frameH": 160,
"cols": 18,
"box": {"x": 9, "y": 18, "w": 40, "h": 32},
"loop": true,
"ms": 1600,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 16, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 17, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}]
},
"sleeping": {
"sheet": "sleeping.png",
"frameW": 220,
"frameH": 240,
"cols": 16,
"box": {"x": 2, "y": 2, "w": 44, "h": 48},
"loop": true,
"ms": 3200,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}, {"i": 56, "ms": 50}, {"i": 57, "ms": 50}, {"i": 58, "ms": 50}, {"i": 59, "ms": 50}, {"i": 60, "ms": 50}, {"i": 61, "ms": 50}, {"i": 62, "ms": 50}, {"i": 63, "ms": 50}]
},
"waking": {
"sheet": "waking.png",
"frameW": 220,
"frameH": 230,
"cols": 15,
"box": {"x": 8, "y": 4, "w": 44, "h": 46},
"loop": false,
"ms": 1500,
"frames": [{"i": 0, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}]
},
"roam-hop": {
"sheet": "roam-hop.png",
"frameW": 185,
"frameH": 150,
"cols": 13,
"box": {"x": 10, "y": 20, "w": 37, "h": 30},
"loop": true,
"ms": 1200,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 12, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}]
},
"react-left": {
"sheet": "react-left.png",
"frameW": 250,
"frameH": 170,
"cols": 14,
"box": {"x": 1, "y": 16, "w": 50, "h": 34},
"loop": false,
"ms": 2000,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}]
},
"react-right": {
"sheet": "react-right.png",
"frameW": 220,
"frameH": 170,
"cols": 14,
"box": {"x": 8, "y": 16, "w": 44, "h": 34},
"loop": false,
"ms": 2000,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}]
},
"react-double": {
"sheet": "react-double.png",
"frameW": 215,
"frameH": 165,
"cols": 16,
"box": {"x": 9, "y": 17, "w": 43, "h": 33},
"loop": false,
"ms": 2400,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
},
"react-drag": {
"sheet": "react-drag.png",
"frameW": 205,
"frameH": 230,
"cols": 12,
"box": {"x": 10, "y": 4, "w": 41, "h": 46},
"loop": true,
"ms": 1200,
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}]
}
},
"idlePool": {
"everyMs": {"mean": 120000, "min": 45000, "max": 300000},
"anims": [
{"anim": "idle-look", "ms": 6800, "weight": 1},
{"anim": "idle-spout", "ms": 6400, "weight": 1}
]
},
"states": {
"idle": ["idle"],
"thinking": ["thinking"],
"working": ["typing"],
"juggling": ["music"],
"error": ["error"],
"attention": ["happy"],
"notification": ["notification"],
"sweeping": ["compacting"],
"carrying": ["carrying"],
"sleeping": ["sleeping"],
"waking": ["waking"],
"roam": ["roam-hop"]
},
"bonus": {},
"tiers": {
"working": [{"min": 3, "anim": "building"}, {"min": 2, "anim": "music"}, {"min": 1, "anim": "typing"}],
"juggling": [{"min": 2, "anim": "conducting"}, {"min": 1, "anim": "music"}]
},
"timings": {
"minDisplay": {
"attention": 5200,
"error": 4800,
"sweeping": 5600,
"notification": 3200,
"carrying": 3200,
"working": 1000,
"thinking": 1000
},
"autoReturn": {"attention": 5200, "error": 4800, "sweeping": 300000, "carrying": 3200},
"wakeMs": 1500
},
"reactions": {
"tapLeft": "react-left",
"tapRight": "react-right",
"tickle": "react-double",
"drag": "react-drag"
},
"roam": {"anim": "roam-hop", "faces": "left"},
"sleep": {"afterMs": 60000}
}
+13
View File
@@ -0,0 +1,13 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/state.dart';
void main() {
test('follow-up behavior reads as the first-party default when unknown', () {
expect(AppState.normalizeFollowUp('steer'), 'steer');
// The removed "immediate" mode was wire-identical to steer.
expect(AppState.normalizeFollowUp('immediate'), 'steer');
expect(AppState.normalizeFollowUp('queue'), 'queue');
expect(AppState.normalizeFollowUp(null), 'queue');
expect(AppState.normalizeFollowUp('bogus'), 'queue');
});
}
+47
View File
@@ -0,0 +1,47 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
void main() {
test('an inbox list item parses its text, delivery and files', () {
final item = InboxItem.fromJson({
'id': 'msg_1',
'sessionID': 'ses_1',
'time': {'created': 123},
'type': 'user',
'delivery': 'queue',
'payload': {
'text': 'hello',
'files': [
{'name': 'a.png', 'mime': 'image/png', 'data': 'AAAA'},
],
},
});
expect(item.id, 'msg_1');
expect(item.text, 'hello');
expect(item.delivery, 'queue');
expect(item.created, 123);
expect(item.files.single.name, 'a.png');
});
test('an enqueued event carries the id beside the item', () {
final item = InboxItem.fromEvent(
'msg_2',
{
'type': 'user',
'delivery': 'steer',
'payload': {'text': 'steer me'},
},
456,
);
expect(item.id, 'msg_2');
expect(item.text, 'steer me');
expect(item.delivery, 'steer');
expect(item.created, 456);
});
test('withDelivery keeps the rest', () {
final item = const InboxItem(id: 'm', text: 't', delivery: 'queue');
expect(item.withDelivery('steer').delivery, 'steer');
expect(item.withDelivery('steer').text, 't');
});
}
+109
View File
@@ -0,0 +1,109 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/pairing.dart';
String _link(Map<String, dynamic> payload) =>
'openchamber://connect?v=2&p=${base64Url.encode(utf8.encode(jsonEncode(payload))).replaceAll('=', '')}';
Map<String, dynamic> _payload({
String? expiresAt,
List<Map<String, dynamic>>? candidates,
}) =>
{
'v': 2,
'pairingId': 'pair_123',
'secret': 'secret-abc',
'label': '我的电脑',
if (expiresAt != null) 'expiresAt': expiresAt,
'candidates': candidates ??
[
{'type': 'lan', 'url': 'http://192.168.1.10:3000', 'priority': 10},
{
'type': 'relay',
'relayUrl': 'wss://relay.openchamber.dev/ws',
'serverId': 'server-1',
'hostEncPubJwk': {
'kty': 'EC',
'crv': 'P-256',
'x': 'abc',
'y': 'def',
},
'priority': 30,
},
],
};
void main() {
test('parses a link with direct and relay candidates, direct first', () {
final payload = parsePairingLink(_link(_payload()));
expect(payload, isNotNull);
expect(payload!.pairingId, 'pair_123');
expect(payload.secret, 'secret-abc');
expect(payload.label, '我的电脑');
expect(payload.candidates, hasLength(2));
expect(payload.candidates.first.isRelay, isFalse);
expect(payload.candidates.first.url, 'http://192.168.1.10:3000');
final relay = payload.candidates.last;
expect(relay.isRelay, isTrue);
expect(relay.relayUrl, 'wss://relay.openchamber.dev/ws');
expect(relay.serverId, 'server-1');
expect(relay.hostKey?['x'], 'abc');
});
test('a relay-only link works and keeps the grant', () {
final payload = parsePairingLink(_link(_payload(candidates: [
{
'type': 'relay',
'relayUrl': 'wss://relay.example/ws',
'serverId': 'srv',
'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-256', 'x': 'x', 'y': 'y'},
'grant': 'g-1',
},
])));
expect(payload, isNotNull);
expect(payload!.candidates.single.isRelay, isTrue);
expect(payload.candidates.single.grant, 'g-1');
});
test('a bare base64url payload is accepted too', () {
final encoded =
base64Url.encode(utf8.encode(jsonEncode(_payload()))).replaceAll('=', '');
expect(parsePairingLink(encoded), isNotNull);
});
test('expired and malformed links are refused', () {
final past = DateTime.now()
.subtract(const Duration(minutes: 1))
.toUtc()
.toIso8601String();
expect(parsePairingLink(_link(_payload(expiresAt: past))), isNull);
expect(parsePairingLink('openchamber://connect?v=2&p=not-json'), isNull);
expect(parsePairingLink('https://example.com'), isNull);
// A candidate with a missing key or a bad scheme invalidates the list.
expect(
parsePairingLink(_link(_payload(candidates: [
{
'type': 'relay',
'relayUrl': 'https://relay.example/ws',
'serverId': 'srv',
'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-256', 'x': 'x', 'y': 'y'},
},
]))),
isNull,
);
expect(
parsePairingLink(_link(_payload(candidates: [
{
'type': 'relay',
'relayUrl': 'wss://relay.example/ws',
'serverId': 'srv',
'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-384', 'x': 'x', 'y': 'y'},
},
]))),
isNull,
);
});
}
+33
View File
@@ -0,0 +1,33 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
void main() {
test('a Windows project path reads as its folder name', () {
expect(pathLeaf(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
'pineapple-notepad');
expect(pathLeaf('/home/blumia/Sources/telegram/'), 'telegram');
expect(pathLeaf('relative'), 'relative');
expect(
ProjectInfo(id: 'p', canonical: r'C:\work\pineapple-notepad').label,
'pineapple-notepad',
);
expect(
ProjectInfo(id: 'p', canonical: '/w/x', name: '显式名称').label,
'显式名称',
);
});
test('the same place compares across separators and Windows case', () {
expect(samePath(r'C:\x\y', 'C:/x/y'), isTrue);
expect(samePath(r'C:\X\y', r'c:\x\Y'), isTrue);
expect(samePath('/a/b/', '/a/b'), isTrue);
expect(samePath('/a/b', '/a/c'), isFalse);
// A POSIX path stays case-sensitive.
expect(samePath('/a/B', '/a/b'), isFalse);
});
test('slashPath only unifies separators', () {
expect(slashPath(r'C:\a\b\'), 'C:/a/b');
});
}
+84
View File
@@ -0,0 +1,84 @@
import 'dart:convert';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/pets/pet_library.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('a zip with a nested pack is unpacked and activated', () async {
SharedPreferences.setMockInitialValues({});
final root = await Directory.systemTemp.createTemp('pet-import-');
addTearDown(() async {
await PetLibrary.instance.remove();
if (await root.exists()) await root.delete(recursive: true);
});
final manifest = jsonEncode({
'id': 'test-pet',
'name': '测试宠物',
'canvas': {'w': 8, 'h': 8},
'anchor': {'x': 4, 'baseline': 7},
'animations': {
'idle': {
'sheet': 'idle.png',
'frameW': 40,
'frameH': 40,
'cols': 1,
'loop': true,
'ms': 100,
'box': {'x': 0, 'y': 0, 'w': 8, 'h': 8},
'frames': [
{'i': 0, 'ms': 100},
],
},
},
'states': {
'idle': ['idle'],
},
});
final archive = Archive();
void add(String name, List<int> bytes) =>
archive.addFile(ArchiveFile(name, bytes.length, bytes));
add('pet/pack.json', utf8.encode(manifest));
add('pet/idle.png', [1, 2, 3, 4]);
add('pet/README.md', utf8.encode('ignored? no, kept'));
final bytes = ZipEncoder().encode(archive);
expect(bytes, isNotNull);
final pack = await PetLibrary.instance.importZip(bytes!, root: root);
expect(pack.id, 'test-pet');
expect(pack.name, '测试宠物');
expect(PetLibrary.instance.hasPet, isTrue);
expect(PetLibrary.instance.enabled, isTrue);
final unpacked = Directory('${root.path}/test-pet');
expect(await File('${unpacked.path}/pack.json').exists(), isTrue);
expect(await File('${unpacked.path}/idle.png').exists(), isTrue);
// The nested folder is stripped, not kept as an extra level.
expect(await Directory('${unpacked.path}/pet').exists(), isFalse);
await PetLibrary.instance.remove();
expect(PetLibrary.instance.pack, isNull);
expect(PetLibrary.instance.enabled, isFalse);
expect(await unpacked.exists(), isFalse);
});
test('a zip without pack.json is refused', () async {
final root = await Directory.systemTemp.createTemp('pet-import-bad-');
addTearDown(() async {
if (await root.exists()) await root.delete(recursive: true);
});
final archive = Archive();
final bytes = ZipEncoder().encode(archive)!;
expect(
() => PetLibrary.instance.importZip(bytes, root: root),
throwsA(isA<PetImportException>()),
);
});
}
+122
View File
@@ -0,0 +1,122 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/pets/pet_library.dart';
import 'package:openchamber/pets/pet_pack.dart';
import 'package:openchamber/widgets/pet_sprite.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final library = PetLibrary.instance;
setUp(() async {
SharedPreferences.setMockInitialValues({});
library.pack = PetPack.fromJson(
jsonDecode(File('test/fixtures/deepy-pack.json').readAsStringSync())
as Map<String, dynamic>,
);
library.enabled = true;
library.size = 52;
library.position = 0.5;
});
tearDown(() {
library.pack = null;
library.enabled = false;
library.position = 0.5;
});
/// The chat's shape: a message area with the pet floating over it and the
/// composer below.
Future<int Function()> pumpChat(WidgetTester tester) async {
var taps = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
Expanded(
child: Stack(
children: [
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => taps++,
child: const ColoredBox(color: Color(0xFF101014)),
),
),
const Positioned.fill(child: PetLayer(state: 'idle')),
],
),
),
const SizedBox(height: 80),
],
),
),
),
);
await tester.pump();
return () => taps;
}
testWidgets('the pet floats over the messages and only its body takes taps',
(tester) async {
final taps = await pumpChat(tester);
expect(find.byType(PetSprite), findsOneWidget);
final pet = tester.getCenter(find.byType(PetSprite));
// The transparent part of the layer is not a hit target: the message
// area still receives the tap.
await tester.tapAt(Offset(pet.dx - 160, pet.dy));
await tester.pump();
expect(taps(), 1);
// The body is: tapping it reacts instead of reaching the page.
await tester.tapAt(pet);
await tester.pump();
expect(taps(), 1);
// Nothing reserved in the layout: the message area runs under the pet, so
// the pet's box reaches the composer's top edge.
final layer = tester.getRect(find.byType(PetLayer));
final sprite = tester.getRect(find.byType(PetSprite));
expect(layer.bottom, closeTo(sprite.bottom - 10, 0.5));
expect(sprite.bottom, greaterThanOrEqualTo(layer.bottom));
await tester.pumpWidget(const SizedBox());
});
testWidgets('dragging the pet moves it and keeps the spot', (tester) async {
await pumpChat(tester);
final before = tester.getTopLeft(find.byType(PetSprite)).dx;
await tester.drag(find.byType(PetSprite), const Offset(80, 0));
await tester.pump();
final after = tester.getTopLeft(find.byType(PetSprite)).dx;
expect(after, greaterThan(before + 50));
expect(library.position, greaterThan(0.5));
final prefs = await SharedPreferences.getInstance();
expect(prefs.getDouble('pet.x.v1'), library.position);
await tester.pumpWidget(const SizedBox());
});
testWidgets('nothing is drawn without an imported, enabled pet',
(tester) async {
library.enabled = false;
final taps = await pumpChat(tester);
expect(find.byType(PetSprite), findsNothing);
await tester.tapAt(const Offset(100, 100));
await tester.pump();
expect(taps(), 1);
await tester.pumpWidget(const SizedBox());
});
}
+64
View File
@@ -0,0 +1,64 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/pets/pet_pack.dart';
void main() {
test('the deepy pack parses into canvas, states and animations', () {
final json = jsonDecode(File('test/fixtures/deepy-pack.json').readAsStringSync())
as Map<String, dynamic>;
final pack = PetPack.fromJson(json);
expect(pack.isValid, isTrue);
expect(pack.id, 'deepy-whale');
expect(pack.name, 'Deepy 小鲸鱼');
expect(pack.canvas.width, closeTo(52, 0.001));
expect(pack.canvas.height, closeTo(52, 0.001));
expect(pack.anchor.dy, closeTo(48, 0.001));
expect(pack.animationForState('idle'), 'idle');
expect(pack.animationForState('thinking'), 'thinking');
expect(pack.animationForState('working'), 'typing');
expect(pack.animationForState('attention'), 'happy');
expect(pack.animationForState('missing'), 'idle');
final idle = pack.animation('idle')!;
expect(idle.frames, isNotEmpty);
expect(idle.frames.first.index, 0);
expect(idle.loop, isTrue);
// The frame is the box at the pack's 5x export.
expect(idle.frameW, (idle.box.width * 5).round());
expect(idle.frameH, (idle.box.height * 5).round());
// 52 frames in a 21-column sheet, so the sheet has several rows.
expect(idle.frames.map((f) => f.index).reduce((a, b) => a > b ? a : b),
greaterThan(idle.cols));
expect(pack.reactions['tapLeft'], 'react-left');
expect(pack.reactions['tapRight'], 'react-right');
});
test('frames default to one column when the pack omits the list', () {
final pack = PetPack.fromJson({
'id': 'p',
'canvas': {'w': 8, 'h': 8},
'animations': {
'idle': {
'sheet': 'idle.png',
'frameW': 40,
'frameH': 40,
'cols': 4,
'ms': 400,
'box': {'x': 0, 'y': 0, 'w': 8, 'h': 8},
},
},
'states': {
'idle': ['idle'],
},
});
expect(pack.isValid, isTrue);
final idle = pack.animation('idle')!;
expect(idle.frames.length, 4);
expect(idle.frames.first.ms, 100);
});
}
+93
View File
@@ -0,0 +1,93 @@
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/qr_scan.dart';
import 'package:qr/qr.dart';
/// Renders [data] as a black-on-white luminance image, like a camera frame's
/// Y plane, with a quiet zone and the requested scale.
Uint8List _qrImage(String data, {int scale = 6, int quiet = 4, int pad = 0}) {
final code = QrCode(
payload: QrPayload.fromString(data),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final image = QrImage(code);
final size = (image.moduleCount + quiet * 2) * scale;
final stride = size + pad;
final out = Uint8List(stride * size)..fillRange(0, stride * size, 255);
for (var r = 0; r < image.moduleCount; r++) {
for (var c = 0; c < image.moduleCount; c++) {
if (!image.isDark(r, c)) continue;
final y0 = (r + quiet) * scale;
final x0 = (c + quiet) * scale;
for (var dy = 0; dy < scale; dy++) {
final row = (y0 + dy) * stride;
out.fillRange(row + x0, row + x0 + scale, 0);
}
}
}
return out;
}
void main() {
const link =
'openchamber://connect?v=2&p=eyJ2IjoyLCJwYWlyaW5nSWQiOiJwYWlyX2FiYyJ9';
test('decodes a QR rendered as a camera Y plane', () {
const scale = 6;
const quiet = 4;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final image = _qrImage(link, scale: scale, quiet: quiet);
expect(decodeQrLuminance(image, size, size, size), link);
});
test('a frame can be decoded in a background isolate', () async {
const scale = 6;
const quiet = 4;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final image = _qrImage(link, scale: scale, quiet: quiet);
final text = await compute(
decodeQrFrame,
QrFrame(
luminance: image,
width: size,
height: size,
rowStride: size,
),
);
expect(text, link);
});
test('respects a padded row stride', () {
const scale = 6;
const quiet = 4;
const pad = 12;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final image = _qrImage(link, scale: scale, quiet: quiet, pad: pad);
expect(decodeQrLuminance(image, size, size, size + pad), link);
});
test('a frame without a QR code yields null', () {
final blank = Uint8List(320 * 240)..fillRange(0, 320 * 240, 255);
expect(decodeQrLuminance(blank, 320, 240, 320), isNull);
});
test('short buffers and impossible sizes are refused', () {
expect(decodeQrLuminance(Uint8List(10), 100, 100, 100), isNull);
expect(decodeQrLuminance(Uint8List(100), 0, 10, 10), isNull);
expect(decodeQrLuminance(Uint8List(100), 20, 10, 10), isNull);
});
}
+67
View File
@@ -0,0 +1,67 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/relay_crypto.dart';
Uint8List _bytes(String text) => Uint8List.fromList(utf8.encode(text));
void main() {
test('P-256 JWK round-trips and fingerprints stably', () {
final pair = newRelayKeyPair();
final jwk = publicJwk(pair.publicKey);
expect(jwk['kty'], 'EC');
expect(jwk['crv'], 'P-256');
final imported = importPublicJwk(jwk);
expect(publicJwk(imported), jwk);
expect(jwkFingerprint(jwk), jwkFingerprint(Map<String, dynamic>.from(jwk)));
expect(jwkFingerprint(jwk), isNot(contains('"d"')));
});
test('both sides derive the same directional keys and can talk', () {
final client = newRelayKeyPair();
final host = newRelayKeyPair();
final nonce = randomBytes(16);
final clientKeys = deriveSessionKeys(client.privateKey, host.publicKey, nonce);
final hostKeys = deriveSessionKeys(host.privateKey, client.publicKey, nonce);
expect(clientKeys.clientToHost, hostKeys.clientToHost);
expect(clientKeys.hostToClient, hostKeys.hostToClient);
expect(clientKeys.clientToHost, isNot(clientKeys.hostToClient));
final encryptor = RelayEncryptor(clientKeys.clientToHost);
final decryptor = RelayDecryptor(hostKeys.clientToHost);
final frame = encryptor.encrypt(_bytes('hello over the relay'));
expect(frame.first, encryptedFrameVersion);
expect(utf8.decode(decryptor.decrypt(frame)), 'hello over the relay');
// A second frame works; a replayed counter does not.
final second = encryptor.encrypt(_bytes('hello over the relay'));
expect(utf8.decode(decryptor.decrypt(second)), 'hello over the relay');
expect(() => decryptor.decrypt(second), throwsA(isA<RelayCryptoError>()));
// A different nonce gives different keys.
final otherKeys =
deriveSessionKeys(client.privateKey, host.publicKey, randomBytes(16));
expect(otherKeys.clientToHost, isNot(clientKeys.clientToHost));
});
test('tampered frames fail closed', () {
final a = newRelayKeyPair();
final b = newRelayKeyPair();
final nonce = randomBytes(16);
final keys = deriveSessionKeys(a.privateKey, b.publicKey, nonce);
final frame = RelayEncryptor(keys.clientToHost).encrypt(_bytes('tamper me'));
final bad = Uint8List.fromList(frame)..[frame.length - 1] ^= 0xff;
expect(() => RelayDecryptor(keys.clientToHost).decrypt(bad),
throwsA(isA<RelayCryptoError>()));
});
test('base64url helpers follow the protocol (no padding)', () {
final bytes = Uint8List.fromList([0, 1, 2, 250, 255]);
final encoded = base64UrlEncodeBytes(bytes);
expect(encoded, isNot(contains('=')));
expect(base64UrlDecodeBytes(encoded), bytes);
});
}
+21
View File
@@ -0,0 +1,21 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/screens/servers_screen.dart';
import 'package:openchamber/state.dart';
void main() {
testWidgets('a new server form offers the password field', (tester) async {
final app = AppState();
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: ServersScreen(app: app, startEditing: true),
));
expect(find.text('添加服务器'), findsOneWidget);
// New servers need it too: a password-protected instance rejects the
// first attempt, and there must be somewhere to type the password.
expect(find.text('密码(如果需要)'), findsOneWidget);
expect(find.text('服务器密码;服务器未设置可留空'), findsOneWidget);
});
}
+34
View File
@@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/screens/settings_screen.dart';
import 'package:openchamber/state.dart';
void main() {
testWidgets('settings shows appearance, chat and the pet placeholder',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(home: SettingsScreen(app: app)));
expect(find.text('外观'), findsOneWidget);
expect(find.text('聊天'), findsOneWidget);
expect(find.text('宠物'), findsOneWidget);
expect(find.text('主题模式'), findsOneWidget);
expect(find.text('主题色'), findsOneWidget);
expect(find.text('追问处理行为'), findsOneWidget);
expect(find.text('尚未导入宠物'), findsOneWidget);
expect(find.text('导入宠物包'), findsOneWidget);
// The choice is the server-backed follow-up behavior.
ChoiceChip chip(String label) =>
tester.widget<ChoiceChip>(find.widgetWithText(ChoiceChip, label));
expect(chip('排队').selected, isTrue);
await tester.tap(find.text('转向'));
await tester.pumpAndSettle();
expect(app.followUpBehavior, 'steer');
expect(chip('转向').selected, isTrue);
expect(chip('排队').selected, isFalse);
});
}
+33
View File
@@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/screens/sessions_screen.dart';
import 'package:openchamber/state.dart';
import 'package:openchamber/storage.dart';
void main() {
testWidgets('the sidebar footer names the server and opens settings',
(tester) async {
final app = AppState();
app.conn = Connection(
id: 'c1',
label: '家里的服务器',
url: 'http://127.0.0.1:3000',
);
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: SessionListPane(app: app)),
));
expect(find.text('家里的服务器'), findsOneWidget);
expect(find.byIcon(Icons.dns_outlined), findsOneWidget);
expect(find.byTooltip('设置'), findsOneWidget);
await tester.tap(find.byTooltip('设置'));
await tester.pumpAndSettle();
// The settings page replaced the shell.
expect(find.text('外观'), findsOneWidget);
expect(find.text('聊天'), findsOneWidget);
expect(find.text('宠物'), findsOneWidget);
});
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/screens/sessions_screen.dart';
import 'package:openchamber/state.dart';
void main() {
testWidgets('the project band matches a session row and keeps the keys in line',
(tester) async {
final app = AppState();
final now = DateTime.now().millisecondsSinceEpoch;
app.sessions = [
Session(
id: 's1',
title: '标签页拖拽与分屏',
agent: 'build',
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
created: now,
updated: now,
),
];
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: SessionListPane(app: app)),
));
await tester.pumpAndSettle();
// A Windows path names the folder, not the whole path.
expect(find.text('pineapple-notepad'), findsOneWidget);
final header = find.ancestor(
of: find.text('pineapple-notepad'),
matching: find.byType(ListTile),
);
final row = find.ancestor(
of: find.text('标签页拖拽与分屏'),
matching: find.byType(ListTile),
);
final headerHeight = tester.getSize(header).height;
expect(tester.getSize(row).height, headerHeight);
// Compact, close to the old 56px project band.
expect(headerHeight, lessThanOrEqualTo(58));
// The project's + and the session's ⋮ share one vertical line.
final add = tester.getCenter(find.byTooltip('在此项目新会话'));
final menu = tester.getCenter(find.byIcon(Icons.more_vert));
expect(add.dx, closeTo(menu.dx, 0.5));
});
}
+126
View File
@@ -0,0 +1,126 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/terminal.dart';
import 'package:openchamber/storage.dart';
import 'package:openchamber/terminal_state.dart';
import 'package:shared_preferences/shared_preferences.dart';
ServerTerminal _term(String id,
{String status = 'running',
int createdAt = 0,
String cwd = '/repo',
String purpose = 'terminal'}) =>
ServerTerminal(
sessionId: id,
cwd: cwd,
status: status,
createdAt: createdAt,
purpose: purpose);
SavedTerminalTab _saved(String id, String label) => SavedTerminalTab(id, label);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('planTabs', () {
test('nothing saved and nothing on the server means one new tab', () {
final plans =
TerminalWorkspace.planTabs(saved: const [], server: const []);
expect(plans, hasLength(1));
expect(plans.single.id, isNull);
expect(plans.single.label, '终端 1');
});
test('saved labels stick to the sessions that are still there', () {
final plans = TerminalWorkspace.planTabs(
saved: [_saved('a', '构建'), _saved('b', '日志')],
server: [_term('a', createdAt: 1), _term('b', createdAt: 2)],
);
expect(plans.map((p) => p.id), ['a', 'b']);
expect(plans.map((p) => p.label), ['构建', '日志']);
});
test('a saved session the server no longer has is dropped', () {
final plans = TerminalWorkspace.planTabs(
saved: [_saved('gone', '终端 1'), _saved('alive', '终端 2')],
server: [_term('alive', createdAt: 1)],
);
expect(plans.map((p) => p.id), ['alive']);
expect(plans.single.label, '终端 2');
});
test('sessions opened elsewhere become tabs in creation order', () {
final plans = TerminalWorkspace.planTabs(
saved: const [],
server: [
_term('new', createdAt: 30),
_term('old', createdAt: 10),
_term('mid', createdAt: 20),
_term('action', createdAt: 5, purpose: 'project-action'),
],
);
expect(plans.map((p) => p.id), ['old', 'mid', 'new']);
expect(plans.map((p) => p.label), ['终端 1', '终端 2', '终端 3']);
});
test('a failed listing keeps the saved tabs', () {
final plans = TerminalWorkspace.planTabs(
saved: [_saved('a', '终端 1'), _saved('b', '终端 2')],
server: null,
);
expect(plans.map((p) => p.id), ['a', 'b']);
expect(plans.map((p) => p.label), ['终端 1', '终端 2']);
});
test('a failed listing with nothing saved still opens one tab', () {
final plans = TerminalWorkspace.planTabs(saved: const [], server: null);
expect(plans, hasLength(1));
expect(plans.single.id, isNull);
});
});
group('freeLabel', () {
test('picks the first unused number so a closed tab frees its name', () {
expect(TerminalWorkspace.freeLabel([]), '终端 1');
expect(TerminalWorkspace.freeLabel(['终端 1', '终端 3']), '终端 2');
expect(TerminalWorkspace.freeLabel(['终端 1', '终端 2']), '终端 3');
expect(TerminalWorkspace.freeLabel(['构建']), '终端 1');
});
});
test('terminal tabs are kept per connection and directory', () async {
SharedPreferences.setMockInitialValues({});
final storage = Storage();
expect(await storage.terminalTabs('srv_a', '/repo'), isNull);
await storage.saveTerminalTabs(
'srv_a',
'/repo',
const SavedTerminalTabs(
[SavedTerminalTab('a', '终端 1'), SavedTerminalTab('b', '构建')],
'b',
),
);
final loaded = await storage.terminalTabs('srv_a', '/repo');
expect(loaded, isNotNull);
expect(loaded!.tabs.map((t) => t.id), ['a', 'b']);
expect(loaded.tabs.map((t) => t.label), ['终端 1', '构建']);
expect(loaded.activeId, 'b');
// Another server's directory is a different set.
expect(await storage.terminalTabs('srv_b', '/repo'), isNull);
await storage.clearTerminalTabs('srv_a', '/repo');
expect(await storage.terminalTabs('srv_a', '/repo'), isNull);
});
test('a 0.4.2 single-session value is read as one tab', () async {
SharedPreferences.setMockInitialValues({
'openchamber.terminalSessions.srv_a': '{"\\/repo":"term-1"}',
});
final loaded = await Storage().terminalTabs('srv_a', '/repo');
expect(loaded, isNotNull);
expect(loaded!.tabs.single.id, 'term-1');
expect(loaded.activeId, 'term-1');
});
}
+88
View File
@@ -0,0 +1,88 @@
// Exercises the private relay end to end: parse a pairing link, open the E2EE
// tunnel, redeem the one-time secret, then use the client like the app does
// (HTTP, SSE, terminal WebSocket).
// dart run tool/relay_probe.dart 'openchamber://connect?v=2&p=...'
import 'dart:async';
import 'dart:io';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/pairing.dart';
import 'package:openchamber/api/relay_transport.dart';
import 'package:openchamber/api/terminal.dart';
Future<void> main(List<String> args) async {
if (args.isEmpty) {
print('usage: dart run tool/relay_probe.dart <pairing link>');
return;
}
final payload = parsePairingLink(args.first);
if (payload == null) {
print('invalid pairing link');
return;
}
PairingCandidate? relay;
for (final candidate in payload.candidates) {
if (candidate.isRelay) {
relay = candidate;
break;
}
}
if (relay == null) {
print('link has no relay candidate');
return;
}
print('relay ${relay.relayUrl} server ${relay.serverId}');
final transport = RelayTransport(
relayUrl: relay.relayUrl,
serverId: relay.serverId,
hostKey: relay.hostKey!,
grant: relay.grant,
version: 'probe',
);
final client = Client(Uri.parse('http://relay.invalid'), transport: transport);
try {
final redeemed = await client.redeemPairing(
pairingId: payload.pairingId,
secret: payload.secret,
installId: 'relay-probe',
clientLabel: 'relay probe',
);
print('redeem ${redeemed.token.isEmpty ? 'no token' : 'ok'}: '
'${redeemed.response['server']}');
if (redeemed.token.isEmpty) return;
client.token = redeemed.token;
final status = await client.sessionStatus();
print('session ${status['authenticated']}');
final page = await client.listSessions(limit: 1);
print('sessions ${page.data.length}'
'${page.data.isEmpty ? '' : ' first=${page.data.first.id}'}');
final sse = <String>[];
final sub = client.streamEvents(types: const ['session.created']).listen(
(event) => sse.add('${event['type']}'),
onError: (Object error) => sse.add('error: $error'),
);
final dir = page.data.isNotEmpty
? page.data.first.directory
: Directory.current.path;
final info = await client.createTerminal(cwd: dir, cols: 80, rows: 24);
print('terminal ${info.sessionId}');
final terminal = TerminalSocket(
transport: transport,
headers: client.eventHeaders,
sessionId: info.sessionId,
onEvent: (event) =>
print('terminal event ${event.type} ${event.data.length}'),
onState: (state, {detail}) => print('terminal state $state $detail'),
);
await terminal.connect();
await Future<void>.delayed(const Duration(seconds: 3));
await sub.cancel();
await terminal.dispose();
await client.closeTerminal(info.sessionId, directory: dir);
print('sse ${sse.take(3).toList()}');
} finally {
transport.close();
}
}