Compare commits

...
34 Commits
Author SHA1 Message Date
blumia cecf5517a5 fix: count only OpenChamber projects as known work areas
0.7.3 still showed the pitchfork/Downloads/OpenCode ports because
app.projects also carries every OpenCode project. The web filters against
the OpenChamber project list, so the phone now uses only rows with a
settings record (metaId) plus the current directory; directory-less
announced servers stay visible. The list now matches the web's two entries
(8080 and 9090).

Version 0.7.4+704.
2026-12-04 15:09:52 +08:00
blumia 4bd9256ef8 fix: match the web's dev-server filtering on the phone
The web's "running dev servers" list shows ports that belong to a known
project (the current one included) or arrive without a directory; ports
started outside every project sit behind "show hidden ports". 0.7.2 listed
every port that answered with a page, which showed more servers on the
phone than in the web. The phone now applies the same known-project filter,
so the telegram server on 8080 and the directory-less 9090 both appear.

Version 0.7.3+703.
2026-12-04 14:32:48 +08:00
blumia b372bce63f fix: list every discovered dev server on the phone, like the web
The web client's "running dev servers" list is machine-wide. The phone
filtered it to the current project's directory, which hid servers from
other checkouts (for example the telegram-antispam-bot server on 8080).
The empty state now shows the same set of ports that answered with a web
page, regardless of their project, and still hides the non-web ports the
web client puts behind "show hidden ports".

Version 0.7.2+702.
2026-12-04 13:43:42 +08:00
blumia 695d27cdd7 feat: preview the host's dev servers through the dev tunnel
- loopback dev-server URLs are no longer opened on the phone's network: the
  panel binds a local 127.0.0.1 TCP listener and pipes each connection over
  an authenticated WebSocket to the host's /api/dev-tunnel, which dials its
  own loopback port; the WebView keeps the original address in the bar while
  the page, absolute URLs, cookies and HMR sockets use the tunneled origin
- the empty state lists /api/dev-servers results for the project (only ports
  that answered with a web page), with title, URL and command; tapping one
  opens it through the tunnel
- relay transports mint oc_url_token themselves; a direct connection mints
  and caches /auth/url-token and also sends the bearer
- a new loopback port opened from a tunnelled page gets its own tunnel
- version 0.7.1+701; tests cover the URL mapping and tunnel helpers
2026-12-04 12:21:09 +08:00
blumia 318276d3b9 feat: browser navigation moves into a menu, and a note on the network
- back, forward, open in the system browser and history now live in the
  address bar's three-dot menu; history is a submenu (last 20 URLs, or a
  disabled "no history" row), leaving the URL field wide enough on a phone
- the browser runs on the phone's network: localhost is the phone, not the
  OpenChamber host; the empty state says so and points at the host's LAN
  address for server-side dev servers
- version 0.7.0+700
2026-12-04 09:29:02 +08:00
blumia ce944751b4 feat: a browser page in the right sidebar, and icon tabs
- the right sidebar gains a Browser tab: address bar (back/forward, URL,
  go, stop/reload, open in the system browser), history, quick links for
  localhost:3000/5173/8080, and an embedded WebView on Android/iOS with an
  error bar and retry; desktop shows a mobile-only hint
- Android allows cleartext traffic so local dev servers over HTTP load in
  the WebView
- the tab row is now icons with tooltips (Files, Project knowledge,
  Terminal, Browser), so four tabs fit a phone without truncated labels;
  the tabs are kept alive offstage, so switching away and back keeps the
  browser page and terminal state
- webview_flutter 4.14.1; version 0.6.7+607; tests cover the tab icons and
  the desktop fallback
2026-12-04 02:02:19 +08:00
blumia fedc4dd79c feat: save/share in the picture viewer, and a tap hides its chrome
- the viewer's top bar gains Save to Photos and Share on Android: saving
  writes through MediaStore into Pictures/Chamber Go (no permission on
  Android 10+, a runtime request on older versions), sharing hands a cache
  file to the system chooser through a FileProvider; both are a small
  native channel, not another plugin
- dsh-Go keeps its title bar always visible; here a single tap hides the
  title, keys and page indicator and the next tap brings them back, so they
  do not cover the picture. Double-tap still zooms, swiping still pages at
  1x, dragging pans while zoomed
- version 0.6.6+606; the viewer test now covers the platform calls, chrome
  toggle, zoom, pan and paging
2026-12-01 11:53:54 +08:00
blumia c2dabbe187 feat: a full-screen, zoomable picture viewer
- conversation pictures (user attachments, generated and tool-read images)
  no longer open in a small dialog: a full-screen black viewer shows the
  title and page number, pinch zooms to 8x, double-tap toggles 2.5x around
  the touched point, and a zoomed picture pans by dragging
- multiple pictures in the same message / tool run are one gallery: swipe
  while at 1x, but once zoomed the drag pans and paging is disabled until
  the picture returns to 1x
- mirrors dsh-Go's ImageViewerPage/ImagePager/ZoomableImage behaviour
- version 0.6.5+605; tests cover zoom, pan and paging
2026-12-01 00:59:04 +08:00
blumia 9ae1e9b97a fix: clear a stale relay banner once the connection is back
- resuming from the background can fail the first relay request (DNS not
  ready yet) while a later session read and the event stream work; the
  banner stayed because only the exact "Connection lost, reconnecting…"
  text was ever cleared, and a successful session read did not clear it
- transport errors (connect, session list/search/more, archive, active,
  permissions, chat settings, projects, fs home, models) are now marked as
  such and cleared by any successful read or by an event arriving on the
  restarted stream; a pin/archive action error is left for the next action
- the sidebar Retry now reconnects the stored connection when there is no
  client, otherwise re-reads the session list and clears the stale error
- version 0.6.4+604; tests cover the stale-error clearing and rollback
2026-11-27 18:37:19 +08:00
blumia ba3c820186 feat: the files panel uses the server's gitignored setting
- OpenChamber keeps filesViewShowGitignored in its profile settings (the web
  UI's "Display gitignored files"); the client now reads it in
  refreshChatSettings instead of starting from a local false, so a server
  that shows ignored files shows them here too
- toggling "Show git-ignored files" writes the same key back through
  PUT /api/config/settings (surface=mobile) and reloads the listing; a
  failed save restores the previous value and reports the error
- while the panel is open, a change to the setting from another client
  reloads the list with the new filter
- version 0.6.3+603; tests cover reading, writing and rollback
2026-11-27 17:44:36 +08:00
blumia 8ac36b1fb1 feat: the archive picker offers only projects that hold archived sessions
- the archive page passes its project set to the shared picker, built from
  the archived sessions' directories (deduped and sorted by name), so the
  sheet no longer lists every server project
- the restricted picker hides the add-project action: the archive page never
  archives anything, so adding a project there would be pointless
- the picker gained an optional onlyProjects argument; chat archives remain
  reachable through the Chat row
- version 0.6.2+602
2026-11-27 13:36:11 +08:00
blumia 83e09e8e25 feat: archive filter uses the shared project sheet, with search
- the archive page's horizontal project chips become the same project
  scope row as new-session / scheduled tasks / stats: tapping it opens the
  shared project bottomsheet (all projects, chat, every project with its
  icon, path and checkmark) and filters the archive
- the shared project sheet gains a search field over project name and path,
  so a long project list can be narrowed; it shows "no matching projects"
  when nothing matches
- version 0.6.1+601
- archive test covers filtering through the sheet
2026-11-27 12:14:44 +08:00
blumia a7e4ed8dd7 feat: an archive page, and the sidebar drops archived sessions
- 全部功能 gains an 归档 entry: the new page lists every archived session
  with a count, search over title / id / project, project chips (all plus
  each project with its count), and a row that opens the chat; each row
  restores the session or opens a menu to open, restore, copy the id or
  delete it
- the sidebar's 显示已归档 button and archived list are gone; the sidebar
  now lists only active sessions, while the archive page owns the archived
  ones (matching OpenChamber's archive page)
- version 0.6.0+600
- tests cover the archive list, project chips, search and restore
2026-11-27 11:10:51 +08:00
blumia c6b5a870c6 feat: add a project from the picker, and keep the context ring
- the project picker has an "Add project" action: a folder browser starts
  at the server user's home, navigates (typed path, up, new folder) and
  adds the chosen folder through POST /api/openchamber/directory; the new
  project becomes the draft's target at once
- refreshProjects merges settings-only projects (newest added first), so a
  project added before its first session still appears in the picker; the
  first session moves it into /api/project as usual
- usageReading no longer hides the composer's context ring when the
  session's model has left the server catalog: a 200K window is assumed,
  the percentage is prefixed with "~", and the usage sheet says the window
  is estimated. A failed model fetch at connect is retried when a chat
  opens, so a normal session shows the real percentage
- tests: the add-project browser flow, settings-only projects, and the
  estimated/known context readings
2026-11-27 09:26:14 +08:00
blumia bd8afeb686 fix: give token bars a height so their fills paint
A Row lays a childless ColoredBox out at zero height (the cross axis is
loose), so the token segments in the model bars, the token-composition bar
and the tool success bars painted nothing, while the single-ColoredBox
steps/cost bars worked. Stretching those rows makes the fills visible; the
stats test now asserts a token segment's height, not only its width.
2026-11-26 20:54:03 +08:00
blumia 2e0308f232 fix: keep a token-model bar visible even at a tiny share
- model bars are 8px tall and a nonzero share paints at least 8px, so a
  model that is a fraction of a percent of the report still reads as a
  sliver on the full-width track instead of an empty bar
- an emulator check of the live report showed the shares were correct
  (the top model is 1.0 and renders full width); the many near-zero rows
  came from the real data, where eight of ten models are under a percent
- widget test covers the tokens bar width and the metric grid
2026-11-26 19:56:31 +08:00
blumia b65498d73e feat: stats page, and the client becomes Chamber Go
- 全部功能 gains 统计 (Stats): ranges Today/7/30/90 days/all time, a
  project scope (reusing the shared project sheet, plus "All projects"),
  session/prompt/token/cost/active-days/streak tiles, a daily activity
  chart (weekly past 92 days), token composition, efficiency tiles, model
  ranking by tokens/cost/steps and on-request tool-call stats; data comes
  from /api/experimental/session/stats and the day buckets use the device's
  IANA zone (a small platform channel; desktop falls back to UTC)
- the model bars draw a full-width track with a left-aligned fill, so a
  small token share reads as a sliver instead of an empty bar
- AI token strings read 词元 (not 令牌) in Chinese
- the client's display name is Chamber Go (launcher, iOS, Linux window,
  About), package unchanged; pairing/login labels and the user-agent
  follow, so a newly paired device shows "Chamber Go" on the web client's
  "Connect to this server" list
- bump to 0.5.6
2026-11-26 17:18:09 +08:00
blumia a70e9290ef feat: one project sheet for sessions and scheduled tasks
- the scheduled-task scope dropdown becomes the same project sheet the
  new-session composer opens: Chat row, project icons, paths, the current
  check mark, and one row per checkout
- a filesystem root ("/") no longer reads as a blank row: pathLeaf falls
  back to the path itself instead of an empty last segment
- the sheet opens at once and refreshes the project list behind it; an
  empty list shows "Loading projects…" until the answer arrives, so the
  project chip no longer waits before anything appears
- bump to 0.5.5
2026-11-26 14:00:35 +08:00
blumia 545778c6f3 feat: show real download progress in the files sidebar
- the download dialog starts from the size fs/stat reported, so the bar is
  determinate even when the response has no Content-Length (the relay
  forwards the body chunked); the server's own total wins when it has one
- the line reads "512.0 KB / 20.0 MB (2.5%)": below 10% one decimal
  shows that the transfer is moving
- bump to 0.5.4
2026-11-26 12:46:25 +08:00
blumia 511c3b006b feat: write the UI in English, select only conversation content
- source strings are English again; Chinese comes from lib/l10n/zh.dart
  through tr()/trArgs() and AppText, and a language without a table
  (Spanish, ...) reads English instead of Chinese
- server and user data (titles, messages, file names, notes, task names)
  is drawn with plain Text, so it is never looked up in the table
- SelectionArea moved from the whole message list to the messages, the
  answer text, an opened tool call's details and the turn footer; status
  lines and folded tool rows no longer start a selection
- a message the transcript does not know (its start event was lost while
  the stream was down) fetches the tail once, so a turn continued from
  another client comes in with its prompt
- bump to 0.5.3
2026-11-26 11:48:16 +08:00
blumia 7b5bccf28f feat: English and Chinese, and selectable chat text
- settings → general → language picks system, Chinese or English; the
  choice is stored on the device and read before the first frame
- our Chinese strings are translated through tr()/trArgs() and AppText,
  with the English in lib/l10n/en_*.dart; a missing entry falls back to
  Chinese and a test checks that every literal in lib has one
- AppText rebuilds on a language change (it depends on the resolved
  locale), so const text and whole pages switch at once; the built-in
  date/time pickers and selection menu follow the same language
- server and user data (titles, messages, prompts, paths) is never
  translated
- the chat list sits in a SelectionArea: long-press selects message text
  and shows the copy/select-all menu
- bump to 0.5.2
2026-11-26 09:04:25 +08:00
blumia da4bfb6826 feat: add scheduled tasks behind a 全部功能 button
- the sidebar footer gains 全部功能 left of 设置; its page lists the
  features the server offers, planned tasks for now
- 计划任务 follows the web client: a project (or the chats scope) picked
  at the top, then its tasks with schedule, last result, next run, model
  and error; the switch pauses, the menu runs now, edits or deletes
- the editor covers name, prompt, daily/weekly/once/cron schedules
  (Chinese date and time pickers), several times a day, weekdays, cron
  examples, enabled, and either the session defaults or a fixed model
  and agent
- the same /api/projects/:id/scheduled-tasks endpoints the web uses; a
  server without them says so instead of failing silently
- the app now pins zh_CN localizations, so the built-in pickers and
  menus are Chinese too
- bump to 0.5.1
2026-11-26 00:36:27 +08:00
blumia 2f5ce61692 feat: add the 通用 settings page and rename the group to 常规
- 常规 now holds two pages: 通用 (the agent's tools and what it may know,
  as the web client's General page) and 聊天 (the follow-up behavior)
- 通用 covers diagrams/prototypes, images with their model, secrets,
  notifications, memory with its background tidying (model and thinking
  level), project knowledge and usage limits
- every switch reads and writes /api/config/settings, the same keys the
  web UI uses; keys the server does not store take its defaults
- image models come from /api/model?types=image and the tidying model
  from the chat model list, both chosen in a sheet and clearable
- bump to 0.5.0
2026-11-25 14:30:29 +08:00
blumia 2185054aab feat: split settings into category pages and add an about page
- the settings screen is now an index: 通用 → 聊天, 外观 → 主题 / 宠物,
  帮助与关于 → 关于; each row opens its own page, the controls moved
  there unchanged
- 关于 shows the app version, the server's OpenCode (/api/info) and
  OpenChamber (/api/version) versions with a refresh, and the open-source
  licenses, listed per package with their full text on tap
- the app version is read from the platform at startup
  (package_info_plus), so pubspec.yaml is the only place it is written;
  the pairing/relay handshake now sends it too instead of a constant that
  had drifted
2026-11-25 12:39:48 +08:00
blumia 00564fe94b fix: reconcile the running state when the app returns
A turn that starts or ends while the app is in the background leaves no
event behind, so the activity strip kept its old state (stayed visible
after the turn ended) and the sidebar's running marks went stale too.

- on return, read the server's active set and the transcript tail once
  and settle both the open chat's strip and the sidebar from them
- do the same on the first event after the stream reconnects, since a
  silent drop loses the same events without leaving the app
- opening a chat whose turn is already under way asks once, so the strip
  is right from the first frame
- when the server cannot answer, the tail decides (an assistant message
  without a completion time is a live turn); a failed request is never
  read as "everything is idle"
2026-11-25 00:23:50 +08:00
blumia 9564019a91 fix: match the background task bar to the activity strip
- draw the task bar in the activity strip's capsule (8px margins, 14px
  padding, 36px min height, stadium radius) so the two read as one stack
- drop the stop button from the bar: its padding pushed the clock off the
  right edge shared with the strip above; the row opens the sheet instead
- in the sheet, show only the clock while running, a stop button with a
  stop icon, and "已结束" once the command ends; no "运行中" label and no
  close x (the drag handle and the scrim already close it)
- say "读取输出…" while the first page loads instead of claiming the
  command has printed nothing
- rest the pet's feet on the status capsule's edge (4px top margin)
  instead of sinking 2px into it
2026-11-24 23:19:47 +08:00
blumia c4de5e84d8 feat: watch background commands, open their output and stop them
A command the agent detached keeps running after its tool call returns;
the chat now shows it above the composer: one row per command with its
clock and a stop, folded under "正在执行 N 条命令" when there are
several, with a subagent tag for a child session's command.

Tapping a row opens the live output in a sheet (a page a second from
shell.output, tail kept), following the tail with a way back to the
newest line. The tool row that started it carries a 后台 tag and shows
the same output when expanded, falling back to the completion note once
the shell is gone; a command stopped from the app says so instead of
showing the Shell.NotFoundError it leaves behind.

The list comes from opencode's own shell jobs (experimental/job,
descendants included), so a foreground command never appears, and an
older server falls back to the shell list narrowed by the detached
calls in the transcript. Stopping confirms, removes the shell, and
leaves the model a note that the stop was the user's, as the
first-party client does.

0.4.14 (414).
2026-11-24 19:31:22 +08:00
blumia 809e0a747a feat: show short paths and generated images in the chat
A file tool's row keeps only the part of the path under the session's
directory (lib/screens/chat_screen.dart instead of the whole absolute
path), as the first-party client does, so a phone still shows the file
name; the diff card's file headings drop the same prefix.

A finished openchamber_image call is lifted out of the folded run and
drawn as the picture it saved, in place, as ShownToolCard does through
GeneratedImages: tap opens the full-screen preview, and the card and
preview share an in-memory cache of the bytes.

0.4.13 (413).
2026-11-24 01:05:00 +08:00
blumia 5c0ea6f6f4 docs: note how to run the desktop build for fast UI checks
Records the Linux build command and the stale-instance trap: an old
debug bundle keeps the window, so clicks land on old code and the UI
looks out of date.
2026-11-24 00:14:57 +08:00
blumia d533bc95ef feat: show edit and write tools as line diffs
Expanding an edit, write or patch call now renders the change as tinted
diff lines instead of an old/new text blob: added lines green, removed
lines red, @@ hunk headers marked, and file header noise hidden. The
patch comes from the server's metadata.files[].patch; older servers fall
back to a line diff of the edit's old/new strings, and a write with only
content shows as added lines.

The tool row also shows +N −M for these calls, as dsh-Go does, and a
phone-sized preview stops at 600 lines.

0.4.12 (412).
2026-11-23 22:36:05 +08:00
blumia 0f850b6191 style: align sidebar tree chevrons and give titles more room
The project band no longer adds inner padding, so its folder chevron and +
sit on the same two vertical lines as the session rows' subagent chevron
and ⋮. Every session row now reserves the same 18px chevron column, so a
session without subagents starts its title exactly where a parent does,
and the compact left/right insets leave the title more width.

0.4.11 (411).
2026-11-23 21:37:16 +08:00
blumia 9cbd97d532 feat: fold subagent trees and open them from Agent Task rows
Subagent sessions now render as a collapsed tree in the sidebar: parents with
workers get an expand/collapse chevron, expanded child rows sit behind a guide
line, and the parent keeps its worker count. The parent of the open subagent
expands once so its child is visible.

Subagent tool rows in the parent chat (subagent or task) are labeled 子代理,
show the description and open the child session on tap; a child outside the
loaded page is fetched by id first.

Subagent chats are read-only by default with the first-party notice;
allowPromptingSubagentSessions permits ordinary subagents, while a Lead's
operator-child worker stays read-only until takeover.

0.4.10 (410).
2026-11-23 21:15:18 +08:00
blumia cebf09048e feat: browse subagent sessions nested under their parent
Sessions with a parentID were filtered out of the sidebar, so a subagent's
conversation was unreachable. They now render indented under the session that
started them (robot marker, "子代理 ·" subtitle), the parent shows its worker
count, and tapping one opens its full chat. Opening a parent also fetches its
children with parentID=<id>, so older workers missing from the loaded page
appear.

A subagent's app bar gets a back arrow to its parent session.

Builds now produce a universal APK plus per-ABI arm64/armv7/x86_64 splits; the
packaging preference is kept in project memory.

0.4.9 (409).
2026-11-23 20:35:21 +08:00
blumia 79221e57d7 feat: group the server's chats and use OpenChamber's project icons
Sessions under the server's managed chats root (chats/<date>/session-…) were
grouped per directory, so each one appeared as its own session-xxxxx band.
GET /api/fs/home now supplies the chats root plus its canonical and legacy
aliases; every chat folder becomes the single 聊天 group. The new-session
picker can target 聊天 too: the first send creates a fresh chat directory
before creating the session, and a new session started from an existing chat
gets a new one instead of sharing its folder.

Projects merge their OpenChamber settings row (label, icon key, colour,
iconBackground and uploaded/auto icon image) with /api/project. Group
headers, the picker and the draft chip draw the chosen icon in its colour,
and custom images are fetched through the client transport (SVG included)
with a themed fallback to the glyph. The chat group uses a chat bubble rather
than a folder.

0.4.8 (408).
2026-11-23 17:42:49 +08:00
79 changed files with 14086 additions and 1204 deletions

No files matched your search

+376
View File
@@ -5,6 +5,382 @@
---
## 0.7.4 已知项目只算 OpenChamber 的项目列表(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 列表 | 0.7.3 用 `app.projects` 做过滤,但这个列表同时包含 OpenCode 发现的所有目录(`~/.config/pitchfork`、`~/Downloads` 等),所以那些端口仍被当成「已知项目」显示。现在只把带 OpenChamber 设置记录的项目(`metaId` 非空)加上当前项目当作已知工作区,和网页端的项目列表一致;没有目录的 announced 端口(9090)仍显示。手机列表恢复为网页端看到的 8080、9090 |
| 版本 | **0.7.4(code 704)** |
---
## 0.7.3 开发服务器列表与网页端同一套过滤(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 列表 | 0.7.2 放开了项目目录过滤,结果把 `~/.config/pitchfork`、`~/Downloads` 等不在项目列表里的端口也列了出来(手机 7 个,网页只有 2 个)。现在按网页端的规则:只列出「返回了网页」且目录属于已知项目(含当前目录)或没有目录(announced)的端口;不在任何项目里的端口像网页端一样隐藏在「显示已隐藏端口」之后。Telegram 的 8080 属于已知项目、9090 没有目录,两者都会显示 |
| 版本 | **0.7.3(code 703)** |
---
## 0.7.2 开发服务器列表改为全机器范围(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 列表 | 网页端的「正在运行的开发服务器」是整台宿主机的列表,不按当前项目过滤;手机端之前多了一层「当前项目目录」过滤,导致 `telegram-antispam-bot` 的 8080 在手机上不显示。现在同样列出服务端发现的所有「返回了网页」的端口(无页面的 adb/模拟器端口仍隐藏),与网页端一致 |
| 版本 | **0.7.2(code 702)** |
---
## 0.7.1 浏览器通过服务端 dev tunnel 预览(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 网络 | 不再是手机本机网络:`localhost` / `127.0.0.1` 地址改为在手机本地绑定一个随机端口的 TCP 监听器,每条连接通过 Relay/直连的 WebSocket 连到服务端 `/api/dev-tunnel?port=…&oc_url_token=…`,由服务端连接它自己 loopback 上的 dev server;页面 origin 是本地监听器,绝对路径、Cookie、HMR WebSocket 都按这个 origin 工作 |
| dev server 列表 | 从 `/api/dev-servers` 读取服务端发现且返回了网页的项目 dev server(按当前项目目录过滤,过滤掉 adb/模拟器等没有页面的端口);空状态列出标题 / URL / 命令,点击即可预览;也可以手动输入 URL |
| 地址栏 | 显示原始 `http://localhost:端口/...`,内部加载本地隧道地址;页面里的同源链接会重写到隧道,跳到另一个 loopback 端口会为新端口开隧道;历史记录保存原始地址 |
| 鉴权 | Relay 由 `RelayTransport` 自动 mint `oc_url_token`;直连时客户端 `POST /auth/url-token` 取短期 token 并缓存,WebSocket 同时带 bearer;服务端仍只允许它发现列表里的端口 |
| 版本 | **0.7.1(code 701)** |
---
## 0.7.0 浏览器地址栏菜单与网络说明(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 地址栏 | 后退 / 前进 / 在系统浏览器中打开 / 历史记录收进右上角「三个点」菜单;历史记录是二级菜单(最近 20 条,空时显示「暂无历史记录」)。地址栏只保留网址输入、停止/刷新和菜单,手机宽度下输入区明显变宽 |
| 网络 | 嵌入式 WebView 运行在**手机本机**,`localhost` 是手机而不是 OpenChamber 服务端;OpenChamber 网页端的浏览器面板同样在客户端渲染,服务端没有通用 URL 代理。空状态明确提示:要预览 OpenChamber 主机上的开发服务器,请输入主机的局域网地址(或让服务监听 0.0.0.0) |
| 版本 | **0.7.0(code 700)** |
---
## 0.6.7 右侧栏浏览器与图标标签(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 浏览器 | 右侧栏新增【浏览器】页:地址栏(后退 / 前进 / 输入网址 / 前进按钮 / 停止或刷新)、历史记录、在系统浏览器中打开;空状态提供 `localhost:3000`、`5173`、`8080` 快捷入口;页面用嵌入式 WebView 打开(Android/iOS),桌面显示仅移动端可用的提示 |
| 地址栏 | 自动补 `http://`(localhost/回环地址)或 `https://`,加载错误时显示错误条和重试;地址字段把光标放在末尾,窄栏也能看到刚访问的部分 |
| 标签 | 右侧栏顶部由文字标签改为**图标 + tooltip**(文件、项目知识、终端、浏览器),项目多/栏窄时不再截断文字;四个页签用懒加载的 Offstage 栈保持各自状态(浏览器页面切走再切回不会重新加载) |
| 明文 | Android 允许 WebView 加载 HTTP(`usesCleartextTraffic`),本地开发服务器可直接预览 |
| 版本 | **0.6.7(code 607)** |
---
## 0.6.6 图片查看器:保存/分享与隐藏顶栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 保存/分享 | 查看器右上角新增保存到相册、分享(Android):保存通过 MediaStore 写入 `Pictures/Chamber Go`(Android 10+ 无需权限,旧版本按需申请存储权限),分享用 FileProvider 生成临时文件并打开系统分享面板;非 Android 平台不显示这两个按钮 |
| 顶栏 | dsh-Go 的查看器顶栏(返回、文件名)是**始终显示**的;按你的建议,我们改为单指点击图片切换顶栏和底部页码的显示/隐藏,再点一次恢复,避免标题和按钮挡住图片;双击仍用于 2.5 倍缩放,未放大时左右滑动翻页,放大后单指拖动平移 |
| 版本 | **0.6.6(code 606)** |
---
## 0.6.5 会话图片全屏查看(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 查看器 | 会话内图片(用户附件、工具生成/读取的图片、生成图片)从对话框改为全屏查看:黑底、返回 + 标题 + 页码;双指缩放最大 8 倍,双击在 2.5 倍与原始大小间切换,缩放后可单指拖动查看局部;多张图片可左右滑动 |
| 翻页与拖动 | 未缩放时单指左右滑动翻页;一旦放大,单指拖动用于平移图片,翻页被禁用,缩回原始大小后恢复翻页 |
| 参考 | dsh-Go 的图片查看器就是这种相册式行为(`ImageViewerPage` + `ImagePager` + `ZoomableImage`:双指 8 倍、双击 2.5 倍、缩放时禁用翻页),本次按同样的交互实现 |
| 版本 | **0.6.5(code 605)** |
---
## 0.6.4 Relay 错误横幅在后台恢复后不消失(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 原因 | 从后台恢复时,Relay 隧道第一次请求可能因 DNS/网络尚未就绪失败,`refreshSessions` 把「无法连接 Relay…」写进 `AppState.error`;后续会话列表或事件流成功后没有清除它(事件流只清除固定的「Connection lost, reconnecting…」文案)。侧栏的「重试」只调用 `refreshSessions`,成功也不清错误,所以看起来没有反应,尽管会话、文件和实时更新都已恢复 |
| 修复 | 区分传输错误与会话操作错误:会话列表、搜索、加载更多、归档、活动状态、权限、聊天设置、项目、文件主页、模型等任一成功请求,以及事件流恢复后的任意事件,都会清除传输错误;置顶/归档等动作错误不会被例行刷新清掉。侧栏「重试」改为 `retryConnection()`:没有客户端时重连已保存的连接,否则重新拉取会话列表并清掉过期的传输错误 |
| 版本 | **0.6.4(code 604)** |
---
## 0.6.3 文件侧栏的 gitignore 开关改用服务端值(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 服务端存储 | OpenChamber 的设置文档里有 `filesViewShowGitignored`(profile scope,网页端也用它),没有该键时默认不显示被 git 忽略的文件。客户端现在从 `/api/config/settings` 读取它,不再写死本地默认值 |
| 切换 | 文件侧栏的【显示被 git 忽略的文件】勾选/取消勾选后立即刷新列表,并通过 `PUT /api/config/settings` 写回服务端(`surface=mobile`);保存失败时恢复原值并显示错误 |
| 同步 | 侧栏打开期间如果服务端值变化(例如网页端改了同一设置),监听 `AppState` 后按新值重新加载列表 |
| 版本 | **0.6.3(code 603)** |
---
## 0.6.2 归档选择器只列有归档的项目(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 筛选范围 | 归档页打开的项目选择器只列出**实际有已归档会话**的项目(按名字排序),不再显示全部项目;同时隐藏「添加项目」按钮(归档页不会新增归档,添加项目在此无意义)。聊天归档仍通过「聊天」行进入 |
| 版本 | **0.6.2(code 602)** |
---
## 0.6.1 归档筛选改用共享项目选择器(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 项目筛选 | 归档页顶部原来的横向项目 chips 改为与新建会话 / 计划任务 / 统计一致的项目选择行:点击打开共享项目 bottomsheet(含「所有项目」「聊天」与全部项目、图标、路径、当前选中标记),选完立即筛选归档列表;项目很多时不会再横向挤在一起 |
| 选择器搜索 | 共享项目 bottomsheet 新增搜索框,按项目名或路径过滤,项目很多时也能快速定位;无匹配时显示「没有匹配的项目」 |
| 版本 | **0.6.1(code 601)** |
---
## 0.6.0 归档页面(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 归档页面 | 全部功能新增【归档】:标题下显示已归档会话数量,支持按标题 / 会话 ID / 项目名搜索,顶部按项目分组的 chips 可筛选(全部 + 各项目及数量),点击行打开会话,行尾可取消归档(恢复)或打开菜单(打开 / 取消归档 / 复制会话 ID / 删除)。页面参考 OpenChamber 手机端归档页 |
| 侧栏 | 去掉【显示已归档】按钮和侧栏里的归档列表;侧栏只保留活动会话,归档统一从【全部功能 → 归档】进入 |
| 列表 | 归档会话按归档时间(缺失时按更新时间)倒序;项目分组按最近归档时间排序;取消归档后该行从归档页移回侧栏的活动列表 |
| 版本 | **0.6.0(code 600)** |
---
## 0.5.7 添加项目与上下文环回退(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 添加项目 | 项目选择器右上角新增【添加项目】:从服务器用户主目录开始浏览文件夹(可输入路径、上一级、新建文件夹),选中后写入 OpenChamber 项目列表并立即作为当前目标;新建会话、计划任务、统计的项目列表共享同一入口 |
| 项目列表 | `/api/project` 只在项目里有会话后才返回该项;`refreshProjects` 现在合并设置文档里的项目(按 `addedAt` 新的在前),所以刚添加、还没有会话的项目也能在选择器里出现 |
| 上下文环 | 旧会话的模型可能已从服务器模型目录移除,`usageReading` 找不到上下文窗口时不再隐藏输入框底部的环:按 200K 窗口估算并显示 `~百分比`;用量弹层注明「该模型不在模型目录中,上下文窗口为估算值」 |
| 版本 | **0.5.7(code 507)** |
---
## 0.5.6 统计页面与 Chamber Go(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 统计 | 全部功能里新增【统计】:时间范围(今天 / 7 天 / 30 天 / 90 天 / 全部)、项目筛选(所有项目或某个检出)、会话 / 提示词 / 令牌 / 费用 / 活跃天数 / 连续天数、每日(超过 92 天按周)活动柱状图、令牌构成、效率指标、模型排行(按令牌 / 费用 / 步数)、按需加载的工具调用统计(调用次数、成功率、失败、中位耗时)。数据来自 `/api/experimental/session/stats`;时区取设备的 IANA 名称(Android 平台通道,桌面回退 UTC) |
| 命名 | 客户端显示名改为 **Chamber Go**(Android 启动器、iOS、Linux 窗口、关于页),包名不变。配对兑换上报的 `clientLabel` / `deviceName`、登录标签与请求 user-agent(`chamber-go/<版本>`)一并改名 |
| 名称来源 | 网页端「连接到此服务器」列表显示服务器保存的 client label:操作员建配对链接时填的名字优先;否则沿用同设备(dedupeKey)已有的名字;第一次配对且都没填时才用客户端自报的 `clientLabel` / `deviceName`。因此老设备改名后仍显示旧名,要在列表里重命名,或撤销后重新配对 |
| 版本 | **0.5.6(code 506)** |
---
## 0.5.5 项目选择与计划任务运行位置(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 空白选项 | 服务器会把根目录 `/` 也列成一个项目;`pathLeaf('/')` 取最后一段时得到空串,标签就成了空白。根路径现在用自己的路径作名称(`/`);同一个 checkout 被服务器列两次(项目记录 + sandbox)时也合并成一行 |
| 新建会话 | 点项目名不再先等项目接口:bottomsheet 立即弹出,列表为空时显示「正在加载项目…」,刷新完成(或已有缓存)后展示列表;确实没有项目时显示「没有可用的项目」 |
| 计划任务 | 运行位置改用与新建会话相同的项目 bottomsheet(含「聊天」scope、图标、路径与当前选中标记),不再用长列表下拉框 |
| 版本 | **0.5.5(code 505)** |
---
## 0.5.4 文件下载进度(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 进度 | 下载对话框的进度条改为确定进度:用 `fs/stat` 取到的文件大小当总量,服务器给出 `Content-Length` 时以服务器为准;显示「已下载 / 总大小 (百分比)」。Relay 把响应体按 chunked 转发、不带 `Content-Length` 时也能看到百分比 |
| 取消 | 取消仍然中断请求并丢弃已下载的数据;完全没有大小信息时保持不确定进度条,并显示已下载字节数 |
| 版本 | **0.5.4(code 504)** |
---
## 0.5.3 英文为源、按范围选择文本(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 语言 | 默认跟随系统(中文系统用中文,其它语言用英文),可在 设置 → 常规 → 语言 里固定「中文 / English」;选择保存在本机,启动时先读取再出第一帧,系统语言变化时「跟随系统」会立即重绘 |
| 文案 | 代码里直接写英文;`tr()` / `trArgs()` 查中文表 `lib/l10n/zh.dart`,`AppText` 同理。没有对应表的语言(西班牙语等)按英文显示,缺条目也回退英文,不会出现空文案。服务器与用户数据(会话标题、消息、任务名、文件内容等)用 `Text` 原样显示 |
| 系统组件 | 接入 `flutter_localizations`,日期/时间选择器、文本选择菜单等系统文案随语言切换 |
| 选择文本 | 只有会话内容可选中:消息气泡、回答正文、展开后的工具调用详情(命令/参数/输出)、一轮结束后的「模型 · 模式 · 耗时」行。未展开的工具调用行与「已完成 · X 次工具调用」等状态提示不可选中 |
| 会话同步 | 事件流断开期间开始的回合,其开始事件收不到:收到未知助手消息的事件时先拉取一次尾部,补齐用户消息与完整答复,而不是只拼出后续增量 |
| 测试 | `test/l10n_test.dart`:中文查表与回退、无表的系统语言读英文、`AppText` 跟随语言、代码里每处 `AppText`/`tr`/`trArgs` 字面量都有中文条目 |
| 验证 | 模拟器:系统英文 → 全英文;切中文后整页与系统时间选择器立即变中文,重启保持;切回「跟随系统」;中文与英文下逐页检查;长按消息文本出现选择菜单,长按未展开的工具行与状态提示不再触发选择;断网重连后从网页端继续会话,手机端自动补齐新回合 |
| 版本 | **0.5.3(code 503)** |
---
## 0.5.2 中英双语与长按选择文本(分支 `flutter`,已被 0.5.3 调整)
- 初版:界面文案以中文写在代码里、查英文表;会话消息区整体包进 `SelectionArea`,长按任意位置都能选文本;接入 `flutter_localizations`。
- 0.5.3 起改为英文为源、按范围选择文本,见上。
---
## 0.5.1 计划任务与「全部功能」入口(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 入口 | 侧栏底部、设置按钮左侧新增「全部功能」按钮,打开一个功能页;目前里面只有【计划任务】一张卡片(图标 + 一句说明) |
| 计划任务 | 对照网页端:顶部选择运行位置(已注册项目 + 「聊天」scope,默认取当前会话所在项目),下面列出该项目的任务。每张卡片显示名称、计划、上次运行/状态、下次运行、模型行与错误;开关直接暂停/启用,菜单里可立即运行、编辑、删除;下拉刷新 |
| 编辑器 | 底部弹层:任务名称(≤80)、提示词(≤20000)、计划类型(每天 / 每周 / 一次性 / Cron)、时间点(可加多个)、星期、日期与时间(中文的日期/时间选择器)、Cron 示例、是否启用;默认「使用默认模型与智能体」,关闭后可选模型(复用模型选择器)与智能体 |
| 接口 | `GET/PUT /api/projects/:id/scheduled-tasks`、`DELETE …/:taskId`、`POST …/:taskId/run`,与网页端同一份数据;`openchamber:chats` 作为聊天 scope;服务器没有该接口(404)时页面写明「服务器不支持计划任务」。时间按服务器时区 |
| 中文化 | 应用整体指定中文(`flutter_localizations`),系统自带的日期/时间选择器、文本选择菜单随之是中文 |
| 测试 | 新增 `test/scheduled_tasks_test.dart`:四种计划的解析与展示文案、保存时只带该类型用到的字段、默认模型判断、状态与相对时间、功能页入口、编辑器的必填校验与草稿;`sidebar_footer_test` 覆盖新按钮;95 项全过 |
| 验证 | 模拟器(真实服务端):侧栏「全部功能」→ 计划任务;默认运行位置取当前会话所在项目(聊天目录与 chats 根不出现在项目列表里,统一归到末尾的「聊天」scope)。新建「Daily time report」(每天 09:00)后列表显示「下次:8 小时 45 分钟后」;「立即运行」→ 服务端 `lastStatus: sent` 并新建一个 scheduled 会话,卡片显示「上次运行 00:16 · 成功」;编辑弹层带出原值;关掉开关变「已暂停」;删除 → 确认 → 列表为空、服务端任务为空(运行产生的会话也已删除);切到「聊天」scope 正常加载 |
| 版本 | **0.5.1(code 501)** |
---
## 0.5.0 设置「常规」分组与「通用」页(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 分组 | 原来的【通用】分组改名【常规】,其下第一项新增【通用】页(智能体工具与记忆),第二项仍是【聊天】 |
| 通用页 | 对照网页端的「通用」页补齐:**在聊天中** —— 图表和原型、图像(开启时可选图像模型)、密钥、通知;**智能体知道的内容** —— 记忆(服务端支持时才出现;开启时带「整理记忆」勾选、模型与思考级别)、项目知识、用量限额。每项都有与网页端一致的一句说明 |
| 数据 | 全部走 `/api/config/settings?surface=mobile`,与网页端读写同一份设置;服务器未返回的键用网页端的默认值(图表/密钥/项目知识默认开,图像/通知/记忆/用量/整理记忆默认关),保存后以服务器返回的设置回填 |
| 模型选择 | 图像模型取 `/api/model?types=image`,整理记忆模型取会话的模型列表,都在底部弹层里选;可以清空回「不指定 / 默认模型」;换模型会清空思考级别 |
| 版本 | 版本号改为 **0.5.0(code 500)**,之后按 0.5.x 递增 |
| 测试 | `test/settings_screen_test.dart` 增加「通用」页:分组标题、六个开关与网页端一致的默认值(记忆需要服务端能力才显示);88 项全过 |
| 验证 | 模拟器(真实服务端):常规 → 通用;开关显示服务端当前值(图表关、图像开 + 图像模型 SenseNova U1.5 Lite、密钥开、通知关、记忆开、项目知识开、用量限额关)。开「图表和原型」后服务端 `agentRenderToolEnabled` 变 true;勾「整理记忆」出现模型行(AxonHub::deepseek-flash / 默认);图像模型弹层列出 Grok Imagine 与 SenseNova 并可清空回「不指定」;整理记忆弹层列出会话模型与「默认模型」。验证后把这两项改回原值 |
| 版本 | **0.5.0(code 500)** |
---
## 0.4.17 设置按分组拆页,新增「关于」(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 分组 | 设置页改成索引,对齐 dsh-Go 的组织方式:【通用】聊天;【外观】主题、宠物;【帮助与关于】关于。每行带图标、一句说明与右箭头,点开是独立子页;原来的全部控件搬进各自子页,索引里只留入口 |
| 版本 | 应用版本改为运行时从平台读取(`package_info_plus` 的 `version`;不含 Android build 号,因为 ABI 拆分会给它加一位、四个 APK 各不相同),`pubspec.yaml` 成为唯一出处;配对/relay 握手里的 `appVersion` 也用它,不再有写死的常量(之前还停在 0.4.14) |
| 关于 | 新增「关于」子页:应用图标与名称、版本号、开源许可入口、服务端 OpenCode 版本(`/api/info`)与 OpenChamber 版本(`/api/version`),右上角可重新获取;开源许可按包列出,点开看完整许可证文本(自绘中文页,不用英文的 `LicensePage`);未连接或取不到时明确写「未连接」「未获取到」 |
| 测试 | `test/settings_screen_test.dart` 重写:索引分组、聊天/主题/宠物/关于四个子页、版本与许可入口;87 项全过 |
| 验证 | 模拟器:设置索引三个分组四行;主题页模式/主题色可用;宠物页显示已导入的「Deepy 小鲸鱼」、启用开关与大小;关于页版本「0.4.17」、OpenCode「2.4.0」、OpenChamber「2.8.0」(取自当前服务器),许可页按包列出、点开显示完整许可证文本 |
| 版本 | **0.4.17(code 417)** |
---
## 0.4.16 回到前台后重新对账运行状态(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 会话进行到一半把应用切到后台,期间这一轮结束了:回到前台时对话区会刷新出新内容,但输入框上方的运行状态条还停在切走时的样子(该消失却没消失)。侧栏的运行标记同样只看事件流,漏掉结束事件后也会一直转 |
| 会话状态条 | 回前台时不再只重载转录,还会读一次 `GET /api/session/active`,再按服务器答复重新算「这一轮是否在跑」:在跑就显示、结束就收起。服务器没答上来时退回转录尾部(最新一条 assistant 消息还没有 `completed` 时间就是在跑),不会把一次失败的请求当成「全部空闲」 |
| 侧栏 | 回前台时刷新活动会话集合(`refreshActive`),侧栏的运行标记与后台会话的嵌套标记随之更新;服务器明确答复后才覆盖本地集合,请求失败保留原状态 |
| 事件流重连 | 同一套对账也挂在事件流恢复后的第一个事件上:socket 静默断过(不一定切过后台)而漏掉「这一轮结束」时,状态条和侧栏同样会自愈 |
| 打开会话 | 打开一个已经在中途的会话时也问一次服务器,状态条从第一帧就是对的(以前要等下一批事件才知道在跑) |
| 测试 | 新增 `test/running_state_test.dart`:服务器说空闲/在跑、服务器无答复时按转录尾部判断(有未完成的 assistant 消息算在跑,全部完成则不算);83 项全过 |
| 验证 | 模拟器:另一个会话里跑一轮长命令 → 切到后台 → 等这一轮结束 → 回到前台:状态条不再出现,侧栏该会话的运行标记消失;再验回前台时仍在进行的一轮保持显示 |
| 版本 | **0.4.16(code 416)** |
---
## 0.4.15 后台任务条细节:外观一致、停止移到弹层、宠物站位(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 外观一致 | 后台任务条改为与运行状态胶囊同一套形状:8 边距、14 水平内边距、36 最小高度、Stadium 圆角、相同的文字大小与基线,两条叠在一起时读作一组;多条任务在同一条胶囊里逐行排列 |
| 停止 | 按反馈去掉任务条上的「停止」按钮:它会把右侧对齐从计时挤开,与上方运行条的右端对不齐。现在点任意一行打开弹层,停止与复制都在弹层里(确认框「停止这个任务?」不变) |
| 弹层状态行 | 不再写「运行中」(弹层开着就是在跑,计时已经说明),也没有会让人误以为「点我刷新」的 `sync` 图标:左边只有计时;「停止」改成带方块停止图标的按钮;命令结束后才显示「已结束」 |
| 弹层关闭 | 去掉右侧的 x:拖动把手下滑和点遮罩都能关,x 是多余的 |
| 宠物 | 宠物站在最上方那条胶囊的边沿:有运行条或后台任务条时按它的 4px 上边距收脚,都不在时按输入框的 6px;之前会陷进胶囊顶边 2px |
| 测试 | `test/shell_jobs_test.dart`:任务条不再有「停止」、点行回调打开弹层、计时仍在;80 项全过 |
| 验证 | 模拟器:运行中 + 一条后台任务,两条胶囊等高同圆角;点任务行打开弹层:计时、带图标的「停止」与「复制」、实时输出与跟随,没有「运行中」字样与 x;首次读取时显示「读取输出…」转圈,不会误报「等待输出」;弹层内停止 → 确认 → shell 消失,弹层转为「已结束」并保留最后输出;从弹层头部下滑确实能关闭(x 去掉的前提);宠物在只有运行条、只有任务条、两者都有时都踩在胶囊上沿 |
| 版本 | **0.4.15(code 415)** |
---
## 0.4.14 后台任务:状态条、实时输出与停止(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 状态条 | 输入框上方新增后台任务条(在运行状态胶囊之下):1 条时直接显示命令、计时、`停止`;多条折叠成「正在执行 N 条命令」,默认 N ≤ 3 展开;子代理会话的任务标「子代理」 |
| 输出 | 点状态条任意一行打开底部弹层:完整命令、运行状态与计时、实时输出(1 秒轮询 `GET /api/shell/:id/output`,cursor 续读、尾部 256KB 封顶)、自动跟随与「回到最新」、复制、停止 |
| 工具行 | 起后台命令的 `bash` 行带「后台」标签;展开后显示「后台输出」预览(最后 8 行,仅展开时轮询)+「查看全部」+「停止」 |
| 数据来源 | 首选 `GET /api/experimental/job?sessionID=…&descendants=true&status=running` 里的 `kind=shell`(opencode 自己的后台记录:`shellID`、`command`、`sessionID`、`time.started`,覆盖子会话,不会混入前台命令);老服务端 404 时退回 `GET /api/shell` + 转录里 `{status:running, shellID}` 的标记 |
| 停止 | 确认框「停止这个任务?」→ `DELETE /api/shell/:id` → 向启动它的会话写一条 synthetic 说明(“用户停止了这条后台命令,随后的 Shell.NotFoundError 不是失败,不要因此重跑”,与上游口径一致),然后刷新列表 |
| 结束后 | 命令结束后,工具行与弹层不再轮询,改用会话里 synthetic `<background-result kind="shell" …>` 的最终输出(shell 被删除后仍能看);如果是用户在 App 里停的,显示「用户停止了这条命令。」而不是 Shell.NotFoundError |
| 刷新 | 打开会话立即刷新,之后 3 秒一次;会话消息变化时也刷新(新任务立刻出现);服务端无该接口时停止轮询 |
| 测试 | 新增 `test/shell_jobs_test.dart`:后台标记识别(前台命令不算)、转录/任务/外壳列表解析、输出页、完成说明与停止标记、计时格式、停止说明,以及状态条 1 条/2 条/多条折叠的布局;80 项全过 |
| 验证 | 模拟器(真实任务):`sleep 900` 单条任务条 → 第二条命令变为「正在执行 2 条命令」+ 两条行;弹层实时输出(每秒 tick);弹层内「停止」→ 确认 → 任务与 shell 消失、模型收到 synthetic 停止说明;工具行「后台」标签 + 展开后的最终输出/「用户停止了这条命令。」。后台进程可用前台命令超时后「移到后台」的方式启动(`timeout` 5 秒、不加 background),这样不会像 `background: true` 那样在超时点被 SIGKILL,任务会一直跑到手动停止 |
| 版本 | **0.4.14(code 414)** |
---
## 0.4.13 相对路径与生成图片的行内展示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 路径显示 | 折叠状态下 `read` / `write` / `edit` 等文件工具只显示相对于会话目录的路径(如 `lib/screens/chat_screen.dart`),不再被 `/home/...` 前缀挤掉文件名;会话目录之外的路径(如 `/tmp/...`)仍显示完整路径。diff 展开后的多文件标题同样去前缀 |
| 生成图片 | 对照上游确认:`openchamber_image`(`action=image.generate`,结果 JSON 里 `data.images[].path`)在 `isShownInPlace` 为真时会从 Activity 折叠里**提升**出来,由 `ShownToolCard → GeneratedImages` 在对话中直接显示图片(懒加载、点开画廊、上方有下载)。现在我们也把它从工具运行段里提出来:运行段在它之前结束,图片以卡片形式出现在原位置,最大高度 380,点击打开既有的全屏预览;运行中仍是「正在生成图片」的普通步骤,失败则留在运行段显示错误 |
| 图片缓存 | 卡片与全屏预览共用一份内存缓存(最多 8 张),列表重建不重复请求 `/api/fs/raw` |
| 测试 | 新增 `test/generated_images_test.dart`:结果 JSON 解析多图、未完成/失败/其它工具/非 JSON 不显示,`relativePath` 去前缀、目录外保留、尾斜杠与相似前缀;65 项全过 |
| 版本 | **0.4.13(code 413)** |
---
## 0.4.12 编辑工具的 diff 显示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 展开为 diff | `edit` / `write` / `patch` 等文件修改工具展开后不再显示一整段 old/new 纯文本,而是逐行 diff:新增行绿色底、删除行红色底、`@@` hunk 头浅色标记、`---/+++` 等元信息变灰;长行软换行,整块可选中复制(对齐 dsh-Go / 上游 `ToolPartDiffPreview`) |
| 数据来源 | 优先用服务端 `state.metadata.files[].patch`(可能多文件,按文件显示标题),其次 `metadata.patch` / `metadata.diff`;老服务端没有 patch 时用输入的 `oldString`/`newString` 做行级 LCS,`write` 只有 `content` 时显示为全新增行 |
| 行尾统计 | 工具行右侧显示 `+N −M`(与 dsh-Go 一致),失败/运行中不显示 |
| 大 diff | 最多渲染 600 行,超出显示「仅显示前 600 行,共 N 行」,避免聊天列表一次构建过多行 |
| 结果行 | diff 下方保留一行工具自身结果(如「Edited PLAN.md (1 replacement)」),错误仍用错误色 |
| 测试 | 新增 `test/diff_view_test.dart`:metadata patch 解析与增删计数、无 patch 的 old/new 回退、`write` 内容回退、失败/非文件工具不显示、DiffView 渲染增删行;57 项全过 |
| 验证 | 桌面快速验证:`PATH=$HOME/SDK/flutter/bin:$HOME/SDK/localbin:$PATH CC=clang CXX=clang++ PKG_CONFIG_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu/pkgconfig:$HOME/SDK/linuxdev/usr/share/pkgconfig flutter build linux --release`,然后 `DISPLAY=:99 build/linux/x64/release/bundle/openchamber` + `ffmpeg -f x11grab` 截图。跑之前先 `pkill -f build/linux`:残留的旧 debug 实例会占着窗口,点到的其实是旧代码(界面看着"不是最新版"就是这个原因)。最终效果仍在模拟器上用触摸验证 |
| 版本 | **0.4.12(code 412)** |
---
## 0.4.11 侧栏对齐调整(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 折叠箭头对齐 | 项目分组带内部 contentPadding 归零(外层仍为 8):分组折叠箭头与有子代理会话行的箭头在同一条竖线上 |
| 左右边距 | 会话行左右均为 8;项目带的 + 与会话行的 ⋮ 也都在右侧 8 的同一竖线上,标题可用宽度更大 |
| 标题起点 | 所有顶层会话行都保留固定 18px 的箭头列(无子代理时留空),标题横向起点一致;子代理行缩进 32 并保留竖线 |
| 测试 | 新增「分组箭头/子代理箭头同列、有无子代理的标题同起点」用例;52 项全过 |
| 版本 | **0.4.11(code 411)** |
---
## 0.4.10 子代理树折叠、Agent Task 行与只读输入(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏树 | 子代理行默认折叠:有子代理的父行左侧出现展开/收起箭头(tooltip「展开子代理/收起子代理」),展开后子行缩进并带一条竖线;父行副标题仍显示「N 个子代理」。当前打开的子代理会自动展开它的父行,手动收起后不会被重新展开 |
| Agent Task | 父会话的工具步骤识别 `subagent` / `task`(上游 Agent Task),显示子代理图标和描述;点击整行直接打开对应子会话(`state.metadata.sessionID`,旧结果从 `sessionID: ses_…` 文本解析)。会话不在当前分页时用 `GET /api/session/{id}` 取回 |
| 只读输入 | 普通子代理会话默认只读,底部显示「无法向子智能体会话发送提示。」;服务端 `allowPromptingSubagentSessions` 为 true 时才显示输入框。Lead 的 operator-child(`metadata.openchamber.kind = 'operator-child'`)始终只读,显示「此会话由 Lead 管理,接管后才能继续。」,直到后续实现接管 |
| 返回父会话 | 0.4.9 的父会话返回保留 |
| 测试 | `test/subagent_readonly_test.dart`(默认只读、设置放开、operator-child 即使放开也只读);侧栏测试改为默认折叠→点箭头展开→打开子行;51 项全过 |
| 版本 | **0.4.10(code 410)** |
---
## 0.4.9 浏览子代理会话(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏嵌套 | 子代理会话(`parentID` 指向父会话)不再被过滤掉:父行下面缩进显示一个子代理行(robot 图标,副标题以「子代理 ·」开头),父行的副标题显示「N 个子代理」;父会话在置顶区也带出它的子代理。子代理行可以点开查看完整会话内容,⋮ 菜单与普通会话一致 |
| 按需加载 | 打开父会话时并行请求 `GET /api/session?parentID=<id>`(每个父会话一次),把不在当前分页里的旧子代理补进列表;断开连接时清空缓存 |
| 父会话返回 | 子代理会话的 AppBar 左侧改为返回箭头(tooltip「返回父会话」),标题前有 robot 标记;点击回到父会话。侧栏点父行也能回去 |
| 测试 | `test/sidebar_rows_test.dart` 新增:父子会话同时显示、缩进/robot 图标、「1 个子代理」副标题、点击子行打开该会话;46 项全过 |
| 版本 | **0.4.9(code 409)** |
---
## 0.4.8 项目图标与聊天图标(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 元数据 | `refreshProjects` 同时读 `/api/config/settings?surface=mobile` 的 `projects`,把 label / icon / color / iconBackground / iconImage 按路径合并到 `/api/project` 的条目上(自定义 data dir、Windows 大小写/分隔符都按路径匹配) |
| 项目图标 | 聊天组改用聊天气泡图标;项目组、项目选择器、草稿的项目 chip 统一用 `ProjectIcon`:OpenChamber 的 46 个 icon key 映射到 Material 图标,`color` 支持 hex 与旧主题 key(primary/error/comment/keyword/string/…),无自定义图标时显示对应颜色的图标/文件夹 |
| 自定义图标 | `iconImage` 存在时经 `GET /api/projects/<settingsId>/icon?theme=…&iconColor=…` 取图(带认证,走 Transport/Relay);SVG 用 `flutter_svg` 渲染,PNG/favicon 用 `Image.memory`;有 `iconBackground` 时加圆角底色;加载失败回退字形,按 theme+updatedAt 缓存 |
| 测试 | 现有 46 项全过;模拟器上确认聊天组是气泡、项目组带各自的颜色/图标、选择器与草稿 chip 一致 |
| 版本 | **0.4.8(code 408)** |
---
## 0.4.7 聊天分组与「聊天」新建目标(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 聊天分组 | 连接后读 `GET /api/fs/home` 的 `chatsRoot` / `canonicalChatsRoot` / 旧版 `.config/openchamber/chats`,所有位于这些根下的会话(`chats/<日期>/session-…`)合并成一个「聊天」组;修复此前按目录 leaf 分组、每个聊天各显示成 `session-xxxxx` 的问题。自定义 data dir、Windows 分隔符/盘符大小写都按路径边界匹配 |
| 新建目标 | 新会话的项目选择器新增「聊天」:选择后草稿 chip 显示聊天图标和「聊天」;首次发送时先在 `chatsRoot/YYYY-MM-DD/session-<id>` 建目录(`POST /api/fs/mkdir`),再在该目录创建会话。已有聊天里点新会话会得到一个新的聊天目录,不会复用旧的 |
| 侧栏 | 聊天组的「+」提示「新建聊天」,直接打开以聊天为目标的草稿;项目选择器不再把聊天目录当作项目列出 |
| 测试 | `test/paths_test.dart` 增加聊天根边界(POSIX/Windows、`chats-other` 不误判);`test/sidebar_rows_test.dart` 增加多个聊天目录合并为唯一「聊天」组、不出现 `session-xxxxx` 的断言;本地服务器上用 curl 验证了在 chatsRoot 下 mkdir + 建会话 + 删除 |
| 版本 | **0.4.7(code 407)** |
---
## 0.4.6 扫码无反应的修复与诊断(分支 `flutter`)
| 项 | 结果 |
+23 -6
View File
@@ -1,19 +1,24 @@
# OpenChamber Native
# Chamber Go
A lightweight OpenChamber client for phones, written in **Flutter** (Dart).
Chamber Go is a lightweight OpenChamber client for phones, written in
**Flutter** (Dart).
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.4.6 — servers (passwordless / password login, HTTP/HTTPS and
Status: 0.7.4 — 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,
context usage ring with a detail sheet (an estimated window when the session's
model has left the server catalog), model/agent switching (Build/Plan only,
current one checked), copy / fork / revert, attachments (photos/files, kept
after a reload), the agent's native forms, permissions. The files sidebar also
after a reload), the agent's native forms, permissions. The project picker can
add a folder from the server: it browses from the server user's home, renames
paths and creates folders, and keeps a project that exists only in OpenChamber's
settings (no session yet) in the list. 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
@@ -22,7 +27,19 @@ 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
grouped by project with date captions, pins, archive and swipe actions;
subagent sessions nest under the session that started them (collapsed until
expanded) and open from the sidebar or the parent's Agent Task row; a subagent
chat is read-only unless the server allows prompting subagents; edit, write
and patch calls open as tinted line diffs with +N −M counts and show their
file path relative to the session directory; a finished image-generation call
shows the picture in the conversation instead of folding it away; commands
running in the background get a strip above the composer with their clock and
a stop, and their live output opens from there; the
server's managed chat folders are one 聊天 group, and a new session can target
聊天 instead of a project. Project rows use the icon and colour chosen in
OpenChamber (including an uploaded/auto icon image), and the chat group has a
chat icon. 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
+4
View File
@@ -42,6 +42,10 @@ android {
}
}
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
+17 -2
View File
@@ -2,15 +2,20 @@
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<!-- Saving to the gallery; Android 10+ uses MediaStore without this. -->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<!-- 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:label="Chamber Go"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"
@@ -33,6 +38,16 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Pictures the image viewer shares out of the app's cache. -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
@@ -1,10 +1,32 @@
package net.blumia.openchamber.flutter
import android.Manifest
import android.content.ClipData
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
class MainActivity : FlutterActivity() {
private data class PendingSave(
val bytes: ByteArray,
val name: String,
val mime: String,
val result: MethodChannel.Result,
)
private var pendingSave: PendingSave? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// The app's private files directory, for imported pet packs. A small
@@ -17,5 +39,189 @@ class MainActivity : FlutterActivity() {
else -> result.notImplemented()
}
}
// The statistics API buckets days by an IANA zone; Dart only knows the
// abbreviation, so the platform reports the real id.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/device")
.setMethodCallHandler { call, result ->
when (call.method) {
"ianaTimeZone" -> result.success(java.util.TimeZone.getDefault().id)
else -> result.notImplemented()
}
}
// The right sidebar's browser hands a page to the system browser.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/browser")
.setMethodCallHandler { call, result ->
when (call.method) {
"openUrl" -> {
val url = call.argument<String>("url")
if (url.isNullOrBlank()) {
result.error("bad_args", "Missing URL", null)
return@setMethodCallHandler
}
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
result.success(true)
} catch (e: Exception) {
result.error("open_failed", e.message ?: "Could not open the URL", null)
}
}
else -> result.notImplemented()
}
}
// Saving a conversation picture to the gallery and sharing it: both
// need Android APIs (MediaStore, FileProvider) that a Dart package
// would pull in another native dependency for.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/media")
.setMethodCallHandler { call, result ->
when (call.method) {
"saveImage" -> {
val bytes = call.argument<ByteArray>("bytes")
val name = call.argument<String>("name")
val mime = call.argument<String>("mime") ?: "image/png"
if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) {
result.error("bad_args", "Missing image data", null)
return@setMethodCallHandler
}
saveImage(bytes, name, mime, result)
}
"shareImage" -> {
val bytes = call.argument<ByteArray>("bytes")
val name = call.argument<String>("name")
val mime = call.argument<String>("mime") ?: "image/png"
if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) {
result.error("bad_args", "Missing image data", null)
return@setMethodCallHandler
}
shareImage(bytes, name, mime, result)
}
else -> result.notImplemented()
}
}
}
private fun saveImage(
bytes: ByteArray,
name: String,
mime: String,
result: MethodChannel.Result,
) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED
) {
if (pendingSave != null) {
result.error("busy", "Another picture is being saved", null)
return
}
pendingSave = PendingSave(bytes, name, mime, result)
requestPermissions(
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_SAVE,
)
return
}
writeImage(bytes, name, mime, result)
}
private fun writeImage(
bytes: ByteArray,
name: String,
mime: String,
result: MethodChannel.Result,
) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, name)
put(MediaStore.Images.Media.MIME_TYPE, mime)
put(
MediaStore.Images.Media.RELATIVE_PATH,
"${Environment.DIRECTORY_PICTURES}/Chamber Go",
)
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val collection = MediaStore.Images.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL_PRIMARY,
)
val uri = contentResolver.insert(collection, values)
?: throw IllegalStateException("Could not create the picture")
contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IllegalStateException("Could not open the picture")
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
contentResolver.update(uri, values, null, null)
} else {
@Suppress("DEPRECATION")
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
?: throw IllegalStateException("Could not decode the picture")
@Suppress("DEPRECATION")
val uri = MediaStore.Images.Media.insertImage(
contentResolver, bitmap, name, null,
) ?: throw IllegalStateException("Could not save the picture")
bitmap.recycle()
@Suppress("DEPRECATION")
MediaScannerConnection.scanFile(
this,
arrayOf(Uri.parse(uri).path ?: ""),
arrayOf(mime),
null,
)
}
result.success(true)
} catch (e: Exception) {
result.error("save_failed", e.message ?: "Could not save the picture", null)
}
}
private fun shareImage(
bytes: ByteArray,
name: String,
mime: String,
result: MethodChannel.Result,
) {
try {
val directory = File(cacheDir, "shared_images").apply { mkdirs() }
val file = File(directory, name)
file.writeBytes(bytes)
val uri = FileProvider.getUriForFile(
this, "$packageName.fileprovider", file,
)
val intent = Intent(Intent.ACTION_SEND).apply {
type = mime
putExtra(Intent.EXTRA_STREAM, uri)
clipData = ClipData.newRawUri("image", uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(intent, "Share image"))
result.success(true)
} catch (e: Exception) {
result.error("share_failed", e.message ?: "Could not share the picture", null)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != REQUEST_SAVE) return
val pending = pendingSave ?: return
pendingSave = null
if (grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
writeImage(pending.bytes, pending.name, pending.mime, pending.result)
} else {
pending.result.error(
"permission",
"Storage permission is required to save the picture",
null,
)
}
}
private companion object {
const val REQUEST_SAVE = 701
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!-- Pictures the viewer writes before sharing them. -->
<cache-path name="shared_images" path="shared_images/" />
</paths>
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Openchamber</string>
<string>Chamber Go</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
+260 -5
View File
@@ -8,6 +8,9 @@ import 'dart:typed_data';
import '../version.dart';
import 'models.dart';
import 'scheduled_tasks.dart';
import 'usage_stats.dart';
import 'shells.dart';
import 'terminal.dart';
import 'transport.dart';
@@ -19,6 +22,11 @@ class ApiError implements Exception {
String toString() => message.isEmpty ? 'HTTP $status' : message;
}
/// What the server sees in request headers; the connect page's device name
/// comes from the pairing label below, not from this.
String _userAgent() =>
'chamber-go/${appVersion.isEmpty ? '0.0' : appVersion}';
class Client {
final Uri base;
@@ -53,7 +61,7 @@ class Client {
required String pairingId,
required String secret,
required String installId,
String clientLabel = 'OpenChamber Native',
String clientLabel = 'Chamber Go',
String clientKind = 'mobile',
String? deviceName,
}) async {
@@ -76,7 +84,7 @@ class Client {
}
Future<Map<String, dynamic>> login(String password, String installId,
{String label = 'OpenChamber Native', String clientKind = 'mobile'}) async {
{String label = 'Chamber Go', String clientKind = 'mobile'}) async {
return _json('POST', '/auth/session', body: {
'password': password,
'trustDevice': true,
@@ -95,6 +103,7 @@ class Client {
String? search,
String? directory,
bool? archived,
String? parentID,
}) async {
final query = <String, String>{
'limit': '$limit',
@@ -103,6 +112,7 @@ class Client {
if (search != null && search.isNotEmpty) 'search': search,
if (directory != null && directory.isNotEmpty) 'directory': directory,
if (archived != null) 'archived': '$archived',
if (parentID != null && parentID.isNotEmpty) 'parentID': parentID,
};
final r = await _json('GET', '/api/session', query: query, directory: directory);
final data = (r['data'] as List? ?? [])
@@ -113,6 +123,30 @@ class Client {
next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?);
}
Future<Session> getSession(String id, {String? directory}) async {
final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}',
directory: directory);
return Session.fromJson(r['data'] as Map<String, dynamic>);
}
/// The versions behind the server. Each endpoint is optional: an older
/// server answers neither, and the about page then says it could not tell.
Future<ServerVersions> serverVersions() async {
var opencode = '';
var openchamber = '';
try {
final info = await _json('GET', '/api/info');
final v = info['version'];
if (v is String) opencode = v;
} catch (_) {}
try {
final version = await _json('GET', '/api/version');
final v = version['openchamberVersion'];
if (v is String) openchamber = v;
} catch (_) {}
return ServerVersions(opencode: opencode, openchamber: openchamber);
}
Future<Set<String>> activeSessions() async {
final r = await _json('GET', '/api/session/active');
final data = r['data'] as Map<String, dynamic>? ?? {};
@@ -153,10 +187,101 @@ class Client {
];
}
/// Adds [path] to OpenChamber's project list (its settings document). A
/// project can be added before any session exists in it, so this is the
/// way a new checkout appears in the project picker; [create] also makes
/// the folder. Returns the server's canonical path, which may resolve a
/// symlink or a trailing slash.
Future<String> addProjectDirectory(String path, {bool create = false}) async {
final r = await _json('POST', '/api/openchamber/directory', body: {
'path': path,
'create': create,
});
final resolved = r['path'];
return resolved is String && resolved.trim().isNotEmpty
? resolved.trim()
: path;
}
/// The dev servers the host discovered, for the browser panel's preview
/// list. [directory] scopes the discovery to a space's own listener.
Future<List<DevServerInfo>> devServers({String? directory}) async {
final r = await _json('GET', '/api/dev-servers', directory: directory);
return [
for (final e in (r['servers'] as List? ?? []))
if (e is Map<String, dynamic>) DevServerInfo.fromJson(e),
];
}
/// A short-lived token for WebSocket upgrades that cannot carry the bearer
/// header. The dev tunnel appends it as `oc_url_token`.
Future<({String token, int expiresIn})> mintUrlToken() async {
final r = await _json('POST', '/auth/url-token');
final expires = r['expiresIn'];
return (
token: r['token'] as String? ?? '',
expiresIn: expires is num ? expires.toInt() : 240,
);
}
/// The server's home and chats root. Sessions filed under a chats root are
/// the "聊天" group, not a project; the root can be relocated away from the
/// home config directory, so it must come from the server.
Future<FsHomeInfo> fsHome() async {
final r = await _json('GET', '/api/fs/home');
return FsHomeInfo.fromJson(r);
}
/// The project's chosen/auto icon image. [projectId] is the OpenChamber
/// settings id; SVG icons are recoloured by the server for [theme] and
/// [iconColor].
Future<Uint8List?> projectIconBytes(String projectId,
{String? theme, String? iconColor}) async {
try {
final res = await _request(
'GET', '/api/projects/${Uri.encodeComponent(projectId)}/icon',
query: {
if (theme != null && theme.isNotEmpty) 'theme': theme,
if (iconColor != null && iconColor.isNotEmpty)
'iconColor': iconColor,
});
if (res.statusCode != 200) return null;
final bytes = await res.collect();
return bytes.isEmpty ? null : Uint8List.fromList(bytes);
} catch (_) {
return null;
}
}
Future<void> deleteSession(String id) async {
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
}
/// The session statistics report. [from] is milliseconds since the epoch and
/// omitted for all time; [project] is the OpenCode project id (not the
/// settings row id); [timezone] is an IANA name and decides how the server
/// buckets days. Tool details cost a scan of every message, so they are only
/// read when [tools] is true.
Future<UsageStats> sessionStats({
int? from,
int? to,
String? project,
required String timezone,
bool tools = false,
String? directory,
}) async {
final r = await _json('GET', '/api/experimental/session/stats',
query: {
if (from != null) 'from': '$from',
if (to != null) 'to': '$to',
if (project != null && project.isNotEmpty) 'project': project,
'timezone': timezone,
'tools': tools ? 'detail' : 'none',
},
directory: directory);
return UsageStats.fromJson(r['data'] as Map<String, dynamic>? ?? const {});
}
Future<Page<Message>> listMessages(String id,
{int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async {
final query = <String, String>{
@@ -191,6 +316,18 @@ class Client {
.toList();
}
/// The models that generate or edit images (`types=image`), for the image
/// tool's model choice in 设置 → 通用.
Future<List<ModelInfo>> imageModels(String directory) async {
final r = await _json('GET', '/api/model', query: {
'types': 'image',
if (directory.isNotEmpty) 'location[directory]': directory,
});
return (r['data'] as List? ?? [])
.map((e) => ModelInfo.fromJson(e as Map<String, dynamic>))
.toList();
}
Future<List<AgentInfo>> agents(String directory) async {
final r = await _json('GET', '/api/agent',
query: directory.isNotEmpty ? {'location[directory]': directory} : null);
@@ -255,6 +392,124 @@ class Client {
directory: directory);
}
/// The shells started in [directory], running ones and ones that just
/// exited (the list keeps an exited shell for a while). A background command
/// is one the transcript marks with `{status: running, shellID}`.
Future<List<ShellTask>> listShells({String? directory}) async {
final r = await _json('GET', '/api/shell', directory: directory);
return shellTasksFromList(r);
}
/// The running jobs of a session (and its children with [descendants]):
/// shell commands opencode detached, plus unrelated kinds the caller
/// filters out. Empty on an opencode without the experimental endpoint
/// (404).
Future<List<ShellTask>> listShellJobs(String sessionId,
{bool descendants = true}) async {
final r = await _json('GET', '/api/experimental/job', query: {
'sessionID': sessionId,
if (descendants) 'descendants': 'true',
'status': 'running',
});
return shellTasksFromJobs(r);
}
/// One page of a shell's output. Without [cursor] the server reads from the
/// start; [size] in the answer says how much there is, so the first call can
/// ask again from `size - tail` for a long command.
Future<ShellOutputPage> shellOutput(String shellId,
{int? cursor, int? limit, String? directory}) async {
final query = <String, String>{
if (cursor != null) 'cursor': '$cursor',
if (limit != null) 'limit': '$limit',
};
final r = await _json(
'GET', '/api/shell/${Uri.encodeComponent(shellId)}/output',
query: query.isEmpty ? null : query, directory: directory);
return ShellOutputPage.fromJson(r);
}
/// One shell by id; null when the server no longer knows it (removed).
Future<ShellTask?> shell(String shellId, {String? directory}) async {
try {
final r = await _json(
'GET', '/api/shell/${Uri.encodeComponent(shellId)}',
directory: directory);
return ShellTask.fromWire(r['data']);
} on ApiError catch (e) {
if (e.status == 404) return null;
rethrow;
}
}
/// Stops a background shell (SIGTERM through its pid). The command's
/// completion notice then reports a `Shell.NotFoundError`-like failure, so
/// [syntheticNote] tells the model that the user stopped it.
Future<void> stopShell(String shellId, {String? directory}) async {
await _json('DELETE', '/api/shell/${Uri.encodeComponent(shellId)}',
directory: directory);
}
/// Writes a note into the session without starting a turn: how the model
/// learns that a command was stopped by the user (or anything else the
/// client did), as the first-party client does.
Future<void> syntheticNote(String sessionId,
{required String text,
String? description,
Map<String, dynamic>? metadata,
String? directory}) async {
await _json('POST',
'/api/session/${Uri.encodeComponent(sessionId)}/synthetic',
directory: directory,
body: {
'text': text,
if (description != null) 'description': description,
if (metadata != null) 'metadata': metadata,
'resume': false,
});
}
// ------------------------------------------------------ scheduled tasks
/// The project id the scheduled-tasks API uses for sessions outside any
/// project: the web client's chats scope.
static const scheduledChatsScope = 'openchamber:chats';
static String _scheduledTasksPath(String projectId) =>
'/api/projects/${Uri.encodeComponent(projectId)}/scheduled-tasks';
static List<ScheduledTask> _scheduledTasks(Map<String, dynamic> r) => [
for (final task in r['tasks'] as List? ?? const [])
if (task is Map<String, dynamic>) ScheduledTask.fromJson(task),
];
Future<List<ScheduledTask>> scheduledTasks(String projectId) async =>
_scheduledTasks(await _json('GET', _scheduledTasksPath(projectId)));
/// Creates or replaces [task]; the server answers with the project's tasks.
Future<List<ScheduledTask>> saveScheduledTask(
String projectId, ScheduledTask task) async {
final r = await _json('PUT', _scheduledTasksPath(projectId),
body: {'task': task.toJson()});
return _scheduledTasks(r);
}
Future<List<ScheduledTask>> deleteScheduledTask(
String projectId, String taskId) async {
final r = await _json('DELETE',
'${_scheduledTasksPath(projectId)}/${Uri.encodeComponent(taskId)}');
return _scheduledTasks(r);
}
/// Starts a run now; the run's task (with its new state) comes back.
Future<ScheduledTask?> runScheduledTask(
String projectId, String taskId) async {
final r = await _json('POST',
'${_scheduledTasksPath(projectId)}/${Uri.encodeComponent(taskId)}/run');
final task = r['task'];
return task is Map<String, dynamic> ? ScheduledTask.fromJson(task) : null;
}
/// Moves a waiting prompt between `steer` and `queue`.
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
{String? directory}) async {
@@ -506,7 +761,7 @@ class Client {
headers: {
'accept': 'text/event-stream',
'cache-control': 'no-cache',
'user-agent': 'openchamber-native/0.3',
'user-agent': _userAgent(),
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
},
));
@@ -789,7 +1044,7 @@ class Client {
/// 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',
'user-agent': _userAgent(),
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
};
@@ -846,7 +1101,7 @@ class Client {
bool noCompression = false}) async {
final headers = <String, String>{
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
'user-agent': 'openchamber-native/0.3',
'user-agent': _userAgent(),
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
};
if (directory != null && directory.isNotEmpty) {
+153
View File
@@ -0,0 +1,153 @@
// A loopback TCP listener that carries each accepted connection through the
// OpenChamber host's dev-server tunnel. The WebView loads
// http://127.0.0.1:<localPort>, so a dev server running on the host (its own
// localhost) can be previewed from the phone; the original URL stays in the
// address bar.
import 'dart:async';
import 'dart:io';
import '../state.dart';
import 'transport.dart';
/// True for an address that means "the host running the dev server".
bool isLoopbackDevHost(String host) {
final h = host.trim().toLowerCase();
return h == 'localhost' ||
h == '127.0.0.1' ||
h == '::1' ||
h == '[::1]' ||
h == '0.0.0.0' ||
h == '::';
}
/// The port a dev-server URL names (80/443 when it has none), or null.
int? devServerPort(Uri uri) {
if (!isLoopbackDevHost(uri.host)) return null;
if (uri.hasPort) return uri.port > 0 ? uri.port : null;
return uri.scheme == 'https' ? 443 : 80;
}
/// The URL the WebView loads: the same path on the tunnel's local port.
Uri localTunnelUri(Uri original, int localPort) => original.replace(
scheme: 'http',
host: '127.0.0.1',
port: localPort,
);
/// Maps a URL the WebView reports back to the original host's URL, so the
/// address bar and history show the dev server's address, not the listener's.
String displayUrlFor(String webUrl, int localPort, String displayOrigin) {
final local = 'http://127.0.0.1:$localPort';
if (webUrl == local) return displayOrigin;
if (webUrl.startsWith('$local/')) {
return '$displayOrigin${webUrl.substring(local.length)}';
}
return webUrl;
}
/// A local TCP listener for [remotePort] on the OpenChamber host.
class DevTunnel {
final AppState app;
final int remotePort;
ServerSocket? _server;
final Set<_Pipe> _pipes = {};
bool _closed = false;
DevTunnel(this.app, this.remotePort);
int get localPort => _server?.port ?? 0;
Future<int> start() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
if (_closed) {
await server.close();
return 0;
}
_server = server;
server.listen(_accept);
return server.port;
}
Future<void> _accept(Socket socket) async {
if (_closed) {
socket.destroy();
return;
}
TransportSocket? tunnel;
try {
tunnel = await app.openDevTunnel(remotePort);
} catch (_) {
socket.destroy();
return;
}
if (_closed) {
socket.destroy();
await tunnel.close().catchError((Object _) {});
return;
}
late final _Pipe pipe;
pipe = _Pipe(socket, tunnel, () => _pipes.remove(pipe));
_pipes.add(pipe);
socket.listen(
pipe.toTunnel,
onError: (_) => pipe.close(),
onDone: () => pipe.close(),
);
tunnel.messages.listen(
pipe.toSocket,
onError: (_) => pipe.close(),
onDone: () => pipe.close(),
);
}
Future<void> close() async {
if (_closed) return;
_closed = true;
await _server?.close();
_server = null;
for (final pipe in [..._pipes]) {
await pipe.close();
}
_pipes.clear();
}
}
class _Pipe {
final Socket socket;
final TransportSocket tunnel;
final void Function() onClosed;
bool _closed = false;
_Pipe(this.socket, this.tunnel, this.onClosed);
void toTunnel(List<int> data) {
if (_closed) return;
try {
tunnel.add(data);
} catch (_) {
close();
}
}
void toSocket(List<int> data) {
if (_closed) return;
try {
socket.add(data);
} catch (_) {
close();
}
}
Future<void> close() async {
if (_closed) return;
_closed = true;
try {
socket.destroy();
} catch (_) {}
try {
await tunnel.close();
} catch (_) {}
onClosed();
}
}
+194 -3
View File
@@ -1,6 +1,10 @@
// OpenChamber API models, ported from the Go client's protocol knowledge.
library;
import 'dart:convert';
import '../l10n.dart';
class ModelRef {
final String id;
final String providerId;
@@ -143,6 +147,32 @@ class Session {
);
}
/// The server's home and managed chats roots (`GET /api/fs/home`).
class FsHomeInfo {
final String home;
final String chatsRoot;
final String? canonicalChatsRoot;
final String? canonicalLegacyChatsRoot;
const FsHomeInfo({
required this.home,
required this.chatsRoot,
this.canonicalChatsRoot,
this.canonicalLegacyChatsRoot,
});
factory FsHomeInfo.fromJson(Map<String, dynamic> j) {
String? nonEmpty(Object? value) =>
value is String && value.trim().isNotEmpty ? value.trim() : null;
return FsHomeInfo(
home: nonEmpty(j['home']) ?? '',
chatsRoot: nonEmpty(j['chatsRoot']) ?? '',
canonicalChatsRoot: nonEmpty(j['canonicalChatsRoot']),
canonicalLegacyChatsRoot: nonEmpty(j['canonicalLegacyChatsRoot']),
);
}
}
/// 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 {
@@ -151,11 +181,26 @@ class ProjectInfo {
final String name;
final String vcs;
/// The OpenChamber settings row this project was decorated from. The icon
/// endpoint keys on this id, not the opencode project id.
final String metaId;
final String icon;
final String color;
final String iconBackground;
final String iconImageMime;
final int iconImageUpdatedAt;
const ProjectInfo({
required this.id,
required this.canonical,
this.name = '',
this.vcs = '',
this.metaId = '',
this.icon = '',
this.color = '',
this.iconBackground = '',
this.iconImageMime = '',
this.iconImageUpdatedAt = 0,
});
factory ProjectInfo.fromJson(Map<String, dynamic> j) => ProjectInfo(
@@ -165,6 +210,36 @@ class ProjectInfo {
vcs: j['vcs'] as String? ?? '',
);
bool get hasIconImage => metaId.isNotEmpty && iconImageUpdatedAt > 0;
/// Decorates the opencode project with its OpenChamber settings row: the
/// operator's label, icon key, colour and uploaded/auto icon image.
ProjectInfo withMeta(Map<String, dynamic>? meta) {
if (meta == null) return this;
String text(Object? value) => value is String ? value.trim() : '';
final label = text(meta['label']);
final image = meta['iconImage'];
var mime = '';
var updatedAt = 0;
if (image is Map) {
mime = text(image['mime']);
final updated = image['updatedAt'];
if (updated is num) updatedAt = updated.toInt();
}
return ProjectInfo(
id: id,
canonical: canonical,
name: label.isNotEmpty ? label : name,
vcs: vcs,
metaId: text(meta['id']),
icon: text(meta['icon']),
color: text(meta['color']),
iconBackground: text(meta['iconBackground']),
iconImageMime: mime,
iconImageUpdatedAt: updatedAt,
);
}
String get label {
if (name.trim().isNotEmpty) return name.trim();
return pathLeaf(canonical);
@@ -175,6 +250,9 @@ class ProjectInfo {
/// 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'[/\\]+$'), '');
// A filesystem root ("/", "C:\") has no last segment; its own path is the
// only name left, and an empty one would render a blank row and menu entry.
if (trimmed.isEmpty) return path.trim();
final index = trimmed.lastIndexOf(RegExp(r'[/\\]'));
return index >= 0 ? trimmed.substring(index + 1) : trimmed;
}
@@ -184,6 +262,32 @@ String pathLeaf(String path) {
String slashPath(String path) =>
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), '');
/// A file inside [directory] shown without it: the tool row says
/// `lib/screens/chat_screen.dart`, as the first-party client does, so a phone
/// still sees the part of the path that matters. Paths elsewhere stay whole.
String relativePath(String path, String directory) {
final file = path.trim();
final dir = slashPath(directory.trim());
if (file.isEmpty || dir.isEmpty) return file;
final normalized = slashPath(file);
if (normalized == dir) return '.';
if (normalized.startsWith('$dir/')) return normalized.substring(dir.length + 1);
return file;
}
/// Whether [directory] is [root] or inside it. Separators are unified and a
/// Windows drive path compares case-insensitively, as [samePath] does.
bool isUnderDirectory(String directory, String root) {
final d = slashPath(directory);
final r = slashPath(root);
if (d.isEmpty || r.isEmpty) return false;
final windows = RegExp(r'^[A-Za-z]:').hasMatch(d) ||
RegExp(r'^[A-Za-z]:').hasMatch(r);
final dd = windows ? d.toLowerCase() : d;
final rr = windows ? r.toLowerCase() : r;
return dd == rr || dd.startsWith('$rr/');
}
/// 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) {
@@ -345,6 +449,10 @@ class Message {
final String reason;
/// Compaction messages: the summary the model wrote for the new history.
final String summary;
/// What the server attached to the message: a synthetic note carries why it
/// was written (a stopped shell, a job report), the chat UI reads that.
final Map<String, dynamic>? metadata;
Message({
required this.id,
required this.type,
@@ -362,6 +470,7 @@ class Message {
this.status = '',
this.reason = '',
this.summary = '',
this.metadata,
});
factory Message.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
@@ -390,6 +499,7 @@ class Message {
status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '',
summary: j['summary'] as String? ?? '',
metadata: j['metadata'] as Map<String, dynamic>?,
);
}
String get partText {
@@ -800,9 +910,9 @@ class AgentMemoryEntry {
);
String get typeLabel => switch (type) {
'preference' => '偏好',
'reference' => '参考',
_ => '事实',
'preference' => tr('Preference'),
'reference' => tr('Reference'),
_ => tr('Fact'),
};
}
@@ -950,3 +1060,84 @@ String _jsonString(Object? o) {
if (o is String) return o;
return o.toString();
}
/// The images an `openchamber_image` call saved. The first-party client lifts
/// such a call out of the folded run and shows the pictures in the chat; this
/// reads the call's result envelope (`{ok, action: image.generate, data:
/// {images: [{path}]}}`) to know which files those are.
List<String> generatedImagePaths(ContentPart part) {
const empty = <String>[];
if (part.type != 'tool' || part.name != 'openchamber_image') return empty;
final state = part.state;
if (state == null || state.status != 'completed') return empty;
final text = state.content
.where((c) => c.type == 'text')
.map((c) => c.text)
.join()
.trim();
if (text.isEmpty) return empty;
Object? decoded;
try {
decoded = jsonDecode(text);
} catch (_) {
return empty;
}
if (decoded is! Map) return empty;
if (decoded['ok'] != true || decoded['action'] != 'image.generate') {
return empty;
}
final data = decoded['data'];
if (data is! Map) return empty;
final images = data['images'];
if (images is! List) return empty;
final out = <String>[];
for (final image in images) {
if (image is! Map) continue;
final path = image['path'];
if (path is String && path.trim().isNotEmpty) out.add(path.trim());
}
return out;
}
/// What the server says it runs: OpenCode itself (`/api/info`) and the
/// OpenChamber web layer in front of it (`/api/version`). Either may be
/// empty on older servers.
class ServerVersions {
final String opencode;
final String openchamber;
const ServerVersions({this.opencode = '', this.openchamber = ''});
}
/// A dev server the OpenChamber host discovered (`GET /api/dev-servers`).
/// [url] is the address to preview (usually a loopback URL on the host); the
/// browser tunnels its port through `/api/dev-tunnel`.
class DevServerInfo {
final int port;
final String url;
final String command;
final String directory;
final String title;
const DevServerInfo({
this.port = 0,
this.url = '',
this.command = '',
this.directory = '',
this.title = '',
});
factory DevServerInfo.fromJson(Map<String, dynamic> j) {
final page = j['page'];
return DevServerInfo(
port: (j['port'] as num?)?.toInt() ?? 0,
url: j['url'] as String? ?? '',
command: j['command'] as String? ?? '',
directory: j['directory'] as String? ?? '',
title: page is Map && page['title'] is String
? (page['title'] as String).trim()
: '',
);
}
String get label => title.isNotEmpty ? title : (url.isNotEmpty ? url : ':$port');
}
+6 -3
View File
@@ -3,6 +3,7 @@
import 'dart:async';
import 'dart:convert';
import '../l10n.dart';
import '../version.dart';
import 'relay_tunnel.dart';
import 'transport.dart';
@@ -19,13 +20,15 @@ class RelayTransport implements Transport {
required String serverId,
required Map<String, dynamic> hostKey,
String? grant,
String version = appVersion,
String? version,
}) : _tunnel = RelayTunnel(
relayUrl: relayUrl,
serverId: serverId,
hostKey: hostKey,
grant: grant,
appVersion: version,
// Read at construction: the version is known once the app has
// started, which is after this default would have been fixed.
appVersion: version ?? appVersion,
);
@override
@@ -81,7 +84,7 @@ class RelayTransport implements Transport {
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})');
throw RelayTunnelException(trArgs('Could not get a WebSocket token ({0})', [response.status]));
}
try {
final decoded = jsonDecode(utf8.decode(bytes, allowMalformed: true));
+18 -15
View File
@@ -12,6 +12,7 @@ import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import '../l10n.dart';
import 'relay_crypto.dart';
import 'transport.dart';
@@ -132,11 +133,11 @@ class RelayTunnel {
try {
decoded = jsonDecode(utf8.decode(payload));
} catch (_) {
finish(error: const RelayTunnelException('响应头无效'));
finish(error: RelayTunnelException(tr('Invalid response headers')));
return;
}
if (decoded is! Map) {
finish(error: const RelayTunnelException('响应头无效'));
finish(error: RelayTunnelException(tr('Invalid response headers')));
return;
}
final status = (decoded['status'] as num?)?.toInt() ?? 0;
@@ -161,7 +162,7 @@ class RelayTunnel {
controller.close();
break;
case RelayFrameType.streamAbort:
var reason = '传输被中断';
var reason = tr('Transfer interrupted');
try {
final decoded = jsonDecode(utf8.decode(payload));
if (decoded is Map && decoded['reason'] is String) {
@@ -268,7 +269,7 @@ class RelayTunnel {
ws = await WebSocket.connect(uri.toString(), customClient: _http)
.timeout(_connectTimeout);
} catch (error) {
throw RelayTunnelException('无法连接 Relay:$error');
throw RelayTunnelException(trArgs('Could not connect to the relay: {0}', [error]));
}
final channel = _RelayChannel(ws);
final ready = Completer<void>();
@@ -325,7 +326,7 @@ class RelayTunnel {
deadline?.cancel();
ready.complete();
} catch (error) {
closeWith(RelayTunnelException('密钥协商失败:$error'));
closeWith(RelayTunnelException(trArgs('Key exchange failed: {0}', [error])));
}
}
return;
@@ -333,7 +334,7 @@ class RelayTunnel {
// 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('握手后收到明文帧'));
closeWith(RelayTunnelException(tr('Received a plaintext frame after the handshake')));
return;
}
if (raw is! List<int>) return;
@@ -343,23 +344,24 @@ class RelayTunnel {
final plaintext = channel.decryptor.decrypt(Uint8List.fromList(raw));
channel.handlePlaintext(plaintext);
} catch (error) {
closeWith(RelayTunnelException('解密失败:$error'));
closeWith(RelayTunnelException(trArgs('Decryption failed: {0}', [error])));
}
}
subscription = ws.listen(
onData,
onError: (Object error) => closeWith(RelayTunnelException('Relay 连接出错:$error')),
onError: (Object error) => closeWith(RelayTunnelException(trArgs('Relay connection error: {0}', [error]))),
onDone: () {
if (!finished) {
closeWith(RelayTunnelException(
'Relay 连接已关闭(${ws.closeCode ?? '-'} ${ws.closeReason ?? ''})'));
closeWith(RelayTunnelException(trArgs(
'Relay connection closed ({0} {1})',
[ws.closeCode ?? '-', ws.closeReason ?? ''])));
}
},
cancelOnError: true,
);
channel.onClosed = () =>
closeWith(const RelayTunnelException('Relay 连接已关闭'));
closeWith(RelayTunnelException(tr('Relay connection closed')));
void sendHello() {
if (finished) return;
@@ -371,13 +373,14 @@ class RelayTunnel {
sendHello();
helloTimer = Timer.periodic(const Duration(seconds: 1), (_) => sendHello());
deadline = Timer(_handshakeTimeout, () {
closeWith(const RelayTunnelException('Relay 握手超时'));
closeWith(RelayTunnelException(tr('Relay handshake timed out')));
});
await ready.future;
if (channel.dead) {
throw RelayTunnelException(
'Relay 连接已关闭(${ws.closeCode ?? '-'} ${ws.closeReason ?? ''})');
throw RelayTunnelException(trArgs(
'Relay connection closed ({0} {1})',
[ws.closeCode ?? '-', ws.closeReason ?? '']));
}
channel.startKeepAlive();
return channel;
@@ -601,7 +604,7 @@ class _RelaySocket implements TransportSocket {
_finish();
break;
case RelayFrameType.streamAbort:
_finish(error: const RelayTunnelException('WebSocket 子流被中断'));
_finish(error: RelayTunnelException(tr('WebSocket substream interrupted')));
break;
}
}
+256
View File
@@ -0,0 +1,256 @@
// Scheduled tasks: prompts the server sends on a schedule, into a new session
// or an existing one. The wire shape follows the web client
// (`/api/projects/:projectId/scheduled-tasks`), which reads the same tasks.
import '../l10n.dart';
class ScheduledTask {
final String id;
final String name;
final bool enabled;
/// 'daily' | 'weekly' | 'once' | 'cron'.
final String kind;
/// Daily and weekly: the `HH:mm` times it runs at.
final List<String> times;
/// Weekly: 0 is Sunday, as the server counts.
final List<int> weekdays;
/// Once: `YYYY-MM-DD` and `HH:mm`.
final String date;
final String time;
/// Cron: the expression.
final String cron;
/// IANA name; empty means the server's own zone.
final String timezone;
/// What a run does: the prompt, and whether the session's defaults are used
/// instead of a fixed model and agent.
final String prompt;
final bool useDefaults;
final String providerId;
final String modelId;
final String variant;
final String agent;
/// Sends into this session instead of a new one; empty means a new session.
final String targetSessionId;
final String lastStatus;
final String lastError;
final int lastRunAt;
final int nextRunAt;
final int lastDurationMs;
final String lastSessionId;
const ScheduledTask({
this.id = '',
this.name = '',
this.enabled = true,
this.kind = 'daily',
this.times = const [],
this.weekdays = const [],
this.date = '',
this.time = '',
this.cron = '',
this.timezone = '',
this.prompt = '',
this.useDefaults = true,
this.providerId = '',
this.modelId = '',
this.variant = '',
this.agent = '',
this.targetSessionId = '',
this.lastStatus = '',
this.lastError = '',
this.lastRunAt = 0,
this.nextRunAt = 0,
this.lastDurationMs = 0,
this.lastSessionId = '',
});
factory ScheduledTask.fromJson(Map<String, dynamic> j) {
final schedule = j['schedule'] as Map<String, dynamic>? ?? const {};
final execution = j['execution'] as Map<String, dynamic>? ?? const {};
final state = j['state'] as Map<String, dynamic>? ?? const {};
String text(Object? value) => value is String ? value : '';
int number(Object? value) => (value is num) ? value.toInt() : 0;
return ScheduledTask(
id: text(j['id']),
name: text(j['name']),
enabled: j['enabled'] != false,
kind: text(schedule['kind']),
times: [
for (final value in schedule['times'] as List? ?? const [])
if (value is String) value,
],
weekdays: [
for (final value in schedule['weekdays'] as List? ?? const [])
if (value is num) value.toInt(),
],
date: text(schedule['date']),
time: text(schedule['time']),
cron: text(schedule['cron']),
timezone: text(schedule['timezone']),
prompt: text(execution['prompt']),
// The web client treats a task without a fixed model as using the
// session's defaults, whatever the flag says.
useDefaults: execution['useDefaults'] == true || text(execution['modelID']).isEmpty,
providerId: text(execution['providerID']),
modelId: text(execution['modelID']),
variant: text(execution['variant']),
agent: text(execution['agent']),
targetSessionId: text(j['targetSessionId']),
lastStatus: text(state['lastStatus']),
lastError: text(state['lastError']),
lastRunAt: number(state['lastRunAt']),
nextRunAt: number(state['nextRunAt']),
lastDurationMs: number(state['lastDurationMs']),
lastSessionId: text(state['lastSessionId']),
);
}
/// What the server is sent on save. State is the server's own; a task keeps
/// it unless it is deliberately replaced.
Map<String, dynamic> toJson() => {
if (id.isNotEmpty) 'id': id,
'name': name,
'enabled': enabled,
'schedule': {
'kind': kind,
if (kind == 'daily' || kind == 'weekly') 'times': times,
if (kind == 'weekly') 'weekdays': weekdays,
if (kind == 'once') ...{'date': date, 'time': time},
if (kind == 'cron') 'cron': cron,
if (timezone.isNotEmpty) 'timezone': timezone,
},
'execution': {
'prompt': prompt,
'useDefaults': useDefaults,
if (!useDefaults && providerId.isNotEmpty) 'providerID': providerId,
if (!useDefaults && modelId.isNotEmpty) 'modelID': modelId,
if (!useDefaults && variant.isNotEmpty) 'variant': variant,
if (!useDefaults && agent.isNotEmpty) 'agent': agent,
},
if (targetSessionId.isNotEmpty) 'targetSessionId': targetSessionId,
};
ScheduledTask copyWith({bool? enabled}) => ScheduledTask(
id: id,
name: name,
enabled: enabled ?? this.enabled,
kind: kind,
times: times,
weekdays: weekdays,
date: date,
time: time,
cron: cron,
timezone: timezone,
prompt: prompt,
useDefaults: useDefaults,
providerId: providerId,
modelId: modelId,
variant: variant,
agent: agent,
targetSessionId: targetSessionId,
lastStatus: lastStatus,
lastError: lastError,
lastRunAt: lastRunAt,
nextRunAt: nextRunAt,
lastDurationMs: lastDurationMs,
lastSessionId: lastSessionId,
);
/// The model line: a fixed choice, or that the run uses the session's.
String get modelLabel {
if (useDefaults || modelId.isEmpty) return tr('Use default model and agent');
final model = [providerId, modelId].where((s) => s.isNotEmpty).join('/');
return agent.isEmpty ? model : '$model · $agent';
}
}
const scheduledWeekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const scheduledTaskKindLabels = {
'daily': 'Daily',
'weekly': 'Weekly',
'once': 'Once',
'cron': 'Cron',
};
/// '每天 09:00', '每周 周一、周三 09:00', '一次性 2026-12-01 09:00', …
String scheduledScheduleText(ScheduledTask task) {
final separator = tr(', ');
final times = task.times.isEmpty ? task.time : task.times.join(separator);
switch (task.kind) {
case 'daily':
return trArgs('Daily {0}', [times.isEmpty ? '--:--' : times]);
case 'weekly':
final days = [
for (final day in task.weekdays)
if (day >= 0 && day < scheduledWeekdays.length)
tr(scheduledWeekdays[day]),
].join(separator);
return trArgs('Weekly {0} {1}', [
days.isEmpty ? tr('no days') : days,
times.isEmpty ? '--:--' : times,
]);
case 'once':
return trArgs('Once {0} {1}', [
task.date.isEmpty ? tr('no date') : task.date,
task.time.isEmpty ? '--:--' : task.time,
]);
case 'cron':
return trArgs('Cron: {0}', [task.cron]);
}
return '';
}
String scheduledStatusLabel(String status) => switch (status) {
'success' || 'sent' => tr('Success'),
'error' || 'failed' => tr('Error'),
'running' => tr('Running'),
'queued' => tr('Queued'),
'skipped' => tr('Skipped'),
'cancelled' => tr('Cancelled'),
_ => tr('Idle'),
};
/// How far away a moment is, in the words the web client uses.
String scheduledRelativeTime(int milliseconds) {
if (milliseconds <= 0) return '';
final diff = milliseconds - DateTime.now().millisecondsSinceEpoch;
final abs = diff.abs();
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
final future = diff >= 0;
if (abs < minute) return future ? tr('In less than a minute') : tr('Just now');
if (abs < hour) {
final m = (abs / minute).round();
return future
? trArgs('In {0} min', [m])
: trArgs('{0} min ago', [m]);
}
if (abs < day) {
final h = abs ~/ hour;
final m = ((abs % hour) / minute).round();
final body =
m > 0 ? trArgs('{0} hr {1} min', [h, m]) : trArgs('{0} hr', [h]);
return future ? trArgs('In {0}', [body]) : trArgs('{0} ago', [body]);
}
final d = abs ~/ day;
final h = ((abs % day) / hour).round();
final body = h > 0 ? trArgs('{0} days {1} hr', [d, h]) : trArgs('{0} days', [d]);
return future ? trArgs('In {0}', [body]) : trArgs('{0} ago', [body]);
}
String scheduledClock(int milliseconds) {
if (milliseconds <= 0) return '';
final at = DateTime.fromMillisecondsSinceEpoch(milliseconds);
String two(int n) => n.toString().padLeft(2, '0');
return '${two(at.hour)}:${two(at.minute)}';
}
+253
View File
@@ -0,0 +1,253 @@
// Background commands of a session (opencode's shells), as the first-party
// client shows them above the composer: the command, how long it has been
// running, and a way to stop it.
import '../l10n.dart';
import 'models.dart';
/// One running (or just ended) shell. `id` is the shell id opencode created
/// (`shellID` on a job); the tool call that detached it carries the same id.
class ShellTask {
final String id;
/// The session that started it (a subagent has its own).
final String sessionId;
final String command;
/// Epoch milliseconds.
final int startedAt;
final bool running;
const ShellTask({
required this.id,
required this.sessionId,
required this.command,
required this.startedAt,
this.running = true,
});
ShellTask copyWith({
String? command,
int? startedAt,
bool? running,
String? sessionId,
}) =>
ShellTask(
id: id,
sessionId: sessionId ?? this.sessionId,
command: command ?? this.command,
startedAt: startedAt ?? this.startedAt,
running: running ?? this.running,
);
static ShellTask? fromWire(Object? raw) {
if (raw is! Map) return null;
final id = raw['id'];
if (id is! String || id.isEmpty) return null;
final metadata = raw['metadata'];
final owner = metadata is Map ? metadata['sessionID'] : null;
final time = raw['time'];
final started = time is Map ? time['started'] : null;
return ShellTask(
id: id,
sessionId: owner is String ? owner : '',
command: (raw['command'] as String?) ?? '',
startedAt: (started as num?)?.toInt() ?? 0,
running: (raw['status'] as String?) == 'running',
);
}
/// One entry of `GET /api/experimental/job` when it is a shell job: its
/// `shellID` is the id the output and stop calls take.
static ShellTask? fromJob(Object? raw) {
if (raw is! Map || raw['kind'] != 'shell') return null;
final shellId = raw['shellID'];
if (shellId is! String || shellId.isEmpty) return null;
final time = raw['time'];
final started = time is Map ? time['started'] : null;
return ShellTask(
id: shellId,
sessionId: (raw['sessionID'] as String?) ?? '',
command: (raw['command'] as String?) ?? '',
startedAt: (started as num?)?.toInt() ?? 0,
running: (raw['status'] as String?) == 'running',
);
}
}
/// The session's shells from `GET /api/shell`, running ones first as the
/// wire lists them. Shells that already exited stay in the answer (status
/// `exited`), so callers filter on [ShellTask.running].
List<ShellTask> shellTasksFromList(Map<String, dynamic> body) {
final data = body['data'];
if (data is! List) return const [];
return [
for (final raw in data) ?ShellTask.fromWire(raw),
];
}
/// The running shell jobs of `GET /api/experimental/job`: opencode's own
/// record of what it detached (a `bash` call that returned while the command
/// kept going). Unlike the transcript this also covers subagent sessions, and
/// it never contains a foreground command.
List<ShellTask> shellTasksFromJobs(Map<String, dynamic> body) {
final data = body['data'];
if (data is! List) return const [];
final out = <ShellTask>[];
for (final raw in data) {
final task = ShellTask.fromJob(raw);
if (task != null && task.running) out.add(task);
}
return out;
}
/// One page of a shell's output (`GET /api/shell/:id/output`): the text read
/// from [cursor], the cursor after it, and the total size so a first read can
/// start near the tail instead of the beginning.
class ShellOutputPage {
final String output;
final int cursor;
final int size;
/// The server cut this page (the requested span was larger than it serves
/// at once); the next read continues from [cursor].
final bool truncated;
const ShellOutputPage({
this.output = '',
this.cursor = 0,
this.size = 0,
this.truncated = false,
});
static ShellOutputPage fromJson(Map<String, dynamic> body) {
final data = body['data'];
if (data is! Map) return const ShellOutputPage();
return ShellOutputPage(
output: (data['output'] as String?) ?? '',
cursor: (data['cursor'] as num?)?.toInt() ?? 0,
size: (data['size'] as num?)?.toInt() ?? 0,
truncated: data['truncated'] == true,
);
}
}
/// A finished background command's report: the synthetic message opencode
/// writes into the session when the job ends (`<background-result …>`), which
/// also holds the output after the shell itself is gone.
class ShellCompletionNote {
final String shellId;
final String state;
final String output;
const ShellCompletionNote({
required this.shellId,
required this.state,
required this.output,
});
bool get failed => state == 'error' || state == 'cancelled';
}
final _backgroundResult = RegExp(
r'<background-result\b([^>]*)>([\s\S]*?)</background-result>');
/// The completion a synthetic message carries, or null for other notes.
ShellCompletionNote? shellCompletionNote(Message message) {
if (message.type != 'synthetic') return null;
final match = _backgroundResult.firstMatch(message.text);
if (match == null) return null;
final attrs = match.group(1) ?? '';
if (!attrs.contains('kind="shell"')) return null;
final id = RegExp(r'id="([^"]+)"').firstMatch(attrs)?.group(1);
if (id == null || id.isEmpty) return null;
final state =
RegExp(r'state="([^"]+)"').firstMatch(attrs)?.group(1) ?? '';
var output = match.group(2) ?? '';
if (output.startsWith('\n')) output = output.substring(1);
return ShellCompletionNote(
shellId: id, state: state, output: output.trimRight());
}
/// The newest completion note for [shellId], if the command has finished.
ShellCompletionNote? shellCompletionFor(
Iterable<Message> messages, String shellId) {
ShellCompletionNote? found;
for (final message in messages) {
final note = shellCompletionNote(message);
if (note != null && note.shellId == shellId) found = note;
}
return found;
}
/// Whether the app itself stopped [shellId]: the note it writes into the
/// session carries `metadata.openchamber.shellStop.shellIDs`.
bool shellWasStopped(Iterable<Message> messages, String shellId) {
for (final message in messages) {
if (message.type != 'synthetic') continue;
final openchamber = message.metadata?['openchamber'];
if (openchamber is! Map) continue;
final stop = openchamber['shellStop'];
if (stop is! Map) continue;
final ids = stop['shellIDs'];
if (ids is List && ids.contains(shellId)) return true;
}
return false;
}
/// The shell id a *background* tool call detached, if this part is one. A
/// foreground command keeps `status: running` on the tool part itself; the
/// detached one is completed and its metadata says the shell still runs:
/// `{status: 'running', shellID: 'sh_…'}`, as the first-party client reads it.
String? backgroundShellId(ContentPart part) {
if (part.type != 'tool') return null;
const shells = {'bash', 'shell', 'pwsh', 'execute'};
if (!shells.contains(part.name ?? '')) return null;
final state = part.state;
if (state == null || state.status != 'completed') return null;
final metadata = state.metadata;
if (metadata == null || metadata['status'] != 'running') return null;
final id = metadata['shellID'];
return id is String && id.isNotEmpty ? id : null;
}
/// A running background command is completed in the transcript (the call
/// returned at once) but still going; that is what the strip lists.
List<ShellTask> backgroundShellsFromMessages(
Iterable<Message> messages, String sessionId) {
final out = <ShellTask>[];
final seen = <String>{};
for (final message in messages) {
for (final part in message.content) {
final id = backgroundShellId(part);
if (id == null || !seen.add(id)) continue;
final input = part.state?.input ?? const <String, dynamic>{};
out.add(ShellTask(
id: id,
sessionId: sessionId,
command: '${input['command'] ?? ''}'.trim(),
startedAt: message.created,
));
}
}
return out;
}
/// Keep a shell under the report size: the first read asks for everything
/// and the UI shows only this much of the tail.
const shellOutputTailBytes = 256 * 1024;
/// `12秒`, `3分05秒`, `1:02:03`: the running clock a task row shows.
String formatElapsed(int milliseconds) {
final secs = milliseconds <= 0 ? 0 : milliseconds ~/ 1000;
if (secs < 60) return trArgs('{0}s', [secs]);
if (secs < 3600) {
final rest = secs % 60;
return trArgs(
'{0}m{1}s', [secs ~/ 60, rest.toString().padLeft(2, '0')]);
}
final hours = secs ~/ 3600;
final mins = (secs % 3600) ~/ 60;
final rest = secs % 60;
return '$hours:${mins.toString().padLeft(2, '0')}:'
'${rest.toString().padLeft(2, '0')}';
}
+7 -4
View File
@@ -6,6 +6,8 @@ import 'dart:io';
import 'package:socks5_proxy/socks_client.dart';
import '../l10n.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.
@@ -96,7 +98,7 @@ class CancelToken {
class DownloadCancelled implements Exception {
const DownloadCancelled();
@override
String toString() => '下载已取消';
String toString() => tr('Download cancelled');
}
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
@@ -118,13 +120,14 @@ ProxyConfig? parseProxy(String? raw) {
if (!normalized.contains('://')) normalized = 'http://$normalized';
final uri = Uri.tryParse(normalized);
if (uri == null || uri.host.isEmpty) {
throw ArgumentError('代理地址无效:$raw');
throw ArgumentError(trArgs('Invalid proxy address: {0}', [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)');
throw ArgumentError(trArgs(
'Unsupported proxy protocol: {0} (supported: http, https, socks5, socks5h)', [scheme]));
}
String? user;
String? pass;
@@ -190,7 +193,7 @@ class DirectTransport implements Transport {
if (_proxyAddress != null) return _proxyAddress!;
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
if (addresses.isEmpty) {
throw const SocketException('无法解析代理主机');
throw SocketException(tr('Could not resolve the proxy host'));
}
return _proxyAddress = addresses.first;
}
+364
View File
@@ -0,0 +1,364 @@
// The OpenCode session statistics report (`/experimental/session/stats`), as
// the OpenChamber web client's 统计 page reads it: prompts, steps, tokens,
// cost, activity, models and (on request) tool calls.
import '../l10n.dart';
/// The ranges the page offers; the server only needs the start timestamp.
enum UsageRange { day, week, month, quarter, all }
extension UsageRangeX on UsageRange {
/// Days included, today counted; null for all time.
int? get days => switch (this) {
UsageRange.day => 1,
UsageRange.week => 7,
UsageRange.month => 30,
UsageRange.quarter => 90,
UsageRange.all => null,
};
/// Local midnight at the start of the range, in milliseconds; null for all
/// time (the server then starts at the oldest message).
int? startFrom(DateTime now) {
final days = this.days;
if (days == null) return null;
final today = DateTime(now.year, now.month, now.day);
return today.subtract(Duration(days: days - 1)).millisecondsSinceEpoch;
}
}
class UsageTokens {
final int input;
final int output;
final int reasoning;
final int cacheRead;
final int cacheWrite;
const UsageTokens({
this.input = 0,
this.output = 0,
this.reasoning = 0,
this.cacheRead = 0,
this.cacheWrite = 0,
});
/// Everything the model read or wrote, cache included.
int get total => input + output + reasoning + cacheRead + cacheWrite;
/// What the model produced: the answer plus its reasoning.
int get produced => output + reasoning;
factory UsageTokens.fromJson(Map<String, dynamic>? j) {
if (j == null) return const UsageTokens();
final cache = j['cache'] as Map<String, dynamic>? ?? const {};
int n(Object? v) => (v as num?)?.toInt() ?? 0;
return UsageTokens(
input: n(j['input']),
output: n(j['output']),
reasoning: n(j['reasoning']),
cacheRead: n(cache['read']),
cacheWrite: n(cache['write']),
);
}
}
class UsageModelStat {
final String providerId;
final String modelId;
final String? variant;
final int steps;
final UsageTokens tokens;
final double cost;
const UsageModelStat({
required this.providerId,
required this.modelId,
this.variant,
this.steps = 0,
this.tokens = const UsageTokens(),
this.cost = 0,
});
factory UsageModelStat.fromJson(Map<String, dynamic> j) {
final model = j['model'] as Map<String, dynamic>? ?? const {};
final variant = model['variant'];
return UsageModelStat(
providerId: model['providerID'] as String? ?? '',
modelId: model['id'] as String? ?? '',
variant: variant is String && variant.isNotEmpty ? variant : null,
steps: (j['steps'] as num?)?.toInt() ?? 0,
tokens: UsageTokens.fromJson(j['tokens'] as Map<String, dynamic>?),
cost: (j['cost'] as num?)?.toDouble() ?? 0,
);
}
}
class UsageToolStat {
final String name;
final int calls;
final int succeeded;
final int failed;
final int unfinished;
/// Median duration in milliseconds; null when the server did not measure it.
final double? durationP50;
const UsageToolStat({
required this.name,
this.calls = 0,
this.succeeded = 0,
this.failed = 0,
this.unfinished = 0,
this.durationP50,
});
factory UsageToolStat.fromJson(Map<String, dynamic> j) => UsageToolStat(
name: j['name'] as String? ?? '',
calls: (j['calls'] as num?)?.toInt() ?? 0,
succeeded: (j['succeeded'] as num?)?.toInt() ?? 0,
failed: (j['failed'] as num?)?.toInt() ?? 0,
unfinished: (j['unfinished'] as num?)?.toInt() ?? 0,
durationP50: (j['durationP50'] as num?)?.toDouble(),
);
}
class UsageTools {
/// `none`, `summary` or `detail`.
final String mode;
final int calls;
final int succeeded;
final int failed;
final int unfinished;
final List<UsageToolStat> rows;
const UsageTools({
this.mode = 'none',
this.calls = 0,
this.succeeded = 0,
this.failed = 0,
this.unfinished = 0,
this.rows = const [],
});
bool get hasTotals => mode == 'summary' || mode == 'detail';
bool get hasDetail => mode == 'detail';
factory UsageTools.fromJson(Map<String, dynamic>? j) {
if (j == null) return const UsageTools();
final totals = j['totals'] as Map<String, dynamic>? ?? const {};
int n(Object? v) => (v as num?)?.toInt() ?? 0;
return UsageTools(
mode: j['mode'] as String? ?? 'none',
calls: n(totals['calls']),
succeeded: n(totals['succeeded']),
failed: n(totals['failed']),
unfinished: n(totals['unfinished']),
rows: [
for (final row in (j['usage'] as List?) ?? const [])
if (row is Map<String, dynamic>) UsageToolStat.fromJson(row),
],
);
}
}
class UsageActivityDay {
final String date;
final int steps;
const UsageActivityDay(this.date, this.steps);
factory UsageActivityDay.fromJson(Map<String, dynamic> j) => UsageActivityDay(
j['date'] as String? ?? '',
(j['steps'] as num?)?.toInt() ?? 0,
);
}
class UsageStats {
final int from;
final int to;
final int sessions;
final int subagents;
final int prompts;
final int steps;
final UsageTokens tokens;
final double cost;
final int activeDays;
final int streak;
final List<UsageActivityDay> activity;
final List<UsageModelStat> models;
final UsageTools tools;
const UsageStats({
this.from = 0,
this.to = 0,
this.sessions = 0,
this.subagents = 0,
this.prompts = 0,
this.steps = 0,
this.tokens = const UsageTokens(),
this.cost = 0,
this.activeDays = 0,
this.streak = 0,
this.activity = const [],
this.models = const [],
this.tools = const UsageTools(),
});
bool get isEmpty => prompts == 0 && steps == 0;
factory UsageStats.fromJson(Map<String, dynamic> j) {
final range = j['range'] as Map<String, dynamic>? ?? const {};
int n(Object? v) => (v as num?)?.toInt() ?? 0;
return UsageStats(
from: n(range['from']),
to: n(range['to']),
sessions: n(j['sessions']),
subagents: n(j['subagents']),
prompts: n(j['prompts']),
steps: n(j['steps']),
tokens: UsageTokens.fromJson(j['tokens'] as Map<String, dynamic>?),
cost: (j['cost'] as num?)?.toDouble() ?? 0,
activeDays: n(j['activeDays']),
streak: n(j['streak']),
activity: [
for (final day in (j['activity'] as List?) ?? const [])
if (day is Map<String, dynamic>) UsageActivityDay.fromJson(day),
],
models: [
for (final model in (j['models'] as List?) ?? const [])
if (model is Map<String, dynamic>) UsageModelStat.fromJson(model),
],
tools: UsageTools.fromJson(j['tools'] as Map<String, dynamic>?),
);
}
}
/// One column of the activity chart: a day, or a week once the range is too
/// long for daily bars.
class UsageBar {
final String start;
final String end;
final int steps;
const UsageBar(this.start, this.end, this.steps);
}
class UsageActivitySeries {
final bool weekly;
final List<UsageBar> bars;
final int max;
const UsageActivitySeries(this.weekly, this.bars, this.max);
}
const _maxDailyBars = 92;
String _dateKey(DateTime date) =>
'${date.year}-${date.month.toString().padLeft(2, '0')}-'
'${date.day.toString().padLeft(2, '0')}';
/// Fills the inactive days with zero so the chart shows the whole range, and
/// groups into weeks past 92 days so the bars stay readable.
UsageActivitySeries buildUsageActivity(UsageStats stats) {
if (stats.from <= 0 || stats.to <= 0) {
return const UsageActivitySeries(false, [], 0);
}
final stepsByDay = {
for (final day in stats.activity) day.date: day.steps,
};
final first = DateTime.fromMillisecondsSinceEpoch(stats.from);
final last = DateTime.fromMillisecondsSinceEpoch(stats.to - 1);
final lastKey = _dateKey(last);
final days = <UsageBar>[];
var cursor = DateTime(first.year, first.month, first.day);
while (true) {
final key = _dateKey(cursor);
days.add(UsageBar(key, key, stepsByDay[key] ?? 0));
if (key == lastKey) break;
cursor = DateTime(cursor.year, cursor.month, cursor.day + 1);
// A bogus timestamp must not spin forever.
if (days.length > 4000) break;
}
if (days.length <= _maxDailyBars) {
return UsageActivitySeries(
false, days, days.fold(0, (peak, day) => day.steps > peak ? day.steps : peak));
}
final weeks = <UsageBar>[];
for (var i = 0; i < days.length; i += 7) {
final chunk = days.sublist(i, (i + 7).clamp(0, days.length));
weeks.add(UsageBar(
chunk.first.start,
chunk.last.end,
chunk.fold(0, (sum, day) => sum + day.steps),
));
}
return UsageActivitySeries(
true, weeks, weeks.fold(0, (peak, week) => week.steps > peak ? week.steps : peak));
}
double? usageCacheHitRate(UsageTokens tokens) {
final misses = tokens.input + tokens.cacheWrite + tokens.cacheRead;
return misses > 0 ? tokens.cacheRead / misses : null;
}
double? usageReasoningShare(UsageTokens tokens) {
final produced = tokens.produced;
return produced > 0 ? tokens.reasoning / produced : null;
}
double? _average(int total, int count) => count > 0 ? total / count : null;
double? usageTokensPerSession(UsageStats stats) =>
_average(stats.tokens.total, stats.sessions);
double? usageStepsPerSession(UsageStats stats) =>
_average(stats.steps, stats.sessions);
double? usageCostPerSession(UsageStats stats) =>
stats.sessions > 0 ? stats.cost / stats.sessions : null;
double? usageCostPerMillionTokens(UsageStats stats) =>
stats.tokens.total > 0
? stats.cost / stats.tokens.total * 1000000
: null;
const _monthNames = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
];
/// `Nov 5` for the chart's ends and `11月5日` in Chinese. Kept here so every
/// caller reads a day the same way.
String usageDayLabel(String day) {
final parts = day.split('-');
if (parts.length != 3) return day;
final month = int.tryParse(parts[1]);
final date = int.tryParse(parts[2]);
if (month == null || date == null) return day;
if (L10n.instance.isEnglish) return '${_monthNames[month - 1]} $date';
return '$month月$date日';
}
/// 1.2K / 3.4M, as the web client compacts totals.
String usageCompactNumber(num value) {
if (value < 1000) return value.toStringAsFixed(0);
final (unit, suffix) = value < 1000000
? (1000.0, 'K')
: value < 1000000000
? (1000000.0, 'M')
: (1000000000.0, 'B');
final scaled = value / unit;
final text = scaled.toStringAsFixed(scaled >= 100 ? 0 : 1);
return '${text.endsWith('.0') ? text.substring(0, text.length - 2) : text}$suffix';
}
String usagePercent(double value) => '${(value * 100).toStringAsFixed(1)}%';
String usageCost(double value) => '\$${value.toStringAsFixed(2)}';
String usageDuration(double ms) {
if (ms < 1000) return '${ms.round()} ms';
final seconds = ms / 1000;
if (seconds < 60) return '${seconds.toStringAsFixed(1)} s';
final whole = seconds.floor();
return '${whole ~/ 60} min ${(whole % 60)} s';
}
/// The local calendar key the report's activity days use.
String usageDateKey(DateTime date) => _dateKey(date);
+213
View File
@@ -0,0 +1,213 @@
// Who is running in the background. opencode records detached commands as
// "shell" jobs (`GET /api/experimental/job`), session-scoped and covering
// subagents, so the list is right without reading the transcript. An older
// server without that endpoint falls back to the shell list, where only the
// transcript can say which commands were detached.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'api/client.dart';
import 'api/shells.dart';
/// The background commands of the open session, refreshed while the chat is
/// on screen.
class ShellTasks extends ChangeNotifier {
ShellTasks(this.client, {required this.sessionId});
final Client client;
final String sessionId;
List<ShellTask> _tasks = const [];
List<ShellTask> get tasks => _tasks;
/// The shell list stopped answering (an opencode without the shell API):
/// polling stops so a chat does not keep asking.
bool available = true;
/// The job endpoint answered 404 once: this server only has `GET /api/shell`.
bool _jobs = true;
/// Fallback only: the detached calls the transcript knows about, with the
/// start time of the message that ran them.
final Map<String, ShellTask> _seeded = {};
/// Every task ever seen, for a tool row that wants its output after the
/// command has left the strip.
final Map<String, ShellTask> _known = {};
String _directory = '';
List<String> _sessionIds = const [];
Timer? _poll;
bool _busy = false;
bool _disposed = false;
/// The transcript's detached calls (fallback path). Called on every chat
/// change; cheap.
void seed(Iterable<ShellTask> tasks) {
var changed = false;
final ids = <String>{};
for (final task in tasks) {
if (!ids.add(task.id)) continue;
final old = _seeded[task.id];
if (old == null ||
old.command != task.command ||
old.startedAt != task.startedAt) {
_seeded[task.id] = task;
changed = true;
}
_known[task.id] ??= task;
}
for (final id in _seeded.keys.toList()) {
if (!ids.contains(id)) {
_seeded.remove(id);
changed = true;
}
}
if (changed) {
_prune();
if (_poll != null) unawaited(refresh());
}
}
/// Starts (or re-arms) the refresh for [directory]. The job list does not
/// need it; the fallback shell list does.
void watch({required String directory, required Set<String> sessionIds}) {
final ids = sessionIds.toList()..sort();
if (_poll != null && directory == _directory && _same(ids, _sessionIds)) {
return;
}
_directory = directory;
_sessionIds = ids;
_poll?.cancel();
_poll = Timer.periodic(const Duration(seconds: 3), (_) => refresh());
refresh();
}
/// Re-reads what is running now (after a stop, or when a tool transition
/// arrives).
Future<void> refresh() async {
if (_disposed || _busy) return;
_busy = true;
try {
if (available && _jobs) {
try {
final jobs = await client.listShellJobs(sessionId);
if (_disposed) return;
_set(jobs);
return;
} on ApiError catch (e) {
if (e.status != 404) rethrow;
_jobs = false;
}
}
if (available) await _refreshShellList();
} on ApiError catch (e) {
if (e.status == 404) {
available = false;
_poll?.cancel();
_poll = null;
}
// A network hiccup keeps the last known tasks on screen.
} catch (_) {
// Same: the next tick tries again.
} finally {
_busy = false;
}
}
/// The fallback: all running shells of the directory, narrowed to the
/// commands the transcript detached.
Future<void> _refreshShellList() async {
if (_seeded.isEmpty) {
_set(const []);
return;
}
final listed = await client.listShells(directory: _directory);
if (_disposed) return;
final byId = {for (final shell in listed) shell.id: shell};
final next = <ShellTask>[];
for (final task in _seeded.values) {
final live = byId[task.id];
if (live == null || !live.running) continue;
next.add(task.copyWith(
command: live.command.isEmpty ? null : live.command,
startedAt: live.startedAt > 0 ? live.startedAt : null,
sessionId: live.sessionId.isEmpty ? null : live.sessionId,
));
}
_set(next);
}
/// Stops [task], then tells the model why its completion notice will look
/// like a failure, as the first-party client does.
Future<void> stop(ShellTask task, String directory) async {
await client.stopShell(task.id, directory: directory);
_seeded.remove(task.id);
_known.remove(task.id);
_set(_tasks.where((t) => t.id != task.id).toList());
// The notice goes to the session that started the command.
try {
await client.syntheticNote(
task.sessionId.isEmpty ? sessionId : task.sessionId,
text: stopNote(task.command),
description: 'Background command stopped by the user',
metadata: {
'openchamber': {
'shellStop': {
'shellIDs': [task.id],
},
},
},
directory: directory,
);
} catch (_) {
// The command is stopped either way; the notice is a courtesy.
}
unawaited(refresh());
}
/// The task with this shell id, for a tool row opening its output.
ShellTask? task(String id) => _known[id];
void _prune() {
_set([
for (final task in _tasks)
if (_seeded.containsKey(task.id)) task,
]);
}
void _set(List<ShellTask> next) {
_tasks = List.unmodifiable(next);
for (final task in next) {
_known[task.id] = task;
}
if (!_disposed) notifyListeners();
}
static bool _same(List<String> a, List<String> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
@override
void dispose() {
_disposed = true;
_poll?.cancel();
super.dispose();
}
}
/// What the model is told when a command is stopped from the app. Without it
/// the completion notice reads as a failure and the model may run it again.
String stopNote(String command) {
final shown = command.replaceAll(RegExp(r'\s+'), ' ').trim();
return 'The user stopped the background command `$shown`. '
'The completion notice that follows reports an error such as '
'Shell.NotFoundError or says that nothing ran; that is the stop, not a '
'failure of the command. Do not start it again just because of that '
'notice.';
}
+178
View File
@@ -0,0 +1,178 @@
// The app speaks English and Chinese. Code writes English; Chinese comes from
// the table in l10n/zh.dart through tr()/trArgs(), and AppText for the many
// Text leaves. 设置 → 常规 → 语言 chooses between the system language, Chinese
// and English; a language we have no table for reads English, and a missing
// entry falls back to the English source, so text never disappears.
import 'dart:async';
import 'dart:ui' show PlatformDispatcher;
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'l10n/zh.dart';
enum AppLanguage { system, zh, en }
/// The language the UI is drawn in, and the lookup behind [tr] and [AppText].
class L10n extends ChangeNotifier {
L10n._();
static final L10n instance = L10n._();
/// Chinese until [ensureLoaded] has read the stored choice: tests and the
/// first frame before the app starts never see a half-changed language.
AppLanguage _choice = AppLanguage.zh;
AppLanguage get choice => _choice;
/// Reads the saved choice. No saved choice means follow the system, which
/// is what a fresh install does.
Future<void> ensureLoaded() async {
try {
final prefs = await SharedPreferences.getInstance();
_choice = switch (prefs.getString('language')) {
'zh' => AppLanguage.zh,
'en' => AppLanguage.en,
_ => AppLanguage.system,
};
} catch (_) {
_choice = AppLanguage.system;
}
notifyListeners();
}
Future<void> setLanguage(AppLanguage choice) async {
apply(choice);
try {
final prefs = await SharedPreferences.getInstance();
if (choice == AppLanguage.system) {
await prefs.remove('language');
} else {
await prefs.setString('language', choice.name);
}
} catch (_) {
// The choice still holds for this run.
}
}
/// Changes the language without touching the stored choice (tests, and the
/// first resolve before prefs are read).
void apply(AppLanguage choice) {
if (_choice == choice) return;
_choice = choice;
notifyListeners();
}
Locale get locale => switch (_choice) {
AppLanguage.zh => const Locale('zh', 'CN'),
AppLanguage.en => const Locale('en'),
// Only Chinese is translated; every other system language reads
// English.
AppLanguage.system =>
_systemIsChinese ? const Locale('zh', 'CN') : const Locale('en'),
};
bool get _systemIsChinese {
try {
return PlatformDispatcher.instance.locale.languageCode == 'zh';
} catch (_) {
return true;
}
}
bool get isEnglish => locale.languageCode == 'en';
/// What a language choice reads as: a language names itself.
String languageLabel(AppLanguage choice) => switch (choice) {
AppLanguage.system => tr('System'),
AppLanguage.zh => '中文',
AppLanguage.en => 'English',
};
/// The Chinese text for [en], or [en] when there is none.
String tr(String en) => isEnglish ? en : (chineseStrings[en] ?? en);
/// Same, for text built from parts: `trArgs('{0} subagents', [n])`. The
/// English template is filled as written; Chinese entries use the same
/// `{0}`, `{1}` placeholders.
String trArgs(String template, [List<Object?> args = const []]) {
var out = isEnglish ? template : (chineseStrings[template] ?? template);
for (var i = 0; i < args.length; i++) {
out = out.replaceAll('{$i}', '${args[i] ?? ''}');
}
return out;
}
/// A system language change reaches the app while it runs; the choice
/// "follow the system" then has to redraw.
void systemLocaleChanged() {
if (_choice == AppLanguage.system) notifyListeners();
}
}
String tr(String en) => L10n.instance.tr(en);
String trArgs(String template, [List<Object?> args = const []]) =>
L10n.instance.trArgs(template, args);
/// [Text] that goes through the same lookup. It is const-constructible, so a
/// tree does not have to give up `const` to be translated. Content that comes
/// from the server (message text, titles) is drawn with plain [Text]: only
/// our own source strings are keys.
class AppText extends StatelessWidget {
final String data;
final TextStyle? style;
final StrutStyle? strutStyle;
final TextAlign? textAlign;
final TextDirection? textDirection;
final Locale? locale;
final bool? softWrap;
final TextOverflow? overflow;
final TextScaler? textScaler;
final int? maxLines;
final String? semanticsLabel;
final TextWidthBasis? textWidthBasis;
final TextHeightBehavior? textHeightBehavior;
final Color? selectionColor;
const AppText(
this.data, {
super.key,
this.style,
this.strutStyle,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
this.textScaler,
this.maxLines,
this.semanticsLabel,
this.textWidthBasis,
this.textHeightBehavior,
this.selectionColor,
});
@override
Widget build(BuildContext context) {
// Reading the resolved locale makes this widget depend on it: when the
// language changes, every AppText — including a const one whose widget
// instance the parent build reuses — is rebuilt in the new language.
final resolved = locale ?? Localizations.localeOf(context);
return Text(
tr(data),
style: style,
strutStyle: strutStyle,
textAlign: textAlign,
textDirection: textDirection,
locale: resolved,
softWrap: softWrap,
overflow: overflow,
textScaler: textScaler,
maxLines: maxLines,
semanticsLabel: semanticsLabel,
textWidthBasis: textWidthBasis,
textHeightBehavior: textHeightBehavior,
selectionColor: selectionColor,
);
}
}
+654
View File
@@ -0,0 +1,654 @@
// Chinese text for every string the code writes in English. Keys are the
// English source, including {0}, {1} placeholders; a missing key falls back
// to the English itself, so an unsupported language simply reads English.
const Map<String, String> chineseStrings = {
'(No summary)': '(摘要为空)',
'(Untitled session)': '(无标题会话)',
', ': '、',
'1st of each month': '每月 1 日',
'A step failed · {0} tool calls': '有步骤失败 · {0} 次工具调用',
'About': '关于',
'Accent color': '主题色',
'Accent color {0}': '主题色 {0}',
'Add attachment': '添加附件',
'Add project': '添加项目',
'Add server': '添加服务器',
'Add this folder': '添加此文件夹',
'Add time': '添加时间',
'Agent': '智能体',
'Agent tools': '通用',
'Agent tools and memory': '智能体工具与记忆',
'All features': '全部功能',
'Allow once': '允许一次',
'Always allow': '总是允许',
'Animation {0} has no sprite sheet': '动画 {0} 没有精灵图',
'App': '应用',
'Appearance': '外观',
'Applies to this device only; not synced to the server': '仅当前设备生效,不同步到服务器',
'Archive': '归档',
'Attachment': '附件',
'Attachments cannot be larger than 10 MB': '附件不能超过 10MB',
'Back': '返回',
'Back to parent session': '返回父会话',
'Background': '后台',
'Background output': '后台输出',
'Build directly': '直接构建',
'Camera permission is required to scan. Allow OpenChamber to use the camera in system settings.': '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。',
'Attachments': '附件',
'Cancel': '取消',
'Canceling…': '正在取消…',
'Cancelled': '已取消',
'Cannot display image': '图片无法显示',
'Cannot open the subagent session': '无法打开子代理会话',
'Cannot preview: {0}': '无法预览:{0}',
'Cannot send prompts to a subagent session.': '无法向子智能体会话发送提示。',
'Change pet pack': '更换宠物包',
'Charts and prototypes': '图表和原型',
'Chat': '聊天',
'Chinese': '中文',
'Choose a session': '选择一个会话',
'Choose one': '请选择',
'Choose project': '选择项目',
'Clear screen': '清屏',
'Close': '关闭',
'Close sidebar': '关闭侧栏',
'Close this terminal': '关闭此终端',
'Collapse subagents': '收起子代理',
'Compact': '压缩',
'Compacting conversation': '正在压缩对话',
'Compaction failed: {0}': '压缩失败:{0}',
'Connect': '连接',
'Connect through Relay': '通过 Relay 连接',
'Connect to your OpenChamber server': '连接你的 OpenChamber 服务器',
'Connect to {0}': '连接 {0}',
'Connected': '已连接',
'Connecting…': '正在连接…',
'Connection closed: check whether the proxy works': '连接被断开:检查代理是否可用',
'Connection failed': '连接失败',
'Connection lost, reconnecting…': '连接中断,正在重连…',
'Connection refused: server or proxy not running, or wrong port': '连接被拒绝:服务器或代理未启动,或端口不对',
'Connection timed out: check the server and proxy address': '连接超时:检查服务器与代理地址',
'Content': '内容',
'Context limit': '上下文上限',
'Context usage': '上下文占用',
'Conversation compacted': '对话已压缩',
'Copied': '已复制',
'Copy': '复制',
'Copy answer': '复制回答',
'Copy message': '复制消息',
'Copy session ID': '复制会话 ID',
'Could not add the project: {0}': '无法添加项目:{0}',
'Could not attach: {0}': '选择失败:{0}',
'Could not connect to the relay: {0}': '无法连接 Relay:{0}',
'Could not create the chat directory: {0}': '无法创建聊天目录:{0}',
'Could not create the folder: {0}': '无法创建文件夹:{0}',
'Could not decode the QR code; try again': '二维码解码出错,请重试',
'Could not get a WebSocket token ({0})': '无法获取 WebSocket 令牌({0})',
'Could not load image: {0}': '图片加载失败:{0}',
'Could not load this folder: {0}': '无法加载此文件夹:{0}',
'Could not load, refresh to retry': '读取失败,请刷新',
'Could not open the camera: {0}': '无法打开相机:{0}',
'Could not open the subagent session: {0}': '无法打开子代理会话:{0}',
'Could not read output: {0}': '读取输出失败:{0}',
'Could not resolve address: check the server or proxy hostname': '无法解析地址:检查服务器或代理主机名',
'Could not resolve the proxy host': '无法解析代理主机',
'Could not stop: {0}': '停止失败:{0}',
'Couldn\'t delete task': '删除任务失败',
'Couldn\'t load scheduled tasks: {0}': '加载计划任务失败:{0}',
'Couldn\'t run task': '运行任务失败',
'Couldn\'t run task: {0}': '运行任务失败:{0}',
'Couldn\'t save': '保存失败',
'Couldn\'t save task': '保存任务失败',
'Couldn\'t save task: {0}': '保存任务失败:{0}',
'Couldn\'t save: {0}': '保存失败:{0}',
'Couldn\'t update task': '更新任务失败',
'Create': '创建',
'Creating…': '正在创建…',
'Cron expression': 'Cron 表达式',
'Cron expression is required': 'Cron 表达式为必填项',
'Cron: {0}': 'Cron:{0}',
'Current: {0}': '当前:{0}',
'Daily': '每天',
'Daily at 9': '每天 9 点',
'Daily sync': '每日同步',
'Daily {0}': '每天 {0}',
'Dark': '深色',
'Date': '日期',
'Decryption failed: {0}': '解密失败:{0}',
'Default': '默认',
'Default agent': '默认智能体',
'Default model': '默认模型',
'Delete': '删除',
'Delete scheduled task?': '删除计划任务?',
'Delete server?': '删除服务器?',
'Delete session?': '删除会话?',
'Delivery': '发送方式',
'Deny': '拒绝',
'Direct address or OpenChamber Relay': '直连地址或 OpenChamber Relay',
'Directory is empty': '目录为空',
'Discard draft': '丢弃草稿',
'Disconnect': '断开当前连接',
'Done': '完成',
'Done · {0} tool calls': '已完成 · {0} 次工具调用',
'Download': '下载',
'Download cancelled': '下载已取消',
'Downloaded {0}': '已下载 {0}',
'Downloading': '正在下载',
'Draft': '草稿',
'Draft · {0}': '草稿 · {0}',
'e.g. docs': '例如 docs',
'e.g. My computer': '如 我的电脑',
'e.g. notes.md': '例如 notes.md',
'Earlier': '更早',
'Earlier this week': '本周早些时候',
'Edit': '编辑',
'Edit memory': '编辑记忆',
'Edit note': '编辑笔记',
'Edit scheduled task': '编辑计划任务',
'Enable pet': '启用宠物',
'Enabled': '已启用',
'Enter a valid folder name': '请输入有效的文件夹名称',
'End-to-end encrypted; the server and device token stay the same': '端到端加密;服务器与设备令牌保持不变',
'Ended': '已结束',
'Error': '错误',
'Every 5 minutes': '每 5 分钟',
'Every hour': '每小时',
'Exit code {0}': '退出码 {0}',
'Exited': '已退出',
'Expand subagents': '展开子代理',
'Extra high': '极高',
'Extracted size exceeds 60 MB': '解压后超过 60MB',
'Fact': '事实',
'Favorites': '收藏',
'Feedback': '反馈',
'Fetch': '抓取',
'Fetch the server version again': '重新获取服务端版本',
'File is empty': '文件为空',
'File is large ({0}), download it to view': '文件较大({0}),请下载后查看',
'File {0}': '文件 {0}',
'Files': '文件',
'Flashlight': '手电筒',
'Folder name': '文件夹名称',
'Folder path': '文件夹路径',
'Follow system': '跟随系统',
'Follow the system, Chinese or English': '跟随系统、中文或 English',
'Follow-up behavior': '追问处理行为',
'Fork from here': '从这里分叉',
'Fri': '周五',
'General': '常规',
'Generate image': '生成图片',
'Generating summary…': '正在生成摘要…',
'Generating; you can still type…': '生成中,仍可输入…',
'Global memory': '全局记忆',
'Go': '前往',
'Goal': '目标',
'Got it': '知道了',
'Help & about': '帮助与关于',
'Hide archived': '隐藏已归档',
'Hide details': '收起详情',
'Hide summary': '隐藏摘要',
'High': '高',
'http://… or socks5://…': 'http://… 或 socks5://…',
'Idle': '空闲',
'Image': '图片',
'Image model': '图像模型',
'Images': '图像',
'Import a pet pack (.zip) and it will stand above the input box.': '导入一个宠物包(.zip)后,它会站在输入框上方。',
'Import failed: {0}': '导入失败:{0}',
'Import pet pack': '导入宠物包',
'Import, enable and size': '导入、启用与大小',
'Imported {0}': '已导入 {0}',
'In chat': '在聊天中',
'In less than a minute': '不到 1 分钟后',
'In the OpenChamber web app, open “Connect a device” and choose the QR code': '在 OpenChamber 网页端打开「连接设备」,选择二维码',
'In the OpenChamber web app, open “Connect a device”, then paste the link or scan the QR code. The link carries a one-time key and either a direct address or a private Relay.': '在 OpenChamber 网页端打开「连接设备」,粘贴链接或直接扫描二维码。链接里带一次性密钥,以及直连地址或私有 Relay。',
'In {0}': '{0}后',
'In {0} min': '{0} 分钟后',
'Init': '初始化',
'Invalid data URL': '无效的 data URL',
'Invalid proxy address: {0}': '代理地址无效:{0}',
'Invalid response headers': '响应头无效',
'Join at the next step; work continues': '在下一步加入,工作继续',
'Joining this turn…': '正在转入当前回合…',
'Jump to latest': '回到最新',
'Just now': '刚刚',
'Key exchange failed: {0}': '密钥协商失败:{0}',
'Keyboard': '键盘',
'Language': '语言',
'Large': '大',
'Large output, loading…': '输出较大,正在载入…',
'Last run {0} · {1}': '上次运行 {0} · {1}',
'Let the agent ask you for API keys, tokens or passwords on a private card in chat. Values never enter the conversation.': '允许智能体在聊天中的私密卡片上向你索取 API 密钥、令牌或密码。值不会进入对话。',
'Let the agent check each provider\'s limits and reset times.': '让智能体查看各提供商的限额及重置时间。',
'Let the agent generate and edit images with the model you choose; the model\'s provider charges for it.': '让智能体用你选择的模型生成和编辑图像,费用由该模型的提供商收取。',
'Let the agent read and update the project\'s notes, todos and plans.': '让智能体读取并更新项目的笔记、待办和计划。',
'Let the agent show charts, tables, diagrams and UI sketches in chat (isolated from your files) and ask you to pick one of them.': '让智能体在聊天中展示图表、表格、示意图和界面草图(与你的文件隔离),并请你在其中选择一个选项。',
'Light': '浅色',
'List': '列出',
'Loading projects…': '正在加载项目…',
'Load earlier messages': '载入更早的消息',
'Load more': '载入更多',
'Loading models…': '正在载入模型…',
'Loading…': '读取中…',
'Low': '低',
'Medium': '中',
'Memory': '记忆',
'Memory is not enabled': '记忆功能未启用',
'Memory is recorded by the agent during sessions; you can edit or delete it here.': '记忆由 agent 在会话中记录;你可以在这里修改或删除它。',
'Minimal': '极低',
'Missing sprite sheet {0}': '缺少精灵图 {0}',
'Mobile client': '手机客户端',
'Mode': '模式',
'Model': '模型',
'Model for tidying memory': '整理记忆使用的模型',
'Mon': '周一',
'Mondays at 9': '每周一 9 点',
'More': '更多',
'Name': '名称',
'Names cannot contain slashes': '名称里不能有斜杠',
'Network error: {0}': '网络错误:{0}',
'Network unreachable': '网络不可达',
'Never run': '从未运行',
'New': '新建',
'New chat': '新建聊天',
'New extension': '新建扩展',
'New file': '新建文件',
'New folder': '新建文件夹',
'New note': '新建笔记',
'New plan': '新建计划',
'New scheduled task': '新建计划任务',
'New session': '新会话',
'New session in this project': '在此项目新会话',
'New task': '新建任务',
'New terminal': '新建终端',
'New todo': '新建待办',
'Next: {0}': '下次:{0}',
'No archived sessions': '没有已归档的会话',
'No camera available': '没有可用的相机',
'No camera frames received; close and try again': '没有收到相机画面,请关闭后重试',
'No commands available': '没有可用的指令',
'No content': '无内容',
'no date': '未选日期',
'no days': '未选',
'No folders here': '此目录没有子文件夹',
'No matching files': '没有匹配的文件',
'No matching files in subdirectories': '子目录里没有匹配的文件',
'No matching memories': '没有匹配的记忆',
'No matching notes': '没有匹配的笔记',
'No matching plans': '没有匹配的计划',
'No matching sessions': '没有匹配的会话',
'No matching todos': '没有匹配的待办',
'No memories yet': '还没有记忆',
'No notes yet': '还没有笔记',
'No output': '无输出',
'No pet imported': '尚未导入宠物',
'No pet is included; pet packs stay on this device.': '默认不提供宠物;宠物包只存放在本机。',
'No plans yet': '还没有计划',
'No projects available': '没有可用的项目',
'No QR code yet; move closer or fill the frame with the code': '还没识别到二维码,试着靠近一点或让二维码占满取景框',
'No results': '没有结果',
'No scheduled tasks yet.': '暂无计划任务。',
'No sessions': '暂无会话',
'No todos yet': '还没有待办',
'None': '无',
'Not a valid zip file': '不是有效的 zip 文件',
'Not available': '未获取到',
'Not connected': '未连接',
'Not connected to a server': '未连接服务器',
'Not selected': '未选择',
'Not sent': '未发送',
'Not started': '未启动',
'Not tied to a project, saved in OpenChamber\'s chat directory': '不关联项目,保存在 OpenChamber 的聊天目录',
'Notes': '笔记',
'Nothing to copy': '没有可复制的文字',
'Notifications': '通知',
'Once': '一次性',
'Once a day, when no session is running, the agent tidies memory in the background: merging duplicates and removing entries that are obsolete or already in the project docs.': '每天一次,在没有会话运行时,智能体会在后台整理记忆:合并重复条目,删除已过时或项目文档中已有的内容。',
'Once {0} {1}': '一次性 {0} {1}',
'Open the session list': '打开会话列表',
'Open-source licenses': '开源许可',
'OpenCode could not send the message: {0}': 'OpenCode 发送消息失败:{0}',
'OpenCode could not send the message; retrying: {0}': 'OpenCode 发送消息失败,正在重试:{0}',
'Other': '其它',
'Other…': '其他…',
'Output copied': '已复制输出',
'pack.json is missing animations or states': 'pack.json 缺少动画或状态',
'pack.json is not a valid pet pack': 'pack.json 不是有效的宠物包',
'Pair and connect': '配对并连接',
'Pairing expired, please pair again': '配对已失效,请重新配对',
'Pairing failed': '配对失败',
'Pairing link': '配对链接',
'Pairing link is invalid or expired': '配对链接无效或已过期',
'Password': '需要密码',
'Password (if required)': '密码(如果需要)',
'Password or saved credentials required': '需要密码或已保存的凭据',
'Paste': '粘贴',
'Patch': '补丁',
'Paused': '已暂停',
'Paused tasks don\'t run on schedule but can still be run manually.': '暂停的任务不会按计划运行,但可以手动运行。',
'Permission': '权限',
'Permission requested: {0}': '请求权限: {0}',
'Personal': '个人',
'Pet': '宠物',
'Pet pack cannot exceed 40 MB': '宠物包不能超过 40MB',
'Pin': '置顶',
'Pinned': '已置顶',
'Plan body (Markdown)': '计划正文(Markdown)',
'Plan first without changing files': '先规划,不改动文件',
'Plan, build, or ask': '规划、构建或提问',
'Plans': '计划',
'Preference': '偏好',
'Preview': '预览',
'Project knowledge': '项目知识',
'Project memory': '项目记忆',
'Prompt': '提示词',
'Prompt can\'t exceed 20,000 characters': '提示词不能超过 20000 个字符',
'Prompt is required': '提示词为必填项',
'Proxy (optional)': '代理(可选)',
'Put the pairing QR code inside the frame': '把配对二维码放进框内',
'Queue': '排队',
'Queue instead': '改为排队',
'Queue: sends after the current turn ends.': '排队:等当前回合结束后再发送。',
'Queued': '已排队',
'Queued; sends after this turn': '已排队,本轮结束后发送',
'Read': '读取',
'Reading output…': '读取输出…',
'Received a plaintext frame after the handshake': '握手后收到明文帧',
'Recent': '最近',
'Reference': '参考',
'Refresh': '刷新',
'Relay connection closed': 'Relay 连接已关闭',
'Relay connection closed ({0} {1})': 'Relay 连接已关闭({0} {1})',
'Relay connection error: {0}': 'Relay 连接出错:{0}',
'Relay handshake timed out': 'Relay 握手超时',
'Relay server': 'Relay 服务器',
'Remember facts about you and each project across sessions.': '跨会话记住关于你和每个项目的事实。',
'Remove': '移除',
'Remove from favorites': '取消收藏',
'Remove pet?': '移除宠物?',
'Remove time': '移除时间',
'Rename': '重命名',
'Replying': '正在回复',
'Required: {0}': '请填写:{0}',
'Reserved output': '输出预留',
'Reserved output assumes at most 32K tokens, matching the official client.': '输出预留按最多 32K tokens 计算,与官方客户端一致。',
'Restart': '重新启动',
'Retry': '重试',
'Review': '审查',
'Run': '运行',
'Run now': '立即运行',
'Running': '运行中',
'Running {0} commands': '正在执行 {0} 条命令',
'Running · {0} tool calls': '执行中 · {0} 次工具调用',
'Runs in': '运行位置',
'Runs in: {0}': '运行位置:{0}',
'Sat': '周六',
'Save': '保存',
'Saved': '已保存',
'Saving…': '保存中…',
'Scan QR code': '扫码',
'Schedule type': '计划类型',
'Scheduled task deleted': '计划任务已删除',
'Scheduled task saved': '计划任务已保存',
'Scheduled tasks': '计划任务',
'Search': '搜索',
'Search notes, todos, and plans': '搜索笔记、待办与计划',
'Search notes, todos, plans, and memory': '搜索笔记、待办、计划与记忆',
'Search sessions': '搜索会话',
'Search subdirectories': '搜索子目录',
'Search this directory…': '搜索当前目录…',
'Searching subdirectories… ({0})': '正在搜索子目录…({0})',
'Secrets': '密钥',
'Select a model, or switch back to the default model': '请选择模型,或改回使用默认模型',
'Select a pet pack (.zip)': '选择宠物包(.zip)',
'Select at least one weekday': '请至少选择一个星期',
'Select model': '选择模型',
'Self-signed certificate fingerprint (optional)': '自签证书指纹(可选)',
'Send': '发送',
'Send a message…': '发消息…',
'Send after this turn ends': '等本轮结束后发送',
'Send prompts to sessions on a schedule': '按时间向会话发送提示词',
'Sends to an existing session': '发送到现有会话',
'Server': '服务端',
'Server address': '服务器地址',
'Server did not provide a chat directory': '服务器没有提供聊天目录',
'Server did not return a device token': '服务器没有返回设备令牌',
'Server password; leave empty if the server has none': '服务器密码;服务器未设置可留空',
'Servers': '服务器',
'Session ID copied': '已复制会话 ID',
'Sessions': '会话',
'Settings': '设置',
'System': '跟随系统',
'SHA-256 hex': 'SHA-256 十六进制',
'Shared': '团队共享',
'Show archived': '显示已归档',
'Show archived ({0})': '显示已归档 ({0})',
'Show details': '显示详情',
'Show git-ignored files': '显示被 git 忽略的文件',
'Show summary': '显示摘要',
'Showing the first {0} of {1} lines': '仅显示前 {0} 行,共 {1} 行',
'Signed in but no token was returned': '登录成功但没有返回令牌',
'Size': '大小',
'Skill': '技能',
'Skipped': '已跳过',
'Small': '小',
'Stands above the input box; off by default': '站在输入框上方,默认关闭',
'Steer': '转向',
'Steer instead': '转为转向',
'Steer into this turn': '转向当前回合',
'Steer: joins the current turn at the next step and work continues.': '转向:在下一步加入当前回合,工作继续。',
'Stop': '停止',
'Stop this task?': '停止这个任务?',
'Stopping…': '停止中…',
'Subagent': '子代理',
'Subagent · {0}': '子代理 · {0}',
'Subdirectory results': '子目录结果',
'Success': '成功',
'Summarize unfinished tasks and suggest next steps': '总结未完成任务并给出下一步建议',
'Sun': '周日',
'Switch terminal': '切换终端',
'Task': '任务',
'Task is already waiting in the queue': '任务已在队列中等待',
'Task name': '任务名称',
'Task name can\'t exceed 80 characters': '任务名称不能超过 80 个字符',
'Task name is required': '任务名称为必填项',
'Task started': '任务已启动',
'Terminal': '终端',
'Terminal 1': '终端 1',
'Terminal connection failed': '终端连接失败',
'Terminal {0}': '终端 {0}',
'The agent notifies you when work finishes or gets stuck.': '工作完成或卡住时,智能体会通知你。',
'The archive has no pack.json': '压缩包里没有 pack.json',
'The model failed to authenticate. Sign in again on the server or check the API key.': '模型的认证失败,请在服务端重新登录或检查 API Key。',
'The model is not in the catalog; the context window is estimated.': '该模型不在模型目录中,上下文窗口为估算值。',
'The pet pack stored on this device will be deleted.': '本机保存的宠物包会被删除。',
'The server doesn\'t support scheduled tasks': '服务器不支持计划任务',
'The theme is stored on this device only and does not sync with the server.': '主题只保存在本机,不随服务器同步。',
'The UI text switches together with the system\'s date and time pickers.': '界面文字与系统自带的日期、时间选择器会一起切换。',
'Theme': '主题',
'Theme mode': '主题模式',
'Theme mode and color': '主题模式与主题色',
'Thinking': '思考',
'Thinking effort': '思考强度',
'Thinking…': '正在思考…',
'Third-party components bundled with this app are listed below; tap one to read its full license.': '下面列出随本应用打包的第三方组件;点开可阅读完整许可证。',
'Third-party components used by this app and their licenses': '本应用使用的第三方组件与它们的许可证',
'This camera does not support the flashlight': '这个相机不支持手电筒',
'This component has no license text.': '该组件没有附带许可证文本。',
'This directory has no commands or skills yet': '这个目录还没有注册指令或技能',
'This file cannot be previewed': '这个文件无法预览',
'This is not an OpenChamber pairing QR code': '这不是 OpenChamber 配对二维码',
'This message and everything after it will be removed from the session and cannot be recovered.': '这条消息及其之后的内容会从会话中删除,且无法恢复。',
'This session has no directory': '这个会话没有关联目录',
'This session is managed by a Lead; take it over to continue.': '此会话由 Lead 管理,接管后才能继续。',
'This turn was stopped.': '本轮已停止。',
'Thought process': '思考过程',
'Thu': '周四',
'Tidy memory': '整理记忆',
'Time': '时间',
'Time must be in HH:mm format': '时间格式必须是 HH:mm',
'Times': '时间点',
'Times follow the server\'s time zone.': '时间按服务器所在时区。',
'Title': '标题',
'Today': '今天',
'Todos': '待办',
'Tokens used': '已用词元',
'Tool': '工具',
'Tools for servers and agents are collected here.': '服务器与智能体的工具都收在这里。',
'Transfer interrupted': '传输被中断',
'Trust self-signed certificates': '信任自签名证书',
'Tue': '周二',
'Turn cost': '本轮费用',
'Turn off to pin the model and agent this run uses.': '关闭后可固定这次运行使用的模型和智能体。',
'Unarchive': '取消归档',
'Unknown': '未知',
'Unknown error': '未知错误',
'Unpin': '取消置顶',
'Unsupported data URL': '不支持的 data URL',
'Unsupported proxy protocol: {0} (supported: http, https, socks5, socks5h)': '不支持的代理协议:{0}(支持 http、https、socks5、socks5h)',
'Untitled project': '未命名项目',
'Up one level': '上一级',
'Usage': '占用',
'Usage limits': '用量限额',
'Use AI to compact the session history and reduce context size': '使用 AI 压缩会话历史以减少上下文大小',
'Use default model and agent': '使用默认模型与智能体',
'Version': '版本',
'Version comes from the currently connected server': '版本取自当前连接的服务器',
'Version, server and open-source licenses': '版本、服务端与开源许可',
'Via Relay · {0}': '经由 Relay · {0}',
'Via {0}': '经由 {0}',
'View all': '查看全部',
'Waiting for output…': '等待输出…',
'WebSocket substream interrupted': 'WebSocket 子流被中断',
'Wed': '周三',
'Weekdays': '星期',
'Weekly': '每周',
'Weekly {0} {1}': '每周 {0} {1}',
'What are we building today?': '我们今天要做什么?',
'What happens by default when you press send while a run is in progress. Synced with the web client\'s setting.': '运行中按发送时,消息默认怎么处理。与网页端设置同步。',
'What needs doing': '要做什么',
'What the agent knows': '智能体知道的内容',
'Withdraw': '撤回',
'Withdraw message?': '撤回消息?',
'Withdraw this and later messages': '撤回此消息及之后',
'Write': '写入',
'Write something for later sessions to read': '记点什么,供之后的会话参考',
'Wrong password, try again': '密码错误,请重试',
'Yesterday': '昨天',
'You stopped this command.': '用户停止了这条命令。',
'Your provider has no image models': '你的提供商中没有图像模型',
'{0}\nvia {1}': '{0}\n经由 {1}',
'{0} ({1})': '{0}({1})',
'{0} / {1} ({2}%)': '{0} / {1}({2}%)',
'{0} ago': '{0}前',
'{0} context': '{0} 上下文',
'{0} days': '{0} 天',
'{0} days {1} hr': '{0} 天 {1} 小时',
'{0} hr': '{0} 小时',
'{0} hr {1} min': '{0} 小时 {1} 分钟',
'{0} in progress': '正在{0}',
'{0} min ago': '{0} 分钟前',
'{0} notes': '{0} 条笔记',
'{0} plans': '{0} 份计划',
'{0} subagents': '{0} 个子代理',
'{0} · {1} frames scanned / {2} decode attempts': '{0} · 已扫描 {1} 帧 / 解码 {2} 次',
'{0}/{1} done': '{0}/{1} 已完成',
'{0}m{1}s': '{0}分{1}秒',
'{0}s': '{0}秒',
'“{0}” and its schedule will be deleted.': '“{0}”及其计划会被删除。',
'“{0}” and its subagent sessions will be deleted permanently.': '“{0}”及其子会话将被删除,且无法恢复。',
'“{0}” will be removed from the list, and its device token will be deleted.': '“{0}”将从列表移除,设备令牌也会删除。',
'📎 {0} attachments': '📎 {0} 个附件',
// stats
'Stats': '统计',
'Prompts, tokens, cost and model activity': '提示词、词元、费用与模型活动',
'All projects': '所有项目',
'7 days': '7 天',
'30 days': '30 天',
'90 days': '90 天',
'All time': '全部时间',
"Couldn't load stats": '无法加载统计',
'Try again': '重试',
'No activity in this period': '这段时间没有活动',
'Sessions you run will show up here.': '你运行的会话会显示在这里。',
'No model usage in this period.': '这段时间没有模型使用。',
'Prompts': '提示词',
'Tokens': '词元',
'Cost': '费用',
'Active days': '活跃天数',
'Longest streak (days)': '最长连续天数',
'Weekly activity': '每周活动',
'Daily activity': '每日活动',
'Model steps per week': '每周的模型步数',
'Model steps per day': '每天的模型步数',
'Token composition': '词元构成',
'Efficiency': '效率',
'Cache hit rate': '缓存命中率',
'Cost / session': '每个会话费用',
'Cost per 1M tokens': '每百万词元费用',
'Tokens / session': '每个会话词元',
'Steps / session': '每个会话步数',
'Reasoning share': '推理占比',
'Input': '输入',
'Output + reasoning': '输出 + 推理',
'Cache reads': '缓存读取',
'Cache writes': '缓存写入',
'Models': '模型',
'Steps': '步数',
'Tool calls': '工具调用',
'Counting them reads every message in the period.': '统计工具调用需要读取这段时间的每条消息。',
'Calls': '调用次数',
'Success rate': '成功率',
'Failed': '失败',
'Unfinished': '未完成',
'Up': '上一级',
'Updated {0}': '更新于 {0}',
'Subagents: {0}': '子代理:{0}',
'In {0} · Out {1} · Cache {2}': '输入 {0} · 输出 {1} · 缓存 {2}',
'{0} · steps: {1}': '{0} · 步数 {1}',
'{0} steps': '{0} 步',
'calls: {0} · median: {1}': '调用 {0} · 中位耗时 {1}',
'calls: {0}': '调用 {0}',
'OpenChamber mobile client': 'OpenChamber 移动客户端',
// archive
'All': '全部',
'Open': '打开',
'1 archived session': '1 个已归档会话',
'{0} archived sessions': '{0} 个已归档会话',
'Search archived sessions': '搜索已归档会话',
'Search projects': '搜索项目',
'No matching archived sessions': '没有匹配的已归档会话',
'No matching projects': '没有匹配的项目',
'Browse archived sessions and restore them': '浏览已归档的会话并恢复',
'Session restored': '会话已恢复',
// image viewer
'Share': '分享',
'Share failed': '分享失败',
'Save to Photos': '保存到相册',
'Saved to Photos': '已保存到相册',
"Couldn't save the picture": '无法保存图片',
'Storage permission is required to save the picture': '保存图片需要存储权限',
// browser
'Browser': '浏览器',
'Enter a URL': '输入网址',
'Web browser': '网页浏览器',
'Enter a URL above to start browsing': '在上方输入网址开始浏览',
'Browser is only available on Android and iOS': '浏览器面板仅支持 Android 和 iOS',
'Open in system browser': '在系统浏览器中打开',
'Forward': '前进',
'Reload': '重新加载',
'History': '历史记录',
'Invalid URL': '无效的网址',
'Could not open the browser: {0}': '无法打开浏览器:{0}',
'No history': '暂无历史记录',
'Dev servers': '开发服务器',
'Enter a URL above, or open a dev server found on the OpenChamber host': '在上方输入网址,或打开在 OpenChamber 主机上发现的开发服务器',
'Could not list dev servers: {0}': '无法获取开发服务器列表:{0}',
'No dev servers found. Start one in the terminal, then refresh.': '没有发现开发服务器。请在终端启动一个,然后刷新。',
'Loopback dev servers (localhost) are previewed through the OpenChamber host; other addresses use this device\'s network.': '本机回环地址(localhost)的开发服务器会通过 OpenChamber 主机预览;其他地址使用手机网络。',
'Could not open the dev server: {0}': '无法打开开发服务器:{0}',
};
+27 -2
View File
@@ -1,12 +1,21 @@
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'appearance_prefs.dart';
import 'l10n.dart';
import 'pets/pet_library.dart';
import 'screens/home_screen.dart';
import 'screens/servers_screen.dart';
import 'state.dart';
import 'version.dart';
void main() {
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// The version goes into every connection's handshake; read it once here so
// nothing waits for it later. The language is read before the first frame
// for the same reason: a saved choice should never flash the other one.
await loadAppVersion();
await L10n.instance.ensureLoaded();
runApp(const OpenChamberApp());
}
@@ -35,6 +44,12 @@ class _OpenChamberAppState extends State<OpenChamberApp>
super.dispose();
}
@override
void didChangeLocales(List<Locale>? locales) {
// "Follow the system" has to redraw when the system language changes.
L10n.instance.systemLocaleChanged();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The socket often dies while the app sits in the background; nothing
@@ -46,13 +61,23 @@ class _OpenChamberAppState extends State<OpenChamberApp>
Widget build(BuildContext context) {
final look = AppearancePrefs.instance;
return ListenableBuilder(
listenable: Listenable.merge([app, look]),
listenable: Listenable.merge([app, look, L10n.instance]),
builder: (context, _) {
final home = app.client == null
? ServersScreen(app: app)
: HomeScreen(app: app);
return MaterialApp(
title: 'OpenChamber',
// Chinese and English, picked in 设置 → 常规 → 语言 or followed
// from the system. The built-in pieces (date and time pickers,
// text selection menu) follow the same choice.
locale: L10n.instance.locale,
supportedLocales: const [Locale('en'), Locale('zh', 'CN')],
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
themeMode: look.themeMode,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
+10 -8
View File
@@ -4,6 +4,8 @@ import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'l10n.dart';
class ModelPrefs {
ModelPrefs._();
static final ModelPrefs instance = ModelPrefs._();
@@ -92,15 +94,15 @@ String formatTokenCount(int tokens) {
/// The Chinese label for an effort variant; unknown ids keep their own name.
String effortLabel(String? variant) {
if (variant == null || variant.isEmpty) return '默认';
if (variant == null || variant.isEmpty) return tr('Default');
return switch (variant.toLowerCase()) {
'default' => '默认',
'none' => '无',
'minimal' => '极低',
'low' => '低',
'medium' || 'mid' => '中',
'high' => '高',
'xhigh' || 'max' => '极高',
'default' => tr('Default'),
'none' => tr('None'),
'minimal' => tr('Minimal'),
'low' => tr('Low'),
'medium' || 'mid' => tr('Medium'),
'high' => tr('High'),
'xhigh' || 'max' => tr('Extra high'),
_ => variant,
};
}
+10 -9
View File
@@ -10,6 +10,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../l10n.dart';
import 'pet_pack.dart';
class PetImportException implements Exception {
@@ -110,16 +111,16 @@ class PetLibrary extends ChangeNotifier {
/// 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.isEmpty) throw PetImportException(tr('File is empty'));
if (bytes.length > 40 * 1024 * 1024) {
throw const PetImportException('宠物包不能超过 40MB');
throw PetImportException(tr('Pet pack cannot exceed 40 MB'));
}
final Archive archive;
try {
archive = ZipDecoder().decodeBytes(bytes, verify: true);
} catch (_) {
throw const PetImportException('不是有效的 zip 文件');
throw PetImportException(tr('Not a valid zip file'));
}
ArchiveFile? manifest;
@@ -133,7 +134,7 @@ class PetLibrary extends ChangeNotifier {
}
}
if (manifest == null) {
throw const PetImportException('压缩包里没有 pack.json');
throw PetImportException(tr('The archive has no pack.json'));
}
final manifestName = manifest.name.replaceAll('\\', '/');
@@ -148,10 +149,10 @@ class PetLibrary extends ChangeNotifier {
if (json is! Map<String, dynamic>) throw const FormatException();
parsed = PetPack.fromJson(json);
} catch (_) {
throw const PetImportException('pack.json 不是有效的宠物包');
throw PetImportException(tr('pack.json is not a valid pet pack'));
}
if (!parsed.isValid) {
throw const PetImportException('pack.json 缺少动画或状态');
throw PetImportException(tr('pack.json is missing animations or states'));
}
final id = _safeId(parsed.id.isNotEmpty ? parsed.id : parsed.name);
@@ -174,7 +175,7 @@ class PetLibrary extends ChangeNotifier {
final content = _content(file);
extracted += content.length;
if (extracted > 60 * 1024 * 1024) {
throw const PetImportException('解压后超过 60MB');
throw PetImportException(tr('Extracted size exceeds 60 MB'));
}
final target = File('${staging.path}/$rel');
await target.parent.create(recursive: true);
@@ -183,11 +184,11 @@ class PetLibrary extends ChangeNotifier {
for (final animation in parsed.animations.values) {
if (animation.sheet.isEmpty) {
throw PetImportException('动画 ${animation.name} 没有精灵图');
throw PetImportException(trArgs('Animation {0} has no sprite sheet', [animation.name]));
}
final sheet = File('${staging.path}/${animation.sheet}');
if (!await sheet.exists()) {
throw PetImportException('缺少精灵图 ${animation.sheet}');
throw PetImportException(trArgs('Missing sprite sheet {0}', [animation.sheet]));
}
}
+360
View File
@@ -0,0 +1,360 @@
// 归档: every archived session in one place, grouped by project and searchable.
// Archived sessions are no longer mixed into the sidebar; this page is the
// only list of them, mirroring OpenChamber's archive page (title, count,
// search, project chips, restore and delete).
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/models.dart';
import '../l10n.dart';
import '../state.dart';
import '../widgets/project_icon.dart';
import '../widgets/project_picker.dart';
class ArchivedSessionsScreen extends StatefulWidget {
final AppState app;
const ArchivedSessionsScreen({super.key, required this.app});
@override
State<ArchivedSessionsScreen> createState() => _ArchivedSessionsScreenState();
}
class _ArchivedSessionsScreenState extends State<ArchivedSessionsScreen> {
final TextEditingController _searchCtrl = TextEditingController();
String _query = '';
/// The selected project bucket key; null is "all projects".
String? _bucket;
AppState get _app => widget.app;
@override
void initState() {
super.initState();
// The sidebar no longer fetches the archive; this page owns it.
if (!_app.archivedLoaded) _app.refreshArchived();
}
@override
void dispose() {
_searchCtrl.dispose();
super.dispose();
}
bool _matches(String directory) {
final selected = _bucket;
if (selected == null) return true;
if (selected == AppState.chatTarget) {
return directory.isEmpty ||
directory == AppState.chatTarget ||
_app.isChatDirectory(directory);
}
return samePath(directory, selected);
}
/// Archived sessions matching the search and the selected project, newest
/// archived first (falling back to updated for old records).
List<Session> _filtered() {
final query = _query.trim().toLowerCase();
return [
for (final session in _app.archivedSessions)
if (_matches(session.directory) &&
(query.isEmpty ||
session.title.toLowerCase().contains(query) ||
session.id.toLowerCase().contains(query) ||
_app
.projectLabelFor(session.directory)
.toLowerCase()
.contains(query)))
session,
]..sort((a, b) => _time(b).compareTo(_time(a)));
}
static int _time(Session session) =>
session.archived > 0 ? session.archived : session.updated;
Future<void> _refresh() => _app.refreshArchived();
/// The projects the picker offers here: only checkouts that actually hold
/// archived sessions. This page never archives anything, so a project
/// without an archive would only get in the way.
List<ProjectInfo> _archiveProjects() {
final byPath = <String, ProjectInfo>{};
for (final session in _app.archivedSessions) {
final directory = session.directory;
if (directory.isEmpty || _app.isChatDirectory(directory)) continue;
final project = _app.projectFor(directory) ??
ProjectInfo(id: '', canonical: directory, name: pathLeaf(directory));
final key = slashPath(project.canonical).toLowerCase();
byPath.putIfAbsent(key, () => project);
}
final projects = byPath.values.toList()
..sort((a, b) => a.label.toLowerCase().compareTo(b.label.toLowerCase()));
return projects;
}
Future<void> _pickProject() async {
final choice = await showProjectPicker(
context,
app: _app,
selected: _bucket ?? allProjectsTarget,
includeAll: true,
onlyProjects: _archiveProjects(),
);
if (choice == null || !mounted) return;
setState(() => _bucket = choice.isAll ? null : choice.canonical);
}
Widget _scopeRow(ThemeData theme) {
final selected = _bucket;
final isChat = selected != null && _app.isChatDirectory(selected);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: InkWell(
borderRadius: BorderRadius.circular(10),
onTap: _pickProject,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
child: Row(
children: [
if (selected == null)
Icon(Icons.folder_copy_outlined,
size: 18, color: theme.hintColor)
else if (isChat)
ProjectIcon(app: _app, chat: true, size: 18)
else
ProjectIcon(
app: _app, project: _app.projectFor(selected), size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
selected == null
? tr('All projects')
: _app.projectLabelFor(selected),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 14),
),
),
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
],
),
),
),
);
}
Future<void> _unarchive(Session session) async {
await _app.setArchived(session, false);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: AppText(tr('Session restored'))));
}
void _copy(Session session) {
Clipboard.setData(ClipboardData(text: session.id));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: AppText(tr('Session ID copied'))));
}
void _confirmDelete(Session session) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const AppText('Delete session?'),
content: AppText(trArgs(
'“{0}” and its subagent sessions will be deleted permanently.',
[session.title])),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const AppText('Cancel')),
FilledButton(
onPressed: () {
Navigator.pop(context);
_app.client?.deleteSession(session.id);
_app.sessions.removeWhere((s) => s.id == session.id);
_app.archivedSessions.removeWhere((s) => s.id == session.id);
_app.touch();
},
child: const AppText('Delete'),
),
],
),
);
}
void _open(Session session) {
_app.openChat(session);
// The archive page sits above the all-features page and the shell; the
// chat opens on the shell.
Navigator.of(context).popUntil((route) => route.isFirst);
}
String _subtitle(Session session, {required bool showProject}) {
final parts = <String>[];
if (showProject) parts.add(_app.projectLabelFor(session.directory));
if (session.isChild) parts.add(tr('Subagent'));
final time = _time(session);
if (time > 0) {
final d = DateTime.fromMillisecondsSinceEpoch(time);
parts.add('${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')} '
'${d.hour.toString().padLeft(2, '0')}:'
'${d.minute.toString().padLeft(2, '0')}');
}
return parts.join(' · ');
}
Widget _row(Session session, {required bool showProject}) {
return ListTile(
// Compact like the sidebar's session rows.
dense: true,
minTileHeight: 56,
contentPadding: const EdgeInsets.only(left: 16, right: 4),
title: Text(
session.title.isEmpty ? tr('(Untitled session)') : session.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 14),
),
subtitle: Text(
_subtitle(session, showProject: showProject),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.unarchive_outlined, size: 20),
tooltip: tr('Unarchive'),
onPressed: () => _unarchive(session),
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
case 'open':
_open(session);
break;
case 'unarchive':
_unarchive(session);
break;
case 'copy':
_copy(session);
break;
case 'delete':
_confirmDelete(session);
break;
}
},
itemBuilder: (_) => [
const PopupMenuItem(value: 'open', child: AppText('Open')),
const PopupMenuItem(
value: 'unarchive', child: AppText('Unarchive')),
const PopupMenuItem(
value: 'copy', child: AppText('Copy session ID')),
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
],
),
onTap: () => _open(session),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const AppText('Archive'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: tr('Refresh'),
onPressed: _app.archivedLoading ? null : _refresh,
),
],
),
body: ListenableBuilder(
listenable: _app,
builder: (context, _) {
final shown = _filtered();
final all = _app.archivedSessions.length;
final count = shown.length == 1
? tr('1 archived session')
: trArgs('{0} archived sessions', [shown.length]);
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 6),
child: TextField(
controller: _searchCtrl,
onChanged: (value) => setState(() => _query = value),
decoration: InputDecoration(
hintText: tr('Search archived sessions'),
prefixIcon: const Icon(Icons.search),
isDense: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
),
_scopeRow(theme),
Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 2),
child: Align(
alignment: Alignment.centerLeft,
child: AppText(
count,
style:
TextStyle(fontSize: 12, color: theme.hintColor),
),
),
),
Expanded(
child: _app.archivedLoading && all == 0
? const Center(child: CircularProgressIndicator())
: RefreshIndicator(
onRefresh: _refresh,
child: shown.isEmpty
? ListView(
// Keep pull-to-refresh working on an empty
// archive.
physics:
const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.all(32),
child: AppText(
all == 0
? 'No archived sessions'
: 'No matching archived sessions',
textAlign: TextAlign.center,
),
),
],
)
: ListView(
physics:
const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(bottom: 24),
children: [
for (final session in shown)
_row(session,
showProject: _bucket == null),
],
),
),
),
],
);
},
),
);
}
}
+563
View File
@@ -0,0 +1,563 @@
// The right sidebar's web browser: an address bar over an embedded WebView,
// with history navigation, reload/stop and opening the page in the system
// browser. A loopback URL (the host's dev server) is carried over the
// OpenChamber dev tunnel through a local TCP listener, so a dev server running
// on the host can be previewed from the phone; other addresses use the phone's
// network. The panel keeps its page while another tab is shown (the tab stack
// keeps it alive).
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../api/dev_tunnel.dart';
import '../api/models.dart';
import '../l10n.dart';
import '../state.dart';
class BrowserPanel extends StatefulWidget {
final AppState app;
/// The session/project whose dev servers the empty state lists.
final String directory;
const BrowserPanel({super.key, required this.app, required this.directory});
@override
State<BrowserPanel> createState() => _BrowserPanelState();
}
class _BrowserPanelState extends State<BrowserPanel> {
static const MethodChannel _channel = MethodChannel('openchamber/browser');
final TextEditingController _url = TextEditingController();
final List<String> _history = [];
WebViewController? _web;
DevTunnel? _tunnel;
int? _tunnelPort;
String? _displayOrigin;
List<DevServerInfo> _servers = const [];
bool _serversLoading = false;
String? _serversError;
bool _loading = false;
bool _hasPage = false;
bool _canBack = false;
bool _canForward = false;
int _progress = 0;
String? _error;
bool get _supported => Platform.isAndroid || Platform.isIOS;
@override
void initState() {
super.initState();
if (!_supported) return;
_web = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(Colors.transparent)
..setNavigationDelegate(NavigationDelegate(
onPageStarted: (url) {
if (!mounted) return;
setState(() {
_loading = true;
_hasPage = true;
_progress = 0;
_error = null;
_setUrl(_displayFor(url));
});
_syncNavigation();
},
onPageFinished: (url) {
if (!mounted) return;
setState(() {
_loading = false;
_progress = 100;
_setUrl(_displayFor(url));
});
_remember(_displayFor(url));
_syncNavigation();
},
onProgress: (value) {
if (mounted) setState(() => _progress = value);
},
onUrlChange: (change) {
final url = change.url;
if (url != null && mounted) setState(() => _setUrl(_displayFor(url)));
},
onNavigationRequest: (request) {
final rewritten = _rewriteNavigation(request.url);
if (rewritten == null) return NavigationDecision.prevent;
if (rewritten != request.url) {
_web?.loadRequest(Uri.parse(rewritten));
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
onWebResourceError: (error) {
if ((error.isForMainFrame ?? true) && mounted) {
setState(() => _error = error.description);
}
},
));
_loadServers();
}
@override
void dispose() {
unawaited(_tunnel?.close());
_url.dispose();
super.dispose();
}
String _displayFor(String url) {
final tunnel = _tunnel;
final origin = _displayOrigin;
if (tunnel == null || origin == null) return url;
return displayUrlFor(url, tunnel.localPort, origin);
}
String? _rewriteNavigation(String url) {
final tunnel = _tunnel;
final origin = _displayOrigin;
if (tunnel == null || origin == null) return url;
final local = 'http://127.0.0.1:${tunnel.localPort}';
if (url == local || url.startsWith('$local/')) return url;
final uri = Uri.tryParse(url);
if (uri == null) return url;
final originOfUrl =
'${uri.scheme}://${uri.host}${uri.hasPort ? ':${uri.port}' : ''}';
if (originOfUrl == origin) {
return localTunnelUri(uri, tunnel.localPort).toString();
}
final port = devServerPort(uri);
if (port != null) {
if (port == _tunnelPort) {
return localTunnelUri(uri, tunnel.localPort).toString();
}
// A loopback link to another dev port means another server on the host.
unawaited(_navigate(url));
return null;
}
return url;
}
Future<void> _syncNavigation() async {
final web = _web;
if (web == null) return;
final back = await web.canGoBack();
final forward = await web.canGoForward();
if (!mounted) return;
setState(() {
_canBack = back;
_canForward = forward;
});
}
/// Puts [url] in the address field with the caret at its end, so the part
/// that was just visited stays visible in the narrow bar.
void _setUrl(String url) {
_url.value = TextEditingValue(
text: url,
selection: TextSelection.collapsed(offset: url.length),
);
}
void _remember(String url) {
if (url.isEmpty) return;
_history.remove(url);
_history.insert(0, url);
if (_history.length > 20) _history.removeLast();
}
Future<void> _loadServers() async {
final cl = widget.app.client;
if (cl == null) return;
setState(() {
_serversLoading = true;
_serversError = null;
});
try {
final list = await cl.devServers(directory: widget.directory);
if (!mounted) return;
// Match the web client's "running dev servers": a port that answered
// with a page is listed when it belongs to a known project (or carries
// no directory, which is how announced servers arrive). Ports started
// outside every project stay behind the web client's "show hidden
// ports" too.
final known = <String>[
if (widget.directory.isNotEmpty) widget.directory,
// Only OpenChamber's own project list counts as work, as on the web;
// an OpenCode project that happens to exist under ~/Downloads or a
// tool's config directory is still outside the user's projects.
for (final project in widget.app.projects)
if (project.canonical.isNotEmpty && project.metaId.isNotEmpty)
project.canonical,
];
bool knownDirectory(String directory) {
if (directory.isEmpty || known.isEmpty) return true;
for (final root in known) {
if (samePath(root, directory) || isUnderDirectory(directory, root)) {
return true;
}
}
return false;
}
final filtered = [
for (final server in list)
if (server.title.isNotEmpty && knownDirectory(server.directory))
server,
]..sort((a, b) => a.port.compareTo(b.port));
setState(() {
_servers = filtered;
_serversLoading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_serversError = '$e';
_serversLoading = false;
});
}
}
Future<DevTunnel?> _ensureTunnel(Uri uri) async {
final port = devServerPort(uri);
if (port == null) {
await _tunnel?.close();
_tunnel = null;
_tunnelPort = null;
_displayOrigin = null;
return null;
}
if (_tunnel != null && _tunnelPort == port) return _tunnel;
await _tunnel?.close();
_tunnel = null;
_tunnelPort = null;
final tunnel = DevTunnel(widget.app, port);
await tunnel.start();
_tunnel = tunnel;
_tunnelPort = port;
_displayOrigin =
'${uri.scheme}://${uri.host}${uri.hasPort ? ':${uri.port}' : ''}';
return tunnel;
}
Future<void> _navigate(String raw) async {
var text = raw.trim();
if (text.isEmpty) return;
if (!text.contains('://')) {
final host = text.split('/').first.split(':').first;
final local = host == 'localhost' ||
host == '127.0.0.1' ||
host == '[::1]' ||
host == '0.0.0.0';
text = '${local ? 'http' : 'https'}://$text';
}
final uri = Uri.tryParse(text);
if (uri == null || !uri.hasAuthority) {
_snack(tr('Invalid URL'));
return;
}
FocusScope.of(context).unfocus();
_setUrl(text);
setState(() {
_loading = true;
_error = null;
});
try {
final tunnel = await _ensureTunnel(uri);
if (!mounted) return;
final target = tunnel == null ? uri : localTunnelUri(uri, tunnel.localPort);
setState(() => _hasPage = true);
await _web?.loadRequest(target);
} catch (e) {
if (!mounted) return;
setState(() {
_loading = false;
_error = trArgs('Could not open the dev server: {0}', [e]);
});
}
}
Future<void> _openExternal() async {
if (!Platform.isAndroid) return;
final url = _url.text.trim();
if (url.isEmpty) return;
try {
await _channel.invokeMethod<bool>('openUrl', {'url': url});
} catch (e) {
if (mounted) _snack(trArgs('Could not open the browser: {0}', [e]));
}
}
void _snack(String text) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: AppText(text)));
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (!_supported) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.public_off, size: 40, color: theme.hintColor),
const SizedBox(height: 12),
const AppText(
'Browser is only available on Android and iOS',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13),
),
],
),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_addressBar(theme),
if (_loading)
LinearProgressIndicator(
value: _progress > 0 && _progress < 100 ? _progress / 100 : null,
minHeight: 2,
),
if (_error != null) _errorBar(theme),
Expanded(
// Keep the WebView attached even before the first address: a
// loadRequest on a controller with no platform view is lost. The
// empty state is an overlay until a page starts.
child: Stack(
children: [
Positioned.fill(child: WebViewWidget(controller: _web!)),
if (!_hasPage)
Positioned.fill(
child: ColoredBox(
color: theme.colorScheme.surface,
child: _empty(theme),
),
),
],
),
),
],
);
}
Widget _addressBar(ThemeData theme) {
final web = _web;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 6, 4, 6),
child: Row(
children: [
Expanded(
child: TextField(
controller: _url,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.go,
onSubmitted: _navigate,
decoration: InputDecoration(
isDense: true,
hintText: tr('Enter a URL'),
prefixIcon: const Icon(Icons.public, size: 18),
suffixIcon: IconButton(
icon: const Icon(Icons.arrow_forward, size: 18),
tooltip: tr('Go'),
onPressed: () => _navigate(_url.text),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
),
IconButton(
icon: Icon(_loading ? Icons.stop : Icons.refresh, size: 20),
tooltip: _loading ? tr('Stop') : tr('Reload'),
onPressed: _loading
? () => web?.runJavaScript('window.stop()')
: web?.reload,
),
MenuAnchor(
builder: (context, controller, child) => IconButton(
icon: const Icon(Icons.more_vert, size: 20),
tooltip: tr('More'),
onPressed: () =>
controller.isOpen ? controller.close() : controller.open(),
),
menuChildren: [
MenuItemButton(
leadingIcon: const Icon(Icons.arrow_back, size: 18),
onPressed: _canBack ? () => web?.goBack() : null,
child: const AppText('Back'),
),
MenuItemButton(
leadingIcon: const Icon(Icons.arrow_forward, size: 18),
onPressed: _canForward ? () => web?.goForward() : null,
child: const AppText('Forward'),
),
if (Platform.isAndroid)
MenuItemButton(
leadingIcon: const Icon(Icons.open_in_browser, size: 18),
onPressed: _openExternal,
child: const AppText('Open in system browser'),
),
MenuItemButton(
leadingIcon: const Icon(Icons.dns_outlined, size: 18),
onPressed: () {
setState(() => _hasPage = false);
_loadServers();
},
child: const AppText('Dev servers'),
),
SubmenuButton(
leadingIcon: const Icon(Icons.history, size: 18),
menuChildren: _history.isEmpty
? [
const MenuItemButton(
onPressed: null,
child: AppText('No history'),
),
]
: [
for (final url in _history)
MenuItemButton(
onPressed: () {
_setUrl(url);
_navigate(url);
},
child: Text(url,
maxLines: 1,
overflow: TextOverflow.ellipsis),
),
],
child: const AppText('History'),
),
],
),
],
),
);
}
Widget _errorBar(ThemeData theme) {
return Container(
color: theme.colorScheme.errorContainer.withValues(alpha: 0.4),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
children: [
Icon(Icons.error_outline,
size: 16, color: theme.colorScheme.error),
const SizedBox(width: 8),
Expanded(
child: Text(
_error!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.colorScheme.error),
),
),
TextButton(
onPressed: () => _web?.reload(),
child: const AppText('Retry'),
),
],
),
);
}
Widget _empty(ThemeData theme) {
return SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(Icons.public, size: 40, color: theme.hintColor),
const SizedBox(height: 8),
const AppText(
'Web browser',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
const SizedBox(height: 2),
const AppText(
'Enter a URL above, or open a dev server found on the OpenChamber host',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12),
),
const SizedBox(height: 14),
Row(
children: [
const Expanded(
child: AppText(
'Dev servers',
style: TextStyle(fontSize: 13.5, fontWeight: FontWeight.w600),
),
),
IconButton(
icon: const Icon(Icons.refresh, size: 18),
tooltip: tr('Refresh'),
onPressed: _serversLoading ? null : _loadServers,
),
],
),
if (_serversLoading)
const Padding(
padding: EdgeInsets.all(16),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2)),
),
)
else if (_servers.isNotEmpty)
for (final server in _servers)
ListTile(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 4),
leading: Icon(Icons.lan_outlined,
size: 20, color: theme.hintColor),
title: Text(server.label,
maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
[
if (server.url.isNotEmpty) server.url,
if (server.command.isNotEmpty) server.command,
].join(' · '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: const Icon(Icons.chevron_right, size: 18),
onTap: () => _navigate(server.url.isEmpty
? 'http://localhost:${server.port}'
: server.url),
)
else
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: AppText(
_serversError != null
? trArgs('Could not list dev servers: {0}', [_serversError!])
: 'No dev servers found. Start one in the terminal, then refresh.',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
),
const SizedBox(height: 10),
const AppText(
'Loopback dev servers (localhost) are previewed through the OpenChamber host; other addresses use this device\'s network.',
style: TextStyle(fontSize: 11.5),
),
],
),
);
}
}
File diff suppressed because it is too large. Load diff
+120
View File
@@ -0,0 +1,120 @@
// 全部功能: the tools the sidebar keeps behind one button, each opening its
// own page. Scheduled tasks so far; more entries go into the grid.
import 'package:flutter/material.dart';
import '../state.dart';
import 'archived_sessions_screen.dart';
import 'scheduled_tasks_screen.dart';
import 'stats_screen.dart';
import '../l10n.dart';
class FeaturesScreen extends StatelessWidget {
final AppState app;
const FeaturesScreen({super.key, required this.app});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const AppText('All features')),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 32),
children: [
AppText('Tools for servers and agents are collected here.',
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
const SizedBox(height: 14),
GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 12,
crossAxisSpacing: 12,
childAspectRatio: 1.25,
children: [
_FeatureTile(
icon: Icons.schedule,
title: 'Scheduled tasks',
caption: 'Send prompts to sessions on a schedule',
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => ScheduledTasksScreen(app: app),
)),
),
_FeatureTile(
icon: Icons.query_stats,
title: 'Stats',
caption: 'Prompts, tokens, cost and model activity',
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => StatsScreen(app: app),
)),
),
_FeatureTile(
icon: Icons.archive_outlined,
title: 'Archive',
caption: 'Browse archived sessions and restore them',
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => ArchivedSessionsScreen(app: app),
)),
),
],
),
],
),
);
}
}
class _FeatureTile extends StatelessWidget {
final IconData icon;
final String title;
final String caption;
final VoidCallback onTap;
const _FeatureTile({
required this.icon,
required this.title,
required this.caption,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(16),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(11),
),
child: Icon(icon,
size: 21, color: theme.colorScheme.onPrimaryContainer),
),
const Spacer(),
AppText(title,
style: const TextStyle(
fontSize: 14.5, fontWeight: FontWeight.w600)),
const SizedBox(height: 2),
AppText(
caption,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
],
),
),
),
);
}
}
+135 -61
View File
@@ -12,15 +12,17 @@ import '../api/models.dart';
import '../api/transport.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
import 'browser_panel.dart';
import 'knowledge_panel.dart';
import 'terminal_panel.dart';
import '../l10n.dart';
Future<void> showFilesPanel(
BuildContext context, AppState app, String directory) {
return showGeneralDialog<void>(
context: context,
barrierDismissible: true,
barrierLabel: '文件',
barrierLabel: tr('Files'),
barrierColor: Colors.black54,
transitionDuration: const Duration(milliseconds: 220),
pageBuilder: (context, _, __) {
@@ -79,8 +81,9 @@ class _FilesPanelState extends State<FilesPanel> {
String? _error;
String _query = '';
/// A project listing hides what git ignores; the menu can show it.
bool _showIgnored = false;
/// The last gitignore choice seen; the app's server-backed setting can
/// change while the panel is open (the switch writes it, a reload reads it).
bool _lastShowIgnored = false;
List<FsEntry> _deepResults = [];
bool _deepDone = false;
@@ -92,6 +95,11 @@ class _FilesPanelState extends State<FilesPanel> {
bool _previewLoading = false;
String? _previewError;
Uint8List? _previewBytes;
/// The file's size from `fs/stat`, even when too large to preview: the
/// download dialog shows a determinate bar against it when the response
/// carries no Content-Length (the relay forwards bodies chunked).
int? _previewSize;
String? _previewText;
bool _previewBinary = false;
bool _previewImage = false;
@@ -103,20 +111,36 @@ class _FilesPanelState extends State<FilesPanel> {
int _tab = 0;
/// Tabs built at least once. Kept alive (offstage) so the browser, terminal
/// and knowledge pages keep their state when another tab is shown.
final Set<int> _built = {0};
@override
void initState() {
super.initState();
_lastShowIgnored = widget.app.showGitignored;
widget.app.addListener(_onApp);
_path = _root;
if (_root.isNotEmpty) _load();
}
@override
void dispose() {
widget.app.removeListener(_onApp);
_editor.dispose();
_search.dispose();
super.dispose();
}
/// The gitignore setting is shared with the web UI; when it changes (here
/// or on another client), reload the listing with the new filter.
void _onApp() {
if (!mounted || widget.app.showGitignored == _lastShowIgnored) return;
_lastShowIgnored = widget.app.showGitignored;
setState(() {});
if (_previewPath == null) _load();
}
// ------------------------------------------------------------- files
Future<void> _load([String? path]) async {
@@ -132,8 +156,8 @@ class _FilesPanelState extends State<FilesPanel> {
_deepDone = false;
});
try {
final list = await client
.fsList(target, directory: _root, respectGitignore: !_showIgnored)
final list = await client.fsList(target,
directory: _root, respectGitignore: !widget.app.showGitignored)
..removeWhere((e) => e.name == '.git');
list.sort((a, b) {
if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
@@ -230,6 +254,7 @@ class _FilesPanelState extends State<FilesPanel> {
_previewLoading = true;
_previewError = null;
_previewBytes = null;
_previewSize = null;
_previewText = null;
_previewBinary = false;
_previewImage = false;
@@ -239,11 +264,15 @@ class _FilesPanelState extends State<FilesPanel> {
if (client == null) return;
try {
final stat = await client.fsStat(entry.path, directory: _root);
if (stat != null && stat.size > 0 && mounted) {
setState(() => _previewSize = stat.size);
}
if (stat != null && stat.size > 2 * 1024 * 1024) {
if (!mounted || _previewPath != entry.path) return;
setState(() {
_previewLoading = false;
_previewError = '文件较大(${_fmtSize(stat.size)}),请下载后查看';
_previewError = trArgs(
'File is large ({0}), download it to view', [_fmtSize(stat.size)]);
});
return;
}
@@ -283,7 +312,7 @@ class _FilesPanelState extends State<FilesPanel> {
_previewText = _editor.text;
_previewBinary = false;
});
_toast('已保存');
_toast('Saved');
} catch (e) {
if (!mounted) return;
setState(() => _saving = false);
@@ -303,6 +332,7 @@ class _FilesPanelState extends State<FilesPanel> {
barrierDismissible: false,
builder: (_) => _DownloadDialog(
name: _previewName,
expectedSize: _previewSize,
start: (onProgress, cancel) => client.downloadFile(path,
directory: _root, onProgress: onProgress, cancel: cancel),
),
@@ -314,9 +344,9 @@ class _FilesPanelState extends State<FilesPanel> {
fileName: _previewName,
bytes: bytes,
);
if (uri != null) _toast('已保存');
if (uri != null) _toast('Saved');
} catch (e) {
_toast('保存失败:$e');
_toast(trArgs('Couldn\'t save: {0}', [e]));
}
}
@@ -325,7 +355,7 @@ class _FilesPanelState extends State<FilesPanel> {
Future<void> _newEntry({required bool directory}) async {
final client = _client;
if (client == null || _path.isEmpty) return;
final name = await _askName(directory ? '新建文件夹' : '新建文件');
final name = await _askName(directory ? 'New folder' : 'New file');
if (name == null) return;
final target = '$_path/$name';
try {
@@ -349,23 +379,23 @@ class _FilesPanelState extends State<FilesPanel> {
final name = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
title: AppText(title),
content: TextField(
controller: controller,
autofocus: true,
decoration: InputDecoration(
labelText: '名称',
hintText: title == '新建文件夹' ? '例如 docs' : '例如 notes.md',
labelText: tr('Name'),
hintText: title == 'New folder' ? tr('e.g. docs') : tr('e.g. notes.md'),
),
onSubmitted: (v) => Navigator.of(context).pop(v),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消')),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.of(context).pop(controller.text),
child: const Text('创建')),
child: const AppText('Create')),
],
),
);
@@ -373,7 +403,7 @@ class _FilesPanelState extends State<FilesPanel> {
final trimmed = name?.trim() ?? '';
if (trimmed.isEmpty) return null;
if (trimmed.contains('/') || trimmed.contains('\\')) {
_toast('名称里不能有斜杠');
_toast(tr('Names cannot contain slashes'));
return null;
}
return trimmed;
@@ -381,7 +411,7 @@ class _FilesPanelState extends State<FilesPanel> {
void _toast(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: AppText(message)));
}
// -------------------------------------------------------------- build
@@ -401,7 +431,20 @@ class _FilesPanelState extends State<FilesPanel> {
children: [
_tabs(theme),
const Divider(height: 1),
Expanded(child: _body(theme)),
Expanded(
child: Stack(
children: [
for (var i = 0; i < 4; i++)
if (_built.contains(i))
Positioned.fill(
child: Offstage(
offstage: _tab != i,
child: _tabBody(i, theme),
),
),
],
),
),
],
),
),
@@ -411,7 +454,14 @@ class _FilesPanelState extends State<FilesPanel> {
/// 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 = ['文件', '项目知识', '终端'];
// Icons only: four labels no longer fit a phone's panel width. The
// tooltips keep them identifiable.
const tabs = [
(Icons.folder_outlined, 'Files'),
(Icons.menu_book_outlined, 'Project knowledge'),
(Icons.terminal, 'Terminal'),
(Icons.public, 'Browser'),
];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 2, 6),
child: Row(
@@ -424,16 +474,25 @@ class _FilesPanelState extends State<FilesPanel> {
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < labels.length; i++)
ButtonSegment(value: i, label: Text(labels[i])),
for (var i = 0; i < tabs.length; i++)
ButtonSegment(
value: i,
icon: Tooltip(
message: tr(tabs[i].$2),
child: Icon(tabs[i].$1, size: 19),
),
),
],
selected: {_tab},
onSelectionChanged: (v) => setState(() => _tab = v.first),
onSelectionChanged: (v) => setState(() {
_tab = v.first;
_built.add(v.first);
}),
),
),
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭侧栏',
tooltip: tr('Close sidebar'),
onPressed: () => Navigator.of(context).maybePop(),
),
],
@@ -441,15 +500,17 @@ class _FilesPanelState extends State<FilesPanel> {
);
}
Widget _body(ThemeData theme) {
Widget _tabBody(int index, ThemeData theme) {
if (_root.isEmpty) {
return const Center(child: Text('这个会话没有关联目录'));
return const Center(child: AppText('This session has no directory'));
}
switch (_tab) {
switch (index) {
case 1:
return KnowledgePanel(app: widget.app, directory: _root);
case 2:
return TerminalPanel(app: widget.app, directory: _root);
case 3:
return BrowserPanel(app: widget.app, directory: _root);
default:
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -485,12 +546,12 @@ class _FilesPanelState extends State<FilesPanel> {
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search, size: 20),
hintText: '搜索当前目录…',
hintText: tr('Search this directory…'),
suffixIcon: _query.trim().isEmpty
? null
: IconButton(
icon: const Icon(Icons.travel_explore, size: 20),
tooltip: '搜索子目录',
tooltip: tr('Search subdirectories'),
onPressed: _searching ? null : _deepSearch,
),
border: OutlineInputBorder(
@@ -513,7 +574,7 @@ class _FilesPanelState extends State<FilesPanel> {
height: 14,
child: CircularProgressIndicator(strokeWidth: 2)),
const SizedBox(width: 8),
Text('正在搜索子目录…(${_deepResults.length})',
AppText(trArgs('Searching subdirectories… ({0})', [_deepResults.length]),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
@@ -535,7 +596,7 @@ class _FilesPanelState extends State<FilesPanel> {
IconButton(
icon: Icon(preview ? Icons.arrow_back : Icons.arrow_upward,
size: 20),
tooltip: preview ? '返回' : '上一级',
tooltip: preview ? tr('Back') : tr('Up one level'),
onPressed: preview
? () => setState(() => _previewPath = null)
: (_path == _root ? null : _up),
@@ -565,7 +626,7 @@ class _FilesPanelState extends State<FilesPanel> {
_crumb(theme, _rootName, () => _load(_root),
last: crumbs.isEmpty),
for (var i = 0; i < crumbs.length; i++) ...[
Text(' / ', style: TextStyle(color: theme.hintColor)),
AppText(' / ', style: TextStyle(color: theme.hintColor)),
_crumb(theme, crumbs[i], () => _goToCrumb(i),
last: i == crumbs.length - 1),
],
@@ -579,7 +640,7 @@ class _FilesPanelState extends State<FilesPanel> {
icon: Icon(_editing
? Icons.visibility_outlined
: Icons.edit_outlined),
tooltip: _editing ? '预览' : '编辑',
tooltip: _editing ? tr('Preview') : tr('Edit'),
onPressed:
_saving ? null : () => setState(() => _editing = !_editing),
),
@@ -591,31 +652,30 @@ class _FilesPanelState extends State<FilesPanel> {
height: 18,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.check),
tooltip: '保存',
tooltip: tr('Save'),
onPressed: _saving ? null : _save,
),
IconButton(
icon: const Icon(Icons.download_outlined),
tooltip: '下载',
tooltip: tr('Download'),
onPressed: _download,
),
] else if (_root.isNotEmpty) ...[
PopupMenuButton<bool>(
icon: const Icon(Icons.add),
tooltip: '新建',
tooltip: tr('New'),
onSelected: (directory) => _newEntry(directory: directory),
itemBuilder: (_) => const [
PopupMenuItem(value: false, child: Text('新建文件')),
PopupMenuItem(value: true, child: Text('新建文件夹')),
PopupMenuItem(value: false, child: AppText('New file')),
PopupMenuItem(value: true, child: AppText('New folder')),
],
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_horiz),
tooltip: '更多',
tooltip: tr('More'),
onSelected: (value) {
if (value == 'ignored') {
setState(() => _showIgnored = !_showIgnored);
_load();
widget.app.setShowGitignored(!widget.app.showGitignored);
} else if (value == 'refresh') {
_load();
}
@@ -623,8 +683,8 @@ class _FilesPanelState extends State<FilesPanel> {
itemBuilder: (_) => [
CheckedPopupMenuItem(
value: 'ignored',
checked: _showIgnored,
child: const Text('显示被 git 忽略的文件'),
checked: widget.app.showGitignored,
child: const AppText('Show git-ignored files'),
),
const PopupMenuItem(
value: 'refresh',
@@ -632,7 +692,7 @@ class _FilesPanelState extends State<FilesPanel> {
children: [
Icon(Icons.refresh, size: 18),
SizedBox(width: 10),
Text('刷新'),
AppText('Refresh'),
],
),
),
@@ -674,7 +734,7 @@ class _FilesPanelState extends State<FilesPanel> {
children: [
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 8),
TextButton(onPressed: () => _load(), child: const Text('重试')),
TextButton(onPressed: () => _load(), child: const AppText('Retry')),
],
),
),
@@ -688,7 +748,7 @@ class _FilesPanelState extends State<FilesPanel> {
.toList();
if (filtered.isEmpty && _deepResults.isEmpty) {
return Center(
child: Text(_query.trim().isEmpty ? '目录为空' : '没有匹配的文件',
child: AppText(_query.trim().isEmpty ? 'Directory is empty' : 'No matching files',
style: TextStyle(color: theme.hintColor)),
);
}
@@ -699,7 +759,7 @@ class _FilesPanelState extends State<FilesPanel> {
if (_query.trim().isNotEmpty && _deepResults.isNotEmpty) ...[
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text('子目录结果',
child: AppText('Subdirectory results',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
for (final e in _deepResults) _tile(theme, e, showPath: true),
@@ -711,7 +771,7 @@ class _FilesPanelState extends State<FilesPanel> {
filtered.isNotEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Text('子目录里没有匹配的文件',
child: AppText('No matching files in subdirectories',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
],
@@ -771,7 +831,7 @@ class _FilesPanelState extends State<FilesPanel> {
Text(_previewError!, textAlign: TextAlign.center),
const SizedBox(height: 8),
if (_previewBytes != null || _previewError != null)
TextButton(onPressed: _download, child: const Text('下载')),
TextButton(onPressed: _download, child: const AppText('Download')),
],
),
),
@@ -793,7 +853,7 @@ class _FilesPanelState extends State<FilesPanel> {
Icon(Icons.insert_drive_file_outlined,
size: 40, color: theme.hintColor),
const SizedBox(height: 10),
Text('这个文件无法预览',
AppText('This file cannot be previewed',
style: TextStyle(color: theme.hintColor)),
const SizedBox(height: 6),
Text(_fmtSize(_previewBytes?.length ?? 0),
@@ -802,7 +862,7 @@ class _FilesPanelState extends State<FilesPanel> {
OutlinedButton.icon(
onPressed: _download,
icon: const Icon(Icons.download_outlined, size: 18),
label: const Text('下载'),
label: const AppText('Download'),
),
],
),
@@ -939,11 +999,16 @@ class _FilesPanelState extends State<FilesPanel> {
/// the dialog closes with no bytes, so nothing is saved.
class _DownloadDialog extends StatefulWidget {
final String name;
/// The file's size from `fs/stat`; the progress bar is determinate against
/// it from the first byte when the response has no Content-Length.
final int? expectedSize;
final Future<Uint8List> Function(
void Function(int received, int? total) onProgress,
CancelToken cancel) start;
const _DownloadDialog({required this.name, required this.start});
const _DownloadDialog(
{required this.name, this.expectedSize, required this.start});
@override
State<_DownloadDialog> createState() => _DownloadDialogState();
@@ -960,6 +1025,7 @@ class _DownloadDialogState extends State<_DownloadDialog> {
@override
void initState() {
super.initState();
_total = (widget.expectedSize ?? 0) > 0 ? widget.expectedSize : null;
_run();
}
@@ -967,14 +1033,17 @@ class _DownloadDialogState extends State<_DownloadDialog> {
try {
final bytes = await widget.start((received, total) {
if (!mounted) return;
// The server's own total is more accurate than the stat we started
// with; keep the latter when the response is chunked.
if (total != null) _total = total;
// 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;
final known = _total;
if (known != null && received < known && now - _lastPaint < 80) return;
_lastPaint = now;
setState(() {
_received = received;
_total = total;
});
}, _cancel);
if (mounted) Navigator.of(context).pop(bytes);
@@ -1000,7 +1069,7 @@ class _DownloadDialogState extends State<_DownloadDialog> {
? (_received / total).clamp(0.0, 1.0)
: null;
return AlertDialog(
title: const Text('正在下载'),
title: const AppText('Downloading'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -1013,11 +1082,16 @@ class _DownloadDialogState extends State<_DownloadDialog> {
if (_error == null) ...[
LinearProgressIndicator(value: fraction),
const SizedBox(height: 8),
Text(
AppText(
total != null
? '${_size(_received)} / ${_size(total)}'
'(${(fraction! * 100).toStringAsFixed(0)}%)'
: '已下载 ${_size(_received)}',
? trArgs('{0} / {1} ({2}%)', [
_size(_received),
_size(total),
// Below 10% one decimal says the transfer is moving;
// whole numbers are enough above it.
(fraction! * 100).toStringAsFixed(fraction < 0.1 ? 1 : 0),
])
: trArgs('Downloaded {0}', [_size(_received)]),
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
] else
@@ -1035,14 +1109,14 @@ class _DownloadDialogState extends State<_DownloadDialog> {
setState(() => _cancelling = true);
_cancel.cancel();
},
child: Text(_cancelling ? '正在取消…' : '取消'),
child: AppText(_cancelling ? 'Canceling…' : 'Cancel'),
)
else
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('关闭'),
child: const AppText('Close'),
),
],
);
}
}
}
+4 -3
View File
@@ -7,6 +7,7 @@ import '../state.dart';
import 'chat_screen.dart';
import 'new_session_screen.dart';
import 'sessions_screen.dart';
import '../l10n.dart';
class HomeScreen extends StatefulWidget {
final AppState app;
@@ -126,13 +127,13 @@ class _HomeScreenState extends State<HomeScreen> {
children: [
Icon(Icons.forum_outlined, size: 40, color: scheme.onSurfaceVariant),
const SizedBox(height: 12),
Text('选择一个会话',
AppText('Choose a session',
style: TextStyle(fontSize: 16, color: scheme.onSurfaceVariant)),
if (!wide) ...[
const SizedBox(height: 12),
FilledButton(
onPressed: () => _scaffold.currentState?.openDrawer(),
child: const Text('打开会话列表'),
child: const AppText('Open the session list'),
),
],
],
@@ -140,4 +141,4 @@ class _HomeScreenState extends State<HomeScreen> {
),
);
}
}
}
+77 -73
View File
@@ -6,6 +6,7 @@ import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
import '../l10n.dart';
class KnowledgePanel extends StatefulWidget {
final AppState app;
@@ -48,7 +49,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
if (client == null || _projectId.isEmpty) {
setState(() {
_loading = false;
_error = '这个会话没有关联目录';
_error = tr('This session has no directory');
});
return;
}
@@ -116,8 +117,8 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
decoration: InputDecoration(
isDense: true,
hintText: _memory == null
? '搜索笔记、待办与计划'
: '搜索笔记、待办、计划与记忆',
? tr('Search notes, todos, and plans')
: tr('Search notes, todos, plans, and memory'),
prefixIcon: const Icon(Icons.search, size: 18),
suffixIcon: _query.isEmpty
? null
@@ -134,7 +135,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
),
),
IconButton(
tooltip: '刷新',
tooltip: tr('Refresh'),
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.refresh, size: 20),
onPressed: _load,
@@ -151,11 +152,11 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
List<(String, String, int)> get _sectionsList {
final context = _context;
return [
('notes', '笔记', context?.notes.length ?? 0),
('todos', '待办', context?.todos.length ?? 0),
('plans', '计划', context?.plans.length ?? 0),
('notes', tr('Notes'), context?.notes.length ?? 0),
('todos', tr('Todos'), context?.todos.length ?? 0),
('plans', tr('Plans'), context?.plans.length ?? 0),
if (_memory != null)
('memory', '记忆',
('memory', tr('Memory'),
(_memory!.global.length + _memory!.project.length)),
];
}
@@ -172,7 +173,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
),
segments: [
for (final (key, label, count) in sections)
ButtonSegment(value: key, label: Text('$label $count')),
ButtonSegment(value: key, label: AppText('$label $count')),
],
selected: {_section},
onSelectionChanged: (value) => setState(() => _section = value.first),
@@ -193,7 +194,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
textAlign: TextAlign.center,
style: TextStyle(color: theme.colorScheme.error, fontSize: 13)),
const SizedBox(height: 8),
FilledButton(onPressed: _load, child: const Text('重试')),
FilledButton(onPressed: _load, child: const AppText('Retry')),
],
),
),
@@ -223,11 +224,12 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
});
return Column(
children: [
_sectionHeader(theme, '${notes.length} 条笔记', '新建笔记', _addNote),
_sectionHeader(theme, trArgs('{0} notes', [notes.length]),
'New note', _addNote),
Expanded(
child: notes.isEmpty
? _empty(theme, Icons.sticky_note_2_outlined,
_query.isEmpty ? '还没有笔记' : '没有匹配的笔记')
_query.isEmpty ? 'No notes yet' : 'No matching notes')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
itemCount: notes.length,
@@ -307,10 +309,10 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
}
},
itemBuilder: (_) => [
const PopupMenuItem(value: 'edit', child: Text('编辑')),
const PopupMenuItem(value: 'edit', child: AppText('Edit')),
PopupMenuItem(
value: 'pin', child: Text(note.pinned ? '取消置顶' : '置顶')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
value: 'pin', child: AppText(note.pinned ? 'Unpin' : 'Pin')),
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
],
@@ -329,11 +331,12 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
final done = todos.where((todo) => todo.completed).length;
return Column(
children: [
_sectionHeader(theme, '$done/${todos.length} 已完成', '新建待办', _addTodo),
_sectionHeader(theme, trArgs('{0}/{1} done', [done, todos.length]),
'New todo', _addTodo),
Expanded(
child: todos.isEmpty
? _empty(theme, Icons.checklist,
_query.isEmpty ? '还没有待办' : '没有匹配的待办')
_query.isEmpty ? 'No todos yet' : 'No matching todos')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 12),
itemCount: todos.length,
@@ -344,7 +347,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
value: todo.completed,
onChanged: (value) => _toggleTodo(todo, value ?? false),
controlAffinity: ListTileControlAffinity.leading,
title: Text(
title: AppText(
todo.text,
style: TextStyle(
fontSize: 13.5,
@@ -370,7 +373,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'delete', child: Text('删除')),
PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
);
@@ -404,11 +407,12 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
});
return Column(
children: [
_sectionHeader(theme, '${plans.length} 份计划', '新建计划', _newPlan),
_sectionHeader(theme, trArgs('{0} plans', [plans.length]),
'New plan', _newPlan),
Expanded(
child: plans.isEmpty
? _empty(theme, Icons.description_outlined,
_query.isEmpty ? '还没有计划' : '没有匹配的计划')
_query.isEmpty ? 'No plans yet' : 'No matching plans')
: ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 12),
itemCount: plans.length,
@@ -464,8 +468,8 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
),
],
const SizedBox(height: 2),
Text(
plan.source == 'shared' ? '团队共享' : '个人',
AppText(
plan.source == 'shared' ? 'Shared' : 'Personal',
style: TextStyle(fontSize: 11, color: theme.hintColor),
),
],
@@ -493,8 +497,8 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
},
itemBuilder: (_) => [
PopupMenuItem(
value: 'pin', child: Text(plan.pinned ? '取消置顶' : '置顶')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
value: 'pin', child: AppText(plan.pinned ? 'Unpin' : 'Pin')),
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
onTap: () => _viewPlan(plan),
@@ -507,7 +511,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
Widget _memoryBody(ThemeData theme) {
final snapshot = _memory;
if (snapshot == null) {
return _empty(theme, Icons.psychology_outlined, '记忆功能未启用');
return _empty(theme, Icons.psychology_outlined, 'Memory is not enabled');
}
final global = snapshot.global
.where((m) => _matches([m.title, m.body]))
@@ -519,20 +523,20 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
return _empty(
theme,
Icons.psychology_outlined,
_query.isEmpty ? '还没有记忆' : '没有匹配的记忆');
_query.isEmpty ? 'No memories yet' : 'No matching memories');
}
return ListView(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
children: [
_memoryGroup(theme, '全局记忆', global, 'global',
_memoryGroup(theme, tr('Global memory'), global, 'global',
failed: snapshot.globalFailed),
const SizedBox(height: 8),
_memoryGroup(theme, '项目记忆', project, 'project',
_memoryGroup(theme, tr('Project memory'), project, 'project',
failed: snapshot.projectFailed),
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
'记忆由 agent 在会话中记录;你可以在这里修改或删除它。',
child: AppText(
'Memory is recorded by the agent during sessions; you can edit or delete it here.',
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
),
@@ -548,20 +552,20 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
children: [
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text('$title(${entries.length})',
child: AppText(trArgs('{0} ({1})', [title, entries.length]),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
if (failed)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text('读取失败,请刷新',
child: AppText('Could not load, refresh to retry',
style: TextStyle(
fontSize: 12, color: theme.colorScheme.error)),
)
else if (entries.isEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text('暂无', style: TextStyle(fontSize: 12, color: theme.hintColor)),
child: AppText('None', style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
for (final entry in entries) _memoryCard(theme, entry, scope),
],
@@ -631,8 +635,8 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'edit', child: Text('编辑')),
PopupMenuItem(value: 'delete', child: Text('删除')),
PopupMenuItem(value: 'edit', child: AppText('Edit')),
PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
],
@@ -700,7 +704,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
child: Row(
children: [
Expanded(
child: Text(summary,
child: AppText(summary,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
TextButton.icon(
@@ -711,7 +715,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
),
onPressed: onTap,
icon: const Icon(Icons.add, size: 16),
label: Text(action, style: const TextStyle(fontSize: 12.5)),
label: AppText(action, style: const TextStyle(fontSize: 12.5)),
),
],
),
@@ -725,7 +729,7 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
children: [
Icon(icon, size: 36, color: theme.hintColor),
const SizedBox(height: 8),
Text(text, style: TextStyle(fontSize: 13, color: theme.hintColor)),
AppText(text, style: TextStyle(fontSize: 13, color: theme.hintColor)),
],
),
);
@@ -737,13 +741,13 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
final text = await showDialog<String>(
context: context,
builder: (_) => _TextPromptDialog(
title: note == null ? '新建笔记' : '编辑笔记',
hint: '记点什么,供之后的会话参考',
title: note == null ? 'New note' : 'Edit note',
hint: tr('Write something for later sessions to read'),
initial: note?.body ?? '',
maxLength: 3000,
maxLines: 10,
minLines: 4,
action: '保存',
action: 'Save',
),
);
if (text == null || text.isEmpty) return;
@@ -765,13 +769,13 @@ class _KnowledgePanelState extends State<KnowledgePanel> {
Future<void> _addTodo() async {
final text = await showDialog<String>(
context: context,
builder: (_) => const _TextPromptDialog(
title: '新建待办',
hint: '要做什么',
builder: (_) => _TextPromptDialog(
title: 'New todo',
hint: tr('What needs doing'),
maxLength: 1000,
maxLines: 1,
minLines: 1,
action: '保存',
action: 'Save',
),
);
if (text == null || text.isEmpty) return;
@@ -888,13 +892,13 @@ class _PlanPageState extends State<_PlanPage> {
if (_editing)
TextButton(
onPressed: _saving ? null : () => setState(() => _editing = false),
child: const Text('取消'),
child: const AppText('Cancel'),
),
TextButton(
onPressed: _saving
? null
: (_editing ? _save : () => setState(() => _editing = true)),
child: Text(_saving ? '保存中…' : (_editing ? '保存' : '编辑')),
child: AppText(_saving ? 'Saving…' : (_editing ? 'Save' : 'Edit')),
),
],
),
@@ -961,7 +965,7 @@ class _TextPromptDialogState extends State<_TextPromptDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(widget.title),
title: AppText(widget.title),
content: SizedBox(
width: double.maxFinite,
child: TextField(
@@ -979,10 +983,10 @@ class _TextPromptDialogState extends State<_TextPromptDialog> {
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(context, _controller.text.trim()),
child: Text(widget.action)),
child: AppText(widget.action)),
],
);
}
@@ -1010,7 +1014,7 @@ class _NewPlanDialogState extends State<_NewPlanDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('新建计划'),
title: const AppText('New plan'),
content: SizedBox(
width: double.maxFinite,
child: Column(
@@ -1020,9 +1024,9 @@ class _NewPlanDialogState extends State<_NewPlanDialog> {
controller: _title,
autofocus: true,
maxLength: 160,
decoration: const InputDecoration(
labelText: '标题',
border: OutlineInputBorder(),
decoration: InputDecoration(
labelText: tr('Title'),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
@@ -1030,10 +1034,10 @@ class _NewPlanDialogState extends State<_NewPlanDialog> {
controller: _body,
maxLines: 10,
minLines: 6,
decoration: const InputDecoration(
decoration: InputDecoration(
alignLabelWithHint: true,
labelText: '计划正文(Markdown)',
border: OutlineInputBorder(),
labelText: tr('Plan body (Markdown)'),
border: const OutlineInputBorder(),
),
),
],
@@ -1042,11 +1046,11 @@ class _NewPlanDialogState extends State<_NewPlanDialog> {
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(
context, (_title.text.trim(), _body.text)),
child: const Text('创建')),
child: const AppText('Create')),
],
);
}
@@ -1078,7 +1082,7 @@ class _MemoryDialogState extends State<_MemoryDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('编辑记忆'),
title: const AppText('Edit memory'),
content: SizedBox(
width: double.maxFinite,
child: Column(
@@ -1088,9 +1092,9 @@ class _MemoryDialogState extends State<_MemoryDialog> {
controller: _title,
autofocus: true,
maxLength: 120,
decoration: const InputDecoration(
labelText: '标题',
border: OutlineInputBorder(),
decoration: InputDecoration(
labelText: tr('Title'),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
@@ -1101,9 +1105,9 @@ class _MemoryDialogState extends State<_MemoryDialog> {
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: const [
ButtonSegment(value: 'fact', label: Text('事实')),
ButtonSegment(value: 'preference', label: Text('偏好')),
ButtonSegment(value: 'reference', label: Text('参考')),
ButtonSegment(value: 'fact', label: AppText('Fact')),
ButtonSegment(value: 'preference', label: AppText('Preference')),
ButtonSegment(value: 'reference', label: AppText('Reference')),
],
selected: {_type},
onSelectionChanged: (value) =>
@@ -1115,10 +1119,10 @@ class _MemoryDialogState extends State<_MemoryDialog> {
maxLength: 2000,
maxLines: 6,
minLines: 4,
decoration: const InputDecoration(
decoration: InputDecoration(
alignLabelWithHint: true,
labelText: '内容',
border: OutlineInputBorder(),
labelText: tr('Content'),
border: const OutlineInputBorder(),
),
),
],
@@ -1126,16 +1130,16 @@ class _MemoryDialogState extends State<_MemoryDialog> {
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context), child: const Text('取消')),
onPressed: () => Navigator.pop(context), child: const AppText('Cancel')),
FilledButton(
onPressed: () {
final title = _title.text.trim();
if (title.isEmpty) return;
Navigator.pop(context, (title, _body.text.trim(), _type));
},
child: const Text('保存'),
child: const AppText('Save'),
),
],
);
}
}
}
+29 -87
View File
@@ -4,14 +4,16 @@
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/project_icon.dart';
import '../widgets/project_picker.dart';
import '../widgets/slash_palette.dart';
import 'files_panel.dart';
import '../l10n.dart';
class NewSessionScreen extends StatefulWidget {
final AppState app;
@@ -175,7 +177,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('选择失败:$e')));
.showSnackBar(SnackBar(content: AppText(trArgs('Could not attach: {0}', [e]))));
}
} finally {
if (mounted) setState(() => _attaching = false);
@@ -206,14 +208,14 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
? null
: IconButton(
icon: const Icon(Icons.menu),
tooltip: '会话',
tooltip: tr('Sessions'),
onPressed: widget.onOpenSessions,
),
title: const Text('新会话'),
title: const AppText('New session'),
actions: [
IconButton(
icon: const Icon(Icons.folder_open_outlined),
tooltip: '文件',
tooltip: tr('Files'),
onPressed: () => showFilesPanel(context, app, draft.directory),
),
],
@@ -227,8 +229,8 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
child: Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Text(
'我们今天要做什么?',
child: AppText(
'What are we building today?',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 26,
@@ -280,6 +282,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
Widget _projectChip(SessionDraft draft) {
final theme = Theme.of(context);
final isChat = draft.directory == AppState.chatTarget;
final label = widget.app.projectLabelFor(draft.directory);
return InkWell(
borderRadius: BorderRadius.circular(18),
@@ -289,13 +292,17 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.folder_outlined,
size: 15, color: theme.hintColor),
ProjectIcon(
app: widget.app,
project: isChat ? null : widget.app.projectFor(draft.directory),
chat: isChat,
size: 15,
),
const SizedBox(width: 5),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 170),
child: Text(
label.isEmpty ? '选择项目' : label,
label.isEmpty ? tr('Choose project') : label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
@@ -316,7 +323,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
Widget body = ComposerBox(
controller: _text,
focusNode: _inputFocus,
hint: '规划、构建或提问',
hint: tr('Plan, build, or ask'),
maxLines: 5,
keyboardInset: keyboardInset,
textInputAction:
@@ -348,7 +355,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
},
leading: _roundKey(
icon: Icons.attach_file,
label: '添加附件',
label: tr('Add attachment'),
onTap: _pickFiles,
busy: _attaching,
),
@@ -455,83 +462,18 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
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 sheet opens right away; it refreshes the project list inside.
final choice = await showProjectPicker(
context,
app: app,
selected: draft.directory,
);
if (choice == null || !mounted) return;
app.updateDraftTarget(choice.canonical);
_slashLoaded = false;
_slashItems = [];
}
/// 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();
}
}
}
+19 -16
View File
@@ -10,6 +10,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/qr_scan.dart';
import '../l10n.dart';
/// Opens the scanner and returns the pairing link, or null when cancelled.
Future<String?> scanPairingQr(BuildContext context) {
@@ -92,7 +93,7 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
return;
}
if (cameras.isEmpty) {
if (mounted) setState(() => _error = '没有可用的相机');
if (mounted) setState(() => _error = tr('No camera available'));
return;
}
CameraDescription pick = cameras.first;
@@ -123,11 +124,12 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
await controller.startImageStream(_onFrame);
_watchdog = Timer(const Duration(seconds: 4), () {
if (!mounted || _frames > 0 || _error != null) return;
setState(() => _hint = '没有收到相机画面,请关闭后重试');
setState(() => _hint = tr('No camera frames received; close and try again'));
});
_slowHint = Timer(const Duration(seconds: 12), () {
if (!mounted || _found || _frames == 0) return;
_showHint('还没识别到二维码,试着靠近一点或让二维码占满取景框', sticky: true);
_showHint(tr('No QR code yet; move closer or fill the frame with the code'),
sticky: true);
});
return;
} catch (error) {
@@ -151,11 +153,11 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
if (error.code == 'CameraAccessDenied' ||
error.code == 'CameraAccessDeniedWithoutPrompt' ||
error.code == 'CameraAccessRestricted') {
return '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。';
return tr('Camera permission is required to scan. Allow OpenChamber to use the camera in system settings.');
}
return '无法打开相机:${error.description ?? error.code}';
return trArgs('Could not open the camera: {0}', [error.description ?? error.code]);
}
return '无法打开相机:$error';
return trArgs('Could not open the camera: {0}', [error]);
}
void _onFrame(CameraImage image) {
@@ -187,14 +189,14 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
if (text.trim().startsWith('openchamber://connect')) {
_accept(text.trim());
} else {
_showHint('这不是 OpenChamber 配对二维码');
_showHint(tr('This is not an OpenChamber pairing QR code'));
}
}).catchError((Object error) {
_decoding = false;
_decodeErrors += 1;
if (_decodeErrors == 1) {
debugPrint('qr: decode failed: $error');
if (mounted) _showHint('二维码解码出错,请重试');
if (mounted) _showHint(tr('Could not decode the QR code; try again'));
}
});
}
@@ -247,7 +249,7 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
await controller.setFlashMode(_torch ? FlashMode.off : FlashMode.torch);
if (mounted) setState(() => _torch = !_torch);
} catch (_) {
if (mounted) _showHint('这个相机不支持手电筒');
if (mounted) _showHint(tr('This camera does not support the flashlight'));
}
}
@@ -279,7 +281,7 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
const SizedBox(height: 16),
FilledButton.tonal(
onPressed: _start,
child: const Text('重试'),
child: const AppText('Retry'),
),
],
),
@@ -294,14 +296,14 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
Row(
children: [
IconButton(
tooltip: '关闭',
tooltip: tr('Close'),
icon: const Icon(Icons.close),
color: Colors.white,
onPressed: () => Navigator.of(context).pop(),
),
const Spacer(),
IconButton(
tooltip: '手电筒',
tooltip: tr('Flashlight'),
icon: Icon(_torch ? Icons.flash_on : Icons.flash_off),
color: Colors.white,
onPressed: _toggleTorch,
@@ -314,13 +316,13 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
child: Column(
children: [
Text(
_hint ?? '把配对二维码放进框内',
_hint ?? tr('Put the pairing QR code inside the frame'),
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white, fontSize: 14),
),
const SizedBox(height: 6),
const Text(
'在 OpenChamber 网页端打开「连接设备」,选择二维码',
const AppText(
'In the OpenChamber web app, open “Connect a device” and choose the QR code',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white60, fontSize: 12),
),
@@ -328,7 +330,8 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'${_frameShape ?? ''} · 已扫描 $_frames 帧 / 解码 $_decodeAttempts 次',
trArgs('{0} · {1} frames scanned / {2} decode attempts',
[_frameShape ?? '', _frames, _decodeAttempts]),
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white38,
+503
View File
@@ -0,0 +1,503 @@
// 计划任务: the server's scheduled prompts, one project (or the chats scope)
// at a time. The list follows the web client: name, schedule, last result,
// next run, and the actions it offers — run now, pause, edit, delete.
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/scheduled_tasks.dart';
import '../state.dart';
import '../widgets/project_picker.dart';
import '../widgets/scheduled_task_editor.dart';
import '../l10n.dart';
/// Where a task runs: a registered project, or the chats scope.
class _TaskScope {
final String id;
final String label;
/// The checkout the tasks run in; empty for the chats scope.
final String directory;
const _TaskScope(this.id, this.label, [this.directory = '']);
}
class ScheduledTasksScreen extends StatefulWidget {
final AppState app;
const ScheduledTasksScreen({super.key, required this.app});
@override
State<ScheduledTasksScreen> createState() => _ScheduledTasksScreenState();
}
class _ScheduledTasksScreenState extends State<ScheduledTasksScreen> {
late final List<_TaskScope> _scopes;
late _TaskScope? _scope;
List<ScheduledTask> _tasks = const [];
bool _loading = true;
String? _error;
String _busyId = '';
AppState get app => widget.app;
@override
void initState() {
super.initState();
_scopes = _buildScopes();
_scope = _defaultScope();
_load();
}
List<_TaskScope> _buildScopes() {
return [
for (final project in selectableProjects(app))
_scopeFor(project),
_chatsScope,
];
}
static _TaskScope _scopeFor(ProjectInfo project) => _TaskScope(
project.metaId.isNotEmpty
? project.metaId
: Client.projectIdFor(project.canonical),
project.label,
project.canonical,
);
_TaskScope get _chatsScope =>
_TaskScope(Client.scheduledChatsScope, tr('Chat'));
_TaskScope? _defaultScope() {
if (_scopes.isEmpty) return null;
final directory = app.directory;
if (directory.isNotEmpty) {
// A session below the chats root schedules into the chats scope.
if (app.isChatDirectory(directory)) return _scopes.last;
for (final scope in _scopes) {
if (slashPath(scope.directory) == slashPath(directory)) return scope;
}
}
return _scopes.first;
}
Future<void> _load() async {
final scope = _scope;
final client = app.client;
if (scope == null || client == null) {
setState(() {
_loading = false;
_tasks = const [];
_error = client == null ? tr('Not connected to a server') : null;
});
return;
}
setState(() {
_loading = true;
_error = null;
});
try {
final tasks = await client.scheduledTasks(scope.id);
if (!mounted || _scope?.id != scope.id) return;
setState(() {
_tasks = tasks;
_loading = false;
});
} on ApiError catch (e) {
if (!mounted || _scope?.id != scope.id) return;
setState(() {
_loading = false;
_tasks = const [];
_error = e.status == 404
? 'The server doesn\'t support scheduled tasks'
: trArgs('Couldn\'t load scheduled tasks: {0}', [e.message]);
});
} catch (e) {
if (!mounted || _scope?.id != scope.id) return;
setState(() {
_loading = false;
_tasks = const [];
_error = trArgs('Couldn\'t load scheduled tasks: {0}', [e]);
});
}
}
void _say(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: AppText(message)));
}
Future<void> _openEditor([ScheduledTask? task]) async {
final scope = _scope;
if (scope == null) return;
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
showDragHandle: true,
builder: (_) => ScheduledTaskEditor(
app: app,
scopeLabel: scope.label,
initial: task,
onSave: (draft) => _save(scope, draft),
),
);
}
Future<bool> _save(_TaskScope scope, ScheduledTask draft) async {
final client = app.client;
if (client == null) {
_say(tr('Not connected to a server'));
return false;
}
try {
final tasks = await client.saveScheduledTask(scope.id, draft);
if (!mounted) return true;
if (_scope?.id == scope.id) setState(() => _tasks = tasks);
_say('Scheduled task saved');
return true;
} on ApiError catch (e) {
_say(e.message.isEmpty ? 'Couldn\'t save task' : e.message);
return false;
} catch (e) {
_say(trArgs('Couldn\'t save task: {0}', [e]));
return false;
}
}
Future<void> _toggle(ScheduledTask task, bool enabled) async {
final scope = _scope;
final client = app.client;
if (scope == null || client == null || _busyId.isNotEmpty) return;
setState(() => _busyId = task.id);
try {
final tasks =
await client.saveScheduledTask(scope.id, task.copyWith(enabled: enabled));
if (!mounted) return;
if (_scope?.id == scope.id) setState(() => _tasks = tasks);
} catch (e) {
_say(e is ApiError && e.message.isNotEmpty ? e.message : 'Couldn\'t update task');
await _load();
} finally {
if (mounted) setState(() => _busyId = '');
}
}
Future<void> _runNow(ScheduledTask task) async {
final scope = _scope;
final client = app.client;
if (scope == null || client == null || _busyId.isNotEmpty) return;
setState(() => _busyId = task.id);
try {
await client.runScheduledTask(scope.id, task.id);
_say('Task started');
await _load();
} on ApiError catch (e) {
_say(e.status == 409 ? 'Task is already waiting in the queue' : (e.message.isEmpty ? 'Couldn\'t run task' : e.message));
} catch (e) {
_say(trArgs('Couldn\'t run task: {0}', [e]));
} finally {
if (mounted) setState(() => _busyId = '');
}
}
Future<void> _delete(ScheduledTask task) async {
final scope = _scope;
final client = app.client;
if (scope == null || client == null) return;
final ok = await showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: const AppText('Delete scheduled task?'),
content: AppText(trArgs('“{0}” and its schedule will be deleted.', [task.name])),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(dialog, true),
child: const AppText('Delete')),
],
),
);
if (ok != true || !mounted) return;
setState(() => _busyId = task.id);
try {
final tasks = await client.deleteScheduledTask(scope.id, task.id);
if (!mounted) return;
if (_scope?.id == scope.id) setState(() => _tasks = tasks);
_say('Scheduled task deleted');
} catch (e) {
_say(e is ApiError && e.message.isNotEmpty ? e.message : 'Couldn\'t delete task');
} finally {
if (mounted) setState(() => _busyId = '');
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const AppText('Scheduled tasks'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: tr('Refresh'),
onPressed: _loading ? null : _load,
),
IconButton(
icon: const Icon(Icons.add),
tooltip: tr('New task'),
onPressed: _scope == null ? null : () => _openEditor(),
),
],
),
body: Column(
children: [
_scopeBar(theme),
const Divider(height: 1),
Expanded(child: _body(theme)),
],
),
);
}
/// The same sheet the new-session composer uses: checkouts and the Chat
/// scope, with the project list refreshed behind it.
Future<void> _pickScope() async {
final selected =
_scope == null || _scope!.directory.isEmpty ? AppState.chatTarget : _scope!.directory;
final choice = await showProjectPicker(
context,
app: app,
selected: selected,
);
if (choice == null || !mounted) return;
final next = choice.isChat ? _chatsScope : _scopeFor(choice.project!);
if (next.id == _scope?.id) return;
setState(() {
_scope = next;
_tasks = const [];
_loading = true;
_error = null;
});
_load();
}
Widget _scopeBar(ThemeData theme) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 8, 6),
child: Row(
children: [
Icon(Icons.folder_outlined, size: 18, color: theme.hintColor),
const SizedBox(width: 8),
AppText('Runs in', style: TextStyle(fontSize: 13, color: theme.hintColor)),
const SizedBox(width: 10),
Expanded(
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: _pickScope,
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
children: [
Expanded(
child: Text(
_scope?.label ?? tr('Choose project'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13.5,
color: theme.colorScheme.onSurface),
),
),
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
],
),
),
),
),
],
),
);
}
Widget _body(ThemeData theme) {
if (_loading) return const Center(child: CircularProgressIndicator());
if (_error != null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!, style: TextStyle(color: theme.hintColor)),
const SizedBox(height: 8),
TextButton(onPressed: _load, child: const AppText('Retry')),
],
),
);
}
if (_tasks.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.event_note_outlined, size: 36, color: theme.hintColor),
const SizedBox(height: 10),
AppText('No scheduled tasks yet.', style: TextStyle(color: theme.hintColor)),
const SizedBox(height: 8),
FilledButton.tonalIcon(
onPressed: () => _openEditor(),
icon: const Icon(Icons.add, size: 18),
label: const AppText('New task'),
),
],
),
);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 24),
itemCount: _tasks.length,
itemBuilder: (context, i) => _card(theme, _tasks[i]),
),
);
}
Widget _card(ThemeData theme, ScheduledTask task) {
final running = task.lastStatus == 'running' || task.lastStatus == 'queued';
final statusColor = switch (task.lastStatus) {
'success' || 'sent' => theme.colorScheme.primary,
'error' || 'failed' => theme.colorScheme.error,
'running' || 'queued' => theme.colorScheme.tertiary,
_ => theme.hintColor,
};
final next = task.nextRunAt > 0 && task.enabled
? trArgs('Next: {0}', [scheduledRelativeTime(task.nextRunAt)])
: (task.enabled ? '' : 'Paused');
final last = task.lastRunAt > 0
? trArgs('Last run {0} · {1}', [
scheduledClock(task.lastRunAt),
scheduledStatusLabel(task.lastStatus),
])
: 'Never run';
return Card(
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 2),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _openEditor(task),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 6, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
task.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 15.5, fontWeight: FontWeight.w600),
),
),
if (_busyId == task.id)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 12),
child: SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 1.8)),
)
else
Switch(
value: task.enabled,
onChanged: (v) => _toggle(task, v),
),
PopupMenuButton<String>(
tooltip: tr('More'),
onSelected: (value) {
switch (value) {
case 'run':
_runNow(task);
case 'edit':
_openEditor(task);
case 'delete':
_delete(task);
}
},
itemBuilder: (_) => [
const PopupMenuItem(value: 'run', child: AppText('Run now')),
const PopupMenuItem(value: 'edit', child: AppText('Edit')),
PopupMenuItem(
value: 'delete',
child: AppText('Delete',
style: TextStyle(color: theme.colorScheme.error)),
),
],
),
],
),
Text(scheduledScheduleText(task),
style: TextStyle(fontSize: 13, color: theme.colorScheme.onSurfaceVariant)),
if (task.targetSessionId.isEmpty)
const SizedBox.shrink()
else
AppText('Sends to an existing session', style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
const SizedBox(height: 4),
Row(
children: [
if (running) ...[
SizedBox(
width: 12,
height: 12,
child: CircularProgressIndicator(
strokeWidth: 1.6, color: statusColor),
),
const SizedBox(width: 6),
] else ...[
Icon(Icons.circle, size: 8, color: statusColor),
const SizedBox(width: 6),
],
Expanded(
child: Text(
last,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
),
if (next.isNotEmpty)
Text(next,
style:
TextStyle(fontSize: 11.5, color: theme.hintColor)),
],
),
if (task.lastError.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
task.lastError,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style:
TextStyle(fontSize: 11.5, color: theme.colorScheme.error),
),
),
const SizedBox(height: 2),
Text(
task.modelLabel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
],
),
),
),
);
}
}
+47 -42
View File
@@ -4,6 +4,7 @@ import 'package:flutter/services.dart';
import '../state.dart';
import '../storage.dart';
import 'scan_qr_screen.dart';
import '../l10n.dart';
/// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget {
@@ -70,11 +71,11 @@ class _ServersScreenState extends State<ServersScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('OpenChamber',
AppText('OpenChamber',
style: theme.textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold)),
const SizedBox(height: 4),
Text('连接你的 OpenChamber 服务器',
AppText('Connect to your OpenChamber server',
style: theme.textTheme.bodyMedium
?.copyWith(color: theme.hintColor)),
],
@@ -98,7 +99,7 @@ class _ServersScreenState extends State<ServersScreen> {
child: OutlinedButton.icon(
onPressed: () => _startEdit(null),
icon: const Icon(Icons.add),
label: const Text('添加服务器'),
label: const AppText('Add server'),
),
),
const SizedBox(width: 8),
@@ -106,7 +107,7 @@ class _ServersScreenState extends State<ServersScreen> {
child: FilledButton.tonalIcon(
onPressed: _pair,
icon: const Icon(Icons.qr_code_2, size: 18),
label: const Text('配对链接'),
label: const AppText('Pairing link'),
),
),
],
@@ -130,10 +131,10 @@ class _ServersScreenState extends State<ServersScreen> {
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(c.isRelay ? '经由 Relay · ${c.serverId}' : c.url,
Text(c.isRelay ? trArgs('Via Relay · {0}', [c.serverId]) : c.url,
maxLines: 1, overflow: TextOverflow.ellipsis),
if (!c.isRelay && c.proxy.isNotEmpty)
Text('经由 ${c.proxy}',
AppText(trArgs('Via {0}', [c.proxy]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
@@ -143,9 +144,9 @@ class _ServersScreenState extends State<ServersScreen> {
mainAxisSize: MainAxisSize.min,
children: [
if (connected)
Text('已连接', style: TextStyle(color: theme.colorScheme.primary))
AppText('Connected', style: TextStyle(color: theme.colorScheme.primary))
else
TextButton(onPressed: () => _connect(c), child: const Text('连接')),
TextButton(onPressed: () => _connect(c), child: const AppText('Connect')),
PopupMenuButton<String>(
onSelected: (v) {
if (v == 'edit') {
@@ -155,8 +156,8 @@ class _ServersScreenState extends State<ServersScreen> {
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'edit', child: Text('编辑')),
PopupMenuItem(value: 'delete', child: Text('删除')),
PopupMenuItem(value: 'edit', child: AppText('Edit')),
PopupMenuItem(value: 'delete', child: AppText('Delete')),
],
),
],
@@ -221,27 +222,28 @@ class _ServersScreenState extends State<ServersScreen> {
setState(() => _editing = false);
},
),
title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'),
title: AppText(_editNew ? 'Add server' : trArgs('Connect to {0}', [_edit!.label])),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
_labelText('名称'),
_labelText('Name'),
TextField(
controller: TextEditingController(text: _label),
onChanged: (v) => _label = v,
decoration: const InputDecoration(hintText: '如 我的电脑', border: OutlineInputBorder()),
decoration: InputDecoration(
hintText: tr('e.g. My computer'), border: const OutlineInputBorder()),
),
const SizedBox(height: 12),
if (_edit?.isRelay == true) ...[
const ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(Icons.lock_outline, size: 20),
title: Text('通过 Relay 连接'),
subtitle: Text('端到端加密;服务器与设备令牌保持不变'),
title: AppText('Connect through Relay'),
subtitle: AppText('End-to-end encrypted; the server and device token stay the same'),
),
] else ...[
_labelText('服务器地址'),
_labelText('Server address'),
TextField(
controller: TextEditingController(text: _url),
onChanged: (v) => _url = v,
@@ -250,38 +252,41 @@ class _ServersScreenState extends State<ServersScreen> {
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('代理(可选)'),
_labelText('Proxy (optional)'),
TextField(
controller: TextEditingController(text: _proxy),
onChanged: (v) => _proxy = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()),
decoration: InputDecoration(
hintText: tr('http://… or socks5://…'),
border: const OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('自签证书指纹(可选)'),
_labelText('Self-signed certificate fingerprint (optional)'),
TextField(
controller: TextEditingController(text: _fingerprint),
onChanged: (v) => _fingerprint = v,
decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()),
decoration: InputDecoration(
hintText: tr('SHA-256 hex'),
border: const OutlineInputBorder()),
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('信任自签名证书'),
title: const AppText('Trust self-signed certificates'),
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('密码(如果需要)'),
_labelText('Password (if required)'),
TextField(
controller: TextEditingController(text: _password),
focusNode: _passwordFocus,
onChanged: (v) => _password = v,
obscureText: true,
decoration: const InputDecoration(
hintText: '服务器密码;服务器未设置可留空',
border: OutlineInputBorder()),
decoration: InputDecoration(
hintText: tr('Server password; leave empty if the server has none'),
border: const OutlineInputBorder()),
),
],
if (_formError != null)
@@ -296,7 +301,7 @@ class _ServersScreenState extends State<ServersScreen> {
child: _connecting
? const SizedBox(
height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('连接'),
: const AppText('Connect'),
),
],
),
@@ -305,7 +310,7 @@ class _ServersScreenState extends State<ServersScreen> {
Widget _labelText(String s) => Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(s, style: Theme.of(context).textTheme.bodySmall),
child: AppText(s, style: Theme.of(context).textTheme.bodySmall),
);
Future<void> _submit() async {
@@ -348,7 +353,8 @@ class _ServersScreenState extends State<ServersScreen> {
/// The server asked for a password: put the caret where it is typed.
void _focusPasswordIfNeeded(String? message) {
if (message == null || !message.contains('需要密码')) return;
// The message is already in the UI's language; look for the same word.
if (message == null || !message.contains(tr('Password'))) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _passwordFocus.requestFocus();
});
@@ -364,16 +370,16 @@ class _ServersScreenState extends State<ServersScreen> {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('删除服务器?'),
content: Text('“${c.label}”将从列表移除,设备令牌也会删除。'),
title: const AppText('Delete server?'),
content: AppText(trArgs('“{0}” will be removed from the list, and its device token will be deleted.', [c.label])),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
TextButton(onPressed: () => Navigator.pop(context), child: const AppText('Cancel')),
FilledButton(
onPressed: () {
Navigator.pop(context);
widget.app.removeConnection(c);
},
child: const Text('删除'),
child: const AppText('Delete'),
),
],
),
@@ -452,7 +458,7 @@ class _PairingDialogState extends State<_PairingDialog> {
}
setState(() {
_busy = false;
_error = widget.app.lastError ?? '配对失败';
_error = widget.app.lastError ?? tr('Pairing failed');
});
widget.app.clearLastError();
}
@@ -461,16 +467,15 @@ class _PairingDialogState extends State<_PairingDialog> {
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
title: const Text('配对链接'),
title: const AppText('Pairing link'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'在 OpenChamber 网页端打开「连接设备」,粘贴链接或直接扫描二维码。'
'链接里带一次性密钥,以及直连地址或私有 Relay。',
AppText(
'In the OpenChamber web app, open “Connect a device”, then paste the link or scan the QR code. The link carries a one-time key and either a direct address or a private Relay.',
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
),
const SizedBox(height: 12),
@@ -497,13 +502,13 @@ class _PairingDialogState extends State<_PairingDialog> {
TextButton.icon(
onPressed: _busy ? null : _scan,
icon: const Icon(Icons.qr_code_scanner, size: 18),
label: const Text('扫码'),
label: const AppText('Scan QR code'),
),
const SizedBox(width: 4),
TextButton.icon(
onPressed: _busy ? null : _paste,
icon: const Icon(Icons.content_paste, size: 18),
label: const Text('粘贴'),
label: const AppText('Paste'),
),
],
),
@@ -513,14 +518,14 @@ class _PairingDialogState extends State<_PairingDialog> {
actions: [
TextButton(
onPressed: _busy ? null : () => Navigator.of(context).pop(),
child: const Text('取消'),
child: const AppText('Cancel'),
),
FilledButton(
onPressed: _busy ? null : _connect,
child: _busy
? const SizedBox(
width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('配对并连接'),
: const AppText('Pair and connect'),
),
],
);
+214 -162
View File
@@ -6,8 +6,11 @@ import 'package:flutter_slidable/flutter_slidable.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/project_icon.dart';
import 'features_screen.dart';
import 'servers_screen.dart';
import 'settings_screen.dart';
import '../l10n.dart';
/// 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
@@ -29,7 +32,11 @@ class _SessionListPaneState extends State<SessionListPane> {
Timer? _timer;
late final TextEditingController _searchCtrl;
final Set<String> _collapsed = {};
bool _showArchived = false;
/// Parents whose subagents are expanded. Collapsed is the default; the
/// parent of the open child expands once so its child is visible.
final Set<String> _expandedChildren = {};
String? _activeChildParent;
@override
void initState() {
@@ -62,6 +69,7 @@ class _SessionListPaneState extends State<SessionListPane> {
return ListenableBuilder(
listenable: _app,
builder: (context, _) {
_syncActiveParent();
final scheme = Theme.of(context).colorScheme;
return SafeArea(
child: Column(
@@ -72,13 +80,13 @@ class _SessionListPaneState extends State<SessionListPane> {
children: [
const SizedBox(width: 12),
const Expanded(
child: Text('会话',
child: AppText('Sessions',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w600)),
),
IconButton(
icon: Icon(_searchOpen ? Icons.close : Icons.search),
tooltip: '搜索',
tooltip: tr('Search'),
onPressed: () {
setState(() {
_searchOpen = !_searchOpen;
@@ -91,7 +99,7 @@ class _SessionListPaneState extends State<SessionListPane> {
),
IconButton(
icon: const Icon(Icons.add),
tooltip: '新会话',
tooltip: tr('New session'),
onPressed: () => _newSession(),
),
],
@@ -104,10 +112,10 @@ class _SessionListPaneState extends State<SessionListPane> {
controller: _searchCtrl,
autofocus: true,
onChanged: _onSearchChanged,
decoration: const InputDecoration(
hintText: '搜索会话',
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
decoration: InputDecoration(
hintText: tr('Search sessions'),
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: true,
),
),
@@ -123,8 +131,8 @@ class _SessionListPaneState extends State<SessionListPane> {
color: scheme.error, fontSize: 13)),
),
TextButton(
onPressed: _app.refreshSessions,
child: const Text('重试')),
onPressed: _app.retryConnection,
child: const AppText('Retry')),
],
),
),
@@ -163,7 +171,7 @@ class _SessionListPaneState extends State<SessionListPane> {
size: 18, color: scheme.onSurfaceVariant),
const SizedBox(width: 8),
Expanded(
child: Text(
child: AppText(
_app.connectionName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -178,9 +186,14 @@ class _SessionListPaneState extends State<SessionListPane> {
),
),
),
IconButton(
icon: const Icon(Icons.widgets_outlined),
tooltip: tr('All features'),
onPressed: _openFeatures,
),
IconButton(
icon: const Icon(Icons.settings_outlined),
tooltip: '设置',
tooltip: tr('Settings'),
onPressed: _openSettings,
),
],
@@ -189,6 +202,13 @@ class _SessionListPaneState extends State<SessionListPane> {
);
}
void _openFeatures() {
widget.onOpened?.call();
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => FeaturesScreen(app: _app),
));
}
void _openSettings() {
// A phone's list is a drawer: close it before the settings page covers
// the shell.
@@ -221,26 +241,23 @@ class _SessionListPaneState extends State<SessionListPane> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_searchCtrl.text.isEmpty ? '暂无会话' : '没有匹配的会话'),
AppText(_searchCtrl.text.isEmpty ? 'No sessions' : 'No matching sessions'),
const SizedBox(height: 8),
FilledButton(
onPressed: () => _newSession(), child: const Text('新会话')),
onPressed: () => _newSession(), child: const AppText('New session')),
],
),
);
}
return RefreshIndicator(
onRefresh: () async {
await app.refreshSessions();
if (app.archivedLoaded) await app.refreshArchived();
},
onRefresh: app.refreshSessions,
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),
_footer(),
],
),
);
@@ -248,19 +265,13 @@ class _SessionListPaneState extends State<SessionListPane> {
// --------------------------------------------------------------- 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'
final key = _app.isChatDirectory(session.directory)
? AppState.chatTarget
: slashPath(session.directory);
map.putIfAbsent(key, () => []).add(session);
}
@@ -268,9 +279,13 @@ class _SessionListPaneState extends State<SessionListPane> {
for (final entry in map.entries)
_SessionGroup(
key: entry.key,
label: _groupLabel(entry.value.first.directory),
label: entry.key == AppState.chatTarget
? tr('Chat')
: _app.projectLabelFor(entry.value.first.directory),
// The first session's own path: the server knows that spelling.
path: entry.key == '\u0000chats' ? '' : entry.value.first.directory,
path: entry.key == AppState.chatTarget
? ''
: entry.value.first.directory,
sessions: entry.value
..sort((a, b) => b.updated.compareTo(a.updated)),
),
@@ -290,7 +305,7 @@ class _SessionListPaneState extends State<SessionListPane> {
if (!collapsed)
for (final entry in _dated(group.sessions)) ...[
_caption(entry.key),
for (final session in entry.value) _row(session),
for (final session in entry.value) ..._rowsWithChildren(session),
],
];
}
@@ -310,21 +325,29 @@ class _SessionListPaneState extends State<SessionListPane> {
// 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),
// The band already insets by 8, the same as a session row's
// content padding. No padding inside it then makes the folder
// chevron and the + share one vertical line with the session rows'
// chevron and ⋮.
contentPadding: EdgeInsets.zero,
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),
ProjectIcon(
app: _app,
project: group.key == AppState.chatTarget
? null
: _app.projectFor(group.path),
chat: group.key == AppState.chatTarget,
size: 16,
),
],
),
title: Text(
group.label.isEmpty ? '未命名项目' : group.label,
group.label.isEmpty ? tr('Untitled project') : group.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
@@ -349,8 +372,13 @@ class _SessionListPaneState extends State<SessionListPane> {
child: IconButton(
icon: const Icon(Icons.add, size: 20),
padding: EdgeInsets.zero,
tooltip: '在此项目新会话',
onPressed: () => _newSession(directory: group.path),
tooltip: group.key == AppState.chatTarget
? tr('New chat')
: tr('New session in this project'),
onPressed: () => _newSession(
directory: group.key == AppState.chatTarget
? AppState.chatTarget
: group.path),
),
),
onTap: () => setState(() {
@@ -368,7 +396,7 @@ class _SessionListPaneState extends State<SessionListPane> {
Widget _caption(String label) {
return Padding(
padding: const EdgeInsets.fromLTRB(28, 6, 12, 2),
child: Text(label,
child: AppText(label,
style: TextStyle(
fontSize: 11, color: Theme.of(context).hintColor)),
);
@@ -381,10 +409,10 @@ class _SessionListPaneState extends State<SessionListPane> {
final yesterday = today.subtract(const Duration(days: 1));
final weekAgo = today.subtract(const Duration(days: 7));
final buckets = <String, List<Session>>{
'今天': [],
'昨天': [],
'本周早些时候': [],
'更早': [],
'Today': [],
'Yesterday': [],
'Earlier this week': [],
'Earlier': [],
};
for (final session in sessions) {
final time = session.updated > 0
@@ -392,12 +420,12 @@ class _SessionListPaneState extends State<SessionListPane> {
: DateTime.fromMillisecondsSinceEpoch(session.created);
final day = DateTime(time.year, time.month, time.day);
final key = day == today
? '今天'
? 'Today'
: day == yesterday
? '昨天'
? 'Yesterday'
: day.isAfter(weekAgo)
? '本周早些时候'
: '更早';
? 'Earlier this week'
: 'Earlier';
buckets[key]!.add(session);
}
return [
@@ -427,7 +455,7 @@ class _SessionListPaneState extends State<SessionListPane> {
size: 13, color: Theme.of(context).hintColor),
const SizedBox(width: 5),
Expanded(
child: Text('已置顶',
child: AppText('Pinned',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
@@ -440,13 +468,13 @@ class _SessionListPaneState extends State<SessionListPane> {
),
),
if (!collapsed)
for (final session in pinned) _row(session),
for (final session in pinned) ..._rowsWithChildren(session),
];
}
Widget _draftRow(SessionDraft draft) {
final theme = Theme.of(context);
final label = draft.firstLine.isEmpty ? '新会话' : draft.firstLine;
final label = draft.firstLine.isEmpty ? tr('New session') : draft.firstLine;
final project = _app.projectLabelFor(draft.directory);
return ListTile(
selected: _app.draftOpen,
@@ -457,14 +485,14 @@ class _SessionListPaneState extends State<SessionListPane> {
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontStyle: FontStyle.italic),
),
subtitle: Text(
project.isEmpty ? '草稿' : '草稿 · $project',
subtitle: AppText(
project.isEmpty ? 'Draft' : trArgs('Draft · {0}', [project]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: IconButton(
icon: const Icon(Icons.close, size: 18),
tooltip: '丢弃草稿',
tooltip: tr('Discard draft'),
onPressed: () => _app.discardDraft(),
),
onTap: () {
@@ -480,37 +508,75 @@ class _SessionListPaneState extends State<SessionListPane> {
.any((s) => s.parentID == session.id && _app.active.contains(s.id));
}
Widget _row(Session session, {bool archived = false}) {
/// The session's worker sessions (subagents). The API lists them among the
/// sessions, so they are drawn nested right below their parent.
List<Session> _childrenOf(Session parent) {
return [
for (final session in _app.sessions)
if (session.parentID == parent.id) session,
]..sort((a, b) => a.created.compareTo(b.created));
}
List<Widget> _rowsWithChildren(Session session) {
final rows = <Widget>[_row(session)];
if (!_expandedChildren.contains(session.id)) return rows;
final theme = Theme.of(context);
for (final child in _childrenOf(session)) {
rows.add(Container(
margin: const EdgeInsets.only(left: 24),
decoration: BoxDecoration(
border: Border(
left: BorderSide(color: theme.dividerColor, width: 1),
),
),
child: _row(child, child: true),
));
}
return rows;
}
/// Expands the parent of the open subagent once, so the sidebar shows where
/// the child is. Collapsing it by hand stays collapsed until another child
/// is opened.
void _syncActiveParent() {
final parent = _app.chat?.session.parentID;
if (parent == _activeChildParent) return;
_activeChildParent = parent;
if (parent != null) _expandedChildren.add(parent);
}
Widget _row(Session session, {bool child = false}) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final running = _isActive(session);
final selected =
!_app.draftOpen && _app.chat?.session.id == session.id;
final children = child ? const <Session>[] : _childrenOf(session);
final expanded = _expandedChildren.contains(session.id);
return Slidable(
key: ValueKey('${archived ? 'a' : 's'}-${session.id}'),
key: ValueKey('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 ? '取消归档' : '归档',
onPressed: (_) => _app.togglePin(session),
icon: Icons.push_pin_outlined,
label: session.isPinned ? tr('Unpin') : tr('Pin'),
backgroundColor: scheme.secondaryContainer,
foregroundColor: scheme.onSecondaryContainer,
),
SlidableAction(
onPressed: (_) => _archive(session),
icon: Icons.archive_outlined,
label: tr('Archive'),
backgroundColor: scheme.surfaceContainerHighest,
foregroundColor: scheme.onSurface,
),
SlidableAction(
onPressed: (_) => _confirmDelete(session),
icon: Icons.delete_outline,
label: '删除',
label: tr('Delete'),
backgroundColor: scheme.errorContainer,
foregroundColor: scheme.onErrorContainer,
),
@@ -520,10 +586,44 @@ class _SessionListPaneState extends State<SessionListPane> {
// Compact: both the project band and a session row are 56 high.
dense: true,
minTileHeight: 56,
// A fixed chevron column for every session row: rows without
// subagents keep the same title start as rows with them. A short gap
// after it keeps the title space wide.
contentPadding: child
? const EdgeInsets.only(left: 32, right: 8)
: const EdgeInsets.only(left: 8, right: 8),
horizontalTitleGap: 8,
selected: selected,
selectedTileColor: scheme.primary.withValues(alpha: 0.10),
leading: child
? null
: children.isEmpty
? const SizedBox(width: 18)
: SizedBox(
width: 18,
height: 40,
child: IconButton(
icon: Icon(
expanded
? Icons.expand_more
: Icons.chevron_right,
size: 18),
tooltip: expanded ? tr('Collapse subagents') : tr('Expand subagents'),
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
constraints:
const BoxConstraints(minWidth: 18, minHeight: 40),
onPressed: () => setState(() {
if (expanded) {
_expandedChildren.remove(session.id);
} else {
_expandedChildren.add(session.id);
}
}),
),
),
title: Text(
session.title.isEmpty ? '(无标题会话)' : session.title,
session.title.isEmpty ? tr('(Untitled session)') : session.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
@@ -531,8 +631,10 @@ class _SessionListPaneState extends State<SessionListPane> {
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
),
),
subtitle: Text(_subtitle(session),
maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
child ? trArgs('Subagent · {0}', [_subtitle(session)]) : _subtitle(session),
maxLines: 1,
overflow: TextOverflow.ellipsis),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -552,7 +654,7 @@ class _SessionListPaneState extends State<SessionListPane> {
strokeWidth: 1.8, color: scheme.primary),
),
),
_menu(session, archived: archived),
_menu(session),
],
),
onTap: () {
@@ -563,7 +665,7 @@ class _SessionListPaneState extends State<SessionListPane> {
);
}
Widget _menu(Session session, {required bool archived}) {
Widget _menu(Session session) {
// The same 48 slot as the project header's +, so the keys line up.
return SizedBox(
width: 48,
@@ -579,7 +681,7 @@ class _SessionListPaneState extends State<SessionListPane> {
_app.togglePin(session);
break;
case 'archive':
_archive(session, archived);
_archive(session);
break;
case 'delete':
_confirmDelete(session);
@@ -587,94 +689,42 @@ class _SessionListPaneState extends State<SessionListPane> {
case 'copy':
Clipboard.setData(ClipboardData(text: session.id));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('已复制会话 ID')));
const SnackBar(content: AppText('Session ID copied')));
break;
}
},
itemBuilder: (_) => [
if (!archived) ...[
const PopupMenuItem(value: 'rename', child: Text('重命名')),
PopupMenuItem(
value: 'pin',
child: Text(session.isPinned ? '取消置顶' : '置顶')),
],
const PopupMenuItem(value: 'rename', child: AppText('Rename')),
PopupMenuItem(
value: 'archive',
child: Text(archived ? '取消归档' : '归档')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
const PopupMenuItem(value: 'copy', child: Text('复制会话 ID')),
value: 'pin',
child: AppText(session.isPinned ? 'Unpin' : 'Pin')),
const PopupMenuItem(value: 'archive', child: AppText('Archive')),
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
const PopupMenuItem(value: 'copy', child: AppText('Copy session ID')),
],
),
);
}
Widget _footer(ColorScheme scheme) {
Widget _footer() {
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)),
),
],
if (!app.hasMoreSessions) return const SizedBox.shrink();
return TextButton(
onPressed: app.loadingMoreSessions ? null : app.loadMoreSessions,
child: app.loadingMoreSessions
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: const AppText('Load more'),
);
}
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);
final children = _childrenOf(s).length;
if (children > 0) parts.add(trArgs('{0} subagents', [children]));
if (s.model != null) parts.add(_app.modelName(s.model));
if (s.updated > 0) {
final t = DateTime.fromMillisecondsSinceEpoch(s.updated);
@@ -692,8 +742,8 @@ class _SessionListPaneState extends State<SessionListPane> {
widget.onOpened?.call();
}
Future<void> _archive(Session session, bool archived) async {
await _app.setArchived(session, !archived);
Future<void> _archive(Session session) async {
await _app.setArchived(session, true);
}
void _rename(Session s) {
@@ -701,18 +751,18 @@ class _SessionListPaneState extends State<SessionListPane> {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('重命名'),
title: const AppText('Rename'),
content: TextField(controller: ctrl, autofocus: true),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
child: const AppText('Cancel')),
FilledButton(
onPressed: () {
Navigator.pop(context);
_app.client?.updateSession(s.id, title: ctrl.text);
},
child: const Text('保存'),
child: const AppText('Save'),
),
],
),
@@ -723,12 +773,12 @@ class _SessionListPaneState extends State<SessionListPane> {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('删除会话?'),
content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'),
title: const AppText('Delete session?'),
content: AppText(trArgs('“{0}” and its subagent sessions will be deleted permanently.', [s.title])),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
child: const AppText('Cancel')),
FilledButton(
onPressed: () {
Navigator.pop(context);
@@ -737,7 +787,7 @@ class _SessionListPaneState extends State<SessionListPane> {
_app.archivedSessions.removeWhere((x) => x.id == s.id);
_app.touch();
},
child: const Text('删除'),
child: const AppText('Delete'),
),
],
),
@@ -754,7 +804,7 @@ class _SessionListPaneState extends State<SessionListPane> {
children: [
const Padding(
padding: EdgeInsets.all(12),
child: Text('服务器',
child: AppText('Servers',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
@@ -762,10 +812,12 @@ class _SessionListPaneState extends State<SessionListPane> {
ListTile(
title: Text(c.label),
subtitle: Text(c.isRelay
? '经由 Relay · ${c.serverId}'
: (c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}')),
? trArgs('Via Relay · {0}', [c.serverId])
: (c.proxy.isEmpty
? c.url
: trArgs('{0}\nvia {1}', [c.url, c.proxy]))),
trailing: app.conn?.id == c.id
? Text('已连接',
? AppText('Connected',
style: TextStyle(
color: Theme.of(context).colorScheme.primary))
: null,
@@ -777,7 +829,7 @@ class _SessionListPaneState extends State<SessionListPane> {
],
ListTile(
leading: const Icon(Icons.add),
title: const Text('添加服务器'),
title: const AppText('Add server'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute(
@@ -787,8 +839,8 @@ class _SessionListPaneState extends State<SessionListPane> {
),
ListTile(
leading: const Icon(Icons.qr_code_2),
title: const Text('配对链接'),
subtitle: const Text('直连地址或 OpenChamber Relay'),
title: const AppText('Pairing link'),
subtitle: const AppText('Direct address or OpenChamber Relay'),
onTap: () {
Navigator.pop(context);
showPairingDialog(context, app);
@@ -797,7 +849,7 @@ class _SessionListPaneState extends State<SessionListPane> {
if (app.client != null)
ListTile(
leading: const Icon(Icons.link_off),
title: const Text('断开当前连接'),
title: const AppText('Disconnect'),
onTap: () {
Navigator.pop(context);
app.disconnect();
@@ -822,4 +874,4 @@ class _SessionGroup {
required this.path,
required this.sessions,
});
}
}
File diff suppressed because it is too large. Load diff
+939
View File
@@ -0,0 +1,939 @@
// 统计: the OpenCode session statistics, as the OpenChamber web client shows
// them — prompts, steps, tokens, cost, activity, models and tool calls — sized
// for a phone. The numbers come from `/api/experimental/session/stats`.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/usage_stats.dart';
import '../l10n.dart';
import '../state.dart';
import '../time_zone.dart';
import '../widgets/project_icon.dart';
import '../widgets/project_picker.dart';
const _tokenColors = [
Color(0xFF7C6CF6),
Color(0xFF3FB6A8),
Color(0xFFE0A03A),
Color(0xFFB06AD6),
];
/// Tools mode used for the model filter of the models section.
enum _ModelDimension { tokens, cost, steps }
class StatsScreen extends StatefulWidget {
final AppState app;
const StatsScreen({super.key, required this.app});
@override
State<StatsScreen> createState() => _StatsScreenState();
}
class _StatsScreenState extends State<StatsScreen> {
UsageRange _range = UsageRange.month;
ProjectInfo? _project;
UsageStats? _stats;
bool _loading = true;
String? _error;
int _fetchedAt = 0;
int _generation = 0;
UsageTools? _tools;
bool _toolsLoading = false;
String? _toolsError;
_ModelDimension _dimension = _ModelDimension.tokens;
int? _activeBar;
AppState get app => widget.app;
@override
void initState() {
super.initState();
_load();
}
String? get _directory => (_project?.canonical.isNotEmpty ?? false)
? _project!.canonical
: app.directory;
Future<void> _load() async {
final client = app.client;
if (client == null) {
setState(() {
_loading = false;
_error = tr('Not connected to a server');
});
return;
}
final generation = ++_generation;
setState(() {
_loading = true;
_error = null;
_activeBar = null;
});
try {
final zone = await deviceTimeZone();
final stats = await client.sessionStats(
from: _range.startFrom(DateTime.now()),
project: _project?.id,
timezone: zone,
directory: _directory,
);
if (!mounted || generation != _generation) return;
setState(() {
_stats = stats;
_loading = false;
_fetchedAt = DateTime.now().millisecondsSinceEpoch;
_tools = null;
_toolsError = null;
});
} catch (e) {
if (!mounted || generation != _generation) return;
setState(() {
_loading = false;
_error = e is ApiError ? e.message : '$e';
});
}
}
/// Tool counts make the server read every message in the window, so they are
/// only requested when the person asks for them (as in the web client).
Future<void> _loadTools() async {
final client = app.client;
final stats = _stats;
if (client == null || stats == null) return;
setState(() {
_toolsLoading = true;
_toolsError = null;
});
try {
final zone = await deviceTimeZone();
final withTools = await client.sessionStats(
from: stats.from,
to: stats.to,
project: _project?.id,
timezone: zone,
tools: true,
directory: _directory,
);
if (!mounted) return;
setState(() {
_tools = withTools.tools;
_toolsLoading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_toolsLoading = false;
_toolsError = e is ApiError ? e.message : '$e';
});
}
}
Future<void> _pickProject() async {
final choice = await showProjectPicker(
context,
app: app,
selected: _project?.canonical ?? allProjectsTarget,
includeAll: true,
includeChat: false,
);
if (choice == null || !mounted) return;
setState(() => _project = choice.isAll ? null : choice.project);
await _load();
}
String _rangeLabel(UsageRange range) => switch (range) {
UsageRange.day => tr('Today'),
UsageRange.week => tr('7 days'),
UsageRange.month => tr('30 days'),
UsageRange.quarter => tr('90 days'),
UsageRange.all => tr('All time'),
};
String _updatedLabel() {
final at = DateTime.fromMillisecondsSinceEpoch(_fetchedAt);
final now = DateTime.now();
final time = '${at.hour.toString().padLeft(2, '0')}:'
'${at.minute.toString().padLeft(2, '0')}';
final sameDay = at.year == now.year && at.month == now.month && at.day == now.day;
final text = sameDay
? time
: '${at.month.toString().padLeft(2, '0')}-'
'${at.day.toString().padLeft(2, '0')} $time';
return trArgs('Updated {0}', [text]);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const AppText('Stats'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: tr('Refresh'),
onPressed: _loading ? null : _load,
),
],
),
body: RefreshIndicator(
onRefresh: _load,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 6, 16, 40),
children: [
Wrap(
spacing: 8,
runSpacing: 4,
children: [
for (final range in UsageRange.values)
ChoiceChip(
label: Text(_rangeLabel(range)),
selected: _range == range,
onSelected: (_) {
if (_range == range) return;
setState(() => _range = range);
_load();
},
),
],
),
const SizedBox(height: 2),
_scopeRow(theme),
if (_loading && _stats != null)
const Padding(
padding: EdgeInsets.only(top: 2),
child: LinearProgressIndicator(minHeight: 2),
),
if (!_loading && _error == null && _fetchedAt > 0)
Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(top: 2, right: 6),
child: Text(_updatedLabel(),
style: TextStyle(fontSize: 11, color: theme.hintColor)),
),
),
const SizedBox(height: 6),
..._body(theme),
],
),
),
);
}
Widget _scopeRow(ThemeData theme) {
return InkWell(
borderRadius: BorderRadius.circular(10),
onTap: _pickProject,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
child: Row(
children: [
if (_project == null)
Icon(Icons.folder_copy_outlined,
size: 18, color: theme.hintColor)
else
ProjectIcon(app: app, project: _project, size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
_project?.label ?? tr('All projects'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 14),
),
),
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
],
),
),
);
}
List<Widget> _body(ThemeData theme) {
final stats = _stats;
if (stats == null) {
if (_loading) {
return const [
Padding(
padding: EdgeInsets.only(top: 48),
child: Center(child: CircularProgressIndicator()),
),
];
}
return [
Padding(
padding: const EdgeInsets.only(top: 40),
child: Column(
children: [
const AppText('Couldn\'t load stats',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
if (_error != null)
Padding(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
child: Text(_error!,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
),
const SizedBox(height: 12),
OutlinedButton(onPressed: _load, child: const AppText('Try again')),
],
),
),
];
}
if (stats.isEmpty) {
return [
Padding(
padding: const EdgeInsets.only(top: 48),
child: Column(
children: [
AppText('No activity in this period',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurface)),
const SizedBox(height: 4),
AppText('Sessions you run will show up here.',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
],
),
),
];
}
final today = _range == UsageRange.day;
final cache = stats.tokens.cacheRead + stats.tokens.cacheWrite;
final activity = buildUsageActivity(stats);
return [
_tiles(theme, [
(
label: tr('Sessions'),
value: usageCompactNumber(stats.sessions),
hint: trArgs('Subagents: {0}', [usageCompactNumber(stats.subagents)]),
),
(label: tr('Prompts'), value: usageCompactNumber(stats.prompts), hint: null),
(
label: tr('Tokens'),
value: usageCompactNumber(stats.tokens.total),
hint: trArgs('In {0} · Out {1} · Cache {2}', [
usageCompactNumber(stats.tokens.input),
usageCompactNumber(stats.tokens.produced),
usageCompactNumber(cache),
]),
),
(label: tr('Cost'), value: usageCost(stats.cost), hint: null),
if (!today)
(
label: tr('Active days'),
value: usageCompactNumber(stats.activeDays),
hint: null,
),
if (!today)
(
label: tr('Longest streak (days)'),
value: usageCompactNumber(stats.streak),
hint: null,
),
]),
if (!today) ...[
const SizedBox(height: 18),
_sectionTitle(
theme,
activity.weekly ? tr('Weekly activity') : tr('Daily activity'),
activity.weekly ? tr('Model steps per week') : tr('Model steps per day'),
),
_activity(theme, activity),
],
if (stats.tokens.total > 0) ...[
const SizedBox(height: 18),
_sectionTitle(theme, tr('Token composition'), null),
_tokenComposition(theme, stats),
],
const SizedBox(height: 18),
_sectionTitle(theme, tr('Efficiency'), null),
_tiles(theme, _efficiencyTiles(stats)),
const SizedBox(height: 18),
_models(theme, stats),
const SizedBox(height: 18),
_toolsSection(theme),
];
}
List<({String label, String value, String? hint})> _efficiencyTiles(
UsageStats stats) {
String? percent(double? value) =>
value == null ? null : usagePercent(value);
return [
(
label: tr('Cache hit rate'),
value: percent(usageCacheHitRate(stats.tokens)) ?? '—',
hint: null,
),
(
label: tr('Cost / session'),
value: usageCostPerSession(stats) == null
? '—'
: usageCost(usageCostPerSession(stats)!),
hint: null,
),
(
label: tr('Cost per 1M tokens'),
value: usageCostPerMillionTokens(stats) == null
? '—'
: usageCost(usageCostPerMillionTokens(stats)!),
hint: null,
),
(
label: tr('Tokens / session'),
value: usageTokensPerSession(stats) == null
? '—'
: usageCompactNumber(usageTokensPerSession(stats)!),
hint: null,
),
(
label: tr('Steps / session'),
value: usageStepsPerSession(stats) == null
? '—'
: usageStepsPerSession(stats)!.toStringAsFixed(1),
hint: null,
),
(
label: tr('Reasoning share'),
value: percent(usageReasoningShare(stats.tokens)) ?? '—',
hint: null,
),
];
}
Widget _sectionTitle(ThemeData theme, String title, String? caption) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(title,
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
color: theme.colorScheme.onSurface)),
if (caption != null) ...[
const SizedBox(width: 8),
Expanded(
child: Text(caption,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
),
],
],
),
);
}
Widget _tiles(
ThemeData theme, List<({String label, String value, String? hint})> tiles) {
return LayoutBuilder(builder: (context, constraints) {
final width = (constraints.maxWidth - 8) / 2;
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final tile in tiles)
SizedBox(
width: width,
child: _StatTile(
label: tile.label,
value: tile.value,
hint: tile.hint,
),
),
],
);
});
}
Widget _activity(ThemeData theme, UsageActivitySeries series) {
if (series.bars.isEmpty) {
return const SizedBox.shrink();
}
final active = _activeBar != null && _activeBar! < series.bars.length
? series.bars[_activeBar!]
: null;
String describe(UsageBar bar) {
final range = bar.start == bar.end
? usageDayLabel(bar.start)
: '${usageDayLabel(bar.start)} – ${usageDayLabel(bar.end)}';
return trArgs('{0} · steps: {1}', [range, usageCompactNumber(bar.steps)]);
}
return Container(
decoration: BoxDecoration(
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.5)),
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
height: 18,
child: Align(
alignment: Alignment.centerLeft,
child: Text(
active != null
? describe(active)
: trArgs('{0} steps', [usageCompactNumber(series.max)]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
),
),
const SizedBox(height: 4),
SizedBox(
height: 96,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
for (var i = 0; i < series.bars.length; i++)
Expanded(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => setState(
() => _activeBar = _activeBar == i ? null : i),
child: Padding(
padding: const EdgeInsets.only(right: 1),
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
height: series.max > 0
? series.bars[i].steps > 0
? math.max(
3,
series.bars[i].steps /
series.max *
90)
: 1.5
: 1.5,
decoration: BoxDecoration(
color: series.bars[i].steps > 0
? (active == null || _activeBar == i
? theme.colorScheme.primary
: theme.colorScheme.primary
.withValues(alpha: 0.35))
: theme.dividerColor,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(1)),
),
),
),
),
),
),
],
),
),
const SizedBox(height: 4),
Row(
children: [
Text(usageDayLabel(series.bars.first.start),
style: TextStyle(fontSize: 11, color: theme.hintColor)),
const Spacer(),
Text(usageDayLabel(series.bars.last.end),
style: TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
],
),
);
}
Widget _tokenComposition(ThemeData theme, UsageStats stats) {
final total = stats.tokens.total;
final segments = <({String label, int value, Color color})>[
(
label: tr('Input'),
value: stats.tokens.input,
color: _tokenColors[0]
),
(
label: tr('Output + reasoning'),
value: stats.tokens.produced,
color: _tokenColors[1]
),
(
label: tr('Cache reads'),
value: stats.tokens.cacheRead,
color: _tokenColors[2]
),
(
label: tr('Cache writes'),
value: stats.tokens.cacheWrite,
color: _tokenColors[3]
),
];
return Container(
decoration: BoxDecoration(
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.5)),
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.all(10),
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(5),
child: SizedBox(
height: 10,
// A Row lays a childless ColoredBox out at zero height unless
// the cross axis is stretched; without this the bar is invisible.
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final segment in segments)
if (segment.value > 0)
Expanded(
flex: segment.value,
child: ColoredBox(color: segment.color),
),
],
),
),
),
const SizedBox(height: 8),
LayoutBuilder(builder: (context, constraints) {
final width = (constraints.maxWidth - 12) / 2;
return Wrap(
spacing: 12,
runSpacing: 6,
children: [
for (final segment in segments)
SizedBox(
width: width,
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: segment.color, shape: BoxShape.circle),
),
const SizedBox(width: 6),
Expanded(
child: Text(segment.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11, color: theme.hintColor)),
),
const SizedBox(width: 4),
Text(
'${usageCompactNumber(segment.value)} · '
'${usagePercent(segment.value / total)}',
style: const TextStyle(fontSize: 11),
),
],
),
),
],
);
}),
],
),
);
}
Widget _models(ThemeData theme, UsageStats stats) {
double valueOf(UsageModelStat model) => switch (_dimension) {
_ModelDimension.tokens => model.tokens.total.toDouble(),
_ModelDimension.cost => model.cost,
_ModelDimension.steps => model.steps.toDouble(),
};
final ranked = [...stats.models]
..sort((a, b) => valueOf(b).compareTo(valueOf(a)));
final max = ranked.fold<double>(0, (peak, model) => math.max(peak, valueOf(model)));
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_sectionTitle(theme, tr('Models'), null),
if (stats.models.isNotEmpty)
Wrap(
spacing: 8,
children: [
for (final dimension in _ModelDimension.values)
ChoiceChip(
label: Text(switch (dimension) {
_ModelDimension.tokens => tr('Tokens'),
_ModelDimension.cost => tr('Cost'),
_ModelDimension.steps => tr('Steps'),
}),
selected: _dimension == dimension,
onSelected: (_) => setState(() => _dimension = dimension),
),
],
),
const SizedBox(height: 6),
if (stats.models.isEmpty)
AppText('No model usage in this period.',
style: TextStyle(fontSize: 12, color: theme.hintColor))
else
for (final model in ranked) _modelRow(theme, model, valueOf, max),
],
);
}
Widget _modelRow(ThemeData theme, UsageModelStat model,
double Function(UsageModelStat) valueOf, double max) {
final value = valueOf(model);
final share =
max > 0 ? (value / max).clamp(0.0, 1.0).toDouble() : 0.0;
final name = app.modelName(ModelRef(model.modelId, model.providerId,
model.variant));
final secondary = [
if (model.variant != null && model.variant != 'default') model.variant!,
model.providerId,
].join(' · ');
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13.5)),
),
const SizedBox(width: 8),
Text(
_dimension == _ModelDimension.steps
? '${usageCompactNumber(model.steps)} · ${usageCost(model.cost)}'
: '${usageCompactNumber(model.tokens.total)} · ${usageCost(model.cost)}',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
],
),
if (secondary.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 1),
child: Text(secondary,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: theme.hintColor)),
),
const SizedBox(height: 4),
LayoutBuilder(builder: (context, constraints) {
// A nonzero share always paints at least a few pixels, so a small
// model reads as a sliver on the track, never as an empty bar.
final visible = share <= 0
? 0.0
: math.max(share, 8 / constraints.maxWidth);
return SizedBox(
height: 8,
child: ClipRRect(
borderRadius: BorderRadius.circular(3),
child: Stack(
fit: StackFit.expand,
children: [
// A full-width track: a small share still reads as a sliver
// of colour on it, not as an empty bar.
ColoredBox(color: theme.dividerColor.withValues(alpha: 0.35)),
if (visible > 0)
Align(
alignment: Alignment.centerLeft,
child: FractionallySizedBox(
widthFactor: visible,
heightFactor: 1,
child: _dimension == _ModelDimension.tokens
? Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final (i, value) in [
model.tokens.input,
model.tokens.produced,
model.tokens.cacheRead,
model.tokens.cacheWrite,
].indexed)
if (value > 0)
Expanded(
flex: value,
child: ColoredBox(color: _tokenColors[i]),
),
])
: ColoredBox(color: theme.colorScheme.primary),
),
),
],
),
),
);
}),
],
),
);
}
Widget _toolsSection(ThemeData theme) {
final tools = _tools != null && _tools!.hasTotals ? _tools : null;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_sectionTitle(theme, tr('Tool calls'), tr('Counting them reads every message in the period.')),
if (tools == null) ...[
if (_toolsError != null)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(_toolsError!,
style: TextStyle(
fontSize: 12, color: theme.colorScheme.error)),
),
Align(
alignment: Alignment.centerLeft,
child: OutlinedButton.icon(
onPressed: _toolsLoading ? null : _loadTools,
icon: _toolsLoading
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.build_outlined, size: 18),
label: AppText(_toolsLoading ? 'Loading…' : 'Show tool calls'),
),
),
] else ...[
_tiles(theme, [
(label: tr('Calls'), value: usageCompactNumber(tools.calls), hint: null),
(
label: tr('Success rate'),
value: tools.calls > 0
? usagePercent(tools.succeeded / tools.calls)
: '—',
hint: null,
),
(
label: tr('Failed'),
value: usageCompactNumber(tools.failed),
hint: null
),
(
label: tr('Unfinished'),
value: usageCompactNumber(tools.unfinished),
hint: null
),
]),
const SizedBox(height: 8),
for (final row in tools.rows.where((row) => row.calls > 0).take(8))
_toolRow(theme, row),
],
],
);
}
Widget _toolRow(ThemeData theme, UsageToolStat tool) {
final stats = tool.durationP50 != null
? trArgs('calls: {0} · median: {1}', [
usageCompactNumber(tool.calls),
usageDuration(tool.durationP50!),
])
: trArgs('calls: {0}', [usageCompactNumber(tool.calls)]);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(tool.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5, fontFamily: 'monospace')),
),
const SizedBox(width: 8),
Text(stats,
style: TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
const SizedBox(height: 3),
ClipRRect(
borderRadius: BorderRadius.circular(3),
child: SizedBox(
height: 5,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (tool.succeeded > 0)
Expanded(
flex: tool.succeeded,
child: ColoredBox(color: theme.colorScheme.primary),
),
if (tool.failed > 0)
Expanded(
flex: tool.failed,
child: ColoredBox(color: theme.colorScheme.error),
),
],
),
),
),
],
),
);
}
}
class _StatTile extends StatelessWidget {
final String label;
final String value;
final String? hint;
const _StatTile({required this.label, required this.value, this.hint});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.45),
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
const SizedBox(height: 2),
Text(value,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 19,
fontWeight: FontWeight.w600,
fontFeatures: [FontFeature.tabularFigures()])),
if (hint != null)
Padding(
padding: const EdgeInsets.only(top: 1),
child: Text(hint!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 10.5, color: theme.hintColor)),
),
],
),
);
}
}
+17 -15
View File
@@ -8,6 +8,7 @@ import 'package:xterm/xterm.dart';
import '../api/terminal.dart';
import '../state.dart';
import '../terminal_state.dart';
import '../l10n.dart';
/// A light palette, so the terminal does not turn into a black hole in the
/// light theme. (xterm ships only dark ones.)
@@ -120,19 +121,20 @@ class _TerminalPanelState extends State<TerminalPanel> {
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),
TerminalLinkState.idle => (tr('Not started'), theme.hintColor),
TerminalLinkState.creating => (tr('Creating…'), theme.hintColor),
TerminalLinkState.connecting => (tr('Connecting…'), theme.hintColor),
TerminalLinkState.reconnecting =>
(tr('Connection lost, reconnecting…'), scheme.error),
TerminalLinkState.open => (tr('Running'), scheme.primary),
TerminalLinkState.exited => (state.detail ?? tr('Exited'), theme.hintColor),
TerminalLinkState.error => (state.detail ?? tr('Connection failed'), scheme.error),
};
return Row(
children: [
Expanded(
child: PopupMenuButton<int>(
tooltip: '切换终端',
tooltip: tr('Switch terminal'),
position: PopupMenuPosition.under,
onSelected: _onTabMenu,
itemBuilder: (_) => [
@@ -168,7 +170,7 @@ class _TerminalPanelState extends State<TerminalPanel> {
children: [
Icon(Icons.add, size: 18),
SizedBox(width: 10),
Text('新建终端'),
AppText('New terminal'),
],
),
),
@@ -205,13 +207,13 @@ class _TerminalPanelState extends State<TerminalPanel> {
),
),
IconButton(
tooltip: '键盘',
tooltip: tr('Keyboard'),
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.keyboard_outlined, size: 18),
onPressed: () => _focus.requestFocus(),
),
IconButton(
tooltip: '重新启动',
tooltip: tr('Restart'),
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.restart_alt, size: 18),
onPressed: state.link == TerminalLinkState.exited ||
@@ -221,7 +223,7 @@ class _TerminalPanelState extends State<TerminalPanel> {
: null,
),
PopupMenuButton<String>(
tooltip: '更多',
tooltip: tr('More'),
icon: const Icon(Icons.more_vert, size: 18),
onSelected: (value) {
switch (value) {
@@ -234,8 +236,8 @@ class _TerminalPanelState extends State<TerminalPanel> {
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'clear', child: Text('清屏')),
PopupMenuItem(value: 'close', child: Text('关闭此终端')),
PopupMenuItem(value: 'clear', child: AppText('Clear screen')),
PopupMenuItem(value: 'close', child: AppText('Close this terminal')),
],
),
],
@@ -353,4 +355,4 @@ class _TerminalPanelState extends State<TerminalPanel> {
void _sendText(TerminalSessionState state, String text) =>
state.model.textInput(text);
}
}
+580 -51
View File
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -7,6 +7,8 @@ import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'l10n.dart';
class Connection {
final String id;
final String label;
@@ -168,7 +170,7 @@ class Storage {
final entry = (await _terminalMap(connectionId))[directory];
if (entry is String && entry.isNotEmpty) {
return SavedTerminalTabs(
[SavedTerminalTab(entry, '终端 1')], entry);
[SavedTerminalTab(entry, tr('Terminal 1'))], entry);
}
if (entry is! Map) return null;
final rawTabs = entry['tabs'];
@@ -180,7 +182,7 @@ class Storage {
final label = raw['label'];
if (id is! String || id.isEmpty) continue;
tabs.add(SavedTerminalTab(
id, label is String && label.trim().isNotEmpty ? label : '终端'));
id, label is String && label.trim().isNotEmpty ? label : tr('Terminal')));
}
if (tabs.isEmpty) return null;
final active = entry['active'];
+9 -7
View File
@@ -8,6 +8,7 @@ import 'package:flutter/foundation.dart';
import 'package:xterm/xterm.dart';
import 'api/terminal.dart';
import 'l10n.dart';
import 'state.dart';
import 'storage.dart';
@@ -113,14 +114,15 @@ class TerminalWorkspace extends ChangeNotifier {
static String freeLabel(Iterable<String> labels) {
final used = <int>{};
for (final label in labels) {
final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim());
final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim()) ??
RegExp(r'^Terminal (\d+)$').firstMatch(label.trim());
if (match != null) used.add(int.parse(match.group(1)!));
}
var n = 1;
while (used.contains(n)) {
n++;
}
return '终端 $n';
return trArgs('Terminal {0}', [n]);
}
Future<SavedTerminalTabs?> _savedTabs() async {
@@ -432,8 +434,8 @@ class TerminalSessionState extends ChangeNotifier {
if (event.status == 'exited') {
_set(TerminalLinkState.exited,
detail: event.exitCode == null
? '已退出'
: '退出码 ${event.exitCode}');
? tr('Exited')
: trArgs('Exit code {0}', [event.exitCode]));
}
break;
case 'restarted':
@@ -447,8 +449,8 @@ class TerminalSessionState extends ChangeNotifier {
case 'exit':
_set(TerminalLinkState.exited,
detail: event.exitCode == null
? '已退出'
: '退出码 ${event.exitCode}');
? tr('Exited')
: trArgs('Exit code {0}', [event.exitCode]));
break;
case 'error':
if (event.fatal) {
@@ -459,7 +461,7 @@ class TerminalSessionState extends ChangeNotifier {
_recoverMissing();
} else {
_set(TerminalLinkState.error,
detail: event.message ?? event.code ?? '终端连接失败');
detail: event.message ?? event.code ?? tr('Terminal connection failed'));
}
}
break;
+21
View File
@@ -0,0 +1,21 @@
// The device's IANA time zone, which the statistics API wants for bucketing
// days. Dart only exposes the abbreviation ("CST"), and Guava/ICU's zone id
// lives on the Android side; the desktop build has no zone plugin, so it
// falls back to UTC (the UI still works, only the day boundaries shift).
import 'package:flutter/services.dart';
const _channel = MethodChannel('openchamber/device');
String? _cached;
Future<String> deviceTimeZone() async {
final cached = _cached;
if (cached != null) return cached;
try {
final name = await _channel.invokeMethod<String>('ianaTimeZone');
if (name != null && name.isNotEmpty) return _cached = name;
} catch (_) {
// No handler (desktop) or a platform failure: UTC keeps the request valid.
}
return _cached = 'UTC';
}
+22 -2
View File
@@ -1,2 +1,22 @@
/// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.6';
// The build's version: shown in 设置 → 关于 and sent to the server in pairing
// and relay handshakes. Read from the platform at startup, so pubspec.yaml
// stays the only place the number is written.
import 'package:package_info_plus/package_info_plus.dart';
/// The version this build was made from, empty until [loadAppVersion] has
/// read it. The Android build number is left out on purpose: an ABI split
/// prefixes it with its own digit, so it would differ between the APKs of one
/// release.
String appVersion = '';
/// Reads the version this build was made from. Failure leaves [appVersion]
/// empty: the handshake still works and 关于 says the version is unknown.
Future<void> loadAppVersion() async {
try {
final info =
await PackageInfo.fromPlatform().timeout(const Duration(seconds: 3));
appVersion = info.version.trim();
} catch (_) {
// Keep the empty fallback.
}
}
+3 -2
View File
@@ -6,6 +6,7 @@ import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../l10n.dart';
class ComposerAttachment {
final String name;
@@ -35,7 +36,7 @@ Future<List<ComposerAttachment>> pickComposerAttachments(
if (bytes.length > 10 * 1024 * 1024) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('附件不能超过 10MB')));
const SnackBar(content: AppText('Attachments cannot be larger than 10 MB')));
}
continue;
}
@@ -132,4 +133,4 @@ Future<String?> _keepImage(String src, String name) async {
} catch (_) {
return null;
}
}
}
+343
View File
@@ -0,0 +1,343 @@
// Line-level diffs for edit/write/patch tool calls, as the first-party and
// dsh-Go clients show them: added and removed lines tinted, hunk headers
// marked, and the before/after text never dumped as one blob.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../l10n.dart';
enum DiffLineKind { context, add, del, hunk, meta }
class DiffLine {
final DiffLineKind kind;
final String text;
const DiffLine(this.kind, this.text);
}
class DiffFile {
/// The path the server put in the tool metadata, when it named one.
final String? path;
final List<DiffLine> lines;
const DiffFile({this.path, required this.lines});
int get added =>
lines.where((line) => line.kind == DiffLineKind.add).length;
int get removed =>
lines.where((line) => line.kind == DiffLineKind.del).length;
}
const _diffTools = {
'edit',
'write',
'create',
'file_write',
'patch',
'apply_patch',
'str_replace',
'str_replace_based_edit_tool',
};
bool isDiffTool(String? name) => _diffTools.contains(name ?? '');
String? _text(Object? value) => value is String ? value : null;
String? _nonEmptyText(Object? value) {
final text = _text(value);
return text == null || text.trim().isEmpty ? null : text;
}
String? _patchText(Object? value) {
if (value is Map) {
return _nonEmptyText(value['patch']) ?? _nonEmptyText(value['diff']);
}
return _nonEmptyText(value);
}
String? _filePath(Map<dynamic, dynamic> file) =>
_nonEmptyText(file['file']) ??
_nonEmptyText(file['filePath']) ??
_nonEmptyText(file['relativePath']) ??
_nonEmptyText(file['movePath']);
/// The diff a tool call carries, from the server's `metadata.files[].patch`
/// (falling back to a top-level patch), or computed from the edit's old/new
/// text when an older server sends no patch.
List<DiffFile> toolDiffFiles(ContentPart part) {
if (part.type != 'tool' || !isDiffTool(part.name)) return const [];
final state = part.state;
if (state == null) return const [];
if (_nonEmptyText(state.error) != null) return const [];
final files = <DiffFile>[];
final metadata = state.metadata;
final rawFiles = metadata?['files'];
if (rawFiles is List) {
for (final raw in rawFiles) {
if (raw is! Map) continue;
final patch =
_patchText(raw['patch']) ?? _patchText(raw['diff']);
if (patch == null) continue;
final lines = parseUnifiedDiff(patch);
if (lines.isEmpty) continue;
files.add(DiffFile(path: _filePath(raw), lines: lines));
}
}
if (files.isEmpty) {
final patch =
_patchText(metadata?['patch']) ?? _patchText(metadata?['diff']);
if (patch != null) {
final lines = parseUnifiedDiff(patch);
if (lines.isNotEmpty) files.add(DiffFile(lines: lines));
}
}
if (files.isEmpty) {
final input = state.input;
final path = _nonEmptyText(input['path']) ??
_nonEmptyText(input['filePath']) ??
_nonEmptyText(input['file_path']);
final oldText = _text(input['oldString']) ??
_text(input['old_string']) ??
_text(input['old_str']);
final newText = _text(input['newString']) ??
_text(input['new_string']) ??
_text(input['new_str']);
if (newText != null) {
final lines = computeLineDiff(oldText ?? '', newText);
if (lines.isNotEmpty) files.add(DiffFile(path: path, lines: lines));
} else if (part.name == 'write' ||
part.name == 'create' ||
part.name == 'file_write') {
final content = _text(input['content']) ?? _text(input['file_text']);
if (content != null && content.isNotEmpty) {
files.add(DiffFile(
path: path,
lines: [
for (final line in content.replaceAll('\r\n', '\n').split('\n'))
DiffLine(DiffLineKind.add, '+$line'),
],
));
}
}
}
return files;
}
/// A unified diff: `@@` hunks, `+++`/`---`/`diff`/`index` metadata, `+` and
/// `-` changes, everything else context. Trailing blank context is dropped so
/// a file's diff ends on its last real line.
List<DiffLine> parseUnifiedDiff(String text) {
final lines = <DiffLine>[];
for (final raw in text.replaceAll('\r\n', '\n').split('\n')) {
final kind = raw.startsWith('@@')
? DiffLineKind.hunk
: raw.startsWith('+++') ||
raw.startsWith('---') ||
raw.startsWith('diff ') ||
raw.startsWith('index ') ||
raw.startsWith('Index: ') ||
raw.startsWith('===')
? DiffLineKind.meta
: raw.startsWith('+')
? DiffLineKind.add
: raw.startsWith('-')
? DiffLineKind.del
: DiffLineKind.context;
lines.add(DiffLine(kind, raw));
}
while (lines.isNotEmpty &&
lines.last.kind == DiffLineKind.context &&
lines.last.text.isEmpty) {
lines.removeLast();
}
return lines;
}
/// Line-level LCS diff for an edit that came without server patches. Very
/// large pairs fall back to one removed and one added block.
List<DiffLine> computeLineDiff(String oldText, String newText) {
final a = oldText.isEmpty ? <String>[] : oldText.split('\n');
final b = newText.isEmpty ? <String>[] : newText.split('\n');
if (a.length * b.length > 400 * 400) {
return [
for (final line in a) DiffLine(DiffLineKind.del, '-$line'),
for (final line in b) DiffLine(DiffLineKind.add, '+$line'),
];
}
final dp = List.generate(
a.length + 1, (_) => List<int>.filled(b.length + 1, 0));
for (var i = a.length - 1; i >= 0; i--) {
for (var j = b.length - 1; j >= 0; j--) {
dp[i][j] = a[i] == b[j]
? dp[i + 1][j + 1] + 1
: math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
final lines = <DiffLine>[];
var i = 0;
var j = 0;
while (i < a.length && j < b.length) {
if (a[i] == b[j]) {
lines.add(DiffLine(DiffLineKind.context, ' ${a[i]}'));
i++;
j++;
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
lines.add(DiffLine(DiffLineKind.del, '-${a[i]}'));
i++;
} else {
lines.add(DiffLine(DiffLineKind.add, '+${b[j]}'));
j++;
}
}
while (i < a.length) {
lines.add(DiffLine(DiffLineKind.del, '-${a[i]}'));
i++;
}
while (j < b.length) {
lines.add(DiffLine(DiffLineKind.add, '+${b[j]}'));
j++;
}
return lines;
}
/// Tinted, horizontally wrapped diff lines. Selection spans the whole block,
/// so the diff can be copied line by line as it reads.
class DiffView extends StatelessWidget {
final List<DiffFile> files;
/// Phone-sized preview: a huge generated diff does not build thousands of
/// rows in the message list; the rest is counted, not drawn.
final int maxLines;
const DiffView({super.key, required this.files, this.maxLines = 600});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final dark = theme.brightness == Brightness.dark;
final addBg = const Color(0xFF22C55E).withValues(alpha: dark ? 0.18 : 0.12);
final addFg =
dark ? const Color(0xFF86E7A6) : const Color(0xFF116329);
final delBg = const Color(0xFFEF4444).withValues(alpha: dark ? 0.18 : 0.12);
final delFg =
dark ? const Color(0xFFFF9B9B) : const Color(0xFFA40E26);
final hunkBg = scheme.primary.withValues(alpha: dark ? 0.10 : 0.07);
const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace');
var remaining = maxLines;
var total = 0;
for (final file in files) {
total += file.lines.length;
}
final rows = <Widget>[];
for (var fileIndex = 0; fileIndex < files.length; fileIndex++) {
final file = files[fileIndex];
if (files.length > 1) {
rows.add(Container(
color: scheme.surfaceContainer,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
child: Row(
children: [
Expanded(
child: Text(
file.path ?? trArgs('File {0}', [fileIndex + 1]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w600,
color: scheme.onSurfaceVariant,
),
),
),
DiffStats(added: file.added, removed: file.removed),
],
),
));
}
for (final line in file.lines) {
// The step row already names the file; `Index:`/`---`/`+++` headers
// are noise above the hunks (the first-party viewer hides them too).
if (line.kind == DiffLineKind.meta) continue;
if (remaining <= 0) break;
remaining--;
final (background, foreground) = switch (line.kind) {
DiffLineKind.add => (addBg, addFg),
DiffLineKind.del => (delBg, delFg),
DiffLineKind.hunk => (hunkBg, scheme.primary),
DiffLineKind.meta => (null, theme.hintColor),
DiffLineKind.context => (null, scheme.onSurfaceVariant),
};
rows.add(Container(
color: background,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
child: Text(
line.text.isEmpty ? ' ' : line.text,
style: mono.copyWith(color: foreground),
),
));
}
}
if (total > maxLines) {
rows.add(Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
child: AppText(
trArgs('Showing the first {0} of {1} lines', [maxLines, total]),
style: TextStyle(fontSize: 11, color: theme.hintColor),
),
));
}
return Container(
width: double.infinity,
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
clipBehavior: Clip.antiAlias,
child: SelectionArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: rows,
),
),
);
}
}
/// `+3 −1`, as the row and a multi-file header show it.
class DiffStats extends StatelessWidget {
final int added;
final int removed;
const DiffStats({super.key, required this.added, required this.removed});
@override
Widget build(BuildContext context) {
final dark = Theme.of(context).brightness == Brightness.dark;
final addFg =
dark ? const Color(0xFF86E7A6) : const Color(0xFF116329);
final delFg =
dark ? const Color(0xFFFF9B9B) : const Color(0xFFA40E26);
const style = TextStyle(fontSize: 11, fontFamily: 'monospace');
return Row(
mainAxisSize: MainAxisSize.min,
children: [
if (added > 0) AppText('+$added', style: style.copyWith(color: addFg)),
if (added > 0 && removed > 0) const SizedBox(width: 4),
if (removed > 0)
AppText('−$removed', style: style.copyWith(color: delFg)),
],
);
}
}
+322
View File
@@ -0,0 +1,322 @@
// The add-project browser: walks the server's directories from the user's
// home and adds the chosen folder to OpenChamber's project list. A project
// stored only in the settings document (no session yet) is still a valid
// target; the first session in it makes OpenCode list it too.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../l10n.dart';
import '../state.dart';
/// Opens the folder browser and returns the canonical path that was added, or
/// null when the sheet was dismissed.
Future<String?> showDirectoryPicker(BuildContext context,
{required AppState app}) {
return showModalBottomSheet<String>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (context) => Padding(
// Keep the sheet above the keyboard; the folder list gets the rest.
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: FractionallySizedBox(
heightFactor: 0.9,
child: _DirectoryPickerSheet(app: app),
),
),
);
}
class _DirectoryPickerSheet extends StatefulWidget {
final AppState app;
const _DirectoryPickerSheet({required this.app});
@override
State<_DirectoryPickerSheet> createState() => _DirectoryPickerSheetState();
}
class _DirectoryPickerSheetState extends State<_DirectoryPickerSheet> {
final TextEditingController _pathCtrl = TextEditingController();
String _path = '';
List<FsEntry> _dirs = const [];
bool _loading = true;
bool _adding = false;
String? _error;
AppState get _app => widget.app;
@override
void initState() {
super.initState();
_start();
}
@override
void dispose() {
_pathCtrl.dispose();
super.dispose();
}
Future<void> _start() async {
var home = _app.homeDirectory.trim();
if (home.isEmpty) {
try {
home = (await _app.client?.fsHome())?.home.trim() ?? '';
} catch (_) {
// Fall back to the filesystem root; the path field still works.
}
}
await _open(home.isEmpty ? '/' : home);
}
/// trims a typed path, keeps the root and drops trailing separators.
String _normalize(String path) {
var p = path.trim();
if (p.isEmpty) return '/';
while (p.length > 1 && (p.endsWith('/') || p.endsWith('\\'))) {
p = p.substring(0, p.length - 1);
}
return p.isEmpty ? '/' : p;
}
String _parent(String path) {
final p = _normalize(path);
if (p == '/') return '/';
final index = p.lastIndexOf(RegExp(r'[/\\]'));
if (index <= 0) return '/';
return p.substring(0, index);
}
String _join(String folder) => _path == '/' ? '/$folder' : '$_path/$folder';
Future<void> _open(String path) async {
final target = _normalize(path);
setState(() {
_path = target;
_pathCtrl.text = target;
_loading = true;
_error = null;
});
final client = _app.client;
if (client == null) {
setState(() {
_loading = false;
_error = tr('Not connected to a server');
});
return;
}
try {
final entries =
await client.fsList(target, respectGitignore: false);
final dirs = [
for (final entry in entries)
if (entry.isDirectory) entry,
]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
if (!mounted) return;
setState(() {
_dirs = dirs;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_dirs = const [];
_loading = false;
_error = trArgs('Could not load this folder: {0}', [e]);
});
}
}
Future<void> _createFolder() async {
final name = await _askFolderName();
if (name == null || !mounted) return;
final client = _app.client;
if (client == null) return;
final target = _join(name);
try {
await client.fsMkdir(target);
if (!mounted) return;
await _open(target);
} catch (e) {
if (!mounted) return;
setState(() => _error = trArgs('Could not create the folder: {0}', [e]));
}
}
Future<String?> _askFolderName() async {
final controller = TextEditingController();
final name = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: const AppText('New folder'),
content: TextField(
controller: controller,
autofocus: true,
decoration: InputDecoration(hintText: tr('Folder name')),
onSubmitted: (value) => Navigator.pop(context, value.trim()),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const AppText('Cancel')),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text.trim()),
child: const AppText('Create')),
],
),
);
controller.dispose();
if (name == null || name.isEmpty) return null;
if (name == '.' || name == '..' || name.contains('/') || name.contains('\\')) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: AppText(tr('Enter a valid folder name'))));
}
return null;
}
return name;
}
Future<void> _add() async {
if (_adding || _loading) return;
setState(() {
_adding = true;
_error = null;
});
try {
final project = await _app.addProjectDirectory(_path);
if (!mounted) return;
Navigator.pop(context, project?.canonical ?? _path);
} catch (e) {
if (!mounted) return;
setState(() {
_adding = false;
_error = trArgs('Could not add the project: {0}', [e]);
});
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(4, 6, 12, 0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.close),
tooltip: tr('Close'),
onPressed: () => Navigator.pop(context)),
const Expanded(
child: AppText('Add project',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 6),
child: TextField(
controller: _pathCtrl,
textInputAction: TextInputAction.go,
onSubmitted: _open,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.folder_outlined, size: 18),
hintText: tr('Folder path'),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
suffixIcon: TextButton(
onPressed: () => _open(_pathCtrl.text),
child: const AppText('Go')),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_upward, size: 18),
tooltip: tr('Up'),
onPressed: _path == '/' ? null : () => _open(_parent(_path)),
),
Expanded(
child: Text(
_path,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
),
TextButton.icon(
onPressed: _createFolder,
icon: const Icon(Icons.create_new_folder_outlined, size: 18),
label: const AppText('New folder'),
),
],
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),
child: Text(_error!,
style: TextStyle(fontSize: 12, color: theme.colorScheme.error)),
),
Expanded(
child: _loading
? const Center(
child: SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2)))
: ListView(
children: [
for (final entry in _dirs)
ListTile(
dense: true,
leading:
const Icon(Icons.folder_outlined, size: 20),
title: Text(entry.name,
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing:
const Icon(Icons.chevron_right, size: 18),
onTap: () => _open(entry.path),
),
if (_dirs.isEmpty && _error == null)
const Padding(
padding: EdgeInsets.all(24),
child: AppText('No folders here',
textAlign: TextAlign.center),
),
],
),
),
SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
child: SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: _adding || _loading ? null : _add,
icon: _adding
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.add, size: 18),
label: const AppText('Add this folder'),
),
),
),
),
],
);
}
}
+460
View File
@@ -0,0 +1,460 @@
// Full-screen picture viewer, modelled on dsh-Go's image gallery: black
// background, one picture per page, pinch to 8x, double-tap to 2.5x around the
// touched point, drag to pan. Paging is disabled while a picture is zoomed so
// a drag pans the picture instead of swiping to the next one. A single tap
// hides the title/keys so nothing covers the picture; another tap brings them
// back.
import 'dart:convert';
import 'dart:io' show Platform;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../l10n.dart';
/// One picture in the viewer. [source] is a `data:` URL or a file path the
/// client can read with the session's directory.
class ImageSlide {
final String title;
final String source;
const ImageSlide(this.title, this.source);
}
/// Opens [images] at [initial] as a full-screen gallery.
Future<void> showImageViewer(
BuildContext context, {
required List<ImageSlide> images,
int initial = 0,
required String directory,
required Client client,
}) {
if (images.isEmpty) return Future.value();
return Navigator.of(context).push(PageRouteBuilder<void>(
opaque: true,
transitionDuration: const Duration(milliseconds: 180),
reverseTransitionDuration: const Duration(milliseconds: 140),
pageBuilder: (_, __, ___) => ImageViewerPage(
images: images,
initial: initial.clamp(0, images.length - 1),
directory: directory,
client: client,
),
transitionsBuilder: (_, animation, __, child) =>
FadeTransition(opacity: animation, child: child),
));
}
class ImageViewerPage extends StatefulWidget {
final List<ImageSlide> images;
final int initial;
final String directory;
final Client client;
/// Whether to offer save/share; null follows the platform (Android only).
/// Tests set it to true on the desktop host.
final bool? mediaActions;
const ImageViewerPage({
super.key,
required this.images,
this.initial = 0,
required this.directory,
required this.client,
this.mediaActions,
});
@override
State<ImageViewerPage> createState() => _ImageViewerPageState();
}
class _ImageViewerPageState extends State<ImageViewerPage> {
static const MethodChannel _media = MethodChannel('openchamber/media');
late int _index = widget.initial;
late final PageController _pages = PageController(initialPage: _index);
final Map<int, Uint8List> _loaded = {};
bool _zoomed = false;
bool _chrome = true;
bool _saving = false;
ImageSlide get _current => widget.images[_index];
Uint8List? get _currentBytes => _loaded[_index];
@override
void dispose() {
_pages.dispose();
super.dispose();
}
void _toggleChrome() => setState(() => _chrome = !_chrome);
void _loadedAt(int index, Uint8List bytes) {
if (_loaded[index] == bytes) return;
// A data URL decodes synchronously, so this can arrive while the page is
// still building; update after the frame.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() => _loaded[index] = bytes);
});
}
void _snack(String text) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text(text)));
}
String _mimeOf(ImageSlide slide) {
final source = slide.source;
if (source.startsWith('data:')) {
final colon = source.indexOf(':');
final semi = source.indexOf(';');
if (colon >= 0 && semi > colon) {
return source.substring(colon + 1, semi);
}
}
final name = slide.title.isNotEmpty ? slide.title : source;
final dot = name.lastIndexOf('.');
final ext = dot >= 0 ? name.substring(dot + 1).toLowerCase() : '';
return switch (ext) {
'jpg' || 'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'webp' => 'image/webp',
'bmp' => 'image/bmp',
'avif' => 'image/avif',
_ => 'image/png',
};
}
String _extensionFor(String mime) => switch (mime) {
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp' => 'bmp',
'image/avif' => 'avif',
_ => 'png',
};
String _fileName(ImageSlide slide) {
var name = slide.title.trim().replaceAll(RegExp(r'[/\\]'), '_');
if (name.isEmpty) name = 'image';
final dot = name.lastIndexOf('.');
if (dot <= 0 || dot == name.length - 1) {
name = '$name.${_extensionFor(_mimeOf(slide))}';
}
return name;
}
Future<void> _save() async {
final bytes = _currentBytes;
if (bytes == null || _saving) return;
setState(() => _saving = true);
try {
await _media.invokeMethod<bool>('saveImage', {
'bytes': bytes,
'name': _fileName(_current),
'mime': _mimeOf(_current),
});
if (mounted) _snack(tr('Saved to Photos'));
} on PlatformException catch (e) {
if (!mounted) return;
_snack(e.code == 'permission'
? tr('Storage permission is required to save the picture')
: (e.message ?? tr("Couldn't save the picture")));
} catch (_) {
if (mounted) _snack(tr("Couldn't save the picture"));
} finally {
if (mounted) setState(() => _saving = false);
}
}
Future<void> _share() async {
final bytes = _currentBytes;
if (bytes == null) return;
try {
await _media.invokeMethod<bool>('shareImage', {
'bytes': bytes,
'name': _fileName(_current),
'mime': _mimeOf(_current),
});
} on PlatformException catch (e) {
if (mounted) _snack(e.message ?? tr('Share failed'));
} catch (_) {
if (mounted) _snack(tr('Share failed'));
}
}
@override
Widget build(BuildContext context) {
final padding = MediaQuery.paddingOf(context);
final image = widget.images[_index];
final canSave = _currentBytes != null;
final showMedia = widget.mediaActions ?? Platform.isAndroid;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: Scaffold(
backgroundColor: Colors.black,
body: Stack(
children: [
Positioned.fill(
child: PageView.builder(
controller: _pages,
physics: _zoomed
? const NeverScrollableScrollPhysics()
: const PageScrollPhysics(),
itemCount: widget.images.length,
onPageChanged: (index) => setState(() {
_index = index;
_zoomed = false;
}),
itemBuilder: (context, index) => _ZoomableImage(
// A page that leaves the viewport forgets its zoom.
key: ValueKey((index, index == _index)),
slide: widget.images[index],
directory: widget.directory,
client: widget.client,
onTap: _toggleChrome,
onLoaded: (bytes) => _loadedAt(index, bytes),
onZoomChanged: (zoomed) {
if (index == _index && zoomed != _zoomed) {
setState(() => _zoomed = zoomed);
}
},
),
),
),
// The title and keys cover part of a picture, so a tap hides them
// until the next tap. The gradient keeps them readable.
Positioned(
top: 0,
left: 0,
right: 0,
child: AnimatedOpacity(
key: const ValueKey('viewer-chrome'),
opacity: _chrome ? 1 : 0,
duration: const Duration(milliseconds: 160),
child: IgnorePointer(
ignoring: !_chrome,
child: Container(
padding: EdgeInsets.only(top: padding.top + 4),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.black54, Colors.transparent],
),
),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back),
color: Colors.white,
tooltip: tr('Back'),
onPressed: () => Navigator.of(context).maybePop(),
),
const SizedBox(width: 4),
Expanded(
child: Text(
image.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500),
),
),
if (showMedia) ...[
IconButton(
icon: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white))
: const Icon(Icons.download_outlined),
color: Colors.white,
tooltip: tr('Save to Photos'),
onPressed: canSave && !_saving ? _save : null,
),
IconButton(
icon: const Icon(Icons.ios_share),
color: Colors.white,
tooltip: tr('Share'),
onPressed: canSave ? _share : null,
),
],
const SizedBox(width: 4),
],
),
),
),
),
),
if (widget.images.length > 1)
Positioned(
left: 0,
right: 0,
bottom: padding.bottom + 16,
child: AnimatedOpacity(
key: const ValueKey('viewer-page-indicator'),
opacity: _chrome ? 1 : 0,
duration: const Duration(milliseconds: 160),
child: IgnorePointer(
child: Text(
'${_index + 1} / ${widget.images.length}',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white70, fontSize: 13),
),
),
),
),
],
),
),
);
}
}
class _ZoomableImage extends StatefulWidget {
final ImageSlide slide;
final String directory;
final Client client;
final VoidCallback? onTap;
final ValueChanged<Uint8List>? onLoaded;
final ValueChanged<bool>? onZoomChanged;
const _ZoomableImage({
super.key,
required this.slide,
required this.directory,
required this.client,
this.onTap,
this.onLoaded,
this.onZoomChanged,
});
@override
State<_ZoomableImage> createState() => _ZoomableImageState();
}
class _ZoomableImageState extends State<_ZoomableImage> {
static const double _maxScale = 8;
static const double _doubleTapScale = 2.5;
final TransformationController _transform = TransformationController();
Uint8List? _bytes;
Object? _error;
bool _loading = true;
bool _zoomed = false;
Offset _doubleTap = Offset.zero;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_transform.dispose();
super.dispose();
}
Future<void> _load() async {
try {
final source = widget.slide.source;
final bytes = source.startsWith('data:')
? _dataUrlBytes(source)
: Uint8List.fromList(
await widget.client.rawFile(source, directory: widget.directory));
if (!mounted) return;
widget.onLoaded?.call(bytes);
setState(() {
_bytes = bytes;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e;
_loading = false;
});
}
}
static Uint8List _dataUrlBytes(String source) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception(tr('Invalid data URL'));
if (!source.substring(5, comma).contains('base64')) {
throw Exception(tr('Unsupported data URL'));
}
return base64Decode(source.substring(comma + 1));
}
void _notifyZoom() {
final zoomed = _transform.value.getMaxScaleOnAxis() > 1.01;
if (zoomed == _zoomed) return;
setState(() => _zoomed = zoomed);
widget.onZoomChanged?.call(zoomed);
}
void _toggleZoom() {
final scale = _transform.value.getMaxScaleOnAxis();
if (scale > 1.01) {
_transform.value = Matrix4.identity();
} else {
final p = _doubleTap;
_transform.value = Matrix4.identity()
..translate(p.dx, p.dy)
..scale(_doubleTapScale)
..translate(-p.dx, -p.dy);
}
_notifyZoom();
}
@override
Widget build(BuildContext context) {
if (_loading) {
return const Center(
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white));
}
if (_bytes == null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Text(
trArgs('Cannot preview: {0}', ['$_error']),
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70),
),
),
);
}
return GestureDetector(
onTap: widget.onTap,
onDoubleTapDown: (details) => _doubleTap = details.localPosition,
onDoubleTap: _toggleZoom,
child: InteractiveViewer(
transformationController: _transform,
minScale: 1,
maxScale: _maxScale,
// One finger swipes to the next picture until a pinch zooms in; from
// then on it pans the zoomed picture instead.
panEnabled: _zoomed,
scaleEnabled: true,
onInteractionEnd: (_) => _notifyZoom(),
child: SizedBox.expand(
child: Image.memory(
_bytes!,
fit: BoxFit.contain,
gaplessPlayback: true,
),
),
),
);
}
}
+5 -4
View File
@@ -6,6 +6,7 @@ import '../api/models.dart';
import '../model_prefs.dart';
import '../state.dart';
import 'model_picker.dart';
import '../l10n.dart';
/// `deepseek-flash · 高` — model and effort together, as dsh-Go shows them.
class ModelPill extends StatelessWidget {
@@ -30,7 +31,7 @@ class ModelPill extends StatelessWidget {
info.variants.contains(model!.variant)
? model!.variant
: null;
final name = model == null ? '模型' : app.modelName(model!);
final name = model == null ? 'Model' : app.modelName(model!);
final label = effort == null ? name : '$name · ${effortLabel(effort)}';
return _Pill(
icon: Icons.smart_toy_outlined,
@@ -89,7 +90,7 @@ class ModeChip extends StatelessWidget {
children: [
const Padding(
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text('模式',
child: AppText('Mode',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
),
for (final id in ids)
@@ -98,13 +99,13 @@ class ModeChip extends StatelessWidget {
id == 'plan' ? Icons.map_outlined : Icons.construction_outlined,
color: id == current ? scheme.primary : null,
),
title: Text(
title: AppText(
names[id]?.isNotEmpty == true ? names[id]! : _label(id),
style: TextStyle(
fontWeight: id == current ? FontWeight.w700 : FontWeight.w400,
),
),
subtitle: Text(id == 'plan' ? '先规划,不改动文件' : '直接构建',
subtitle: AppText(id == 'plan' ? 'Plan first without changing files' : 'Build directly',
style: const TextStyle(fontSize: 12)),
trailing: id == current
? Icon(Icons.check, size: 20, color: scheme.primary)
+18 -16
View File
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import '../api/models.dart';
import '../model_prefs.dart';
import '../state.dart';
import '../l10n.dart';
Future<void> showModelPickerSheet(
BuildContext context, {
@@ -69,16 +70,16 @@ class _PickerSheetState extends State<_PickerSheet> {
children: [
const Padding(
padding: EdgeInsets.fromLTRB(12, 12, 12, 4),
child: Text('选择模型',
child: AppText('Select model',
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(),
decoration: InputDecoration(
hintText: tr('Search'),
border: const OutlineInputBorder(),
isDense: true),
),
),
@@ -92,7 +93,7 @@ class _PickerSheetState extends State<_PickerSheet> {
Widget _models() {
final all = widget.app.modelList;
if (all.isEmpty) {
return const Center(child: Text('正在载入模型…'));
return const Center(child: AppText('Loading models…'));
}
final filter = _filter.trim().toLowerCase();
final matching = filter.isEmpty
@@ -103,7 +104,7 @@ class _PickerSheetState extends State<_PickerSheet> {
m.id.toLowerCase().contains(filter))
m,
];
if (matching.isEmpty) return const Center(child: Text('没有结果'));
if (matching.isEmpty) return const Center(child: AppText('No results'));
final byKey = {
for (final m in all) ModelPrefs.keyFor(m.providerId, m.id): m,
@@ -125,7 +126,7 @@ class _PickerSheetState extends State<_PickerSheet> {
final children = <Widget>[];
if (filter.isEmpty) {
if (favorites.isNotEmpty) {
children.add(_sectionHeader('收藏', 'favorites', count: favorites.length));
children.add(_sectionHeader(tr('Favorites'), 'favorites', count: favorites.length));
if (!_collapsed.contains('favorites')) {
for (final model in favorites) {
children.add(_modelRow(model));
@@ -133,7 +134,7 @@ class _PickerSheetState extends State<_PickerSheet> {
}
}
if (recents.isNotEmpty) {
children.add(_sectionHeader('最近', 'recents', count: recents.length));
children.add(_sectionHeader(tr('Recent'), 'recents', count: recents.length));
if (!_collapsed.contains('recents')) {
for (final model in recents) {
children.add(_modelRow(model));
@@ -142,7 +143,7 @@ class _PickerSheetState extends State<_PickerSheet> {
}
}
for (final entry in providers.entries) {
final label = entry.key.isEmpty ? '其它' : entry.key;
final label = entry.key.isEmpty ? tr('Other') : entry.key;
children.add(_sectionHeader(label, 'provider:${entry.key}',
count: entry.value.length));
if (!_collapsed.contains('provider:${entry.key}')) {
@@ -172,8 +173,8 @@ class _PickerSheetState extends State<_PickerSheet> {
size: 16, color: Theme.of(context).hintColor),
const SizedBox(width: 4),
Expanded(
child: Text(
count == null ? label : '$label($count)',
child: AppText(
count == null ? label : trArgs('{0} ({1})', [label, count]),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
@@ -211,7 +212,8 @@ class _PickerSheetState extends State<_PickerSheet> {
],
),
subtitle: model.context > 0
? Text('${formatTokenCount(model.context)} 上下文',
? AppText(
trArgs('{0} context', [formatTokenCount(model.context)]),
style: TextStyle(fontSize: 11, color: theme.hintColor))
: null,
trailing: Row(
@@ -230,7 +232,7 @@ class _PickerSheetState extends State<_PickerSheet> {
size: 18,
color: favorite ? theme.colorScheme.primary : theme.hintColor,
),
tooltip: favorite ? '取消收藏' : '收藏',
tooltip: favorite ? tr('Remove from favorites') : tr('Favorites'),
onPressed: () async {
await _prefs.toggleFavorite(key);
if (mounted) setState(() {});
@@ -287,7 +289,7 @@ class _PickerSheetState extends State<_PickerSheet> {
children: [
Row(
children: [
const Text('思考强度',
const AppText('Thinking effort',
style: TextStyle(
fontSize: 13, fontWeight: FontWeight.w700)),
const SizedBox(width: 6),
@@ -300,7 +302,7 @@ class _PickerSheetState extends State<_PickerSheet> {
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('完成'),
child: const AppText('Done'),
),
],
),
@@ -310,7 +312,7 @@ class _PickerSheetState extends State<_PickerSheet> {
children: [
for (final option in options)
ChoiceChip(
label: Text(effortLabel(option),
label: AppText(effortLabel(option),
style: const TextStyle(fontSize: 12.5)),
selected: (_effortVariant ?? '') == (option ?? ''),
onSelected: (_) => _pickEffort(model, option),
+9 -3
View File
@@ -16,7 +16,12 @@ import '../pets/pet_pack.dart';
/// 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});
/// How far below the layer's bottom edge the feet stand: the composer's
/// top padding, or the status capsule's edge when one sits above it.
final double footOffset;
const PetLayer({super.key, required this.state, this.footOffset = 6});
@override
State<PetLayer> createState() => _PetLayerState();
@@ -62,8 +67,9 @@ class _PetLayerState extends State<PetLayer> {
// 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;
final bottom = -((pack.canvas.height - pack.anchor.dy) * scale +
widget.footOffset) +
_lift;
return Stack(
clipBehavior: Clip.none,
+165
View File
@@ -0,0 +1,165 @@
// A project's sidebar icon: the operator's chosen icon in its colour, a custom
// icon image from the project, or a folder. OpenChamber's managed chats have
// no project and get a chat bubble instead.
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../api/models.dart';
import '../state.dart';
/// The Flutter equivalent of OpenChamber's `PROJECT_ICON_MAP` keys.
IconData? projectIconData(String key) => switch (key) {
'code' => Icons.code,
'terminal' => Icons.terminal,
'rocket' => Icons.rocket_launch_outlined,
'flask' => Icons.science_outlined,
'gamepad' => Icons.sports_esports_outlined,
'briefcase' => Icons.work_outline,
'home' => Icons.home_outlined,
'globe' => Icons.public,
'leaf' => Icons.eco_outlined,
'shield' => Icons.shield_outlined,
'palette' => Icons.palette_outlined,
'server' => Icons.dns_outlined,
'phone' => Icons.smartphone,
'database' => Icons.storage,
'lightbulb' => Icons.lightbulb_outline,
'music' => Icons.music_note_outlined,
'camera' => Icons.photo_camera_outlined,
'book' => Icons.menu_book_outlined,
'heart' => Icons.favorite_outline,
'cpu' => Icons.memory,
'cloud' => Icons.cloud_outlined,
'store' => Icons.storefront_outlined,
'school' => Icons.school_outlined,
'chat' => Icons.chat_bubble_outline,
'mail' => Icons.mail_outline,
'map' => Icons.place_outlined,
'robot' => Icons.smart_toy_outlined,
'ai' => Icons.psychology_outlined,
'plugin' => Icons.extension_outlined,
'tools' => Icons.build_outlined,
'chart' => Icons.bar_chart,
'writing' => Icons.edit_outlined,
'image' => Icons.image_outlined,
'film' => Icons.movie_outlined,
'trophy' => Icons.emoji_events_outlined,
'travel' => Icons.flight,
'coffee' => Icons.coffee_outlined,
'bug' => Icons.bug_report_outlined,
'apple' => Icons.apple,
'android' => Icons.android,
'windows' => Icons.window,
'github' => Icons.code,
'stack' => Icons.layers_outlined,
'finance' => Icons.account_balance_outlined,
'team' => Icons.groups_outlined,
'fire' => Icons.local_fire_department_outlined,
'planet' => Icons.public,
_ => null,
};
/// A stored project colour as a Flutter colour. Newer projects store hex;
/// older ones a theme/syntax key, resolved against the app's scheme.
Color? projectColor(String value, ColorScheme scheme) {
final hex = projectHexColor(value);
if (hex != null) return hex;
return switch (value.trim()) {
'primary' => scheme.primary,
'error' => scheme.error,
'success' => Colors.green,
'keyword' => scheme.primary,
'string' => Colors.green,
'number' => Colors.orange,
'type' => Colors.teal,
'constant' => Colors.blue,
'comment' => scheme.onSurfaceVariant,
_ => null,
};
}
Color? projectHexColor(String value) {
final text = value.trim();
if (!text.startsWith('#')) return null;
var hex = text.substring(1);
if (hex.length == 3) {
hex = hex.split('').map((c) => '$c$c').join();
}
if (hex.length != 6 && hex.length != 8) return null;
final parsed = int.tryParse(hex, radix: 16);
if (parsed == null) return null;
return Color(hex.length == 6 ? 0xff000000 | parsed : parsed);
}
String _hexOf(Color color) =>
'#${(color.toARGB32() & 0xffffff).toRadixString(16).padLeft(6, '0')}';
class ProjectIcon extends StatelessWidget {
final AppState app;
final ProjectInfo? project;
final bool chat;
final double size;
const ProjectIcon({
super.key,
required this.app,
this.project,
this.chat = false,
this.size = 16,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
if (chat) {
return Icon(Icons.chat_bubble_outline, size: size, color: scheme.primary);
}
final project = this.project;
if (project == null) {
return Icon(Icons.folder_outlined, size: size, color: theme.hintColor);
}
final color = projectColor(project.color, scheme) ?? theme.hintColor;
final glyph = Icon(projectIconData(project.icon) ?? Icons.folder_outlined,
size: size, color: color);
if (!project.hasIconImage) return glyph;
final future = app.projectIcon(
project,
dark: theme.brightness == Brightness.dark,
iconColor: _hexOf(scheme.onSurface),
);
return FutureBuilder<Uint8List?>(
future: future,
builder: (context, snapshot) {
final bytes = snapshot.data;
if (bytes == null || bytes.isEmpty) {
// Loading or unavailable: keep the glyph so the row does not jump.
return glyph;
}
final Widget image = project.iconImageMime.contains('svg')
? SvgPicture.memory(bytes,
width: size, height: size, fit: BoxFit.contain)
: Image.memory(bytes,
width: size,
height: size,
fit: BoxFit.contain,
gaplessPlayback: true);
final background = projectHexColor(project.iconBackground);
if (background == null) return image;
return Container(
width: size,
height: size,
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(3),
),
clipBehavior: Clip.antiAlias,
child: image,
);
},
);
}
}
+284
View File
@@ -0,0 +1,284 @@
// Choosing a project, shared by the new-session draft and scheduled tasks.
// The sheet opens at once and refreshes the project list behind it: a tap on
// the project chip should never wait for the server before anything appears.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../l10n.dart';
import '../state.dart';
import 'directory_picker.dart';
import 'project_icon.dart';
/// The "All projects" row of the stats scope picker, where a report is not
/// narrowed to one checkout.
const allProjectsTarget = '\u0000all-projects';
/// What the picker returns: the Chat row, the All projects row, or a checkout.
class ProjectChoice {
/// Null for the Chat and All projects rows.
final ProjectInfo? project;
final bool all;
const ProjectChoice.chat()
: project = null,
all = false;
const ProjectChoice.allProjects()
: project = null,
all = true;
const ProjectChoice.project(this.project) : all = false;
bool get isChat => project == null && !all;
bool get isAll => all;
String get canonical =>
all ? allProjectsTarget : (project?.canonical ?? AppState.chatTarget);
String get label => all ? tr('All projects') : (project?.label ?? tr('Chat'));
}
/// Opens the project sheet and returns the chosen target, or null when the
/// person dismissed it. [selected] is a checkout path, or [AppState.chatTarget]
/// for the Chat row. [onlyProjects] limits the list to exactly those projects
/// (the archive page offers only projects that hold archived sessions, since
/// it never archives anything itself); null lists every selectable checkout.
Future<ProjectChoice?> showProjectPicker(
BuildContext context, {
required AppState app,
required String selected,
bool includeAll = false,
bool includeChat = true,
List<ProjectInfo>? onlyProjects,
}) {
return showModalBottomSheet<ProjectChoice>(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.6,
maxChildSize: 0.9,
builder: (context, controller) => _ProjectPickerSheet(
app: app,
selected: selected,
includeAll: includeAll,
includeChat: includeChat,
projects: onlyProjects,
controller: controller,
),
),
);
}
/// The projects a picker offers: checkouts, not the server's chat folders.
/// 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(AppState app) {
final byPath = <String, ProjectInfo>{};
for (final project in app.projects) {
if (project.canonical.isEmpty) continue;
if (app.isChatDirectory(project.canonical)) continue;
final existing = byPath[project.canonical];
if (existing == null ||
(existing.vcs.isEmpty && project.vcs.isNotEmpty)) {
byPath[project.canonical] = project;
}
}
return byPath.values.toList();
}
class _ProjectPickerSheet extends StatefulWidget {
final AppState app;
final String selected;
final bool includeAll;
final bool includeChat;
/// Null offers every selectable checkout; a list limits the picker to it
/// (the archive page) and hides the add-project action.
final List<ProjectInfo>? projects;
final ScrollController controller;
const _ProjectPickerSheet({
required this.app,
required this.selected,
required this.includeAll,
required this.includeChat,
required this.projects,
required this.controller,
});
@override
State<_ProjectPickerSheet> createState() => _ProjectPickerSheetState();
}
class _ProjectPickerSheetState extends State<_ProjectPickerSheet> {
/// True until the list behind the sheet has been refreshed. The sheet is
/// already up by then; only its body shows the spinner.
bool _refreshing = true;
final TextEditingController _searchCtrl = TextEditingController();
String _filter = '';
@override
void initState() {
super.initState();
_refresh();
}
@override
void dispose() {
_searchCtrl.dispose();
super.dispose();
}
Future<void> _refresh() async {
await Future.wait([
widget.app.refreshProjects(),
widget.app.refreshFsHome(),
]);
if (!mounted) return;
setState(() => _refreshing = false);
}
/// Browses the server's folders and returns with the new project selected.
Future<void> _addProject() async {
final path = await showDirectoryPicker(context, app: widget.app);
if (path == null || !mounted) return;
final project = widget.app.projectFor(path) ??
ProjectInfo(id: '', canonical: path, name: pathLeaf(path));
Navigator.pop(context, ProjectChoice.project(project));
}
@override
Widget build(BuildContext context) {
final chat = widget.selected == AppState.chatTarget;
// A cached list is shown at once; the refresh updates it in place.
final projects = widget.projects ?? selectableProjects(widget.app);
final query = _filter.trim().toLowerCase();
final visible = query.isEmpty
? projects
: [
for (final project in projects)
if (project.label.toLowerCase().contains(query) ||
project.canonical.toLowerCase().contains(query))
project,
];
final loading = _refreshing && projects.isEmpty;
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 8, 0),
child: Row(
children: [
const Expanded(
child: AppText('Choose project',
style:
TextStyle(fontSize: 17, fontWeight: FontWeight.w600)),
),
if (widget.projects == null)
TextButton.icon(
onPressed: _addProject,
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 8)),
icon: const Icon(Icons.create_new_folder_outlined, size: 18),
label: const AppText('Add project'),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 2, 12, 6),
child: TextField(
controller: _searchCtrl,
onChanged: (value) => setState(() => _filter = value),
decoration: InputDecoration(
hintText: tr('Search projects'),
prefixIcon: const Icon(Icons.search, size: 18),
isDense: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
),
),
),
Expanded(
child: loading
? const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2)),
SizedBox(height: 12),
AppText('Loading projects…'),
],
),
),
)
: ListView(
controller: widget.controller,
children: [
if (widget.includeAll)
ListTile(
dense: true,
leading: Icon(Icons.folder_copy_outlined,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant),
title: const AppText('All projects'),
trailing: widget.selected == allProjectsTarget
? Icon(Icons.check,
size: 18,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () => Navigator.pop(
context, const ProjectChoice.allProjects()),
),
if (widget.includeChat)
ListTile(
dense: true,
leading:
ProjectIcon(app: widget.app, chat: true, size: 20),
title: const AppText('Chat'),
subtitle: const AppText(
'Not tied to a project, saved in OpenChamber\'s chat directory'),
trailing: chat
? Icon(Icons.check,
size: 18,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () =>
Navigator.pop(context, const ProjectChoice.chat()),
),
for (final project in visible)
ListTile(
dense: true,
leading: ProjectIcon(
app: widget.app, project: project, size: 20),
title: Text(project.label,
maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(project.canonical,
maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: samePath(project.canonical, widget.selected)
? Icon(Icons.check,
size: 18,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () => Navigator.pop(
context, ProjectChoice.project(project)),
),
if (!_refreshing && visible.isEmpty)
Padding(
padding: const EdgeInsets.all(24),
child: AppText(
query.isEmpty
? 'No projects available'
: 'No matching projects',
textAlign: TextAlign.center),
),
],
),
),
],
);
}
}
+495
View File
@@ -0,0 +1,495 @@
// The scheduled-task editor: name, prompt, schedule and the run's model. The
// server validates the same limits again; saving hands the draft back so the
// page can keep the list it answers with.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../api/scheduled_tasks.dart';
import '../state.dart';
import 'model_picker.dart';
import '../l10n.dart';
class ScheduledTaskEditor extends StatefulWidget {
final AppState app;
/// What the task runs in, as the page names it.
final String scopeLabel;
/// Null creates a task.
final ScheduledTask? initial;
/// Saves the draft; false keeps the sheet open (the page has said why).
final Future<bool> Function(ScheduledTask draft) onSave;
const ScheduledTaskEditor({
super.key,
required this.app,
required this.scopeLabel,
required this.onSave,
this.initial,
});
@override
State<ScheduledTaskEditor> createState() => _ScheduledTaskEditorState();
}
class _ScheduledTaskEditorState extends State<ScheduledTaskEditor> {
late final TextEditingController _name;
late final TextEditingController _prompt;
late final TextEditingController _cron;
late String _kind;
late List<String> _times;
late Set<int> _weekdays;
late DateTime _date;
late String _time;
late bool _useDefaults;
late String _providerId;
late String _modelId;
late String _variant;
late String _agent;
late bool _enabled;
bool _saving = false;
@override
void initState() {
super.initState();
final task = widget.initial;
_name = TextEditingController(text: task?.name ?? '');
_prompt = TextEditingController(text: task?.prompt ?? '');
_cron = TextEditingController(
text: task?.kind == 'cron' && task!.cron.isNotEmpty
? task.cron
: '0 9 * * *');
_kind = task != null && task.kind.isNotEmpty ? task.kind : 'daily';
_times = task != null && task.times.isNotEmpty
? [...task.times]
: [task?.time.isNotEmpty == true ? task!.time : '09:00'];
_weekdays = task != null && task.weekdays.isNotEmpty
? {...task.weekdays}
: {1};
_date = _parseDate(task?.date ?? '') ?? _tomorrow();
_time = task != null && task.time.isNotEmpty ? task.time : '09:00';
_useDefaults = task?.useDefaults ?? true;
_providerId = task?.providerId ?? '';
_modelId = task?.modelId ?? '';
_variant = task?.variant ?? '';
_agent = task?.agent ?? '';
_enabled = task?.enabled ?? true;
if (widget.app.modelList.isEmpty) widget.app.refreshModels();
}
@override
void dispose() {
_name.dispose();
_prompt.dispose();
_cron.dispose();
super.dispose();
}
static DateTime _tomorrow() {
final now = DateTime.now();
return DateTime(now.year, now.month, now.day + 1);
}
static DateTime? _parseDate(String value) {
final parts = value.split('-');
if (parts.length != 3) return null;
final year = int.tryParse(parts[0]);
final month = int.tryParse(parts[1]);
final day = int.tryParse(parts[2]);
if (year == null || month == null || day == null) return null;
return DateTime(year, month, day);
}
static String _two(int value) => value.toString().padLeft(2, '0');
static String _dateText(DateTime date) =>
'${date.year}-${_two(date.month)}-${_two(date.day)}';
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return FractionallySizedBox(
heightFactor: 0.92,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 12, 4),
child: Row(
children: [
Expanded(
child: AppText(
widget.initial == null ? 'New scheduled task' : 'Edit scheduled task',
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.w600),
),
),
TextButton(
onPressed: _saving ? null : _save,
child: AppText(_saving ? 'Saving…' : 'Save'),
),
],
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 32),
children: [
AppText(trArgs('Runs in: {0}', [widget.scopeLabel]),
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
const SizedBox(height: 12),
TextField(
controller: _name,
maxLength: 80,
decoration: InputDecoration(
labelText: tr('Task name'),
hintText: tr('Daily sync'),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _prompt,
minLines: 4,
maxLines: 10,
decoration: InputDecoration(
labelText: tr('Prompt'),
hintText: tr('Summarize unfinished tasks and suggest next steps'),
border: const OutlineInputBorder(),
alignLabelWithHint: true,
),
),
const SizedBox(height: 16),
const _FieldLabel('Schedule type'),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final entry in scheduledTaskKindLabels.entries)
ChoiceChip(
label: AppText(entry.value),
selected: _kind == entry.key,
onSelected: (_) => setState(() => _kind = entry.key),
),
],
),
const SizedBox(height: 8),
..._scheduleFields(theme),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Use default model and agent'),
subtitle: const AppText('Turn off to pin the model and agent this run uses.'),
value: _useDefaults,
onChanged: (v) => setState(() => _useDefaults = v),
),
if (!_useDefaults) ..._executionFields(theme),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Enabled'),
subtitle: const AppText('Paused tasks don\'t run on schedule but can still be run manually.'),
value: _enabled,
onChanged: (v) => setState(() => _enabled = v),
),
const SizedBox(height: 8),
FilledButton(
onPressed: _saving ? null : _save,
child: AppText(_saving ? 'Saving…' : 'Save'),
),
],
),
),
],
),
);
}
List<Widget> _scheduleFields(ThemeData theme) {
switch (_kind) {
case 'daily':
return [_timesField(theme)];
case 'weekly':
return [
const _FieldLabel('Weekdays'),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (var day = 0; day < scheduledWeekdays.length; day++)
FilterChip(
label: AppText(scheduledWeekdays[day]),
selected: _weekdays.contains(day),
onSelected: (selected) => setState(() {
if (selected) {
_weekdays.add(day);
} else if (_weekdays.length > 1) {
_weekdays.remove(day);
}
}),
),
],
),
const SizedBox(height: 8),
_timesField(theme),
];
case 'once':
return [
ListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Date'),
trailing: Text(_dateText(_date)),
onTap: _pickDate,
),
ListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Time'),
trailing: Text(_time),
onTap: () async {
final picked = await _pickTime(_time);
if (picked != null) setState(() => _time = picked);
},
),
];
case 'cron':
return [
TextField(
controller: _cron,
decoration: InputDecoration(
labelText: tr('Cron expression'),
hintText: '*/5 * * * *',
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final example in const [
('Every 5 minutes', '*/5 * * * *'),
('Every hour', '0 * * * *'),
('Daily at 9', '0 9 * * *'),
('Mondays at 9', '0 9 * * 1'),
('1st of each month', '0 9 1 * *'),
])
ActionChip(
label: AppText(example.$1),
onPressed: () =>
setState(() => _cron.text = example.$2),
),
],
),
];
}
return const [];
}
Widget _timesField(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const _FieldLabel('Times'),
for (var i = 0; i < _times.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () async {
final picked = await _pickTime(_times[i]);
if (picked != null) setState(() => _times[i] = picked);
},
child: Text(_times[i]),
),
),
IconButton(
icon: const Icon(Icons.remove_circle_outline, size: 20),
tooltip: tr('Remove time'),
onPressed: _times.length <= 1
? null
: () => setState(() => _times.removeAt(i)),
),
],
),
),
TextButton.icon(
onPressed: () async {
final picked = await _pickTime(_times.isEmpty ? '09:00' : _times.last);
if (picked != null) setState(() => _times.add(picked));
},
icon: const Icon(Icons.add, size: 18),
label: const AppText('Add time'),
),
AppText('Times follow the server\'s time zone.', style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
],
);
}
List<Widget> _executionFields(ThemeData theme) {
final model = _modelId.isEmpty
? 'Select model'
: (widget.app.modelNames['$_providerId/$_modelId'] ?? '$_providerId/$_modelId');
final agent = _agent.isEmpty ? 'Default agent' : _agent;
return [
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.memory, size: 20),
title: const AppText('Model'),
trailing: Text(model, overflow: TextOverflow.ellipsis),
onTap: _pickModel,
),
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.smart_toy_outlined, size: 20),
title: const AppText('Agent'),
trailing: AppText(agent, overflow: TextOverflow.ellipsis),
onTap: _pickAgent,
),
];
}
Future<void> _pickDate() async {
final now = DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: _date,
firstDate: now.subtract(const Duration(days: 1)),
lastDate: now.add(const Duration(days: 365 * 5)),
);
if (picked != null) setState(() => _date = picked);
}
Future<String?> _pickTime(String current) async {
final parts = current.split(':');
final picked = await showTimePicker(
context: context,
initialTime: TimeOfDay(
hour: int.tryParse(parts.first) ?? 9,
minute: parts.length > 1 ? int.tryParse(parts[1]) ?? 0 : 0,
),
);
if (picked == null) return null;
return '${_two(picked.hour)}:${_two(picked.minute)}';
}
Future<void> _pickModel() async {
final current = _modelId.isEmpty
? null
: ModelRef(_modelId, _providerId, _variant.isEmpty ? null : _variant);
await showModelPickerSheet(
context,
app: widget.app,
model: current,
onModel: (model) {
setState(() {
_modelId = model.id;
_providerId = model.providerId;
_variant = model.variant ?? '';
});
},
);
}
Future<void> _pickAgent() async {
if (widget.app.agentList.isEmpty) await widget.app.refreshModels();
if (!mounted) return;
final chosen = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheet) => ListView(
shrinkWrap: true,
children: [
ListTile(
title: const AppText('Default agent'),
trailing: _agent.isEmpty ? const Icon(Icons.check, size: 20) : null,
onTap: () => Navigator.pop(sheet, ''),
),
for (final agent in widget.app.agentList)
ListTile(
title: Text(agent.name.isEmpty ? agent.id : agent.name),
trailing: _agent == agent.id
? const Icon(Icons.check, size: 20)
: null,
onTap: () => Navigator.pop(sheet, agent.id),
),
],
),
);
if (chosen == null) return;
setState(() => _agent = chosen);
}
Future<void> _save() async {
final name = _name.text.trim();
final prompt = _prompt.text.trim();
final messenger = ScaffoldMessenger.of(context);
String? problem;
if (name.isEmpty) {
problem = 'Task name is required';
} else if (name.length > 80) {
problem = 'Task name can\'t exceed 80 characters';
} else if (prompt.isEmpty) {
problem = 'Prompt is required';
} else if (prompt.length > 20000) {
problem = 'Prompt can\'t exceed 20,000 characters';
} else if ((_kind == 'daily' || _kind == 'weekly') &&
_times.any((t) => !RegExp(r'^([01]\d|2[0-3]):[0-5]\d$').hasMatch(t))) {
problem = 'Time must be in HH:mm format';
} else if (_kind == 'weekly' && _weekdays.isEmpty) {
problem = 'Select at least one weekday';
} else if (_kind == 'cron' && _cron.text.trim().isEmpty) {
problem = 'Cron expression is required';
} else if (!_useDefaults && _modelId.isEmpty) {
problem = 'Select a model, or switch back to the default model';
}
if (problem != null) {
messenger.showSnackBar(SnackBar(content: AppText(problem)));
return;
}
setState(() => _saving = true);
final initial = widget.initial;
final draft = ScheduledTask(
id: initial?.id ?? '',
name: name,
enabled: _enabled,
kind: _kind,
times: _kind == 'daily' || _kind == 'weekly'
? ([..._times]..sort())
: const [],
weekdays: _kind == 'weekly' ? ([..._weekdays]..sort()) : const [],
date: _kind == 'once' ? _dateText(_date) : '',
time: _kind == 'once' ? _time : '',
cron: _kind == 'cron' ? _cron.text.trim() : '',
timezone: initial?.timezone ?? '',
prompt: prompt,
useDefaults: _useDefaults,
providerId: _useDefaults ? '' : _providerId,
modelId: _useDefaults ? '' : _modelId,
variant: _useDefaults ? '' : _variant,
agent: _useDefaults ? '' : _agent,
targetSessionId: initial?.targetSessionId ?? '',
);
final ok = await widget.onSave(draft);
if (!mounted) return;
setState(() => _saving = false);
if (ok) Navigator.of(context).pop();
}
}
class _FieldLabel extends StatelessWidget {
final String text;
const _FieldLabel(this.text);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: AppText(text,
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
);
}
}
+750
View File
@@ -0,0 +1,750 @@
// The background-command surfaces: a strip above the composer that names what
// is running, a sheet with its live output, and the output preview inside the
// tool row that detached the command.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/client.dart';
import '../api/shells.dart';
import '../l10n.dart';
/// One line of "正在执行 N 条命令", folding when there are many.
class ShellTaskBar extends StatefulWidget {
final List<ShellTask> tasks;
/// The chat's own session: a task from a child session is marked.
final String sessionId;
/// Tapping a row opens its output; the stop lives in that sheet.
final void Function(ShellTask task) onOpen;
const ShellTaskBar({
super.key,
required this.tasks,
required this.sessionId,
required this.onOpen,
});
@override
State<ShellTaskBar> createState() => _ShellTaskBarState();
}
class _ShellTaskBarState extends State<ShellTaskBar> {
/// Null until the person folds or unfolds: by default a short list shows.
bool? _expanded;
bool get _open => _expanded ?? widget.tasks.length <= 3;
@override
Widget build(BuildContext context) {
final tasks = widget.tasks;
if (tasks.isEmpty) return const SizedBox.shrink();
final theme = Theme.of(context);
final single = tasks.length == 1;
// The same capsule as the activity strip above it: one row of text in the
// same stadium, with the same margins, so the two read as one stack.
return Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Material(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.7),
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 36),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!single) _header(theme, tasks.length),
if (single || _open)
for (final task in tasks)
_ShellTaskRow(
key: ValueKey(task.id),
task: task,
subagent: task.sessionId.isNotEmpty &&
task.sessionId != widget.sessionId,
onTap: () => widget.onOpen(task),
),
],
),
),
),
),
);
}
Widget _header(ThemeData theme, int count) {
return InkWell(
onTap: () => setState(() => _expanded = !_open),
child: SizedBox(
height: 24,
child: Row(
children: [
Icon(Icons.terminal, size: 15, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(
trArgs('Running {0} commands', [count]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurface,
),
),
),
Icon(_open ? Icons.expand_less : Icons.expand_more,
size: 18, color: theme.hintColor),
],
),
),
);
}
}
class _ShellTaskRow extends StatelessWidget {
final ShellTask task;
final bool subagent;
final VoidCallback onTap;
const _ShellTaskRow({
super.key,
required this.task,
required this.subagent,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return InkWell(
onTap: onTap,
child: SizedBox(
height: 24,
child: Row(
children: [
Icon(Icons.terminal, size: 15, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(
task.command.replaceAll(RegExp(r'\s+'), ' ').trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5, fontFamily: 'monospace', height: 1.3),
),
),
if (subagent) ...[
const SizedBox(width: 6),
AppText('Subagent',
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurfaceVariant,
)),
],
const SizedBox(width: 8),
// The clock ends on the capsule's inner edge, the same line the
// activity strip's clock ends on above it; stopping is a tap away
// in the sheet, so no button here to break that line.
ShellElapsed(startedAt: task.startedAt),
],
),
),
);
}
}
/// `3分05秒`, ticking while the command runs.
class ShellElapsed extends StatefulWidget {
final int startedAt;
final bool running;
const ShellElapsed(
{super.key, required this.startedAt, this.running = true});
@override
State<ShellElapsed> createState() => _ShellElapsedState();
}
class _ShellElapsedState extends State<ShellElapsed> {
Timer? _timer;
@override
void initState() {
super.initState();
if (widget.running) {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.startedAt <= 0 || !widget.running) return const SizedBox.shrink();
final label =
formatElapsed(DateTime.now().millisecondsSinceEpoch - widget.startedAt);
return Text(
label,
style: TextStyle(
fontSize: 12,
color: Theme.of(context).hintColor,
fontFeatures: const [FontFeature.tabularFigures()],
),
);
}
}
/// Opens the live output of [task] in a sheet. A command that already ended
/// hands in its completion text instead, since the shell (and its output
/// file) may be gone.
Future<void> showShellOutput(
BuildContext context, {
required Client client,
required ShellTask task,
required String directory,
required Future<void> Function() onStop,
String? finalOutput,
bool done = false,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
showDragHandle: true,
builder: (_) => FractionallySizedBox(
heightFactor: 0.8,
child: ShellOutputSheet(
client: client,
task: task,
directory: directory,
onStop: onStop,
finalOutput: finalOutput,
done: done,
),
),
);
}
/// The command, its status, and the output so far, following the tail.
class ShellOutputSheet extends StatefulWidget {
final Client client;
final ShellTask task;
final String directory;
final Future<void> Function() onStop;
/// The completion text when the command has already ended; the sheet then
/// does not poll a shell that may no longer exist.
final String? finalOutput;
final bool done;
const ShellOutputSheet({
super.key,
required this.client,
required this.task,
required this.directory,
required this.onStop,
this.finalOutput,
this.done = false,
});
@override
State<ShellOutputSheet> createState() => _ShellOutputSheetState();
}
class _ShellOutputSheetState extends State<ShellOutputSheet> {
late final ShellOutputFeed _feed = ShellOutputFeed(
client: widget.client,
task: widget.task,
directory: widget.directory,
);
final ScrollController _scroll = ScrollController();
bool _stick = true;
bool _stopping = false;
String get _text => widget.done ? (widget.finalOutput ?? '') : _feed.text;
bool get _running => !widget.done && !_feed.ended;
@override
void initState() {
super.initState();
_scroll.addListener(() {
if (!_scroll.hasClients) return;
final atBottom =
_scroll.position.maxScrollExtent - _scroll.position.pixels <= 40;
if (atBottom != _stick) setState(() => _stick = atBottom);
});
if (!widget.done) _feed.start(_onFeed);
}
void _onFeed() {
if (!mounted) return;
setState(() {});
if (_stick) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
}
@override
void dispose() {
_feed.dispose();
_scroll.dispose();
super.dispose();
}
Future<void> _stop() async {
final ok = await confirmStopShell(context, widget.task.command);
if (ok != true || !mounted) return;
setState(() => _stopping = true);
try {
await widget.onStop();
} finally {
if (mounted) setState(() => _stopping = false);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final running = _running;
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// The drag handle above and a tap on the scrim close the sheet;
// a close button would only repeat them.
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.terminal, size: 18, color: theme.hintColor),
const SizedBox(width: 10),
Expanded(
child: Text(
widget.task.command,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 13, fontFamily: 'monospace', height: 1.4),
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Row(
children: [
// No "运行中" label: a live sheet is running by definition,
// and the clock says since when. Only the end is worth saying.
if (running)
ShellElapsed(
startedAt: widget.task.startedAt, running: true)
else ...[
Icon(Icons.check_circle_outline,
size: 15, color: theme.hintColor),
const SizedBox(width: 6),
AppText('Ended',
style:
TextStyle(fontSize: 12, color: theme.hintColor)),
],
const Spacer(),
if (running)
TextButton.icon(
onPressed: _stopping ? null : _stop,
icon: const Icon(Icons.stop_rounded, size: 17),
label: AppText(_stopping ? 'Stopping…' : 'Stop'),
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.error,
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 10),
),
),
TextButton.icon(
onPressed: _text.isEmpty ? null : _copy,
icon: const Icon(Icons.copy, size: 15),
label: const AppText('Copy'),
style: TextButton.styleFrom(
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 10),
),
),
],
),
),
const Divider(height: 1),
Expanded(
child: Stack(
children: [
Positioned.fill(
child: _text.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_feed.error == null && !_feed.loaded) ...[
const SizedBox(
width: 16,
height: 16,
child:
CircularProgressIndicator(strokeWidth: 1.8),
),
const SizedBox(height: 10),
],
AppText(
_feed.error ??
(!_feed.loaded
? 'Reading output…'
: running
? 'Waiting for output…'
: 'No output'),
style: TextStyle(
fontSize: 13, color: theme.hintColor),
),
],
),
)
: Scrollbar(
controller: _scroll,
child: SingleChildScrollView(
controller: _scroll,
padding: const EdgeInsets.all(16),
child: SelectableText(
_text,
style: const TextStyle(
fontSize: 12,
fontFamily: 'monospace',
height: 1.45),
),
),
),
),
if (!_stick && _text.isNotEmpty)
Positioned(
right: 12,
bottom: 12,
child: FilledButton.tonalIcon(
onPressed: () {
setState(() => _stick = true);
_onFeed();
},
icon: const Icon(Icons.arrow_downward, size: 15),
label: const AppText('Jump to latest'),
style: FilledButton.styleFrom(
visualDensity: VisualDensity.compact,
),
),
),
],
),
),
],
),
);
}
Future<void> _copy() async {
await Clipboard.setData(ClipboardData(text: _text));
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: AppText('Output copied')));
}
}
}
/// The live output inside the tool row that detached the command: the last
/// lines, with the way to the full sheet.
class ShellOutputInline extends StatefulWidget {
final Client client;
final ShellTask task;
final String directory;
final VoidCallback onOpen;
final Future<void> Function() onStop;
/// The report of a command that already ended (the shell may be gone, so
/// there is nothing left to poll).
final String? finalOutput;
final bool done;
const ShellOutputInline({
super.key,
required this.client,
required this.task,
required this.directory,
required this.onOpen,
required this.onStop,
this.finalOutput,
this.done = false,
});
@override
State<ShellOutputInline> createState() => _ShellOutputInlineState();
}
class _ShellOutputInlineState extends State<ShellOutputInline> {
late final ShellOutputFeed _feed = ShellOutputFeed(
client: widget.client,
task: widget.task,
directory: widget.directory,
);
@override
void initState() {
super.initState();
if (!widget.done) {
_feed.start(() {
if (mounted) setState(() {});
});
}
}
@override
void dispose() {
_feed.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final ended = widget.done || _feed.ended;
final text = widget.done ? (widget.finalOutput ?? '') : _feed.text;
final tail = _tail(text, 8);
return Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(10, 8, 10, 4),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.terminal, size: 15, color: theme.hintColor),
const SizedBox(width: 8),
AppText('Background output',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
const SizedBox(width: 8),
if (!ended)
AppText('Running',
style: TextStyle(
fontSize: 12, color: theme.colorScheme.primary)),
if (ended && text.isEmpty)
AppText('Ended',
style:
TextStyle(fontSize: 12, color: theme.hintColor)),
const Spacer(),
if (!ended)
TextButton(
onPressed: _stop,
style: TextButton.styleFrom(
foregroundColor: theme.colorScheme.error,
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 8),
textStyle: const TextStyle(fontSize: 12.5),
),
child: const AppText('Stop'),
),
TextButton(
onPressed: widget.onOpen,
style: TextButton.styleFrom(
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 8),
textStyle: const TextStyle(fontSize: 12.5),
),
child: const AppText('View all'),
),
],
),
if (tail.isEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: AppText(
_feed.error ?? (ended ? 'No output' : 'Waiting for output…'),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
)
else
Padding(
padding: const EdgeInsets.only(top: 2, bottom: 6),
child: SelectableText(
tail,
style: const TextStyle(
fontSize: 12, fontFamily: 'monospace', height: 1.4),
),
),
],
),
);
}
Future<void> _stop() async {
final ok = await confirmStopShell(context, widget.task.command);
if (ok == true) await widget.onStop();
}
static String _tail(String text, int lines) {
if (text.isEmpty) return '';
final all = text.split('\n');
if (all.length <= lines) return text;
return '…\n${all.sublist(all.length - lines).join('\n')}';
}
}
/// "停止这个任务?" with the command, as the first-party client asks.
Future<bool?> confirmStopShell(BuildContext context, String command) {
return showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: const AppText('Stop this task?'),
content: Text(
command,
maxLines: 4,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: const AppText('Cancel')),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: Theme.of(dialog).colorScheme.error,
foregroundColor: Theme.of(dialog).colorScheme.onError,
),
onPressed: () => Navigator.pop(dialog, true),
child: const AppText('Stop'),
),
],
),
);
}
/// Reads a shell's output a page at a time (one poll a second) and says when
/// the command ended. Shared by the sheet and the tool row preview.
class ShellOutputFeed {
ShellOutputFeed({
required this.client,
required this.task,
required this.directory,
});
final Client client;
final ShellTask task;
final String directory;
String text = '';
/// The first page has been read: before that, an empty [text] means the
/// read is still under way, not that the command has printed nothing.
bool loaded = false;
bool ended = false;
String? error;
int _cursor = 0;
bool _first = true;
bool _busy = false;
int _ticks = 0;
Timer? _timer;
VoidCallback? _onUpdate;
void start(VoidCallback onUpdate) {
if (_timer != null) return;
_onUpdate = onUpdate;
unawaited(_poll());
_timer = Timer.periodic(const Duration(seconds: 1), (_) => _poll());
}
Future<void> _poll() async {
if (_busy) return;
_busy = true;
try {
if (_first) {
final page = await client.shellOutput(task.id, directory: directory);
_first = false;
if (page.size > shellOutputTailBytes) {
// Long command: start near the end instead of reading it all.
final tail = await client.shellOutput(
task.id,
cursor: page.size - shellOutputTailBytes,
limit: shellOutputTailBytes,
directory: directory,
);
text = tail.output;
_cursor = tail.cursor;
} else {
text = page.output;
_cursor = page.cursor;
}
error = null;
loaded = true;
} else if (!ended) {
final page = await client.shellOutput(task.id,
cursor: _cursor, directory: directory);
if (page.output.isNotEmpty) text = _keepTail(text + page.output);
_cursor = page.cursor;
error = null;
}
if (!ended && ++_ticks % 3 == 0) {
final shell = await client.shell(task.id, directory: directory);
if (shell == null || !shell.running) {
if (!ended) {
final last = await client
.shellOutput(task.id, cursor: _cursor, directory: directory)
.catchError((_) => const ShellOutputPage());
if (last.output.isNotEmpty) text = _keepTail(text + last.output);
_cursor = last.cursor;
}
ended = true;
_timer?.cancel();
_timer = null;
}
}
_onUpdate?.call();
} on ApiError catch (e) {
if (e.status == 404) {
ended = true;
loaded = true;
error = null;
_timer?.cancel();
_timer = null;
} else {
error = trArgs('Could not read output: {0}', [e.message]);
}
_onUpdate?.call();
} catch (e) {
error = trArgs('Could not read output: {0}', ['$e']);
_onUpdate?.call();
} finally {
_busy = false;
}
}
static String _keepTail(String text) => text.length <= shellOutputTailBytes
? text
: text.substring(text.length - shellOutputTailBytes);
void dispose() {
_timer?.cancel();
_timer = null;
}
}
+12 -11
View File
@@ -3,16 +3,17 @@
import 'package:flutter/material.dart';
import '../state.dart';
import '../l10n.dart';
const _slashLabels = {
'compact': '压缩',
'init': '初始化',
'review': '审查',
'goal': '目标',
'new-extension': '新建扩展',
'permission': '权限',
'plan': '计划',
'feedback': '反馈',
'compact': 'Compact',
'init': 'Init',
'review': 'Review',
'goal': 'Goal',
'new-extension': 'New extension',
'permission': 'Permission',
'plan': 'Plans',
'feedback': 'Feedback',
};
String? slashLabel(SlashItem item) =>
@@ -118,7 +119,7 @@ class SlashPalette extends StatelessWidget {
child: CircularProgressIndicator(strokeWidth: 2)),
),
)
: row(Icons.search_off, '没有可用的指令', '这个目录还没有注册指令或技能'))
: row(Icons.search_off, 'No commands available', 'This directory has no commands or skills yet'))
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
@@ -159,7 +160,7 @@ class SlashPalette extends StatelessWidget {
children: [
Row(
children: [
Text('/${item.name}',
AppText('/${item.name}',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
@@ -167,7 +168,7 @@ class SlashPalette extends StatelessWidget {
if (label != null)
Padding(
padding: const EdgeInsets.only(left: 6),
child: Text(label,
child: AppText(label,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
+1 -1
View File
@@ -33,7 +33,7 @@ static void my_application_activate(GApplication* application) {
// gtk_header_bar_set_show_close_button(header_bar, TRUE);
// gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
gtk_window_set_title(window, "openchamber");
gtk_window_set_title(window, "Chamber Go");
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
+191 -143
View File
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones."
publish_to: 'none'
version: 0.4.6+406
version: 0.7.4+704
environment:
sdk: ^3.14.0
@@ -22,6 +22,11 @@ dependencies:
pointycastle: ^4.0.0
camera: ^0.12.2
zxing2: ^0.2.4
flutter_svg: ^2.5.0
package_info_plus: ^10.2.2
flutter_localizations:
sdk: flutter
webview_flutter: ^4.14.1
dev_dependencies:
flutter_test:
sdk: flutter
+146
View File
@@ -0,0 +1,146 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/screens/archived_sessions_screen.dart';
import 'package:openchamber/state.dart';
class _FakeTransport implements Transport {
final List<Map<String, dynamic>> archived;
_FakeTransport(this.archived);
@override
Future<TransportResponse> send(TransportRequest r) async {
Object? body;
if (r.path == '/api/session') {
body = {'data': archived};
} else if (r.path == '/api/project') {
body = [
{'id': 'p1', 'canonical': '/home/me/alpha', 'vcs': 'git'},
{'id': 'p2', 'canonical': '/home/me/beta', 'vcs': 'git'},
// A project with no archived sessions must not be offered.
{'id': 'p3', 'canonical': '/home/me/gamma', 'vcs': 'git'},
];
} else if (r.path == '/api/config/settings') {
body = {'projects': <dynamic>[]};
} else if (r.path == '/api/fs/home') {
body = {'home': '/home/me'};
} else if (r.method == 'PATCH') {
archived.removeWhere((s) => s['id'] == r.path.split('/').last);
body = {'data': <String, dynamic>{}};
} else if (r.method == 'DELETE') {
archived.removeWhere((s) => s['id'] == r.path.split('/').last);
body = <String, dynamic>{};
} else {
body = <String, dynamic>{};
}
return TransportResponse(
200,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
Map<String, dynamic> _session(
String id, String title, String directory, int archived) =>
{
'id': id,
'title': title,
'time': {'created': archived - 1000, 'updated': archived - 500, 'archived': archived},
'location': {'directory': directory},
};
void main() {
setUp(() => L10n.instance.apply(AppLanguage.en));
tearDown(() => L10n.instance.apply(AppLanguage.zh));
testWidgets('archived sessions are listed, filtered and restored',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport([
_session('a1', 'Old alpha', '/home/me/alpha', 1000),
_session('b1', 'Old beta', '/home/me/beta', 2000),
]);
app.client = Client(Uri.parse('http://test'), transport: transport);
await tester.pumpWidget(MaterialApp(home: ArchivedSessionsScreen(app: app)));
await tester.pumpAndSettle();
expect(find.text('Archive'), findsOneWidget);
expect(find.text('2 archived sessions'), findsOneWidget);
expect(find.text('Old alpha'), findsOneWidget);
expect(find.text('Old beta'), findsOneWidget);
expect(find.text('All projects'), findsOneWidget);
// The shared project sheet narrows the archive; "All projects" brings both
// back.
await tester.tap(find.text('All projects'));
await tester.pumpAndSettle();
// Only projects with archived sessions are offered; no add-project here.
expect(find.text('Add project'), findsNothing);
expect(find.text('/home/me/gamma'), findsNothing);
await tester.tap(find.text('/home/me/alpha'));
await tester.pumpAndSettle();
expect(find.text('Old alpha'), findsOneWidget);
expect(find.text('Old beta'), findsNothing);
expect(find.text('1 archived session'), findsOneWidget);
await tester.tap(find.text('alpha'));
await tester.pumpAndSettle();
await tester.tap(find.text('All projects'));
await tester.pumpAndSettle();
expect(find.text('Old beta'), findsOneWidget);
// Search across projects.
await tester.enterText(find.byType(TextField), 'beta');
await tester.pumpAndSettle();
expect(find.text('Old alpha'), findsNothing);
expect(find.text('Old beta'), findsOneWidget);
expect(find.text('1 archived session'), findsOneWidget);
// Restoring removes the row from the archive and from the list.
await tester.tap(find.byIcon(Icons.unarchive_outlined));
await tester.pumpAndSettle();
expect(find.text('Old beta'), findsNothing);
expect(find.text('Session restored'), findsOneWidget);
expect(app.archivedSessions.map((s) => s.id), ['a1']);
});
testWidgets('the project sheet filters the archive', (tester) async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport([
_session('a1', 'Old alpha', '/home/me/alpha', 1000),
_session('b1', 'Old beta', '/home/me/beta', 2000),
]);
app.client = Client(Uri.parse('http://test'), transport: transport);
await tester.pumpWidget(MaterialApp(home: ArchivedSessionsScreen(app: app)));
await tester.pumpAndSettle();
await tester.tap(find.text('All projects'));
await tester.pumpAndSettle();
expect(find.text('/home/me/gamma'), findsNothing);
await tester.tap(find.text('/home/me/beta'));
await tester.pumpAndSettle();
expect(find.text('Old beta'), findsOneWidget);
expect(find.text('Old alpha'), findsNothing);
});
}
+83
View File
@@ -0,0 +1,83 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/screens/browser_panel.dart';
import 'package:openchamber/screens/files_panel.dart';
import 'package:openchamber/state.dart';
class _FakeTransport implements Transport {
@override
Future<TransportResponse> send(TransportRequest r) async {
final body = switch (r.path) {
'/api/fs/list' => {'entries': <dynamic>[]},
_ => <String, dynamic>{},
};
return TransportResponse(
200,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
void main() {
setUp(() => L10n.instance.apply(AppLanguage.en));
tearDown(() => L10n.instance.apply(AppLanguage.zh));
testWidgets('the browser tab shows the mobile-only hint on desktop',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: BrowserPanel(app: app, directory: '/home/me')),
));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.public_off), findsOneWidget);
expect(find.text('Browser is only available on Android and iOS'),
findsOneWidget);
});
testWidgets('the panel tabs are icons with tooltips and open the browser',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
app.client =
Client(Uri.parse('http://test'), transport: _FakeTransport());
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: FilesPanel(app: app, directory: '/home/me')),
));
await tester.pumpAndSettle();
for (final label in [
'Files',
'Project knowledge',
'Terminal',
'Browser',
]) {
expect(find.byTooltip(label), findsOneWidget, reason: label);
}
await tester.tap(find.byTooltip('Browser'));
await tester.pumpAndSettle();
expect(find.text('Browser is only available on Android and iOS'),
findsOneWidget);
});
}
+43
View File
@@ -0,0 +1,43 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/dev_tunnel.dart';
void main() {
test('loopback hosts and ports are recognised', () {
for (final host in [
'localhost',
'127.0.0.1',
'::1',
'[::1]',
'0.0.0.0',
'::',
]) {
expect(isLoopbackDevHost(host), isTrue, reason: host);
}
expect(isLoopbackDevHost('192.168.1.10'), isFalse);
expect(devServerPort(Uri.parse('http://localhost:5173/')), 5173);
expect(devServerPort(Uri.parse('http://127.0.0.1')), 80);
expect(devServerPort(Uri.parse('https://localhost')), 443);
expect(devServerPort(Uri.parse('https://example.com:8443')), isNull);
});
test('the tunnel keeps path, query and fragment', () {
final local = localTunnelUri(
Uri.parse('http://localhost:5173/a/b?x=1#top'), 4000);
expect(local.toString(), 'http://127.0.0.1:4000/a/b?x=1#top');
});
test('the address bar is mapped back to the dev server', () {
expect(
displayUrlFor('http://127.0.0.1:4000/a', 4000, 'http://localhost:5173'),
'http://localhost:5173/a',
);
expect(
displayUrlFor('http://127.0.0.1:4000', 4000, 'http://localhost:5173'),
'http://localhost:5173',
);
expect(
displayUrlFor('https://example.com/x', 4000, 'http://localhost:5173'),
'https://example.com/x',
);
});
}
+129
View File
@@ -0,0 +1,129 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/widgets/diff_view.dart';
ContentPart editPart({
String name = 'edit',
Map<String, dynamic> input = const {},
Map<String, dynamic>? metadata,
String status = 'completed',
String? error,
}) {
return ContentPart(
type: 'tool',
name: name,
state: ToolState(
status: status,
input: input,
metadata: metadata,
error: error,
),
);
}
void main() {
test('an edit uses the server patch from metadata.files', () {
final part = editPart(
input: {'path': 'PLAN.md'},
metadata: {
'files': [
{
'file': 'PLAN.md',
'patch': '--- PLAN.md\n'
'+++ PLAN.md\n'
'@@ -1,3 +1,4 @@\n'
' same\n'
'-old line\n'
'+new line\n'
'+added line\n'
' tail\n',
},
],
},
);
final files = toolDiffFiles(part);
expect(files, hasLength(1));
expect(files.single.path, 'PLAN.md');
expect(files.single.added, 2);
expect(files.single.removed, 1);
expect(files.single.lines.first.kind, DiffLineKind.meta);
expect(
files.single.lines.where((line) => line.kind == DiffLineKind.hunk),
hasLength(1),
);
expect(
files.single.lines.map((line) => line.text),
containsAll(['-old line', '+new line', '+added line']),
);
});
test('an edit without a patch is diffed from its old and new text', () {
final part = editPart(input: {
'path': '/tmp/a.txt',
'oldString': 'one\ntwo',
'newString': 'one\ntwo\nthree',
});
final files = toolDiffFiles(part);
expect(files, hasLength(1));
expect(files.single.added, 1);
expect(files.single.removed, 0);
expect(files.single.lines.last.text, '+three');
});
test('a new write without a patch shows its content as added lines', () {
final part = editPart(
name: 'write',
input: {'path': 'hello.txt', 'content': 'hello\nworld'},
);
final files = toolDiffFiles(part);
expect(files, hasLength(1));
expect(files.single.added, 2);
expect(files.single.removed, 0);
expect(files.single.lines.map((line) => line.text),
['+hello', '+world']);
});
test('a failed tool and a non-diff tool have no diff', () {
expect(
toolDiffFiles(editPart(
metadata: {
'files': [
{'file': 'a', 'patch': '@@ -1 +1 @@\n-a\n+b\n'},
],
},
error: 'file not found',
)),
isEmpty,
);
expect(
toolDiffFiles(editPart(name: 'bash', input: {'command': 'ls'})),
isEmpty,
);
});
testWidgets('the diff view tints added and removed lines', (tester) async {
final files = toolDiffFiles(editPart(
metadata: {
'files': [
{
'file': 'a.txt',
'patch': '@@ -1,2 +1,2 @@\n old\n-removed\n+added\n',
},
],
},
));
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: DiffView(files: files)),
));
expect(find.text('@@ -1,2 +1,2 @@'), findsOneWidget);
expect(find.text(' old'), findsOneWidget);
expect(find.text('-removed'), findsOneWidget);
expect(find.text('+added'), findsOneWidget);
});
}
+175
View File
@@ -0,0 +1,175 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/state.dart';
import 'package:openchamber/widgets/project_picker.dart';
/// A server with one project folder, and an add-project endpoint that records
/// the folder in both its project list and its settings document.
class _FakeTransport implements Transport {
final List<Map<String, dynamic>> projects = [];
Map<String, dynamic> settings = {'projects': <dynamic>[]};
@override
Future<TransportResponse> send(TransportRequest r) async {
Object? body;
switch (r.path) {
case '/api/fs/home':
body = {'home': '/home/me'};
break;
case '/api/fs/list':
final path = r.query['path'] ?? '/';
body = {
'entries': [
{'name': 'project', 'path': '$path/project', 'isDirectory': true},
{'name': 'notes.txt', 'path': '$path/notes.txt', 'isDirectory': false},
],
};
break;
case '/api/project':
body = projects;
break;
case '/api/config/settings':
body = settings;
break;
case '/api/openchamber/directory':
final payload = jsonDecode(utf8.decode(r.body!)) as Map<String, dynamic>;
final path = payload['path'] as String;
projects.add({'id': 'oc1', 'canonical': path, 'vcs': 'git'});
settings = {
'projects': [
{
'id': 'settings1',
'path': path,
'label': 'Project',
'addedAt': 1,
}
]
};
body = {'success': true, 'path': path};
break;
default:
body = <String, dynamic>{};
}
return TransportResponse(
200,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
void main() {
setUp(() => L10n.instance.apply(AppLanguage.en));
tearDown(() => L10n.instance.apply(AppLanguage.zh));
testWidgets('a folder can be browsed and added as a project',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport();
app.client = Client(Uri.parse('http://test'), transport: transport);
ProjectChoice? choice;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => TextButton(
onPressed: () async {
choice = await showProjectPicker(context,
app: app, selected: AppState.chatTarget);
},
child: const Text('open'),
),
),
),
));
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Add project'), findsOneWidget);
await tester.tap(find.text('Add project'));
await tester.pumpAndSettle();
// The browser starts at home and lists folders, not files.
expect(find.text('project'), findsOneWidget);
expect(find.text('notes.txt'), findsNothing);
await tester.tap(find.text('project'));
await tester.pumpAndSettle();
expect(find.text('/home/me/project'), findsWidgets);
await tester.tap(find.text('Add this folder'));
await tester.pumpAndSettle();
expect(choice, isNotNull);
expect(choice!.canonical, '/home/me/project');
expect(app.projects.any((p) => p.canonical == '/home/me/project'), isTrue);
});
testWidgets('a project added before it has a session is still listed',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
app.client = Client(Uri.parse('http://test'), transport: _SettingsOnly());
await app.refreshProjects();
expect(app.projects.map((p) => p.canonical),
contains('/home/me/fresh-project'));
expect(app.projectLabelFor('/home/me/fresh-project'), 'Fresh');
});
}
/// `/api/project` is empty, but the settings document already has the folder:
/// the state must keep it so the picker can offer a first session there.
class _SettingsOnly implements Transport {
@override
Future<TransportResponse> send(TransportRequest r) async {
final body = switch (r.path) {
'/api/project' => <dynamic>[],
'/api/config/settings' => {
'projects': [
{
'id': 'settings1',
'path': '/home/me/fresh-project',
'label': 'Fresh',
'addedAt': 1,
}
]
},
_ => <String, dynamic>{},
};
return TransportResponse(
200,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
+92
View File
@@ -0,0 +1,92 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
ContentPart imageTool({
String name = 'openchamber_image',
String status = 'completed',
String text = '',
String? error,
}) {
return ContentPart(
type: 'tool',
name: name,
state: ToolState(
status: status,
content: [ContentPart(type: 'text', text: text)],
error: error,
),
);
}
const envelope =
'{"schemaVersion":1,"ok":true,"action":"image.generate","data":'
'{"model":"axonhub-image/sensenova-u1.5-lite","images":['
'{"path":"/tmp/opencode/generated-images/a.png","mime":"image/png"},'
'{"path":"/tmp/opencode/generated-images/b.png","mime":"image/png"}]}}';
void main() {
group('generatedImagePaths', () {
test('reads every path from a finished image call', () {
final part = imageTool(text: envelope);
expect(generatedImagePaths(part), [
'/tmp/opencode/generated-images/a.png',
'/tmp/opencode/generated-images/b.png',
]);
});
test('shows nothing while the call still runs', () {
expect(generatedImagePaths(imageTool(status: 'running', text: envelope)),
isEmpty);
});
test('shows nothing for a failed call', () {
expect(
generatedImagePaths(
imageTool(status: 'error', text: envelope, error: 'no model')),
isEmpty,
);
});
test('only the openchamber_image tool is lifted out', () {
expect(generatedImagePaths(imageTool(name: 'bash', text: envelope)),
isEmpty);
expect(
generatedImagePaths(ContentPart(type: 'text', text: envelope)),
isEmpty,
);
});
test('a plain text result is not a picture', () {
expect(generatedImagePaths(imageTool(text: '图片已生成')), isEmpty);
expect(
generatedImagePaths(imageTool(text: '{"ok":false,"action":"x"}')),
isEmpty,
);
});
});
group('relativePath', () {
test('drops the session directory', () {
expect(
relativePath('/home/blumia/src/app/lib/main.dart',
'/home/blumia/src/app'),
'lib/main.dart',
);
});
test('keeps paths outside it whole', () {
expect(
relativePath('/tmp/opencode/generated-images/a.png',
'/home/blumia/src/app'),
'/tmp/opencode/generated-images/a.png',
);
});
test('tolerates a trailing slash and a file elsewhere', () {
expect(relativePath('/a/b/c.txt', '/a/b/'), 'c.txt');
expect(relativePath('/a/bc/c.txt', '/a/b'), '/a/bc/c.txt');
expect(relativePath('x.txt', ''), 'x.txt');
expect(relativePath('/a/b', '/a/b'), '.');
});
});
}
+89
View File
@@ -0,0 +1,89 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/state.dart';
/// A server that keeps `/api/config/settings` in memory, like OpenChamber's
/// settings document. [failWrites] makes the PUT answer 500 so the rollback
/// can be checked.
class _FakeTransport implements Transport {
Map<String, dynamic> settings;
bool failWrites;
_FakeTransport(this.settings, {this.failWrites = false});
@override
Future<TransportResponse> send(TransportRequest r) async {
final isSettings = r.path == '/api/config/settings';
if (isSettings && r.method == 'PUT' && failWrites) {
return TransportResponse(
500,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(
utf8.encode(jsonEncode({'error': 'save failed'})))),
);
}
if (isSettings && r.method == 'PUT' && r.body != null) {
final patch = jsonDecode(utf8.decode(r.body!)) as Map<String, dynamic>;
settings = {...settings, ...patch};
}
final body = isSettings ? settings : <String, dynamic>{};
return TransportResponse(
200,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
void main() {
test('the server gitignore setting is read and written', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport({'filesViewShowGitignored': true});
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.refreshChatSettings();
expect(app.showGitignored, isTrue);
expect(await app.setShowGitignored(false), isTrue);
expect(app.showGitignored, isFalse);
expect(transport.settings['filesViewShowGitignored'], isFalse);
});
test('an absent setting starts off', () async {
final app = AppState();
addTearDown(app.dispose);
app.client =
Client(Uri.parse('http://test'), transport: _FakeTransport({}));
await app.refreshChatSettings();
expect(app.showGitignored, isFalse);
});
test('a failed save restores the previous value', () async {
final app = AppState();
addTearDown(app.dispose);
app.client = Client(Uri.parse('http://test'),
transport: _FakeTransport({'filesViewShowGitignored': true},
failWrites: true));
await app.refreshChatSettings();
expect(await app.setShowGitignored(false), isFalse);
expect(app.showGitignored, isTrue);
});
}
+138
View File
@@ -0,0 +1,138 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/widgets/image_viewer.dart';
class _NoopTransport implements Transport {
@override
Future<TransportResponse> send(TransportRequest r) async =>
throw UnimplementedError();
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
// A 1x1 transparent PNG.
const _png =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
void main() {
setUp(() => L10n.instance.apply(AppLanguage.en));
tearDown(() => L10n.instance.apply(AppLanguage.zh));
final client = Client(Uri.parse('http://test'), transport: _NoopTransport());
Future<void> pumpViewer(WidgetTester tester, {bool mediaActions = false}) async {
await tester.pumpWidget(MaterialApp(
home: ImageViewerPage(
images: const [
ImageSlide('One', 'data:image/png;base64,$_png'),
ImageSlide('Two', 'data:image/png;base64,$_png'),
],
directory: '/home/me',
client: client,
mediaActions: mediaActions,
),
));
await tester.pumpAndSettle();
await tester.pump(const Duration(milliseconds: 200));
}
testWidgets('a picture opens full screen and can be zoomed and panned',
(tester) async {
await pumpViewer(tester);
expect(find.text('One'), findsOneWidget);
expect(find.text('1 / 2'), findsOneWidget);
final viewer = find.byType(InteractiveViewer);
expect(viewer, findsOneWidget);
final center = tester.getCenter(viewer);
final left = await tester.startGesture(center - const Offset(20, 0));
final right = await tester.startGesture(center + const Offset(20, 0));
await left.moveTo(center - const Offset(80, 0));
await right.moveTo(center + const Offset(80, 0));
await tester.pump();
await left.up();
await right.up();
await tester.pumpAndSettle();
final zoomed = tester.widget<InteractiveViewer>(viewer);
final controller = zoomed.transformationController!;
expect(controller.value.getMaxScaleOnAxis(), greaterThan(1.0));
// Once zoomed, a one-finger drag pans the picture instead of paging.
final before = controller.value.getTranslation();
await tester.drag(viewer, const Offset(30, 12));
await tester.pumpAndSettle();
final after = controller.value.getTranslation();
expect(after.x, isNot(before.x));
});
testWidgets('a swipe moves to the next picture while not zoomed',
(tester) async {
await pumpViewer(tester);
await tester.drag(find.byType(InteractiveViewer), const Offset(-600, 0));
await tester.pumpAndSettle();
expect(find.text('Two'), findsOneWidget);
expect(find.text('2 / 2'), findsOneWidget);
});
testWidgets('save and share send the current picture to the platform',
(tester) async {
final calls = <MethodCall>[];
const channel = MethodChannel('openchamber/media');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return true;
});
addTearDown(() => TestDefaultBinaryMessengerBinding.instance
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null));
await pumpViewer(tester, mediaActions: true);
await tester.tap(find.byTooltip('Save to Photos'));
await tester.pump();
await tester.tap(find.byTooltip('Share'));
await tester.pump();
expect(calls.map((call) => call.method),
containsAll(['saveImage', 'shareImage']));
final save = calls.firstWhere((call) => call.method == 'saveImage');
final args = save.arguments as Map;
expect(args['name'], 'One.png');
expect(args['mime'], 'image/png');
expect(args['bytes'], isA<Uint8List>());
});
testWidgets('a tap hides the title and keys until the next tap',
(tester) async {
await pumpViewer(tester);
double chromeOpacity() => tester
.widget<AnimatedOpacity>(find.byKey(const ValueKey('viewer-chrome')))
.opacity;
expect(chromeOpacity(), 1);
await tester.tap(find.byType(InteractiveViewer));
await tester.pump(const Duration(milliseconds: 400));
expect(chromeOpacity(), 0);
await tester.tap(find.byType(InteractiveViewer));
await tester.pump(const Duration(milliseconds: 400));
expect(chromeOpacity(), 1);
});
}
+109
View File
@@ -0,0 +1,109 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/l10n/zh.dart';
/// Strings that are deliberately the same in both languages, or not UI text
/// at all (a screen reader label, a path pattern built at runtime).
const _notTranslated = <String>{
'English',
'中文',
'Chamber Go',
// Product names, separators and glyphs read the same everywhere.
'OpenChamber',
'OpenCode',
' / ',
'·',
'🖼',
' *',
};
/// The literal arguments of AppText, tr and trArgs in [source]: the strings
/// our own code writes and therefore the ones a translation exists for.
Iterable<String> _uiLiterals(String source) sync* {
const quote = r'''(?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")''';
final patterns = <RegExp>[
RegExp('AppText\\(\\s*(?:$quote)(?:\\s*(?:$quote))*'),
RegExp(r'\btr\(\s*(?:' + quote + ')'),
RegExp(r'\btrArgs\(\s*(?:' + quote + r')(?:\s*(?:' + quote + '))*'),
];
final single = RegExp(quote);
for (final pattern in patterns) {
for (final match in pattern.allMatches(source)) {
final call = match.group(0)!;
final joined = single
.allMatches(call)
.map((m) => m.group(0)!.substring(1, m.group(0)!.length - 1))
.map((s) => s.replaceAll(r'\n', '\n').replaceAll(r"\'", "'"))
.join();
// Interpolated text is built at runtime, not a translation key.
if (joined.contains(r'$')) continue;
yield joined;
}
}
}
void main() {
tearDown(() {
L10n.instance.apply(AppLanguage.en);
});
test('Chinese lookup falls back on the English it was given', () {
L10n.instance.apply(AppLanguage.zh);
expect(tr('Save'), '保存');
expect(tr('A text with no translation'), 'A text with no translation');
expect(trArgs('{0} subagents', [3]), '3 个子代理');
expect(trArgs('{0} notes', [1]), isNot(contains('notes')));
});
test('English is the source, so it needs no table', () {
L10n.instance.apply(AppLanguage.en);
expect(tr('Save'), 'Save');
expect(trArgs('{0} subagents', [3]), '3 subagents');
});
test('a language without a table reads English', () {
L10n.instance.apply(AppLanguage.zh);
// Spanish follows the system language branch; the app has no Spanish
// table, so everything is the English source.
final dispatcher = TestWidgetsFlutterBinding.instance.platformDispatcher;
dispatcher.localeTestValue = const Locale('es', 'ES');
addTearDown(dispatcher.clearLocaleTestValue);
L10n.instance.apply(AppLanguage.system);
expect(L10n.instance.locale.languageCode, 'en');
expect(tr('Save'), 'Save');
expect(trArgs('{0} subagents', [3]), '3 subagents');
});
testWidgets('AppText follows the chosen language', (tester) async {
L10n.instance.apply(AppLanguage.en);
await tester
.pumpWidget(const MaterialApp(home: Scaffold(body: AppText('Save'))));
expect(find.text('Save'), findsOneWidget);
L10n.instance.apply(AppLanguage.zh);
await tester
.pumpWidget(const MaterialApp(home: Scaffold(body: AppText('Save'))));
expect(find.text('保存'), findsOneWidget);
});
test('every UI string the code writes has a Chinese entry', () {
final missing = <String>{};
for (final entity in Directory('lib').listSync(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.dart')) continue;
if (entity.path.startsWith('lib/l10n')) continue;
final source = entity.readAsStringSync();
for (final text in _uiLiterals(source)) {
if (text.trim().isEmpty) continue;
if (chineseStrings.containsKey(text)) continue;
if (_notTranslated.contains(text)) continue;
missing.add(text);
}
}
expect(missing, isEmpty,
reason: 'Add these to lib/l10n/zh.dart (or to _notTranslated if they '
'are not UI text):\n${missing.join('\n')}');
});
}
+12
View File
@@ -30,4 +30,16 @@ void main() {
test('slashPath only unifies separators', () {
expect(slashPath(r'C:\a\b\'), 'C:/a/b');
});
test('a directory is recognised under a chats root', () {
expect(isUnderDirectory('/home/me/.config/openchamber/chats/2026-11-23/x',
'/home/me/.config/openchamber/chats'), isTrue);
expect(isUnderDirectory(r'C:\Users\me\.config\openchamber\chats\a\b',
r'c:\users\me\.config\openchamber\chats'), isTrue);
expect(isUnderDirectory('/home/me/.config/openchamber/chats-other/x',
'/home/me/.config/openchamber/chats'), isFalse);
expect(isUnderDirectory('/home/me/project', '/home/me/.config/openchamber/chats'),
isFalse);
expect(isUnderDirectory('', '/x'), isFalse);
});
}
+46
View File
@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/widgets/project_icon.dart';
void main() {
test('OpenChamber icon keys map to Flutter icons', () {
expect(projectIconData('code'), Icons.code);
expect(projectIconData('terminal'), Icons.terminal);
expect(projectIconData('ai'), Icons.psychology_outlined);
expect(projectIconData('unknown'), isNull);
expect(projectIconData(''), isNull);
});
test('hex and legacy project colours resolve', () {
final scheme = ColorScheme.fromSeed(seedColor: Colors.indigo);
expect(projectHexColor('#30a46c'), const Color(0xff30a46c));
expect(projectHexColor('#abc'), const Color(0xffaabbcc));
expect(projectHexColor('30a46c'), isNull);
expect(projectColor('error', scheme), scheme.error);
expect(projectColor('primary', scheme), scheme.primary);
expect(projectColor('comment', scheme), scheme.onSurfaceVariant);
expect(projectColor('#30a46c', scheme), const Color(0xff30a46c));
expect(projectColor('', scheme), isNull);
});
test('a settings row decorates the project with label and icon metadata', () {
const project = ProjectInfo(id: 'p1', canonical: '/w/app');
final merged = project.withMeta({
'id': 'path_L3cL2FwcA',
'path': '/w/app',
'label': 'My App',
'icon': 'rocket',
'color': '#30a46c',
'iconBackground': '#101010',
'iconImage': {'mime': 'image/svg+xml', 'updatedAt': 42},
});
expect(merged.label, 'My App');
expect(merged.icon, 'rocket');
expect(merged.color, '#30a46c');
expect(merged.metaId, 'path_L3cL2FwcA');
expect(merged.hasIconImage, isTrue);
expect(merged.iconImageMime, 'image/svg+xml');
expect(merged.iconImageUpdatedAt, 42);
});
}
+114
View File
@@ -0,0 +1,114 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/screens/scheduled_tasks_screen.dart';
import 'package:openchamber/state.dart';
import 'package:openchamber/widgets/project_picker.dart';
void main() {
setUp(() => L10n.instance.apply(AppLanguage.en));
tearDown(() => L10n.instance.apply(AppLanguage.zh));
test('a filesystem root keeps its own name', () {
expect(pathLeaf('/'), '/');
expect(pathLeaf('/home/me/project/'), 'project');
expect(pathLeaf(r'C:\Users\me'), 'me');
});
testWidgets('the picker lists checkouts and the Chat row', (tester) async {
final app = AppState();
addTearDown(app.dispose);
app.projects = const [
ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'),
// The server also knows the root; it must not read as a blank row.
ProjectInfo(id: 'root', canonical: '/'),
// The same checkout listed twice (a project record and a sandbox).
ProjectInfo(
id: 'p2', canonical: '/home/me/project', name: 'My project', vcs: 'git'),
];
ProjectChoice? choice;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => TextButton(
onPressed: () async {
choice = await showProjectPicker(context,
app: app, selected: AppState.chatTarget);
},
child: const Text('open'),
),
),
),
));
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('Choose project'), findsOneWidget);
expect(find.text('Chat'), findsWidgets);
expect(find.text('My project'), findsOneWidget);
// The root's label and its path are the same text.
expect(find.text('/'), findsWidgets);
await tester.tap(find.text('My project'));
await tester.pumpAndSettle();
expect(choice, isNotNull);
expect(choice!.canonical, '/home/me/project');
expect(choice!.isChat, isFalse);
});
testWidgets('the stats picker adds All projects and drops the Chat row',
(tester) async {
final app = AppState();
addTearDown(app.dispose);
app.projects = const [
ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'),
];
ProjectChoice? choice;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => TextButton(
onPressed: () async {
choice = await showProjectPicker(context,
app: app,
selected: allProjectsTarget,
includeAll: true,
includeChat: false);
},
child: const Text('open'),
),
),
),
));
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.text('All projects'), findsOneWidget);
expect(find.text('Chat'), findsNothing);
expect(find.text('My project'), findsOneWidget);
await tester.tap(find.text('All projects'));
await tester.pumpAndSettle();
expect(choice, isNotNull);
expect(choice!.isAll, isTrue);
});
testWidgets('scheduled tasks open the same project sheet', (tester) async {
final app = AppState();
addTearDown(app.dispose);
app.projects = const [
ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'),
];
await tester.pumpWidget(MaterialApp(home: ScheduledTasksScreen(app: app)));
await tester.pumpAndSettle();
await tester.tap(find.text('My project'));
await tester.pumpAndSettle();
expect(find.text('Choose project'), findsOneWidget);
expect(find.text('My project'), findsWidgets);
});
}
+106
View File
@@ -0,0 +1,106 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/state.dart';
void main() {
group('context reading', () {
late AppState app;
late ChatState chat;
setUp(() {
app = AppState();
chat = ChatState(app, Session(id: 'ses_a', title: '会话'));
});
tearDown(() {
chat.dispose();
app.dispose();
});
Message assistant() => Message(
id: 'a1',
type: 'assistant',
model: ModelRef('getdeepin/deepseek-flash', 'axonhub'),
tokens: TokenUsage(input: 33800, output: 810, cacheRead: 1792),
);
test('a known model reports its limit and no estimate', () {
app.modelLimits = {
'axonhub/getdeepin/deepseek-flash': (1000000, 100000),
};
chat.msgs = [assistant()];
final reading = chat.usageReading();
expect(reading.$1, 36402);
expect(reading.$2, 1000000);
expect(reading.$5, isTrue);
expect(reading.$6, isFalse);
});
test('an unknown model keeps the ring and marks the window estimated', () {
app.modelLimits = {};
chat.msgs = [assistant()];
final reading = chat.usageReading();
expect(reading.$5, isTrue);
expect(reading.$6, isTrue);
expect(reading.$2, ChatState.estimatedContextWindow);
expect(reading.$4, greaterThan(0));
});
test('no assistant tokens means no ring', () {
chat.msgs = [Message(id: 'u1', type: 'user')];
expect(chat.usageReading().$5, isFalse);
});
});
// The app can be in the background while a turn starts or ends; the events
// that said so never arrive, so the chat's running flag has to be taken
// from the server again when the app comes back.
group('reconciling a turn on return', () {
late AppState app;
late ChatState chat;
setUp(() {
app = AppState();
chat = ChatState(app, Session(id: 'ses_a', title: '会话'));
});
tearDown(() {
chat.dispose();
app.dispose();
});
test('the server saying idle ends a turn that was left running', () {
chat.running = true;
chat.reconcileRunning({'ses_other'}, known: true);
expect(chat.running, isFalse);
});
test('the server saying running keeps the strip, even without events', () {
chat.running = false;
chat.reconcileRunning({'ses_a'}, known: true);
expect(chat.running, isTrue);
});
test('the server not answering falls back on the transcript tail', () {
chat.running = false;
chat.msgs = [
Message(id: 'u1', type: 'user'),
Message(id: 'a1', type: 'assistant', completed: 100),
Message(id: 'u2', type: 'user'),
Message(id: 'a2', type: 'assistant'),
];
chat.reconcileRunning(const {}, known: false);
expect(chat.running, isTrue);
chat.running = true;
chat.msgs = [
Message(id: 'u1', type: 'user'),
Message(id: 'a1', type: 'assistant', completed: 100),
];
chat.reconcileRunning(const {}, known: false);
expect(chat.running, isFalse);
});
});
}
+207
View File
@@ -0,0 +1,207 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/scheduled_tasks.dart';
import 'package:openchamber/screens/features_screen.dart';
import 'package:openchamber/screens/scheduled_tasks_screen.dart';
import 'package:openchamber/state.dart';
import 'package:openchamber/widgets/scheduled_task_editor.dart';
Map<String, dynamic> dailyJson() => {
'id': 'task_1',
'name': '每日同步',
'enabled': true,
'schedule': {
'kind': 'daily',
'times': ['09:00', '18:30'],
'timezone': 'Asia/Shanghai',
},
'execution': {
'prompt': '总结未完成任务',
'providerID': 'axonhub',
'modelID': 'deepseek-flash',
'agent': 'build',
},
'state': {
'lastStatus': 'success',
'lastRunAt': 1000,
'nextRunAt': 2000,
'lastDurationMs': 4000,
},
};
void main() {
group('scheduled task wire shape', () {
test('a daily task reads its schedule, execution and state', () {
final task = ScheduledTask.fromJson(dailyJson());
expect(task.id, 'task_1');
expect(task.name, '每日同步');
expect(task.enabled, isTrue);
expect(task.kind, 'daily');
expect(task.times, ['09:00', '18:30']);
expect(task.timezone, 'Asia/Shanghai');
expect(task.prompt, '总结未完成任务');
expect(task.useDefaults, isFalse);
expect(task.providerId, 'axonhub');
expect(task.modelId, 'deepseek-flash');
expect(task.agent, 'build');
expect(task.lastStatus, 'success');
expect(task.nextRunAt, 2000);
expect(scheduledScheduleText(task), '每天 09:00、18:30');
expect(task.modelLabel, 'axonhub/deepseek-flash · build');
});
test('missing useDefaults means the session defaults', () {
final json = dailyJson();
(json['execution'] as Map<String, dynamic>)
..remove('providerID')
..remove('modelID')
..remove('agent');
final task = ScheduledTask.fromJson(json);
expect(task.useDefaults, isTrue);
expect(task.modelLabel, '使用默认模型与智能体');
expect(scheduledScheduleText(task), '每天 09:00、18:30');
});
test('weekly, once and cron schedules read as the web client says', () {
final weekly = ScheduledTask.fromJson({
'schedule': {
'kind': 'weekly',
'times': ['09:00'],
'weekdays': [1, 3],
},
});
expect(scheduledScheduleText(weekly), '每周 周一、周三 09:00');
final once = ScheduledTask.fromJson({
'schedule': {
'kind': 'once',
'date': '2026-12-01',
'time': '08:05',
},
});
expect(scheduledScheduleText(once), '一次性 2026-12-01 08:05');
final cron = ScheduledTask.fromJson({
'schedule': {'kind': 'cron', 'cron': '*/5 * * * *'},
});
expect(scheduledScheduleText(cron), 'Cron:*/5 * * * *');
});
test('saving sends only the schedule fields the kind uses', () {
const daily = ScheduledTask(
id: 'task_9',
name: '每日同步',
kind: 'daily',
times: ['09:00'],
prompt: '总结',
useDefaults: true,
);
final json = daily.toJson();
expect(json['id'], 'task_9');
expect(json['schedule'], {'kind': 'daily', 'times': ['09:00']});
expect(json['execution'], {'prompt': '总结', 'useDefaults': true});
expect(json.containsKey('targetSessionId'), isFalse);
const once = ScheduledTask(
name: '一次性',
kind: 'once',
date: '2026-12-01',
time: '08:05',
prompt: '提醒',
useDefaults: false,
providerId: 'axonhub',
modelId: 'deepseek-flash',
agent: 'plan',
);
final onceJson = once.toJson();
expect(onceJson.containsKey('id'), isFalse);
expect(onceJson['schedule'],
{'kind': 'once', 'date': '2026-12-01', 'time': '08:05'});
expect(onceJson['execution'], {
'prompt': '提醒',
'useDefaults': false,
'providerID': 'axonhub',
'modelID': 'deepseek-flash',
'agent': 'plan',
});
});
test('status labels and relative times', () {
expect(scheduledStatusLabel('success'), '成功');
expect(scheduledStatusLabel('running'), '运行中');
expect(scheduledStatusLabel('failed'), '错误');
expect(scheduledStatusLabel(''), '空闲');
final soon = scheduledRelativeTime(
DateTime.now().add(const Duration(minutes: 5)).millisecondsSinceEpoch);
expect(soon, contains('分钟后'));
final past = scheduledRelativeTime(
DateTime.now().subtract(const Duration(hours: 2)).millisecondsSinceEpoch);
expect(past, contains('小时前'));
expect(scheduledRelativeTime(0), '');
});
});
group('screens', () {
testWidgets('全部功能 lists the scheduled tasks entry', (tester) async {
final app = AppState();
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(home: FeaturesScreen(app: app)));
expect(find.text('全部功能'), findsOneWidget);
expect(find.text('计划任务'), findsOneWidget);
expect(find.text('按时间向会话发送提示词'), findsOneWidget);
expect(find.text('统计'), findsOneWidget);
expect(find.text('提示词、词元、费用与模型活动'), findsOneWidget);
await tester.tap(find.text('计划任务'));
await tester.pumpAndSettle();
// No client in the test: the page says so instead of listing tasks.
expect(find.byType(ScheduledTasksScreen), findsOneWidget);
expect(find.text('未连接服务器'), findsOneWidget);
});
testWidgets('the editor validates and hands back the draft', (tester) async {
final app = AppState();
addTearDown(app.dispose);
ScheduledTask? saved;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: SizedBox(
height: 900,
child: ScheduledTaskEditor(
app: app,
scopeLabel: 'openchamber-android-native',
onSave: (draft) async {
saved = draft;
return false;
},
),
),
),
));
expect(find.text('新建计划任务'), findsOneWidget);
expect(find.text('运行位置:openchamber-android-native'), findsOneWidget);
// An empty name is refused with a message, not saved.
await tester.tap(find.widgetWithText(TextButton, '保存'));
await tester.pump();
expect(find.text('任务名称为必填项'), findsOneWidget);
expect(saved, isNull);
await tester.enterText(find.byType(TextField).at(0), '每日同步');
await tester.enterText(find.byType(TextField).at(1), '总结未完成任务');
await tester.tap(find.widgetWithText(TextButton, '保存'));
await tester.pumpAndSettle();
expect(saved, isNotNull);
expect(saved!.name, '每日同步');
expect(saved!.prompt, '总结未完成任务');
expect(saved!.kind, 'daily');
expect(saved!.times, ['09:00']);
expect(saved!.enabled, isTrue);
expect(saved!.useDefaults, isTrue);
});
});
}
+93 -9
View File
@@ -4,23 +4,65 @@ 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 {
Future<AppState> pumpSettings(WidgetTester tester) async {
final app = AppState();
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(home: SettingsScreen(app: app)));
return app;
}
testWidgets('settings is an index of categories, not one long page',
(tester) async {
await pumpSettings(tester);
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);
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.
// The category pages keep their controls off the index.
expect(find.text('主题模式'), findsNothing);
expect(find.byType(Switch), findsNothing);
});
testWidgets('通用 opens the agent-tool page with the web defaults',
(tester) async {
final app = await pumpSettings(tester);
app.memoryToolsAvailable = true;
await tester.pump();
await tester.tap(find.text('通用'));
await tester.pumpAndSettle();
expect(find.text('在聊天中'), findsOneWidget);
expect(find.text('图表和原型'), findsOneWidget);
expect(find.text('密钥'), findsOneWidget);
expect(find.text('项目知识'), findsOneWidget);
expect(find.text('用量限额'), findsOneWidget);
SwitchListTile tile(String title) => tester
.widget<SwitchListTile>(find.widgetWithText(SwitchListTile, title));
// The same defaults the web client starts from.
expect(tile('图表和原型').value, isTrue);
expect(tile('图像').value, isFalse);
expect(tile('密钥').value, isTrue);
expect(tile('通知').value, isFalse);
expect(tile('记忆').value, isFalse);
expect(tile('项目知识').value, isTrue);
expect(tile('用量限额').value, isFalse);
});
testWidgets('聊天 opens the follow-up behavior page', (tester) async {
final app = await pumpSettings(tester);
await tester.tap(find.text('聊天'));
await tester.pumpAndSettle();
expect(find.text('追问处理行为'), findsOneWidget);
ChoiceChip chip(String label) =>
tester.widget<ChoiceChip>(find.widgetWithText(ChoiceChip, label));
expect(chip('排队').selected, isTrue);
@@ -31,4 +73,46 @@ void main() {
expect(chip('转向').selected, isTrue);
expect(chip('排队').selected, isFalse);
});
testWidgets('主题 opens the theme page', (tester) async {
await pumpSettings(tester);
await tester.tap(find.text('主题'));
await tester.pumpAndSettle();
expect(find.text('主题模式'), findsOneWidget);
expect(find.text('主题色'), findsOneWidget);
expect(find.text('跟随系统'), findsOneWidget);
});
testWidgets('宠物 opens the pet page', (tester) async {
await pumpSettings(tester);
await tester.tap(find.text('宠物'));
await tester.pumpAndSettle();
expect(find.text('尚未导入宠物'), findsOneWidget);
expect(find.text('导入宠物包'), findsOneWidget);
});
testWidgets('关于 shows the app version, the server versions and licenses',
(tester) async {
await pumpSettings(tester);
await tester.tap(find.text('关于'));
await tester.pumpAndSettle();
expect(find.text('版本'), findsOneWidget);
expect(find.text('未知'), findsOneWidget); // no platform version in a test
expect(find.text('开源许可'), findsOneWidget);
expect(find.widgetWithText(ListTile, 'OpenCode'), findsOneWidget);
// The header carries the name too, so look for the server row itself.
expect(find.widgetWithText(ListTile, 'OpenChamber'), findsOneWidget);
// No client: both server rows say so instead of showing a dash.
expect(find.text('未连接'), findsNWidgets(2));
await tester.tap(find.text('开源许可'));
await tester.pumpAndSettle();
expect(find.textContaining('第三方组件'), findsOneWidget);
});
}
+306
View File
@@ -0,0 +1,306 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/api/shells.dart';
import 'package:openchamber/background_jobs.dart';
import 'package:openchamber/widgets/shell_jobs.dart';
ContentPart shellCall({
String name = 'bash',
String status = 'completed',
String command = 'pnpm dev',
Map<String, dynamic>? metadata,
}) {
return ContentPart(
type: 'tool',
name: name,
state: ToolState(
status: status,
input: {'command': command},
metadata: metadata,
),
);
}
void main() {
group('backgroundShellId', () {
test('a detached command is completed with a running shell id', () {
expect(
backgroundShellId(shellCall(metadata: {
'status': 'running',
'shellID': 'sh_abc',
})),
'sh_abc',
);
});
test('a foreground command has the id but no detached marker', () {
expect(backgroundShellId(shellCall(metadata: {'shellID': 'sh_abc'})),
isNull);
expect(
backgroundShellId(shellCall(
status: 'running',
metadata: {'status': 'running', 'shellID': 'sh_abc'},
)),
isNull,
);
});
test('other tools and broken metadata say nothing', () {
expect(
backgroundShellId(
shellCall(name: 'read', metadata: {'status': 'running', 'shellID': 'sh_a'})),
isNull,
);
expect(backgroundShellId(shellCall(metadata: null)), isNull);
expect(
backgroundShellId(shellCall(metadata: {'status': 'running', 'shellID': ''})),
isNull,
);
});
});
test('the transcript gives command and start time for the strip', () {
final messages = [
Message(id: 'm1', type: 'assistant', created: 1000, content: [
shellCall(command: 'sleep 600', metadata: {
'status': 'running',
'shellID': 'sh_one',
}),
shellCall(metadata: {'shellID': 'sh_foreground'}),
]),
];
final tasks = backgroundShellsFromMessages(messages, 'ses_x');
expect(tasks, hasLength(1));
expect(tasks.single.id, 'sh_one');
expect(tasks.single.command, 'sleep 600');
expect(tasks.single.startedAt, 1000);
expect(tasks.single.sessionId, 'ses_x');
});
test('the job list gives shell jobs with their shell id and owner', () {
final tasks = shellTasksFromJobs({
'data': [
{
'id': 'job_a',
'kind': 'shell',
'status': 'running',
'sessionID': 'ses_a',
'shellID': 'sh_a',
'command': 'npm run dev',
'time': {'started': 1795000000000},
},
{
'id': 'job_b',
'kind': 'image',
'status': 'running',
'sessionID': 'ses_a',
'path': '/tmp/a.png',
'model': 'm',
'time': {'started': 1795000000000},
},
{
'id': 'job_c',
'kind': 'shell',
'status': 'completed',
'sessionID': 'ses_a',
'shellID': 'sh_c',
'command': 'npm test',
'time': {'started': 1794000000000},
},
],
});
expect(tasks, hasLength(1));
expect(tasks.single.id, 'sh_a');
expect(tasks.single.sessionId, 'ses_a');
expect(tasks.single.command, 'npm run dev');
expect(tasks.single.startedAt, 1795000000000);
});
test('a completion note gives the shell id, state and output', () {
final note = shellCompletionNote(Message(
id: 's',
type: 'synthetic',
text: '<background-result kind="shell" id="sh_a" state="completed" '
'command="echo hi">\nhi\nthere\n</background-result>',
));
expect(note, isNotNull);
expect(note!.shellId, 'sh_a');
expect(note.state, 'completed');
expect(note.output, 'hi\nthere');
expect(note.failed, isFalse);
final failed = shellCompletionNote(Message(
id: 's2',
type: 'synthetic',
text: '<background-result kind="shell" id="sh_b" state="error">\n'
'Shell.NotFoundError\n</background-result>',
));
expect(failed!.failed, isTrue);
expect(
shellCompletionNote(
Message(id: 's3', type: 'synthetic', text: 'plain note')),
isNull,
);
expect(
shellCompletionNote(Message(
id: 's4',
type: 'synthetic',
text: '<background-result kind="subagent" id="x" state="completed">'
'\ndone\n</background-result>',
)),
isNull,
);
});
test('the newest completion for a shell wins', () {
Message note(String id, String output) => Message(
id: id,
type: 'synthetic',
text: '<background-result kind="shell" id="sh_a" '
'state="completed">\n$output\n</background-result>',
);
final found = shellCompletionFor(
[note('n1', 'first'), note('n2', 'second')], 'sh_a');
expect(found!.output, 'second');
expect(shellCompletionFor([note('n1', 'x')], 'sh_other'), isNull);
});
test('a stop note marks its shells as stopped by the user', () {
final messages = [
Message(
id: 's',
type: 'synthetic',
text: 'The user stopped the background command `sleep 1`.',
metadata: {
'openchamber': {
'shellStop': {
'shellIDs': ['sh_a', 'sh_b'],
},
},
},
),
Message(id: 'a', type: 'assistant', text: 'ok'),
];
expect(shellWasStopped(messages, 'sh_a'), isTrue);
expect(shellWasStopped(messages, 'sh_b'), isTrue);
expect(shellWasStopped(messages, 'sh_c'), isFalse);
expect(shellWasStopped(const [], 'sh_a'), isFalse);
});
test('the shell list keeps owner, clock and running state', () {
final tasks = shellTasksFromList({
'location': {'directory': '/repo'},
'data': [
{
'id': 'sh_a',
'status': 'running',
'command': 'npm run dev',
'metadata': {'sessionID': 'ses_a'},
'time': {'started': 1795000000000},
},
{
'id': 'sh_b',
'status': 'exited',
'command': 'npm test',
'metadata': {},
'time': {'started': 1794000000000},
},
],
});
expect(tasks.map((t) => t.id), ['sh_a', 'sh_b']);
expect(tasks.first.running, isTrue);
expect(tasks.first.sessionId, 'ses_a');
expect(tasks.first.startedAt, 1795000000000);
expect(tasks.last.running, isFalse);
});
test('an output page reads text, cursor and size', () {
final page = ShellOutputPage.fromJson({
'data': {'output': 'one\ntwo\n', 'cursor': 8, 'size': 8, 'truncated': false},
});
expect(page.output, 'one\ntwo\n');
expect(page.cursor, 8);
expect(page.size, 8);
expect(page.truncated, isFalse);
expect(ShellOutputPage.fromJson({}).output, '');
});
test('elapsed reads in seconds, minutes and hours', () {
expect(formatElapsed(0), '0秒');
expect(formatElapsed(12 * 1000), '12秒');
expect(formatElapsed(185 * 1000), '3分05秒');
expect(formatElapsed(3723 * 1000), '1:02:03');
});
test('the stop note names the command and says it was the user', () {
final note = stopNote(' pnpm dev ');
expect(note, contains('pnpm dev'));
expect(note, contains('user stopped'));
expect(note, contains('Shell.NotFoundError'));
});
group('ShellTaskBar', () {
ShellTask task(String id, {String command = 'pnpm dev', String session = 'ses_a'}) =>
ShellTask(
id: id,
sessionId: session,
command: command,
startedAt: DateTime.now().millisecondsSinceEpoch - 65000,
);
Future<void> pump(WidgetTester tester, List<ShellTask> tasks,
{void Function(ShellTask)? onOpen}) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Column(
children: [
ShellTaskBar(
tasks: tasks,
sessionId: 'ses_a',
onOpen: onOpen ?? (_) {},
),
],
),
),
));
}
testWidgets('one command is its own row, with its clock', (tester) async {
ShellTask? opened;
await pump(tester, [task('sh_1', command: 'pnpm dev')],
onOpen: (t) => opened = t);
expect(find.text('pnpm dev'), findsOneWidget);
expect(find.text('1分05秒'), findsOneWidget);
expect(find.textContaining('正在执行'), findsNothing);
// Stopping is in the sheet the row opens, not a button on the bar.
expect(find.text('停止'), findsNothing);
await tester.tap(find.text('pnpm dev'));
expect(opened?.id, 'sh_1');
});
testWidgets('two commands share a count header and both show',
(tester) async {
await pump(tester, [
task('sh_1', command: 'pnpm dev'),
task('sh_2', command: 'pnpm test', session: 'ses_child'),
]);
expect(find.text('正在执行 2 条命令'), findsOneWidget);
expect(find.text('pnpm dev'), findsOneWidget);
expect(find.text('pnpm test'), findsOneWidget);
expect(find.text('子代理'), findsOneWidget);
expect(find.text('停止'), findsNothing);
});
testWidgets('a long list folds until asked', (tester) async {
await pump(tester, [for (var i = 0; i < 4; i++) task('sh_$i', command: 'cmd $i')]);
expect(find.text('正在执行 4 条命令'), findsOneWidget);
expect(find.text('cmd 0'), findsNothing);
await tester.tap(find.text('正在执行 4 条命令'));
await tester.pump();
expect(find.text('cmd 0'), findsOneWidget);
expect(find.text('cmd 3'), findsOneWidget);
});
});
}
+8
View File
@@ -21,8 +21,16 @@ void main() {
expect(find.text('家里的服务器'), findsOneWidget);
expect(find.byIcon(Icons.dns_outlined), findsOneWidget);
expect(find.byTooltip('全部功能'), findsOneWidget);
expect(find.byTooltip('设置'), findsOneWidget);
// 全部功能 sits left of the settings key and holds the scheduled tasks.
await tester.tap(find.byTooltip('全部功能'));
await tester.pumpAndSettle();
expect(find.text('计划任务'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('设置'));
await tester.pumpAndSettle();
// The settings page replaced the shell.
+134
View File
@@ -5,6 +5,90 @@ import 'package:openchamber/screens/sessions_screen.dart';
import 'package:openchamber/state.dart';
void main() {
testWidgets('chat folders group under 聊天, not under session-xxxxx',
(tester) async {
final app = AppState();
app.chatRoots = const [r'C:\Users\me\.config\openchamber\chats'];
final now = DateTime.now().millisecondsSinceEpoch;
app.sessions = [
Session(
id: 'c1',
title: 'OpenCode 图像模型配置',
location: Location(
r'C:\Users\me\.config\openchamber\chats\2026-11-23\session-a'),
created: now,
updated: now,
),
Session(
id: 'c2',
title: 'LC_ALL 环境变量的设置来源',
location: Location(
r'C:\Users\me\.config\openchamber\chats\2026-11-22\session-b'),
created: now - 1000,
updated: now - 1000,
),
];
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: SessionListPane(app: app)),
));
await tester.pumpAndSettle();
// One chats group, labelled the same as the first-party sidebar.
expect(find.text('聊天'), findsOneWidget);
expect(find.byTooltip('新建聊天'), findsOneWidget);
expect(find.textContaining('session-'), findsNothing);
expect(find.text('OpenCode 图像模型配置'), findsOneWidget);
expect(find.text('LC_ALL 环境变量的设置来源'), findsOneWidget);
});
testWidgets('a subagent session shows nested under its parent and opens',
(tester) async {
final app = AppState();
final now = DateTime.now().millisecondsSinceEpoch;
app.sessions = [
Session(
id: 'parent',
title: '子代理输出 hello',
agent: 'build',
location: Location('/home/me/Sources/app'),
created: now,
updated: now,
),
Session(
id: 'child',
parentID: 'parent',
title: '输出 hello',
agent: 'general',
location: Location('/home/me/Sources/app'),
created: now - 500,
updated: now - 500,
),
];
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: SessionListPane(app: app)),
));
await tester.pumpAndSettle();
expect(find.text('子代理输出 hello'), findsOneWidget);
// Tree rows start collapsed; the parent alone shows the count.
expect(find.text('输出 hello'), findsNothing);
expect(find.byTooltip('展开子代理'), findsOneWidget);
expect(find.textContaining('1 个子代理'), findsOneWidget);
await tester.tap(find.byTooltip('展开子代理'));
await tester.pump();
expect(find.text('输出 hello'), findsOneWidget);
expect(find.textContaining('子代理 · general'), findsOneWidget);
await tester.tap(find.text('输出 hello'));
await tester.pump();
expect(app.chat?.session.id, 'child');
});
testWidgets('the project band matches a session row and keeps the keys in line',
(tester) async {
final app = AppState();
@@ -47,4 +131,54 @@ void main() {
final menu = tester.getCenter(find.byIcon(Icons.more_vert));
expect(add.dx, closeTo(menu.dx, 0.5));
});
testWidgets('tree chevrons line up with the folder chevron and titles start alike',
(tester) async {
final app = AppState();
final now = DateTime.now().millisecondsSinceEpoch;
app.sessions = [
Session(
id: 'parent',
title: '子代理输出 hello',
agent: 'build',
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
created: now,
updated: now,
),
Session(
id: 'child',
parentID: 'parent',
title: '输出 hello',
agent: 'general',
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
created: now - 500,
updated: now - 500,
),
Session(
id: 'plain',
title: '无子代理的会话',
agent: 'build',
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
created: now - 1000,
updated: now - 1000,
),
];
addTearDown(app.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(body: SessionListPane(app: app)),
));
await tester.pumpAndSettle();
// The folder chevron and a parent's subagent chevron are on one line.
final folder = tester.getCenter(find.byIcon(Icons.expand_more).first);
final tree = tester.getCenter(find.byTooltip('展开子代理'));
expect(tree.dx, closeTo(folder.dx, 0.5));
// A session without subagents keeps the chevron column, so its title
// starts where a parent's does and loses no width.
final parentTitle = tester.getTopLeft(find.text('子代理输出 hello')).dx;
final plainTitle = tester.getTopLeft(find.text('无子代理的会话')).dx;
expect(plainTitle, closeTo(parentTitle, 0.5));
});
}
+108
View File
@@ -0,0 +1,108 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/state.dart';
/// A relay connection that drops the first session-list read, then works.
class _FakeTransport implements Transport {
bool failList;
bool failArchive;
_FakeTransport({this.failList = true, this.failArchive = false});
@override
Future<TransportResponse> send(TransportRequest r) async {
if (r.path == '/api/session' && failList) {
failList = false;
return _reply(503, {
'error':
'Could not connect to the relay: SocketException: Failed host lookup: relay.example'
});
}
if (r.path == '/api/session') {
return _reply(200, {
'data': [
{
'id': 'ses_1',
'title': 'Session',
'time': {'created': 1, 'updated': 2},
'location': {'directory': '/home/me/project'},
}
]
});
}
if (r.path.startsWith('/api/session/') && r.method == 'PATCH') {
if (failArchive) {
return _reply(500, {'error': 'archive failed'});
}
return _reply(200, {'data': <String, dynamic>{}});
}
return _reply(200, <String, dynamic>{});
}
TransportResponse _reply(int status, Object body) => TransportResponse(
status,
const {'content-type': 'application/json'},
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
);
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
void main() {
test('a successful session read clears a stale relay error', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport();
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.refreshSessions();
expect(app.error, contains('relay'));
// The tunnel came back on its own; the next read succeeds.
await app.refreshSessions();
expect(app.sessions, hasLength(1));
expect(app.error, isNull);
});
test('the banner Retry reads the list again and clears the error', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport();
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.refreshSessions();
expect(app.error, isNotNull);
await app.retryConnection();
expect(app.sessions, hasLength(1));
expect(app.error, isNull);
});
test('a session action error is not wiped by a routine refresh', () async {
final app = AppState();
addTearDown(app.dispose);
final transport = _FakeTransport(failList: false, failArchive: true);
app.client = Client(Uri.parse('http://test'), transport: transport);
await app.setArchived(Session(id: 'ses_2', title: 'Old'), true);
expect(app.error, contains('archive failed'));
await app.refreshSessions();
// The banner Retry dismisses action errors; a background refresh does not.
expect(app.error, contains('archive failed'));
});
}
+136
View File
@@ -0,0 +1,136 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/client.dart';
import 'package:openchamber/l10n.dart';
import 'package:openchamber/api/transport.dart';
import 'package:openchamber/screens/stats_screen.dart';
import 'package:openchamber/state.dart';
class _FakeTransport implements Transport {
final Map<String, dynamic> report;
_FakeTransport(this.report);
@override
Future<TransportResponse> send(TransportRequest r) async {
final body = utf8.encode(jsonEncode({'data': report}));
return TransportResponse(200, {'content-type': 'application/json'}, Stream.value(Uint8List.fromList(body)));
}
@override
Future<TransportSocket> webSocket(String path,
{String? rawQuery, Map<String, String> headers = const {}}) async =>
throw UnimplementedError();
@override
void setBearerToken(String? token) {}
@override
void close() {}
}
Map<String, dynamic> _report() => {
'range': {'from': 1000, 'to': 2000},
'sessions': 2,
'subagents': 1,
'prompts': 4,
'steps': 120,
'tokens': {
'input': 110000,
'output': 52000,
'reasoning': 20000,
'cache': {'read': 900000, 'write': 5000},
},
'cost': 0,
'activeDays': 2,
'streak': 1,
'activity': [
{'date': '2026-11-24', 'steps': 40},
{'date': '2026-11-25', 'steps': 80},
],
'models': [
{
'model': {'providerID': 'axonhub', 'id': 'deepseek-flash'},
'steps': 100,
'tokens': {
'input': 56900000,
'output': 4000000,
'reasoning': 1400000,
'cache': {'read': 1266000000, 'write': 0},
},
'cost': 0,
},
{
'model': {'providerID': 'p2', 'id': 'small'},
'steps': 20,
'tokens': {
'input': 3000,
'output': 1000,
'reasoning': 500,
'cache': {'read': 500, 'write': 0},
},
'cost': 0,
},
],
'tools': {'mode': 'none'},
};
void main() {
setUp(() => L10n.instance.apply(AppLanguage.en));
tearDown(() => L10n.instance.apply(AppLanguage.zh));
Future<void> pump(WidgetTester tester) async {
final app = AppState();
addTearDown(app.dispose);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('openchamber/device'),
(call) async => 'Asia/Shanghai',
);
app.client = Client(Uri.parse('http://test'), transport: _FakeTransport(_report()));
await tester.pumpWidget(MaterialApp(home: StatsScreen(app: app)));
await tester.pumpAndSettle();
}
testWidgets('the tokens model bar paints a share of the row', (tester) async {
await pump(tester);
await tester.scrollUntilVisible(find.text('deepseek-flash'), 300,
scrollable: find.byType(Scrollable).last);
await tester.pumpAndSettle();
const colors = [
Color(0xFF7C6CF6),
Color(0xFF3FB6A8),
Color(0xFFE0A03A),
Color(0xFFB06AD6),
];
double widest = 0;
for (final color in colors) {
for (final box in tester
.renderObjectList<RenderBox>(find.byWidgetPredicate(
(w) => w is ColoredBox && w.color == color))) {
// A Row of childless ColoredBoxes collapses to zero height unless the
// cross axis is stretched; that is what made the bars look empty.
expect(box.size.height, greaterThan(0),
reason: 'token segments must have height, got ${box.size}');
widest = box.size.width > widest ? box.size.width : widest;
}
}
// The top model has most of all tokens, so its fill is hundreds of px.
expect(widest, greaterThan(200),
reason: 'token-segment fills must paint; widest was $widest');
});
testWidgets('the metric grid shows the report', (tester) async {
await pump(tester);
expect(find.text('Prompts'), findsOneWidget);
expect(find.text('4'), findsWidgets); // prompts in the report
expect(find.text('1.1M'), findsWidgets); // 1100k tokens compact
await tester.scrollUntilVisible(find.text('deepseek-flash'), 300,
scrollable: find.byType(Scrollable).last);
expect(find.text('deepseek-flash'), findsWidgets);
});
}
+30
View File
@@ -0,0 +1,30 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
import 'package:openchamber/state.dart';
void main() {
test('subagent chats are read-only unless the server allows prompting them',
() {
final app = AppState();
addTearDown(app.dispose);
final child = Session(id: 'child', title: '输出 hello', parentID: 'parent');
expect(app.promptReadOnlyFor(child), isTrue);
app.allowPromptingSubagentSessions = true;
expect(app.promptReadOnlyFor(child), isFalse);
// A lead's operator worker stays read-only until taken over, whatever the
// subagent setting says.
final worker = Session(
id: 'worker',
title: 'worker',
metadata: {
'openchamber': {'kind': 'operator-child', 'parentID': 'lead'},
},
);
expect(app.promptReadOnlyFor(worker), isTrue);
final root = Session(id: 'root', title: 'root');
expect(app.promptReadOnlyFor(root), isFalse);
});
}
+114
View File
@@ -0,0 +1,114 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/usage_stats.dart';
void main() {
test('a report reads tokens, tools and models', () {
final stats = UsageStats.fromJson({
'range': {'from': 1000, 'to': 2000},
'sessions': 3,
'subagents': 5,
'prompts': 12,
'steps': 240,
'tokens': {
'input': 100,
'output': 40,
'reasoning': 10,
'cache': {'read': 900, 'write': 50},
},
'cost': 0.25,
'activeDays': 2,
'streak': 1,
'activity': [
{'date': '2026-11-25', 'steps': 40},
],
'tools': {
'mode': 'detail',
'totals': {'calls': 9, 'succeeded': 8, 'failed': 1, 'unfinished': 0},
'usage': [
{
'name': 'read',
'calls': 4,
'succeeded': 4,
'failed': 0,
'unfinished': 0,
'durationP50': 25.5,
},
],
},
'models': [
{
'model': {'providerID': 'p', 'id': 'm', 'variant': 'high'},
'steps': 240,
'tokens': {
'input': 100,
'output': 40,
'reasoning': 10,
'cache': {'read': 900, 'write': 50},
},
'cost': 0.25,
},
],
});
expect(stats.isEmpty, isFalse);
expect(stats.sessions, 3);
expect(stats.tokens.total, 1100);
expect(stats.tokens.produced, 50);
expect(stats.tools.hasTotals, isTrue);
expect(stats.tools.rows.single.durationP50, 25.5);
expect(stats.models.single.variant, 'high');
expect(stats.models.single.tokens.cacheRead, 900);
});
test('an empty report says so', () {
expect(const UsageStats().isEmpty, isTrue);
});
test('ranges start at local midnight', () {
final now = DateTime(2026, 11, 26, 15, 30);
expect(UsageRange.day.startFrom(now),
DateTime(2026, 11, 26).millisecondsSinceEpoch);
expect(UsageRange.week.startFrom(now),
DateTime(2026, 11, 20).millisecondsSinceEpoch);
expect(UsageRange.month.startFrom(now),
DateTime(2026, 10, 28).millisecondsSinceEpoch);
expect(UsageRange.all.startFrom(now), isNull);
});
test('activity fills quiet days and groups long ranges into weeks', () {
final from = DateTime(2026, 11, 20).millisecondsSinceEpoch;
final to = DateTime(2026, 11, 26).millisecondsSinceEpoch;
final series = buildUsageActivity(UsageStats(
from: from,
to: to,
activity: const [
UsageActivityDay('2026-11-21', 4),
UsageActivityDay('2026-11-24', 6),
],
));
expect(series.weekly, isFalse);
expect(series.bars.length, 6);
expect(series.bars.map((bar) => bar.steps), [0, 4, 0, 0, 6, 0]);
expect(series.max, 6);
// More than 92 days become weekly bars.
final long = buildUsageActivity(UsageStats(
from: DateTime(2026, 1, 1).millisecondsSinceEpoch,
to: DateTime(2026, 6, 1).millisecondsSinceEpoch,
));
expect(long.weekly, isTrue);
expect(long.bars.length, lessThanOrEqualTo(92));
});
test('the number and duration helpers read like the web client', () {
expect(usageCompactNumber(999), '999');
expect(usageCompactNumber(1234), '1.2K');
expect(usageCompactNumber(1234567), '1.2M');
expect(usageCompactNumber(123.4), '123');
expect(usagePercent(0.1234), '12.3%');
expect(usageCost(1.5), r'$1.50');
expect(usageDuration(48), '48 ms');
expect(usageDuration(1500), '1.5 s');
expect(usageDuration(65000), '1 min 5 s');
});
}