Compare commits

..
10 Commits
Author SHA1 Message Date
blumia 9b53338908 feat: the files sidebar, Markdown thinking, a banner that clears
- The chat's top-right menu only repeated the per-turn menu. It now opens a
  files sidebar that slides in from the right, the way the official client's
  right panel does: browse the session directory with a breadcrumb and an up
  key, filter the current directory, search its subdirectories (bounded,
  skipping .git/node_modules/build and friends), preview text/code/Markdown/
  images, edit and save text files, create files and folders, and download
  any file through the system save dialog.
- The panel's "..." menu carries the official client's "显示被 git 忽略的文件"
  toggle (the listing asks the server to respect gitignore by default) and a
  refresh. 项目知识 and 终端 have their tabs, marked as coming later.
- Thinking blocks are Markdown too (headings, lists, inline code), rendered
  with the shared MarkdownView at a smaller, quieter size.
- The reconnect banner stayed forever: the stream loop sets it when the SSE
  connection drops and nothing cleared it. Any event proves the stream is
  back (the server greets every connection with server.connected), so it now
  clears the message then.
- Markdown rendering moved to lib/widgets/markdown_view.dart, shared by
  messages, thinking, compaction summaries and file previews.
Version 0.3.9 (code 309).
2026-11-20 18:25:28 +08:00
blumia b9433c30cb feat: built-in /compact and compaction rows in the transcript
- /compact is not one of the directory's commands: OpenChamber's own
  client supplies it and runs POST /api/session/:id/compact. The palette now
  starts with that local command (压缩), so picking it compacts without the
  model seeing anything.
- A compaction message (status running/completed/failed, reason, summary,
  tokens) is part of the timeline. It now shows as the official client's
  row: a scissors glyph and "正在压缩对话" / "对话已压缩", a 显示摘要 toggle,
  and the summary as Markdown (revealed with the same height animation as
  the other folds). Failed compactions keep the error block.
- Live compaction events are subscribed: started adds the running record
  (or refreshes the tail when it names no id), delta appends the streaming
  summary, ended/failed fetch the server's settled record.
- Version 0.3.8 (code 308).
2026-11-20 12:26:15 +08:00
blumia fbadf6f858 fix: keep loaded tool output when the tail page only has its shell
List responses ask the server to elide large tool output
(`x-openchamber-part-shells: v1`): the part comes back as an empty text
plus an `openchamberContentShell` marker, and the full text is fetched
when a step is expanded. Every tail refresh (a turn starting, the app
returning) then replaced the loaded message with that shell again, so an
expanded step fell back to "无输出" — the more the session was used, the
more it looked like shell steps never had output.

reloadTail now keeps an already-loaded tool part when the server's copy of
that part is a shell (matched by position and call id), and the pending
state reads "输出较大,正在载入…" instead of claiming there was no output.
Version 0.3.7 (code 307).
2026-11-20 09:18:04 +08:00
blumia 6c00e5e026 feat: slash commands and skills in the composer, readable turn errors
- Typing `/` opens a palette above the composer, dsh-Go's shape: icon, the
  first-party Chinese label, /name, a one-line description, the first match
  highlighted and a return hint. It lists the directory's commands
  (/api/command) and skills (/api/skill), filters by name, label or
  description, and keeps the field focused while it opens.
- Picking completes `/name ` when the command takes arguments (its
  description shows a `[...]` form) and runs argument-free commands at once;
  skills complete and ride the next prompt as a `skills` attachment. Enter
  picks the highlighted row, arrows move, Esc closes.
- Sends route by name: commands go through POST /api/session/:id/command so
  the server expands the template (and writes the user message), skills go
  through the normal prompt with their id attached, anything else stays a
  plain message. A failed command keeps the draft for a retry.
- A failed turn now says so in the transcript: the last step's error is
  rendered under it as a quiet red block with the 中文 reading (auth, retry,
  stopped, send failure) and the provider's raw response behind 显示详情.
  Failed compactions and idle errors not already carried by the step are
  shown too; an error that a later step recovered from is not the turn's
  outcome and stays hidden.
- The tail is refetched when a turn starts, so a command's server-written
  user message (or another client's) appears without reopening the session;
  a successful send clears the stale error banner.
Version 0.3.6 (code 306).
2026-11-20 02:20:35 +08:00
blumia d7cec9d155 feat: animated folds that hold their header, folded-by-default runs
- Rebuilt the fold after dsh-Go's ExpandReveal/_holdHeader: the body grows
  from its top edge and fades in over 280ms (easeInOutCubic), and every
  frame reports the height it adds or removes *before layout*, so the list
  can scroll by exactly that much and keep the header under the finger.
  Folds nobody can see take their new size without animating or dragging
  the view.
- Finished runs now fold to their summary line, as in dsh-Go; running ones
  stay open. A tap overrides either default and is remembered.
- Streamed tool parts only carry an id and input, never the tool name, so
  live steps showed a generic "工具" label. Each step now swaps in the
  server's copy of its message when it ends, which brings the name, the
  full input and the attachments (and with them the right icon, label and
  image handling).
- getMessage read the message from the response envelope directly and
  would have thrown; it now unpacks `data`.
Version 0.3.5 (code 305).
2026-11-20 00:26:09 +08:00
blumia 32277564f9 fix: dark markdown, steadier folds, readable tool details, live refresh
- gpt_markdown renders through its own Material port, whose Theme.of falls
  back to a light theme: code panels stayed light and their text black in
  the dark theme. The chat now wraps markdown in a matching `mui.Theme`.
- Folding a run changed the height below its header and threw the header
  out of view. The toggle remembers the header's screen position, corrects
  the scroll offset, and parks the header at the top when the run is
  longer than the viewport.
- Step details show what a tool actually did: the command and its output
  for shell steps, the remaining inputs and the result for the rest, in
  monospace; toolOutput falls back to metadata. A read/write/edit of an
  image is no longer foldable — its path opens the preview.
- The event stream now times out without a heartbeat, so a half-open
  connection is noticed and reopened; returning to the foreground restarts
  the stream, refreshes the session list and the open chat, and reloadTail
  merges the newest page instead of dropping loaded history.
- A page shorter than the limit means there is nothing older, so short
  sessions no longer offer "load earlier".
- Version 0.3.4 (code 304).
2026-11-19 20:18:04 +08:00
blumia 2baa0a2730 feat: tool steps as foldable runs with icon, label and summary
The old rows ("已思考 ▸", "✓ shell ▸") said nothing about what a step did
and could only be expanded one at a time.

- A turn is one or more assistant messages (the server writes a message
  per step), so grouping per message produced a header for every step.
  Rows are now grouped per turn: one "已完成 · N 次工具调用" header, split
  where the reply has text. Header shows running/complete/failed, and the
  whole run folds away.
- Every step shows a rounded icon for its kind (thought, shell, read,
  write, edit, patch, search, fetch, task, skill), its label and a
  one-line summary: the command, the file path, the pattern, the URL, the
  skill id, and so on.
- A step opens to its reasoning text or the tool's input and output;
  image references stay listed and clickable.
- A lone thought needs no header; a reasoning-only run reads "思考过程".
- Version 0.3.3 (code 303).
2026-11-19 14:58:18 +08:00
blumia 61977d2b14 fix: full chat history, picked model/agent, usage sheet, image previews
- The chat loaded only one page of history: a desc page's older side is
  cursor.next, not previous, and the server rejects a cursor combined
  with order (InvalidCursorError). The first page stores `next`, later
  pages pass only `cursor`. tool/history_probe.dart walks a 1698-message
  session down to the oldest message with no gaps.
- The message list is now reversed (newest at offset 0), so older pages
  grow above and the viewport stays put; near the top it loads by itself
  and a "load earlier" row remains as a fallback.
- The agent picker filtered only on mode, so Compaction/Title/Summary
  (primary but hidden) showed up. Filter `hidden` too, and mark the
  current model or agent with a check.
- The usage ring's sheet was guarded by a flag nothing ever set; the
  ring now opens the context detail sheet.
- Tool image previews use a self-loading dialog and Image.memory: no
  temp file and no path_provider, whose Android implementation throws
  ClassNotFoundException: Landroid/content/Context; on the emulator.
- "Add server" in the connected server sheet now opens the form and
  returns to the session list once connected.
- Add a Linux desktop target for fast local UI checks, plus the probe
  that pages history.
- Version 0.3.2 (code 302).
2026-11-19 12:34:25 +08:00
blumia 2f5aad3814 test: local SOCKS5 and HTTP proxies for the proxy probe 2026-11-18 22:19:40 +08:00
blumia 55dac37baf fix: working HTTP and SOCKS5 proxies; save only working servers
- SOCKS5 had been fed to HttpClient.findProxy, which supports only HTTP
  proxies ("Invalid proxy configuration"), and socks5h was treated as an
  HTTP proxy ("Invalid request method"). HTTP/HTTPS proxies stay on
  findProxy; socks5/socks5h tunnel through socks5_proxy, which resolves
  names at the proxy; user:pass in the proxy URL is passed along.
- Saving moved to the successful path: a failed attempt stays in the form
  with a short reason, and the server list keeps no duplicates.
- package net.blumia.openchamber.flutter (namespace, applicationId,
  MainActivity, iOS bundle id), version 0.3.1 (code 301).
- show the proxy in the instance and server lists; clearer connect errors.
- tool/proxy_probe.dart checks direct, socks5, socks5h and HTTP proxies
  (requests and SSE) against a live server.
2026-11-18 22:18:45 +08:00
33 changed files with 4166 additions and 353 deletions

No files matched your search

+3
View File
@@ -21,6 +21,9 @@ migration:
- platform: ios
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
- platform: linux
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
# User provided section
+124
View File
@@ -27,6 +27,130 @@
---
## 0.3.9 文件侧栏、思考 Markdown 与重连提示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 文件侧栏 | 会话顶栏原来的 ⋮(和每轮底部的菜单重复)换成侧栏按钮,从右侧滑出面板:目录浏览、面包屑、上一级、搜索(当前目录即时过滤 + 子目录递归搜索,跳过 .git/node_modules/build 等,最多 400 个目录/200 条结果)、新建文件/文件夹、刷新 |
| 预览 | 文本与代码等宽显示;Markdown 按 Markdown 渲染(共用聊天那套主题修正);图片用 InteractiveViewer 缩放;二进制提示无法预览。文本可切到编辑并保存(`/api/fs/write`) |
| 下载 | `/api/fs/raw` 取原始字节,交给系统保存对话框(Android SAF / 桌面对话框) |
| 显示被忽略的文件 | 「⋯」菜单里的开关(`respectGitignore=false`),默认按下图与官方一致的行为隐藏 git 忽略项;另含刷新 |
| 占位页 | 「项目知识」「终端」两个页签已在位,内容标注「即将支持」 |
| 思考 Markdown | 展开思考块时不再按纯文本渲染,改用与回答一致的 Markdown 渲染(字号更小、颜色更淡) |
| 重连提示 | 事件流恢复(服务端每个连接都会先发 `server.connected`)即清除「连接中断,正在重连…」,不再一直挂着 |
| 版本 | **0.3.9(code 309)** |
---
## 0.3.8 内置 `/compact` 与压缩记录(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| `/compact` | 官方客户端的内置指令不在 `/api/command` 里,是客户端自己提供的;现在面板会先列出本地指令(`compact`,中文名「压缩」),选中即执行 `POST /api/session/:id/compact`,不需要模型参与 |
| 其它内置 | 看了 opencode 官方实现:`undo`/`redo`(撤回语义)、`timeline`(时间线视图)、`btw`(临时子会话)、`fork`、`handoff-review`,以及 `summary`/`workspace-review`/`plan-feature`/`craft-goal`/`schedule-task`/`catch-up`/`debug`/`weigh`/`explore`(成对的可见提示 + 隐藏指令)。本轮只做 `/compact`;其余需要对应 UI 或官方提示词文本,未加 |
| 压缩记录 | 消息列表里的 `compaction` 消息(`status` running/completed/failed、`reason`、`summary`、`tokens`)现在会显示成一行「正在压缩对话 / 对话已压缩」+「显示摘要」,展开是 Markdown 摘要;运行中有转圈,结束后自动换成完成态 |
| 实时 | 订阅 `session.compaction.started/delta/ended/failed`:开始时插入运行中的记录或拉一次尾部,delta 追加到摘要,结束/失败时拉一次服务端版本(摘要、token、错误都齐) |
| 失败 | 压缩失败仍用错误块显示(「压缩失败:…」+ 原始响应详情) |
| 版本 | **0.3.8(code 308)** |
---
## 0.3.7 工具输出被“壳”覆盖(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 现象 | 会话列表接口带 `x-openchamber-part-shells: v1` 时,大一点的工具输出只给一个空壳:`content:[{type:'text',text:''}]` + `metadata.openchamberContentShell`。展开步骤时客户端会单条拉完整消息(`/message/:id`,不带壳),输出就出来了 |
| 根因 | 每次 `reloadTail()`(每轮 `execution.started`、回到前台等)都用**带壳**的列表覆盖本地消息,把刚加载出来的输出又盖回空壳,于是展开着的那一步变回「无输出」——看起来就像“始终无输出” |
| 修复 | `reloadTail` 合并消息时,如果服务端给的是壳、本地这一条已经加载过完整内容,就保留本地那条(按 part 顺序与 call id 对齐),不再降级;真没有输出的命令仍然显示「无输出」 |
| 提示 | 壳还没加载完时不再显示「无输出」,而是「输出较大,正在载入…」 |
| 版本 | **0.3.7(code 307)** |
---
## 0.3.6 斜杠指令与错误显示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| `/` 指令面板 | 输入框以 `/` 开头且还没打空格时,在输入条上方弹出(dsh-Go 的样子:图标 + 中文名 + `/name` + 一行说明,最多 5.5 行,首条高亮,右侧 ↵)。来源是这个会话目录的 `GET /api/command` 与 `GET /api/skill`,第一次打开时加载并缓存;支持按名称/说明过滤,↑/↓ 选择、回车选中、Esc 关闭 |
| 选中行为 | 说明里带 `[…]` 参数形式的指令补全成 `/name ` 并等待参数;没有参数的(如 `/init`)立即执行;技能补全为文本随下一条消息发出。未知的 `/xxx` 仍是普通消息 |
| 发送路由 | 指令走 `POST /api/session/:id/command`(`{name, text}`,服务端展开模板并写用户消息);技能走普通 `/prompt` 并附 `skills: [{id}]`;失败时保留草稿 |
| 错误显示 | 解析消息上的 `error`(`provider.*`、`provider.auth`、`MessageAbortedError` 等):只显示结束这一轮的那一步的错误(被后续步骤接上的失败不算),另外显示失败的压缩消息和未被助手消息覆盖的 idle 错误。样式为浅红圆角块 + 图标 + 中文说明(认证失败、重试中、已停止、发送失败),provider 的原始响应放在「显示详情」里(美化过的 JSON) |
| 刷新 | `session.execution.started` 时拉一次尾部:指令这条由服务端写入的用户消息(以及别的客户端发的消息)能立刻出现,不用重进会话 |
| 版本 | **0.3.6(code 306)** |
---
## 0.3.5 折叠动画与流式修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 折叠定位 | 照 dsh-Go 的 `ExpandReveal`/`_holdHeader` 重做:内容用 `SizeTransition` 从顶部往下长、同时淡入,280ms `easeInOutCubic`;每一帧在**布局之前**把长出来的高度补进滚动位置,表头因此停在手指按下的位置。列表两端补不动时停在边界;看不见的折叠(历史里自动收起的一轮)直接换尺寸,不做动画、不拽视图 |
| 默认折叠 | 与 dsh-Go 一致:**已结束的一轮收成一行摘要**(`已完成 · N 次工具调用`),运行中的保持展开;点一下记住你的选择(手动展开的在结束后也不会自动收起) |
| 工具详情 | 不再铺请求 JSON:`运行` 是完整命令 + 其余参数 + 输出(空则「无输出」),其它工具是摘要之外的参数 + 结果;`toolOutput` 在 `content` 为空时回退 `metadata` 的 output/result/stdout |
| 图片读取 | `读取`/`写入`/`编辑` 指向图片时该行不可折叠,路径直接点开大图;读取失败的行仍是普通可折叠步骤 |
| 流式工具名 | 事件里只有工具 id 和 input,没有名字,直播中的步骤只能显示「工具」。现在每一步结束(`session.step.ended`)后用 `getMessage` 换回服务端那条消息:名字、完整输入、附件都齐了,标签立刻变成 `运行`/`读取` 等 |
| 会话自动刷新 | SSE 30s 无数据(服务端有 `: heartbeat`)即判定断线并重连;回到前台重开事件流、刷新会话列表并合并 `reloadTail()` |
| 版本 | **0.3.5(code 305)** |
---
## 0.3.4 主题与工具细节(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 暗色主题代码块/行内代码 | `gpt_markdown` 用的是它自带的 `material_ui` 移植版 Material,`Theme.of` 找不到宿主主题时回落成**亮色**,于是代码块面板亮、正文黑。现在渲染前用同一套亮/暗 `mui.ThemeData` 包一层,面板、行内代码、表格、语法配色都跟随应用主题 |
| 折叠时视口跳动 | 折叠/展开会改变分组高度:现在记录表头在屏幕上的位置,重建后按差值补偿滚动;若因列表边界补不回来,就把表头停到列表顶部。展开时始终看到分组头部,不再落到分组末尾 |
| 工具详情 | 不再直接铺请求 JSON:`运行` 显示完整命令(可选中、换行)+ 输出,其它工具显示摘要之外的参数与结果;输出为空时显示「无输出」。`toolOutput` 在 `content` 为空时回退到 `metadata` 的 output/result/stdout |
| 图片读取 | `读取`/`写入`/`编辑` 指向图片时,该行不再展开,路径直接可点,打开大图预览 |
| 会话不自动刷新 | SSE 增加 30s 心跳超时(服务端每几秒发 `: heartbeat`),断流会被发现并重连;应用回到前台时重开事件流、刷新会话列表并 `reloadTail()`(合并而不是替换已加载的历史页) |
| 「载入更早」误显示 | 服务端对已经包含全部内容的页也会给 cursor,现在短于一页即视为没有更早内容 |
| openui-lang | 暂未渲染:pub 上的 `openui_lang` 0.18.2 组件签名与 OpenChamber 的 DSL 不一致(`Card` 首参是 children 而非标题,且没有 `Badge`/`KeyValue`/`Stat`/`Details`),接入需要一层组件映射;本轮先跳过 |
| 版本 | **0.3.4(code 304)** |
---
## 0.3.3 工具调用展示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 为什么要改 | 旧版每个 reasoning/tool part 只显示一行「已思考 ▸ / ✓ shell ▸」,既没有概要也不能整组收起,长回合里几乎不可读 |
| 分组依据 | 服务端每个 step 各写一条 assistant 消息,所以按**消息**分组会得到「5 组」;现在按**回合**(连续的 assistant 消息)分组,`text` 分隔出新的组。与 dsh-Go 一致:一组一个「已完成 · N 次工具调用」表头 |
| 表头 | 左侧状态图标(进行中转圈 / 完成对勾 / 失败警告),「已完成 · N 次工具调用」/「执行中 · …」/「有步骤失败 · …」;只有一个思考步骤时不显示表头,直接显示「思考」行;纯思考的组显示「思考过程」 |
| 每行 | 26px 圆角图标 + 名称 + 「· 概要」+ 展开箭头;图标按工具类型(思考=psychology、运行=terminal、读取=description、写入/编辑/补丁、搜索、抓取、任务、技能…),未知工具用工具名 |
| 概要 | bash=命令、read/write/edit=文件路径、grep/glob=模式、webfetch=URL、task=描述、skill=id,其余取 description/path/command/query/url/pattern/name/id,再退化为紧凑 JSON |
| 展开 | 单行展开后显示推理全文或工具的 input/输出(等宽、可选中);图片引用仍以 🖼 行列出,点击预览 |
| 版本 | **0.3.3(code 303)** |
---
## 0.3.2 修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 会话历史只加载一段 | 两个原因:`order=desc` 的“更早”方向是 `cursor.next`(此前用了 `previous`,取到 0 条),以及服务端拒绝 `cursor` 与 `order` 同时出现(`InvalidCursorError`)。现在首次加载记下 `next`,后续只带 `cursor`。`tool/history_probe.dart` 对 1698 条的会话验证 30 条/页翻到最早一条,无缺口 |
| 加载时视图跳动 | 消息列表改为 `reverse: true`(最新在底部,偏移 0),更早的页追加在上方,视口自然保持不动;接近顶部自动加载,并提供「载入更早的消息」按钮 |
| 智能体列表 | 过滤 `hidden`(Compaction/Title/Summary 是 `mode=primary` 但 `hidden=true`),只留 Build/Plan;模型与智能体列表用对勾标出当前选中项,切换后由 SSE 事件与本状态同步 |
| 用量环 | 点击打开「上下文占用」详情(模型、已用 tokens、上限、输出预留、百分比);此前被 `_usageOpen` 守卫拦掉 |
| 图片预览 | 对话框改为自加载的 StatefulWidget(此前预览流程在 widget 重建后失去状态);图片直接 `Image.memory(bytes)`,不再落盘。`path_provider_android 2.3.1` 在本机模拟器上抛 `ClassNotFoundException: Landroid/content/Context;`,因此移除 path_provider(附件缓存改用 `Directory.systemTemp`)。经 SOCKS5/HTTP 代理取 `/api/fs/raw` 均可预览 |
| 已连接时添加服务器 | 服务器面板的「添加服务器」此前只关闭面板;现在打开表单,连接成功后回到会话列表 |
| 版本 | **0.3.2(code 302)** |
| 测试环境 | 新增 Linux 桌面目标(`flutter create --platforms=linux`),本机 clang 从 `clang-17` 包解出、libsecret/jsoncpp 头文件解出,配合 Xvfb + xdotool/ffmpeg 截图自测,比模拟器快很多 |
---
## 0.3.1 修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 代理 | 支持 `http://`、`https://`(`HttpClient.findProxy`)与 `socks5://`、`socks5h://`(`socks5_proxy` 包为 `HttpClient` 建 SOCKS 隧道,统一在代理解析域名),可带 `user:pass@`。此前 `socks5` 直接塞进 `findProxy` 导致 “Invalid proxy configuration”,`socks5h` 被当成 HTTP 代理导致 “Invalid request method” |
| 验证 | `tool/proxy_probe.dart` 对本机服务器 + 本地 SOCKS5(1080)/HTTP(8081) 测试代理跑通 direct / socks5 / socks5h / http 与 SSE;模拟器上分别用 `socks5://127.0.0.1:1080` 和 `http://127.0.0.1:8081` 连上并列出会话 |
| 失败不落库 | 连接成功才保存(`_connected` upsert);失败的尝试留在表单并显示简短原因(如「连接被拒绝:服务器或代理未启动,或端口不对」),返回列表后不残留错误 |
| 包名 | `net.blumia.openchamber.flutter`(namespace、applicationId、MainActivity、iOS bundle id 同步) |
| 版本 | **0.3.1(code 301)** |
| 小改进 | 实例/服务器列表显示「经由 <代理>」,区分同地址不同代理;连接错误中文化 |
---
## 0.2 迁移到 MyGo(2026-11-18,分支 `mygo`,0.3.0)
**背景**:Asuka 0.2 把应用语言从 Go 换成了自研 Asuka 语言(C 内核、无 Go 运行时),继续留在 Go 线已没有上游维护;
+35 -9
View File
@@ -5,20 +5,23 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity.
Status: 0.3.0 — servers (passwordless / password login, HTTP/SOCKS5 proxy,
self-signed certificates and pinning), session list with search and live
events, chat with streaming Markdown, tool rows with image previews, a
context usage ring with a detail sheet, model/agent switching, copy / fork /
revert, attachments (photos/files), permissions. Android 7.0 (API 24)+.
Status: 0.3.9 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a
context usage ring with a detail sheet, model/agent switching (Build/Plan only,
current one checked), copy / fork / revert, attachments (photos/files),
permissions. Android 7.0 (API 24)+, plus a Linux desktop target used for local
testing.
## What is here
| Path | What |
| --- | --- |
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP proxy via `HttpClient.findProxy`, SOCKS5 via dart:io's SOCKS, pinning/self-signed via `badCertificateCallback` |
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback` |
| `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) |
| `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding |
| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets) |
| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets); the message list is reversed so older pages grow above without moving the viewport |
| `lib/widgets/` | The context usage ring |
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
@@ -44,11 +47,34 @@ export JAVA_HOME=$HOME/SDK/jdk-21
flutter pub get
flutter test
flutter build apk --release # dist artifacts in build/app/outputs/flutter-apk
flutter build linux --debug # faster UI checks on the desktop
```
`android/app/build.gradle.kts` sets `minSdk 24` and signs releases with
The Linux build only needs a C toolchain and GTK 3 development headers; on
this machine `clang` was extracted into `~/SDK/localbin` (from the
`clang-17` package) and the two missing `-dev` files (`libsecret-1-dev`,
`libjsoncpp-dev`) into `~/SDK/linuxdev`, so:
```bash
export PATH=$HOME/SDK/localbin:$HOME/SDK/flutter/bin:$PATH
export PKG_CONFIG_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu/pkgconfig
export LIBRARY_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu
flutter build linux --debug
DISPLAY=:99 GDK_BACKEND=x11 ./build/linux/x64/debug/bundle/openchamber
```
`tool/history_probe.dart` pages a session exactly as the chat does and reports
whether every message is reached.
`android/app/build.gradle.kts` sets the application id
`net.blumia.openchamber.flutter`, `minSdk 24`, and signs releases with
`~/SDK/test-upload.jks` (override via `OPENCHAMBER_KEYSTORE*` env). Dart's
`HttpClient` dials sockets itself, so plain `http://` LAN servers work in
release without a cleartext manifest flag, as with the Go clients.
release without a cleartext manifest flag, as with the Go clients. Only a
working connection is saved: a failed attempt stays in the form.
Proxies accept `http://`, `https://`, `socks5://` and `socks5h://` (the
last two resolve names at the proxy). `tool/proxy_probe.dart` checks the
client against a live server through local test proxies.
Earlier attempts: `main` (Asuka/Go, 0.2.x) and `mygo` (MyGo, 0.3.0).
+1
View File
@@ -14,6 +14,7 @@ analyzer:
- build/**
- android/**
- ios/**
- linux/**
linter:
# The lint rules applied to this project can be customized in the
+2 -2
View File
@@ -5,7 +5,7 @@ plugins {
}
android {
namespace = "com.openchamber.openchamber"
namespace = "net.blumia.openchamber.flutter"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
@@ -15,7 +15,7 @@ android {
}
defaultConfig {
applicationId = "com.openchamber.native"
applicationId = "net.blumia.openchamber.flutter"
minSdk = 24
targetSdk = flutter.targetSdkVersion
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
@@ -1,4 +1,4 @@
package com.openchamber.openchamber
package net.blumia.openchamber.flutter
import io.flutter.embedding.android.FlutterActivity
+6 -6
View File
@@ -383,7 +383,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
@@ -399,7 +399,7 @@
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber.RunnerTests;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -416,7 +416,7 @@
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber.RunnerTests;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
@@ -431,7 +431,7 @@
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber.RunnerTests;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
@@ -564,7 +564,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -586,7 +586,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.openchamber.openchamber;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
+227 -23
View File
@@ -6,6 +6,8 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:socks5_proxy/socks_client.dart';
import 'models.dart';
class ApiError implements Exception {
@@ -16,6 +18,48 @@ class ApiError implements Exception {
String toString() => message.isEmpty ? 'HTTP $status' : message;
}
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
class _ProxyConfig {
final String scheme; // http | https | socks5 | socks5h
final String host;
final int port;
final String? username;
final String? password;
_ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]);
bool get socks => scheme.startsWith('socks');
}
_ProxyConfig? _parseProxy(String? raw) {
final s = raw?.trim() ?? '';
if (s.isEmpty) return null;
var normalized = s;
if (!normalized.contains('://')) normalized = 'http://$normalized';
final uri = Uri.tryParse(normalized);
if (uri == null || uri.host.isEmpty) {
throw ArgumentError('代理地址无效:$raw');
}
final scheme = uri.scheme.toLowerCase();
final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h';
final http = scheme == 'http' || scheme == 'https';
if (!socks && !http) {
throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)');
}
String? user;
String? pass;
if (uri.userInfo.isNotEmpty) {
final i = uri.userInfo.indexOf(':');
if (i >= 0) {
user = Uri.decodeComponent(uri.userInfo.substring(0, i));
pass = Uri.decodeComponent(uri.userInfo.substring(i + 1));
} else {
user = Uri.decodeComponent(uri.userInfo);
}
}
final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080);
return _ProxyConfig(scheme, uri.host, port, user, pass);
}
class Client {
final Uri base;
final String? proxy; // http://host:port or socks5://host:port
@@ -23,6 +67,8 @@ class Client {
final String? fingerprint;
String? token;
late HttpClient _http;
_ProxyConfig? _proxyConfig;
InternetAddress? _proxyAddress;
Client(
this.base, {
@@ -32,23 +78,50 @@ class Client {
}) {
_http = HttpClient();
_http.connectionTimeout = const Duration(seconds: 20);
if (proxy != null && proxy!.isNotEmpty) {
_http.findProxy = (uri) {
final u = Uri.parse(proxy!);
final scheme = u.scheme.toLowerCase();
if (scheme == 'socks5' || scheme == 'socks') {
return 'SOCKS ${u.host}:${u.port}';
_proxyConfig = _parseProxy(proxy);
if (_proxyConfig != null && _proxyConfig!.socks) {
// Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy
// package tunnels the socket and hands a Socket back to the client.
_http.connectionFactory = (uri, _, __) async {
final address = await _resolveProxyAddress();
final settings = ProxySettings(address, _proxyConfig!.port,
username: _proxyConfig!.username, password: _proxyConfig!.password);
final tunnel = SocksTCPClient.connect(
[settings],
// A unix-type address carries the host name, so the proxy resolves
// it (socks5h semantics) instead of resolving it here.
InternetAddress(uri.host, type: InternetAddressType.unix),
uri.port,
);
if (uri.scheme == 'https') {
final secure = tunnel.then(
(s) => s.secure(uri.host, onBadCertificate: _badCertificate));
return ConnectionTask.fromSocket(secure, () {});
}
return 'PROXY ${u.host}:${u.port}';
return ConnectionTask.fromSocket(tunnel, () {});
};
} else if (_proxyConfig != null) {
_http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}';
}
if (insecure || (fingerprint != null && fingerprint!.isNotEmpty)) {
_http.badCertificateCallback = (cert, host, port) {
if (insecure) return true;
final der = _sha256(cert.der);
return der == fingerprint!.replaceAll(':', '');
};
_http.badCertificateCallback = (cert, host, port) => _badCertificate(cert);
}
Future<InternetAddress> _resolveProxyAddress() async {
if (_proxyAddress != null) return _proxyAddress!;
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
if (addresses.isEmpty) {
throw const SocketException('无法解析代理主机');
}
return _proxyAddress = addresses.first;
}
/// True for a certificate the app was told to accept: the user trusts any
/// (insecure), or its SHA-256 matches the pinned fingerprint.
bool _badCertificate(X509Certificate cert) {
if (insecure) return true;
final pinned = fingerprint?.replaceAll(':', '').toLowerCase();
if (pinned == null || pinned.isEmpty) return false;
return _sha256(cert.der) == pinned;
}
String get baseUrl => base.toString();
@@ -124,7 +197,9 @@ class Client {
{int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async {
final query = <String, String>{
'limit': '$limit',
'order': order,
// The server rejects a cursor combined with order: the cursor already
// carries the direction.
if (cursor == null) 'order': order,
if (cursor != null) 'cursor': cursor,
};
final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}/message',
@@ -141,7 +216,7 @@ class Client {
final r = await _json('GET',
'/api/session/${Uri.encodeComponent(sessionId)}/message/${Uri.encodeComponent(messageId)}',
directory: directory);
return Message.fromJson(r);
return Message.fromJson(r['data'] as Map<String, dynamic>);
}
Future<List<ModelInfo>> models(String directory) async {
@@ -175,15 +250,73 @@ class Client {
}
Future<void> prompt(String sessionId,
{String text = '', String? messageId, String? directory, List<Map<String, String>>? files}) async {
{String text = '',
String? messageId,
String? directory,
List<Map<String, String>>? files,
List<String>? skillIds}) async {
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory,
body: {
if (text.isNotEmpty) 'text': text,
if (messageId != null) 'id': messageId,
if (files != null && files.isNotEmpty) 'files': files,
if (skillIds != null && skillIds.isNotEmpty)
'skills': [
for (final id in skillIds) {'id': id},
],
});
}
/// Runs a registered slash command (`/initialize`, `/review`, …). The
/// server expands the command template and starts the turn.
Future<void> command(String sessionId,
{required String name, String text = '', String? directory,
List<Map<String, String>>? files}) async {
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/command',
directory: directory,
body: {
'name': name,
'text': text,
if (files != null && files.isNotEmpty) 'files': files,
});
}
/// Asks the server to summarize the history into a compaction record.
/// Returns that record's message id, when the server names it.
Future<String?> compact(String sessionId, {String? directory}) async {
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/compact',
directory: directory, body: const {});
final data = r['data'];
return data is Map ? data['id'] as String? : null;
}
/// The commands this directory registers (`/api/command`).
Future<List<Map<String, String>>> commands({String? directory}) async {
final r = await _json('GET', '/api/command', directory: directory);
return [
for (final e in (r['data'] as List? ?? []))
if (e is Map)
{
'name': e['name'] as String? ?? '',
'description': e['description'] as String? ?? '',
},
];
}
/// The skills opencode knows in this directory (`/api/skill`).
Future<List<Map<String, String>>> skills({String? directory}) async {
final r = await _json('GET', '/api/skill', directory: directory);
return [
for (final e in (r['data'] as List? ?? []))
if (e is Map)
{
'id': e['id'] as String? ?? '',
'name': e['name'] as String? ?? '',
'description': e['description'] as String? ?? '',
},
];
}
Future<bool> interrupt(String sessionId, {String? directory}) async {
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/interrupt',
directory: directory, body: const {});
@@ -222,13 +355,66 @@ class Client {
'path': path,
'allowOutsideWorkspace': 'true',
},
directory: directory);
directory: directory,
rawDirectory: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true));
}
return res.body;
}
// ------------------------------------------------------------ files
Future<List<FsEntry>> fsList(String path,
{String? directory, bool respectGitignore = true}) async {
final r = await _json('GET', '/api/fs/list',
query: {
'path': path,
if (respectGitignore) 'respectGitignore': 'true',
},
directory: directory,
rawDirectory: true);
return [
for (final e in (r['entries'] as List? ?? []))
if (e is Map<String, dynamic>) FsEntry.fromJson(e),
];
}
Future<String> fsRead(String path, {String? directory}) async {
final res = await _request('GET', '/api/fs/read',
query: {'path': path}, directory: directory, rawDirectory: true);
final text = utf8.decode(res.body, allowMalformed: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(res.statusCode, text.trim());
}
return text;
}
Future<FsStat?> fsStat(String path, {String? directory}) async {
final r = await _json('GET', '/api/fs/stat',
query: {'path': path}, directory: directory, rawDirectory: true);
final data = r['path'] == null ? r['data'] : r;
if (data is! Map<String, dynamic>) return null;
return FsStat.fromJson(data);
}
Future<void> fsWrite(String path, String content, {String? directory}) async {
await _json('POST', '/api/fs/write',
body: {'path': path, 'content': content},
directory: directory,
rawDirectory: true);
}
Future<void> fsMkdir(String path, {String? directory}) async {
await _json('POST', '/api/fs/mkdir',
body: {'path': path}, directory: directory, rawDirectory: true);
}
Future<void> fsDelete(String path, {String? directory}) async {
await _json('POST', '/api/fs/delete',
body: {'path': path}, directory: directory, rawDirectory: true);
}
/// Subscribes to GET /api/event, yielding each SSE event. The stream ends
/// when the connection drops; the caller restarts it with backoff.
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
@@ -249,7 +435,14 @@ class Client {
throw ApiError(res.statusCode, 'event stream failed');
}
String data = '';
await for (final line in utf8.decoder.bind(res).transform(const LineSplitter())) {
// The server sends a `: heartbeat` comment every few seconds; if nothing
// at all arrives for a while the connection is dead and the caller should
// reconnect rather than wait on a half-open socket.
final lines = utf8.decoder
.bind(res)
.transform(const LineSplitter())
.timeout(const Duration(seconds: 30));
await for (final line in lines) {
if (line.isEmpty) {
if (data.isNotEmpty) {
final ev = jsonDecode(data) as Map<String, dynamic>;
@@ -270,9 +463,14 @@ class Client {
{Map<String, String>? query,
Map<String, dynamic>? body,
String? directory,
bool partShells = false}) async {
bool partShells = false,
bool rawDirectory = false}) async {
final res = await _request(method, path,
query: query, body: body, directory: directory, partShells: partShells);
query: query,
body: body,
directory: directory,
partShells: partShells,
rawDirectory: rawDirectory);
final text = utf8.decode(res.body, allowMalformed: true);
if (res.statusCode < 200 || res.statusCode >= 300) {
String msg = text;
@@ -294,7 +492,8 @@ class Client {
{Map<String, String>? query,
Map<String, dynamic>? body,
String? directory,
bool partShells = false}) async {
bool partShells = false,
bool rawDirectory = false}) async {
final q = Uri(queryParameters: query ?? {});
final uri = base.resolve(path).replace(queryParameters: q.queryParameters.isEmpty ? null : q.queryParameters);
final req = await _http.openUrl(method, uri);
@@ -305,8 +504,13 @@ class Client {
req.headers.set('Authorization', 'Bearer $token');
}
if (directory != null && directory.isNotEmpty) {
req.headers.set('x-opencode-directory', Uri.encodeComponent(directory));
req.headers.set('x-opencode-directory-encoding', 'uri');
// The file routes compare this header with the workspace path, so they
// need it as written; the rest of the API wants it URI-encoded.
req.headers.set('x-opencode-directory',
rawDirectory ? directory : Uri.encodeComponent(directory));
if (!rawDirectory) {
req.headers.set('x-opencode-directory-encoding', 'uri');
}
}
if (partShells) {
req.headers.set('x-openchamber-part-shells', 'v1');
+79 -3
View File
@@ -158,6 +158,59 @@ class ToolState {
};
}
/// The error OpenCode recorded on a message (a failed step, a failed
/// compaction). `body` is the provider's raw response, when there was one.
/// One row of a directory listing (`/api/fs/list`).
class FsEntry {
final String name;
final String path;
final bool isDirectory;
const FsEntry({required this.name, required this.path, this.isDirectory = false});
factory FsEntry.fromJson(Map<String, dynamic> j) => FsEntry(
name: j['name'] as String? ?? '',
path: j['path'] as String? ?? '',
isDirectory: j['isDirectory'] as bool? ?? false,
);
String get extension {
final dot = name.lastIndexOf('.');
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
}
}
/// `/api/fs/stat` answer (only what the file browser uses).
class FsStat {
final String path;
final bool isFile;
final int size;
const FsStat({required this.path, this.isFile = false, this.size = 0});
factory FsStat.fromJson(Map<String, dynamic> j) => FsStat(
path: j['path'] as String? ?? '',
isFile: j['isFile'] as bool? ?? false,
size: (j['size'] as num?)?.toInt() ?? 0,
);
}
class MessageError {
final String type;
final String message;
final int? status;
final String? body;
const MessageError({this.type = '', this.message = '', this.status, this.body});
factory MessageError.fromJson(Map<String, dynamic> j) {
final data = j['data'];
final response = j['response'];
return MessageError(
type: (j['type'] ?? j['name'] ?? '') as String? ?? '',
message: (j['message'] as String?) ??
(data is Map ? data['message'] as String? : null) ??
'',
status: (j['status'] as num?)?.toInt(),
body: response is Map ? response['body'] as String? : null,
);
}
bool get isEmpty => type.isEmpty && message.isEmpty;
}
class Message {
final String id;
final String type;
@@ -171,6 +224,14 @@ class Message {
final String finish;
final double cost;
final TokenUsage? tokens;
/// Set when the step (or compaction) failed.
final MessageError? error;
/// Compaction messages: 'running' | 'completed' | 'failed'.
final String status;
/// Compaction messages: why it ran ('manual' | 'auto').
final String reason;
/// Compaction messages: the summary the model wrote for the new history.
final String summary;
Message({
required this.id,
required this.type,
@@ -184,6 +245,10 @@ class Message {
this.finish = '',
this.cost = 0,
this.tokens,
this.error,
this.status = '',
this.reason = '',
this.summary = '',
});
factory Message.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
@@ -206,6 +271,12 @@ class Message {
finish: j['finish'] as String? ?? '',
cost: (j['cost'] as num?)?.toDouble() ?? 0,
tokens: j['tokens'] == null ? null : TokenUsage.fromJson(j['tokens'] as Map<String, dynamic>),
error: j['error'] == null
? null
: MessageError.fromJson(j['error'] as Map<String, dynamic>),
status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '',
summary: j['summary'] as String? ?? '',
);
}
String get partText {
@@ -262,9 +333,14 @@ class AgentInfo {
final String id;
final String name;
final String mode;
AgentInfo(this.id, this.name, this.mode);
factory AgentInfo.fromJson(Map<String, dynamic> j) =>
AgentInfo(j['id'] as String, j['name'] as String? ?? '', j['mode'] as String? ?? '');
final bool hidden;
AgentInfo(this.id, this.name, this.mode, [this.hidden = false]);
factory AgentInfo.fromJson(Map<String, dynamic> j) => AgentInfo(
j['id'] as String,
j['name'] as String? ?? '',
j['mode'] as String? ?? '',
j['hidden'] as bool? ?? false,
);
}
class PermissionRequest {
+16 -1
View File
@@ -14,15 +14,30 @@ class OpenChamberApp extends StatefulWidget {
State<OpenChamberApp> createState() => _OpenChamberAppState();
}
class _OpenChamberAppState extends State<OpenChamberApp> {
class _OpenChamberAppState extends State<OpenChamberApp>
with WidgetsBindingObserver {
final AppState app = AppState();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
app.init();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The socket often dies while the app sits in the background; nothing
// reports it, so reopen the stream and refresh the open chat on return.
if (state == AppLifecycleState.resumed) app.onResumed();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
+1386 -253
View File
File diff suppressed because it is too large. Load diff
+937
View File
@@ -0,0 +1,937 @@
// The right-side panel: files of the session's directory (browse, preview,
// search, create, download). Project knowledge and the terminal are planned
// and get their places in the tab row already.
import 'dart:convert';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/markdown_view.dart';
Future<void> showFilesPanel(
BuildContext context, AppState app, Session session) {
return showGeneralDialog<void>(
context: context,
barrierDismissible: true,
barrierLabel: '文件',
barrierColor: Colors.black54,
transitionDuration: const Duration(milliseconds: 220),
pageBuilder: (context, _, __) {
final width = MediaQuery.of(context).size.width;
return Align(
alignment: Alignment.centerRight,
child: Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
width: width * 0.92,
height: double.infinity,
child: FilesPanel(app: app, session: session),
),
),
);
},
transitionBuilder: (context, animation, _, child) => SlideTransition(
position: Tween(begin: const Offset(1, 0), end: Offset.zero).animate(
CurvedAnimation(parent: animation, curve: Curves.easeOutCubic)),
child: child,
),
);
}
class FilesPanel extends StatefulWidget {
final AppState app;
final Session session;
const FilesPanel({super.key, required this.app, required this.session});
@override
State<FilesPanel> createState() => _FilesPanelState();
}
const _imageExts = {
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif', 'ico',
};
const _markdownExts = {'md', 'markdown', 'mdx'};
/// Walks skip these: they are huge and never what a phone search wants.
const _skipDirs = {
'.git', 'node_modules', 'build', '.dart_tool', '.gradle', '.idea',
'dist', 'target', 'vendor', 'Pods', '.venv', '__pycache__', '.next',
};
class _FilesPanelState extends State<FilesPanel> {
String get _root => widget.session.directory;
Client? get _client => widget.app.client;
String _path = '';
List<FsEntry> _entries = [];
bool _loading = false;
String? _error;
String _query = '';
/// A project listing hides what git ignores; the menu can show it.
bool _showIgnored = false;
List<FsEntry> _deepResults = [];
bool _deepDone = false;
bool _searching = false;
/// Preview state. `_previewPath == null` shows the browser.
String? _previewPath;
String _previewName = '';
bool _previewLoading = false;
String? _previewError;
Uint8List? _previewBytes;
String? _previewText;
bool _previewBinary = false;
bool _previewImage = false;
bool _editing = false;
bool _saving = false;
final TextEditingController _editor = TextEditingController();
final TextEditingController _search = TextEditingController();
int _tab = 0;
@override
void initState() {
super.initState();
_path = _root;
if (_root.isNotEmpty) _load();
}
@override
void dispose() {
_editor.dispose();
_search.dispose();
super.dispose();
}
// ------------------------------------------------------------- files
Future<void> _load([String? path]) async {
final client = _client;
if (client == null) return;
final target = path ?? _path;
setState(() {
_path = target;
_loading = true;
_error = null;
_previewPath = null;
_deepResults = [];
_deepDone = false;
});
try {
final list = await client
.fsList(target, directory: _root, respectGitignore: !_showIgnored)
..removeWhere((e) => e.name == '.git');
list.sort((a, b) {
if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
if (!mounted) return;
setState(() {
_entries = list;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_loading = false;
_error = e is ApiError ? e.message : '$e';
});
}
}
void _up() {
if (_path == _root) return;
final cut = _path.lastIndexOf('/');
if (cut <= _root.length) {
_load(_root);
} else {
_load(_path.substring(0, cut));
}
}
List<String> get _crumbs {
if (_path == _root) return const [];
final rel = _path.startsWith(_root) ? _path.substring(_root.length) : _path;
return rel.split('/').where((s) => s.isNotEmpty).toList();
}
String get _rootName {
final parts = _root.split('/').where((s) => s.isNotEmpty).toList();
return parts.isEmpty ? _root : parts.last;
}
Future<void> _goToCrumb(int index) async {
final crumbs = _crumbs;
final target = '$_root/${crumbs.take(index + 1).join('/')}';
await _load(target == '$_root/' ? _root : target);
}
Future<void> _deepSearch() async {
final client = _client;
final q = _query.trim().toLowerCase();
if (client == null || q.isEmpty) return;
setState(() {
_searching = true;
_deepResults = [];
_deepDone = false;
});
final found = <FsEntry>[];
final queue = <String>[_path];
var dirs = 0;
while (queue.isNotEmpty && dirs < 400 && found.length < 200) {
if (!mounted) return;
final dir = queue.removeAt(0);
dirs++;
List<FsEntry> list;
try {
list = await client.fsList(dir, directory: _root);
} catch (_) {
continue;
}
for (final e in list) {
if (e.isDirectory) {
if (!_skipDirs.contains(e.name)) queue.add(e.path);
} else if (e.name.toLowerCase().contains(q) && found.length < 200) {
found.add(e);
}
}
if (found.length != _deepResults.length) {
setState(() => _deepResults = List.of(found));
}
}
if (!mounted) return;
setState(() {
_searching = false;
_deepDone = true;
_deepResults = found;
});
}
// ----------------------------------------------------------- preview
Future<void> _openPreview(FsEntry entry) async {
setState(() {
_previewPath = entry.path;
_previewName = entry.name;
_previewLoading = true;
_previewError = null;
_previewBytes = null;
_previewText = null;
_previewBinary = false;
_previewImage = false;
_editing = false;
});
final client = _client;
if (client == null) return;
try {
final stat = await client.fsStat(entry.path, directory: _root);
if (stat != null && stat.size > 2 * 1024 * 1024) {
if (!mounted || _previewPath != entry.path) return;
setState(() {
_previewLoading = false;
_previewError = '文件较大(${_fmtSize(stat.size)}),请下载后查看';
});
return;
}
final bytes =
Uint8List.fromList(await client.rawFile(entry.path, directory: _root));
if (!mounted || _previewPath != entry.path) return;
final image = _imageExts.contains(entry.extension);
final text = image ? null : _decodeText(bytes);
setState(() {
_previewBytes = bytes;
_previewImage = image;
_previewText = text;
_previewBinary = !image && text == null;
_previewLoading = false;
_editor.text = text ?? '';
});
} catch (e) {
if (!mounted || _previewPath != entry.path) return;
setState(() {
_previewLoading = false;
_previewError = e is ApiError ? e.message : '$e';
});
}
}
Future<void> _save() async {
final client = _client;
final path = _previewPath;
if (client == null || path == null) return;
setState(() => _saving = true);
try {
await client.fsWrite(path, _editor.text, directory: _root);
if (!mounted) return;
setState(() {
_saving = false;
_editing = false;
_previewText = _editor.text;
_previewBinary = false;
});
_toast('已保存');
} catch (e) {
if (!mounted) return;
setState(() => _saving = false);
_toast(e is ApiError ? e.message : '$e');
}
}
Future<void> _download() async {
final client = _client;
final path = _previewPath;
if (client == null || path == null) return;
try {
final bytes = _previewBytes ??
Uint8List.fromList(await client.rawFile(path, directory: _root));
final uri = await FilePicker.saveFile(
fileName: _previewName,
bytes: bytes,
);
if (uri != null) _toast('已保存');
} catch (e) {
_toast('下载失败:$e');
}
}
// ---------------------------------------------------------- new file
Future<void> _newEntry({required bool directory}) async {
final client = _client;
if (client == null || _path.isEmpty) return;
final name = await _askName(directory ? '新建文件夹' : '新建文件');
if (name == null) return;
final target = '$_path/$name';
try {
if (directory) {
await client.fsMkdir(target, directory: _root);
} else {
await client.fsWrite(target, '', directory: _root);
}
if (!mounted) return;
await _load();
if (!directory) {
await _openPreview(FsEntry(name: name, path: target));
}
} catch (e) {
_toast(e is ApiError ? e.message : '$e');
}
}
Future<String?> _askName(String title) async {
final controller = TextEditingController();
final name = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: TextField(
controller: controller,
autofocus: true,
decoration: InputDecoration(
labelText: '名称',
hintText: title == '新建文件夹' ? '例如 docs' : '例如 notes.md',
),
onSubmitted: (v) => Navigator.of(context).pop(v),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.of(context).pop(controller.text),
child: const Text('创建')),
],
),
);
controller.dispose();
final trimmed = name?.trim() ?? '';
if (trimmed.isEmpty) return null;
if (trimmed.contains('/') || trimmed.contains('\\')) {
_toast('名称里不能有斜杠');
return null;
}
return trimmed;
}
void _toast(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
// -------------------------------------------------------------- build
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_header(theme),
_tabs(theme),
const Divider(height: 1),
Expanded(child: _body(theme)),
],
),
);
}
Widget _header(ThemeData theme) {
return Padding(
padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
child: Row(
children: [
if (_previewPath != null)
IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: '返回',
onPressed: () => setState(() => _previewPath = null),
)
else
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_previewPath != null ? _previewName : '文件',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600)),
if (_previewPath == null && _root.isNotEmpty)
Text(_rootName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: theme.hintColor)),
],
),
),
if (_previewPath != null) ...[
if (_previewText != null)
IconButton(
icon: Icon(_editing ? Icons.visibility_outlined : Icons.edit_outlined),
tooltip: _editing ? '预览' : '编辑',
onPressed: _saving
? null
: () => setState(() => _editing = !_editing),
),
if (_editing)
IconButton(
icon: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.check),
tooltip: '保存',
onPressed: _saving ? null : _save,
),
IconButton(
icon: const Icon(Icons.download_outlined),
tooltip: '下载',
onPressed: _download,
),
] else if (_root.isNotEmpty) ...[
PopupMenuButton<bool>(
icon: const Icon(Icons.add),
tooltip: '新建',
onSelected: (directory) => _newEntry(directory: directory),
itemBuilder: (_) => const [
PopupMenuItem(value: false, child: Text('新建文件')),
PopupMenuItem(value: true, child: Text('新建文件夹')),
],
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_horiz),
tooltip: '更多',
onSelected: (value) {
if (value == 'ignored') {
setState(() => _showIgnored = !_showIgnored);
_load();
} else if (value == 'refresh') {
_load();
}
},
itemBuilder: (_) => [
CheckedPopupMenuItem(
value: 'ignored',
checked: _showIgnored,
child: const Text('显示被 git 忽略的文件'),
),
const PopupMenuItem(
value: 'refresh',
child: Row(
children: [
Icon(Icons.refresh, size: 18),
SizedBox(width: 10),
Text('刷新'),
],
),
),
],
),
],
IconButton(
icon: const Icon(Icons.close),
tooltip: '关闭',
onPressed: () => Navigator.of(context).maybePop(),
),
],
),
);
}
Widget _tabs(ThemeData theme) {
const labels = ['文件', '项目知识', '终端'];
return Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
child: SegmentedButton<int>(
showSelectedIcon: false,
style: const ButtonStyle(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
segments: [
for (var i = 0; i < labels.length; i++)
ButtonSegment(value: i, label: Text(labels[i])),
],
selected: {_tab},
onSelectionChanged: (v) => setState(() => _tab = v.first),
),
);
}
Widget _body(ThemeData theme) {
if (_root.isEmpty) {
return const Center(child: Text('这个会话没有关联目录'));
}
switch (_tab) {
case 1:
return _placeholder(theme, Icons.menu_book_outlined, '项目知识',
'笔记、待办与计划会在这里。');
case 2:
return _placeholder(
theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。');
default:
if (_previewPath != null) return _previewBody(theme);
return _browser(theme);
}
}
Widget _placeholder(
ThemeData theme, IconData icon, String title, String note) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 40, color: theme.hintColor),
const SizedBox(height: 12),
Text(title,
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 6),
Text(note,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: theme.hintColor)),
const SizedBox(height: 10),
Chip(
label: const Text('即将支持'),
visualDensity: VisualDensity.compact,
side: BorderSide(color: theme.dividerColor),
),
],
),
),
);
}
Widget _browser(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pathBar(theme),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
child: Row(
children: [
Expanded(
child: TextField(
controller: _search,
onChanged: (v) => setState(() {
_query = v;
_deepResults = [];
_deepDone = false;
}),
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search, size: 20),
hintText: '搜索当前目录…',
suffixIcon: _query.trim().isEmpty
? null
: IconButton(
icon: const Icon(Icons.travel_explore, size: 20),
tooltip: '搜索子目录',
onPressed: _searching ? null : _deepSearch,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12)),
contentPadding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
),
),
),
],
),
),
if (_searching)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2)),
const SizedBox(width: 8),
Text('正在搜索子目录…(${_deepResults.length})',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
),
Expanded(child: _list(theme)),
],
);
}
Widget _pathBar(ThemeData theme) {
final crumbs = _crumbs;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 0, 8, 4),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_upward, size: 20),
tooltip: '上一级',
onPressed: _path == _root ? null : _up,
),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
_crumb(theme, _rootName, () => _load(_root), last: crumbs.isEmpty),
for (var i = 0; i < crumbs.length; i++) ...[
Text(' / ', style: TextStyle(color: theme.hintColor)),
_crumb(theme, crumbs[i], () => _goToCrumb(i),
last: i == crumbs.length - 1),
],
],
),
),
),
],
),
);
}
Widget _crumb(ThemeData theme, String text, VoidCallback onTap,
{required bool last}) {
return InkWell(
onTap: last ? null : onTap,
borderRadius: BorderRadius.circular(6),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
child: Text(
text,
style: TextStyle(
fontSize: 13,
color: last ? theme.colorScheme.onSurface : theme.colorScheme.primary,
fontWeight: last ? FontWeight.w600 : FontWeight.w400,
),
),
),
);
}
Widget _list(ThemeData theme) {
if (_loading) return const Center(child: CircularProgressIndicator());
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 8),
TextButton(onPressed: () => _load(), child: const Text('重试')),
],
),
),
);
}
final filtered = _query.trim().isEmpty
? _entries
: _entries
.where((e) =>
e.name.toLowerCase().contains(_query.trim().toLowerCase()))
.toList();
if (filtered.isEmpty && _deepResults.isEmpty) {
return Center(
child: Text(_query.trim().isEmpty ? '目录为空' : '没有匹配的文件',
style: TextStyle(color: theme.hintColor)),
);
}
return ListView(
padding: const EdgeInsets.only(bottom: 16),
children: [
for (final e in filtered) _tile(theme, e),
if (_query.trim().isNotEmpty && _deepResults.isNotEmpty) ...[
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text('子目录结果',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
for (final e in _deepResults) _tile(theme, e, showPath: true),
],
if (_query.trim().isNotEmpty &&
_deepDone &&
_deepResults.isEmpty &&
!_searching &&
filtered.isNotEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Text('子目录里没有匹配的文件',
style: TextStyle(fontSize: 12, color: theme.hintColor)),
),
],
);
}
Widget _tile(ThemeData theme, FsEntry entry, {bool showPath = false}) {
final icon = entry.isDirectory
? Icons.folder_outlined
: _fileIcon(entry.extension);
return ListTile(
dense: true,
leading: Icon(icon,
color: entry.isDirectory
? theme.colorScheme.primary
: theme.colorScheme.onSurfaceVariant),
title: Text(entry.name,
maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 14)),
subtitle: showPath
? Text(_relative(entry.path),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: theme.hintColor))
: null,
trailing: entry.isDirectory
? Icon(Icons.chevron_right, size: 18, color: theme.hintColor)
: null,
onTap: () {
if (entry.isDirectory) {
_load(entry.path);
} else {
_openPreview(entry);
}
},
);
}
String _relative(String path) {
if (path.startsWith(_root)) {
final rel = path.substring(_root.length);
return rel.startsWith('/') ? rel.substring(1) : rel;
}
return path;
}
Widget _previewBody(ThemeData theme) {
if (_previewLoading) {
return const Center(child: CircularProgressIndicator());
}
if (_previewError != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_previewError!, textAlign: TextAlign.center),
const SizedBox(height: 8),
if (_previewBytes != null || _previewError != null)
TextButton(onPressed: _download, child: const Text('下载')),
],
),
),
);
}
if (_previewImage && _previewBytes != null) {
return InteractiveViewer(
maxScale: 6,
child: Center(
child: Image.memory(_previewBytes!, fit: BoxFit.contain),
),
);
}
if (_previewBinary) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.insert_drive_file_outlined,
size: 40, color: theme.hintColor),
const SizedBox(height: 10),
Text('这个文件无法预览',
style: TextStyle(color: theme.hintColor)),
const SizedBox(height: 6),
Text(_fmtSize(_previewBytes?.length ?? 0),
style: TextStyle(fontSize: 12, color: theme.hintColor)),
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: _download,
icon: const Icon(Icons.download_outlined, size: 18),
label: const Text('下载'),
),
],
),
);
}
if (_editing) {
return Padding(
padding: const EdgeInsets.all(12),
child: TextField(
controller: _editor,
maxLines: null,
expands: true,
style: const TextStyle(fontSize: 13, fontFamily: 'monospace', height: 1.4),
textAlignVertical: TextAlignVertical.top,
decoration: InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
contentPadding: const EdgeInsets.all(10),
),
),
);
}
final text = _previewText ?? '';
if (_markdownExts.contains(_fileExt(_previewName))) {
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
child: MarkdownView(text, fontSize: 14),
);
}
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 24),
child: SelectableText(
text,
style: const TextStyle(
fontSize: 12.5, height: 1.45, fontFamily: 'monospace'),
),
);
}
static String _fileExt(String name) {
final dot = name.lastIndexOf('.');
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
}
static IconData _fileIcon(String ext) {
if (_imageExts.contains(ext)) return Icons.image_outlined;
if (_markdownExts.contains(ext)) return Icons.description_outlined;
switch (ext) {
case 'json':
case 'yaml':
case 'yml':
case 'toml':
case 'ini':
case 'conf':
return Icons.tune;
case 'dart':
case 'kt':
case 'java':
case 'js':
case 'ts':
case 'tsx':
case 'jsx':
case 'py':
case 'go':
case 'rs':
case 'c':
case 'h':
case 'cpp':
case 'cc':
case 'hpp':
case 'cs':
case 'swift':
case 'rb':
case 'php':
case 'lua':
return Icons.code;
case 'sh':
case 'bash':
case 'zsh':
case 'fish':
return Icons.terminal;
case 'html':
case 'css':
case 'scss':
case 'less':
case 'xml':
return Icons.web_outlined;
case 'png':
case 'jpg':
case 'jpeg':
case 'gif':
case 'webp':
case 'svg':
return Icons.image_outlined;
case 'pdf':
return Icons.picture_as_pdf_outlined;
case 'zip':
case 'tar':
case 'gz':
case 'tgz':
case 'xz':
case '7z':
return Icons.folder_zip_outlined;
default:
return Icons.insert_drive_file_outlined;
}
}
static String? _decodeText(Uint8List bytes) {
if (bytes.isEmpty) return '';
final n = bytes.length < 8000 ? bytes.length : 8000;
var control = 0;
for (var i = 0; i < n; i++) {
final b = bytes[i];
if (b == 0) return null;
if (b < 8 || (b > 13 && b < 32)) control++;
}
if (control > n * 0.02) return null;
try {
return utf8.decode(bytes);
} catch (_) {
return null;
}
}
static String _fmtSize(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
}
}
+33 -16
View File
@@ -6,7 +6,11 @@ import '../storage.dart';
/// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget {
final AppState app;
const ServersScreen({super.key, required this.app});
/// Open the "add server" form straight away (pushed from the server sheet
/// while a connection is live).
final bool startEditing;
const ServersScreen({super.key, required this.app, this.startEditing = false});
@override
State<ServersScreen> createState() => _ServersScreenState();
@@ -25,6 +29,12 @@ class _ServersScreenState extends State<ServersScreen> {
bool _connecting = false;
String? _formError;
@override
void initState() {
super.initState();
if (widget.startEditing) _editing = true;
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
@@ -92,7 +102,17 @@ class _ServersScreenState extends State<ServersScreen> {
margin: const EdgeInsets.only(bottom: 10),
child: ListTile(
title: Text(c.label, style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
if (c.proxy.isNotEmpty)
Text('经由 ${c.proxy}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -146,6 +166,8 @@ class _ServersScreenState extends State<ServersScreen> {
}
void _startEdit(Connection? c) {
widget.app.error = null;
widget.app.clearLastError();
setState(() {
_editing = true;
_editNew = c == null;
@@ -166,7 +188,11 @@ class _ServersScreenState extends State<ServersScreen> {
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => setState(() => _editing = false),
onPressed: () {
widget.app.error = null;
widget.app.clearLastError();
setState(() => _editing = false);
},
),
title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'),
),
@@ -257,23 +283,14 @@ class _ServersScreenState extends State<ServersScreen> {
insecure: _insecure,
fingerprint: _fingerprint,
);
if (_editNew) {
await widget.app.saveConnection(c);
} else {
final list = [...widget.app.connections];
for (var i = 0; i < list.length; i++) {
if (list[i].id == c.id) {
list[i] = c;
break;
}
}
widget.app.connections = list;
await widget.app.storage.saveConnections(list);
}
// Only a connection that works is saved (AppState saves it on success),
// so failed attempts do not pile up in the server list.
await widget.app.connect(c, password: _password);
if (mounted) {
if (widget.app.client != null) {
setState(() => _editing = false);
// Pushed on top of a live session list: return there.
if (Navigator.of(context).canPop()) Navigator.of(context).pop();
} else {
setState(() {
_connecting = false;
+9 -2
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../api/models.dart';
import '../state.dart';
import 'servers_screen.dart';
import 'chat_screen.dart';
/// The connected screen: the live session list.
@@ -304,7 +305,7 @@ class _SessionsScreenState extends State<SessionsScreen> {
for (final c in app.connections) ...[
ListTile(
title: Text(c.label),
subtitle: Text(c.url),
subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'),
trailing: app.conn?.id == c.id
? Text('已连接', style: TextStyle(color: Theme.of(context).colorScheme.primary))
: null,
@@ -317,7 +318,13 @@ class _SessionsScreenState extends State<SessionsScreen> {
ListTile(
leading: const Icon(Icons.add),
title: const Text('添加服务器'),
onTap: () => Navigator.pop(context),
onTap: () {
Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute(
builder: (_) =>
ServersScreen(app: app, startEditing: true),
));
},
),
if (app.client != null)
ListTile(
+421 -29
View File
@@ -3,6 +3,7 @@
library;
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
@@ -36,6 +37,10 @@ const _eventTypes = [
'session.tool.called',
'session.tool.success',
'session.tool.failed',
'session.compaction.started',
'session.compaction.delta',
'session.compaction.ended',
'session.compaction.failed',
'permission.asked',
'permission.replied',
];
@@ -109,15 +114,37 @@ class AppState extends ChangeNotifier {
_connected(cl, c);
} catch (e) {
busy = false;
error = e.toString();
error = friendlyConnectError(e);
if (!silent) {
// Surface in the form: the UI reads error itself.
_lastError = e.toString();
_lastError = error;
}
notifyListeners();
}
}
/// A short, actionable message for a failed connect.
String friendlyConnectError(Object e) {
if (e is ApiError) return e.message;
if (e is ArgumentError) return e.message?.toString() ?? e.toString();
if (e is TimeoutException) return '连接超时:检查服务器与代理地址';
final s = e.toString();
if (e is SocketException) {
if (s.contains('Connection refused')) {
return '连接被拒绝:服务器或代理未启动,或端口不对';
}
if (s.contains('Failed host lookup') || s.contains('nodename nor servname')) {
return '无法解析地址:检查服务器或代理主机名';
}
if (s.contains('Network is unreachable')) return '网络不可达';
if (s.contains('Connection closed') || s.contains('reset by peer')) {
return '连接被断开:检查代理是否可用';
}
return '网络错误:$s';
}
return s;
}
String? _lastError;
String? get lastError => _lastError;
void clearLastError() => _lastError = null;
@@ -249,20 +276,36 @@ class AppState extends ChangeNotifier {
m.id;
}
StreamSubscription<Map<String, dynamic>>? _events;
int _streamGen = 0;
void _startStream() {
final cl = client;
if (cl == null) return;
final gen = ++_streamGen;
_events?.cancel().ignore();
Future<void> loop() async {
while (client == cl) {
try {
await for (final ev in cl.streamEvents(types: _eventTypes)) {
while (client == cl && gen == _streamGen) {
final done = Completer<void>();
_events = cl.streamEvents(types: _eventTypes).listen(
(ev) {
if (client != cl) return;
// Anything arriving means the stream is back (the server greets
// every connection with `server.connected`), so the "reconnecting"
// banner has done its job.
if (error == '连接中断,正在重连…') error = null;
_applyEvent(ev);
}
} catch (_) {
// Connection dropped; fall through to the retry below.
}
if (client != cl) return;
},
onError: (Object _) {
if (!done.isCompleted) done.complete();
},
onDone: () {
if (!done.isCompleted) done.complete();
},
cancelOnError: true,
);
await done.future;
if (client != cl || gen != _streamGen) return;
error = '连接中断,正在重连…';
notifyListeners();
await Future.delayed(const Duration(seconds: 2));
@@ -271,6 +314,16 @@ class AppState extends ChangeNotifier {
loop();
}
/// Reopens the event stream and refreshes what is on screen. Called when the
/// app comes back to the foreground: a socket that died while the process
/// was in the background never reports it.
Future<void> onResumed() async {
if (client == null) return;
_startStream();
await refreshSessions();
if (chat != null) await chat!.reloadTail();
}
void _applyEvent(Map<String, dynamic> ev) {
final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {};
@@ -434,6 +487,29 @@ class AppState extends ChangeNotifier {
// The open chat.
// ---------------------------------------------------------------------------
/// One entry of the composer's `/` palette: a command registered for the
/// directory, or a skill opencode can attach to a prompt.
class SlashItem {
final String name;
final String description;
final bool skill;
final String id;
/// A command the client runs itself (`compact`), rather than a prompt.
final String action;
const SlashItem({
required this.name,
this.description = '',
this.skill = false,
this.id = '',
this.action = '',
});
/// Commands whose description shows an argument form (`[commit|branch|pr]`)
/// expect one; the palette completes those and runs the rest outright.
bool get takesArgs => description.contains('[');
}
class ChatState extends ChangeNotifier {
final AppState app;
final Session session;
@@ -450,14 +526,17 @@ class ChatState extends ChangeNotifier {
bool hasMore = false;
bool loadingOlder = false;
Map<String, List<String>> imagePaths = {};
final Map<String, String> previewCache = {};
bool previewOpen = false;
String previewTitle = '';
String? previewPath;
bool previewLoading = false;
int previewSeq = 0;
ModelRef? selectedModel;
String selectedAgent;
ChatState(this.app, this.session);
/// `/` palette contents, loaded once per open chat.
List<SlashItem> slashItems = [];
bool slashLoading = false;
bool _slashLoaded = false;
ChatState(this.app, this.session)
: selectedModel = session.model,
selectedAgent = session.agent;
/// Public way to signal UI changes.
void touch() => notifyListeners();
@@ -471,9 +550,13 @@ class ChatState extends ChangeNotifier {
try {
final page = await app.client!.listMessages(id, directory: dir);
_setMessages(page.data);
olderCursor = page.previous;
hasMore = page.previous != null;
// A desc page's `next` cursor points at the older side. The server also
// hands out a cursor for a page that already holds everything, so a
// short page means there is nothing older.
olderCursor = page.next;
hasMore = page.next != null && page.data.length >= _pageSize;
loading = false;
error = null;
notifyListeners();
await reloadTail();
} catch (e) {
@@ -483,14 +566,131 @@ class ChatState extends ChangeNotifier {
}
}
/// Loads the directory's commands and skills for the `/` palette. Called
/// when the palette first opens and before a `/name` send, so a typed
/// command never falls through to the model as plain text.
Future<void> ensureSlash() async {
if (_slashLoaded || slashLoading) return;
final cl = app.client;
if (cl == null) return;
slashLoading = true;
notifyListeners();
try {
final results = await Future.wait([
cl.commands(directory: dir),
cl.skills(directory: dir),
]);
const local = [
SlashItem(
name: 'compact',
description: '使用 AI 压缩会话历史以减少上下文大小',
action: 'compact',
),
];
final localNames = {for (final c in local) c.name};
slashItems = [
...local,
for (final c in results[0])
if ((c['name'] ?? '').isNotEmpty && !localNames.contains(c['name']))
SlashItem(
name: c['name']!,
description: c['description'] ?? '',
),
for (final k in results[1])
if ((k['name'] ?? '').isNotEmpty)
SlashItem(
name: k['name']!,
description: k['description'] ?? '',
skill: true,
id: k['id'] ?? '',
),
];
_slashLoaded = true;
} catch (_) {
// Keep the palette empty; a send falls back to a plain prompt.
}
slashLoading = false;
notifyListeners();
}
SlashItem? slashFor(String text) {
final m = RegExp(r'^/([^\s/]+)').firstMatch(text.trimLeft());
if (m == null) return null;
final name = m.group(1)!;
for (final item in slashItems) {
if (item.name == name) return item;
}
return null;
}
/// A page keeps large tool outputs out (`x-openchamber-part-shells`); the
/// message itself still carries them. Such a part reads as an empty text.
static bool _shelledPart(ContentPart p) =>
p.type == 'tool' &&
(p.state?.metadata?.containsKey('openchamberContentShell') ?? false);
/// The server's copy of a message, except that a tool output already loaded
/// in full is kept: taking the shell back would turn the step's output into
/// "无输出" again on the next tail refresh.
static Message _keepLoadedOutput(Message local, Message server) {
if (!server.content.any(_shelledPart)) return server;
final parts = <ContentPart>[];
for (var i = 0; i < server.content.length; i++) {
final s = server.content[i];
final l = i < local.content.length ? local.content[i] : null;
final loaded = l != null &&
l.type == 'tool' &&
l.id == s.id &&
(l.state?.content.any((c) => c.text.isNotEmpty) ?? false);
parts.add(_shelledPart(s) && loaded ? l : s);
}
return Message(
id: server.id,
type: server.type,
created: server.created,
completed: server.completed,
agent: server.agent,
model: server.model,
content: parts,
text: server.text,
files: server.files,
finish: server.finish,
cost: server.cost,
tokens: server.tokens,
error: server.error,
status: server.status,
reason: server.reason,
summary: server.summary,
);
}
/// Refreshes the newest page without dropping the older pages that were
/// already loaded; the server's copy wins for messages it returns.
Future<void> reloadTail() async {
try {
final page = await app.client!.listMessages(id, directory: dir);
_setMessages(page.data);
if (msgs.isEmpty) {
_setMessages(page.data);
} else {
final fresh = {for (final m in page.data) m.id: m};
final merged = <Message>[
for (final m in msgs)
switch (fresh.remove(m.id)) {
final Message s => _keepLoadedOutput(m, s),
null => m,
},
for (final m in page.data)
if (fresh.containsKey(m.id)) m,
];
msgs = merged;
_sortMsgs();
}
notifyListeners();
} catch (_) {}
}
static const _pageSize = 30;
Future<void> loadOlder() async {
if (!hasMore || loadingOlder) return;
loadingOlder = true;
@@ -501,9 +701,9 @@ class ChatState extends ChangeNotifier {
final seen = msgs.map((m) => m.id).toSet();
final older = page.data.where((m) => !seen.contains(m.id)).toList();
msgs = [...older, ...msgs];
_reindex();
olderCursor = page.previous;
hasMore = page.previous != null;
_sortMsgs();
olderCursor = page.next;
hasMore = page.next != null && page.data.length >= _pageSize;
} catch (_) {}
loadingOlder = false;
notifyListeners();
@@ -511,6 +711,15 @@ class ChatState extends ChangeNotifier {
void _setMessages(List<Message> list) {
msgs = list;
_sortMsgs();
}
/// Oldest first: a page arrives newest-first (order: desc).
void _sortMsgs() {
msgs.sort((a, b) {
if (a.created == b.created) return a.id.compareTo(b.id);
return a.created.compareTo(b.created);
});
_reindex();
}
@@ -521,8 +730,85 @@ class ChatState extends ChangeNotifier {
Future<String?> send({String? text, List<Map<String, String>>? files}) async {
final t = (text ?? draft).trim();
if (t.isEmpty && (files == null || files.isEmpty)) return null;
if (t.startsWith('/')) {
await ensureSlash();
final item = slashFor(t);
if (item != null) {
final args =
(RegExp(r'^/\S+\s*([\s\S]*)$').firstMatch(t)?.group(1) ?? '').trim();
draft = '';
if (item.action == 'compact') {
try {
final cid = await app.client!.compact(this.id, directory: dir);
error = null;
if (cid != null && byId[cid] == null) {
msgs.add(Message(
id: cid,
type: 'compaction',
status: 'running',
reason: 'manual',
created: DateTime.now().millisecondsSinceEpoch,
));
_sortMsgs();
}
notifyListeners();
await reloadTail();
return '';
} catch (e) {
draft = t;
error = e.toString();
notifyListeners();
return null;
}
}
if (!item.skill) {
// A command is expanded by the server, which also writes the user
// message; there is no id to show optimistically.
try {
await app.client!.command(this.id,
name: item.name, text: args, directory: dir, files: files);
error = null;
await reloadTail();
return '';
} catch (e) {
draft = t;
error = e.toString();
notifyListeners();
return null;
}
}
final id = _newMsgId();
msgs.add(Message(
id: id,
type: 'user',
text: t,
created: DateTime.now().millisecondsSinceEpoch,
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
));
_sortMsgs();
notifyListeners();
try {
// The skill is attached by id; the text still names it, as the
// official composer sends it.
await app.client!.prompt(this.id,
text: t, messageId: id, directory: dir, files: files,
skillIds: [item.id]);
error = null;
notifyListeners();
return id;
} catch (e) {
msgs.removeWhere((m) => m.id == id);
_reindex();
draft = t;
error = e.toString();
notifyListeners();
return null;
}
}
}
final id = _newMsgId();
draft = '';
error = null;
msgs.add(Message(
id: id,
type: 'user',
@@ -530,10 +816,14 @@ class ChatState extends ChangeNotifier {
created: DateTime.now().millisecondsSinceEpoch,
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
));
_reindex();
_sortMsgs();
notifyListeners();
try {
await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files);
if (error != null) {
error = null;
notifyListeners();
}
return id;
} catch (e) {
// The prompt did not reach the server: take the optimistic message back
@@ -594,6 +884,8 @@ class ChatState extends ChangeNotifier {
Future<void> switchModel(ModelRef model) async {
try {
await app.client!.switchModel(id, model, directory: dir);
selectedModel = model;
notifyListeners();
} catch (e) {
error = e.toString();
notifyListeners();
@@ -603,6 +895,8 @@ class ChatState extends ChangeNotifier {
Future<void> switchAgent(String agent) async {
try {
await app.client!.switchAgent(id, agent, directory: dir);
selectedAgent = agent;
notifyListeners();
} catch (e) {
error = e.toString();
notifyListeners();
@@ -645,6 +939,9 @@ class ChatState extends ChangeNotifier {
switch (type) {
case 'session.execution.started':
running = true;
// A command's user message is written by the server, and another
// client may have sent it: take the tail from the server.
reloadTail();
break;
case 'session.execution.succeeded':
case 'session.execution.failed':
@@ -671,7 +968,17 @@ class ChatState extends ChangeNotifier {
cost: (data['cost'] as num?)?.toDouble() ?? m.cost,
tokens: data['tokens'] == null
? m.tokens
: TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>)));
: TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>),
error: data['error'] == null
? m.error
: MessageError.fromJson(data['error'] as Map<String, dynamic>),
status: m.status,
reason: m.reason,
summary: m.summary));
// Live events name a tool only by id, so a streamed step would keep
// a generic label ("工具") until the session was reopened. The
// finished message has the names, inputs and attachments.
_refreshMessage(mid);
}
break;
case 'session.text.started':
@@ -696,14 +1003,87 @@ class ChatState extends ChangeNotifier {
case 'session.tool.progress':
if (mid != null) _applyTool(mid, type, data);
break;
case 'session.compaction.started':
final cid = data['inputID'] as String?;
if (cid != null && byId[cid] == null) {
msgs.add(Message(
id: cid,
type: 'compaction',
status: 'running',
reason: data['reason'] as String? ?? '',
created: created,
));
_sortMsgs();
} else if (cid == null) {
reloadTail();
}
break;
case 'session.compaction.delta':
final text = data['text'] as String? ?? '';
if (text.isNotEmpty) {
for (var i = msgs.length - 1; i >= 0; i--) {
final m = msgs[i];
if (m.type == 'compaction' && m.status == 'running') {
msgs[i] = Message(
id: m.id,
type: m.type,
created: m.created,
completed: m.completed,
agent: m.agent,
model: m.model,
content: m.content,
text: m.text,
files: m.files,
finish: m.finish,
cost: m.cost,
tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason,
summary: m.summary + text,
);
_reindex();
break;
}
}
}
break;
case 'session.compaction.ended':
case 'session.compaction.failed':
reloadTail();
break;
case 'session.model.selected':
final model = data['model'];
if (model is Map<String, dynamic>) {
selectedModel = ModelRef.fromJson(model);
}
break;
case 'session.agent.selected':
final agent = data['agent'];
if (agent is String && agent.isNotEmpty) selectedAgent = agent;
break;
}
notifyListeners();
}
/// Swaps a just-finished streamed message for the server's copy.
Future<void> _refreshMessage(String mid) async {
final cl = app.client;
if (cl == null) return;
try {
final m = await cl.getMessage(id, mid, directory: dir);
final i = msgs.indexWhere((x) => x.id == mid);
if (i < 0 || app.client != cl) return;
msgs[i] = m;
_sortMsgs();
notifyListeners();
} catch (_) {}
}
void _ensureAssistant(String id, int created) {
if (byId.containsKey(id)) return;
msgs.add(Message(id: id, type: 'assistant', created: created));
_reindex();
_sortMsgs();
}
void _applyDelta(String mid, int ordinal, String kind, String type, Map<String, dynamic> data) {
@@ -739,7 +1119,11 @@ class ChatState extends ChangeNotifier {
files: m.files,
finish: m.finish,
cost: m.cost,
tokens: m.tokens);
tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason,
summary: m.summary);
});
}
@@ -799,7 +1183,11 @@ class ChatState extends ChangeNotifier {
files: m.files,
finish: m.finish,
cost: m.cost,
tokens: m.tokens);
tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason,
summary: m.summary);
}
}
content.add(part);
@@ -815,7 +1203,11 @@ class ChatState extends ChangeNotifier {
files: m.files,
finish: m.finish,
cost: m.cost,
tokens: m.tokens);
tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason,
summary: m.summary);
});
}
+50
View File
@@ -0,0 +1,50 @@
// The chat's Markdown renderer, shared by message text, thinking blocks,
// compaction summaries and file previews.
import 'package:flutter/material.dart';
import 'package:gpt_markdown/gpt_markdown.dart';
// gpt_markdown renders through its own Material port; its colours come from
// that port's theme, so it has to be handed ours.
import 'package:material_ui/material_ui.dart' as mui;
/// gpt_markdown builds its widgets with `material_ui`, whose `Theme.of` falls
/// back to a light theme: without this the code panel and inline chips stayed
/// light (and their text dark) in the dark theme.
mui.ThemeData markdownThemeData(ThemeData theme) => mui.ThemeData(
useMaterial3: true,
brightness: theme.brightness,
colorScheme: mui.ColorScheme.fromSeed(
seedColor: theme.colorScheme.primary,
brightness: theme.brightness,
),
);
class MarkdownView extends StatelessWidget {
final String text;
final double fontSize;
final Color? color;
/// A little air around headings; messages use the default, thinking blocks
/// and previews a tighter one.
final double height;
const MarkdownView(
this.text, {
super.key,
this.fontSize = 15,
this.color,
this.height = 1.45,
});
@override
Widget build(BuildContext context) {
return mui.Theme(
data: markdownThemeData(Theme.of(context)),
child: GptMarkdown(
text,
// The server already streams deltas; show them as they arrive.
isStreaming: false,
style: TextStyle(fontSize: fontSize, height: height, color: color),
),
);
}
}
+1
View File
@@ -0,0 +1 @@
flutter/ephemeral
+128
View File
@@ -0,0 +1,128 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "openchamber")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "net.blumia.openchamber.openchamber")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the hook/build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
+88
View File
@@ -0,0 +1,88 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
}
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
+25
View File
@@ -0,0 +1,25 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
flutter_secure_storage_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
+26
View File
@@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
+6
View File
@@ -0,0 +1,6 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}
+129
View File
@@ -0,0 +1,129 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
gtk_window_set_default_size(window, 1280, 720);
// If you want to use a header bar, uncomment the following lines.
// Header bars are commonly used in GNOME based desktop environments and
// allow additional widgets to be added to the title bar.
// See https://docs.gtk.org/gtk3/class.HeaderBar.html
// GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
// gtk_widget_show(GTK_WIDGET(header_bar));
// 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");
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#000000");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}
+21
View File
@@ -0,0 +1,21 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
G_DECLARE_FINAL_TYPE(MyApplication,
my_application,
MY,
APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_
+13 -5
View File
@@ -313,18 +313,18 @@ packages:
dependency: transitive
description:
name: jni
sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c"
sha256: "822c3f004742158b80b558773ebed29891f407058d5798992436a68bdf14ccda"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.2"
version: "1.2.0"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
sha256: "586594ad345b403bda8a794b0b8a9e34298238b86c2a7d7f15160b092fe9ef3d"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.4+1"
version: "1.1.0"
jni_util:
dependency: transitive
description:
@@ -446,7 +446,7 @@ packages:
source: hosted
version: "1.1.0"
path_provider:
dependency: "direct main"
dependency: transitive
description:
name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
@@ -594,6 +594,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
socks5_proxy:
dependency: "direct main"
description:
name: socks5_proxy
sha256: a4b95506cbd962fa403e862777432671d36511230c4aedd125a28ddb922e6399
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.2"
source_span:
dependency: transitive
description:
+2 -3
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones."
publish_to: 'none'
version: 0.3.0+300
version: 0.3.9+309
environment:
sdk: ^3.14.0
@@ -14,9 +14,8 @@ dependencies:
shared_preferences: ^2.3.0
flutter_secure_storage: ^11.2.0
file_picker: ^13.0.0
path_provider: ^2.1.0
gpt_markdown: ^1.4.0
socks5_proxy: ^2.1.2
dev_dependencies:
flutter_test:
sdk: flutter
+37
View File
@@ -0,0 +1,37 @@
// Prints live SSE events for a few seconds: their type, session id and the
// keys of their payload. Run against a live server:
// dart run tool/event_probe.dart [seconds]
import 'dart:async';
import 'dart:io';
import 'package:openchamber/api/client.dart';
Future<void> main(List<String> args) async {
final seconds = args.isEmpty ? 20 : int.tryParse(args[0]) ?? 20;
final client = Client(Uri.parse('http://127.0.0.1:3000'));
final seen = <String, int>{};
final sub = client.streamEvents(types: [
'session.created', 'session.renamed', 'session.execution.started',
'session.execution.succeeded', 'session.execution.failed',
'session.execution.interrupted', 'session.step.started',
'session.step.ended', 'session.step.failed', 'session.text.started',
'session.text.delta', 'session.text.ended', 'session.reasoning.started',
'session.reasoning.delta', 'session.reasoning.ended',
'session.tool.called', 'session.tool.success', 'session.tool.failed',
'permission.asked', 'permission.replied',
]).listen((ev) {
final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {};
seen[type] = (seen[type] ?? 0) + 1;
final sid = data['sessionID'] ?? data['sessionId'];
print('$type session=$sid message=${data['assistantMessageID'] ?? data['messageID']} '
'keys=${data.keys.take(6).join(',')}');
}, onError: (Object e) => print('stream error: $e'));
await Future.delayed(Duration(seconds: seconds));
await sub.cancel();
print('----');
print(seen);
client.close();
exit(0);
}
+65
View File
@@ -0,0 +1,65 @@
// Pages a session's history exactly as ChatState does, and reports whether
// every message is reached. Run against a live server:
// dart run tool/history_probe.dart <sessionId> [directory]
import 'dart:io';
import 'package:openchamber/api/client.dart';
Future<void> main(List<String> args) async {
final id = args.isEmpty ? '' : args[0];
final dir = args.length > 1
? args[1]
: Directory.current.path;
if (id.isEmpty) {
print('usage: dart run tool/history_probe.dart <sessionId> [directory]');
exit(2);
}
final client = Client(Uri.parse('http://127.0.0.1:3000'));
// 1. What ChatState loads first, then each "load earlier" page.
final first = await client.listMessages(id, limit: 30, directory: dir);
final seen = <String>{for (final m in first.data) m.id};
print('page 1: ${first.data.length} msgs next=${first.next != null}');
var cursor = first.next;
var page = 2;
var oldest = 0;
while (cursor != null && page <= 200) {
final p = await client.listMessages(id,
limit: 30, cursor: cursor, directory: dir);
if (p.data.isEmpty) {
print('page $page: empty (cursor exhausted)');
break;
}
final added = p.data.where((m) => seen.add(m.id)).length;
oldest = p.data
.map((m) => m.created)
.reduce((a, b) => a < b ? a : b);
print('page $page: ${p.data.length} msgs (+$added new, '
'oldest=${DateTime.fromMillisecondsSinceEpoch(oldest)})');
cursor = p.next;
page++;
if (added == 0) {
print('no progress at page $page: stopping');
break;
}
}
// 2. The full list, for comparison.
final all = <String>{};
var c = null as String?;
do {
final p = await client.listMessages(id,
limit: 200, cursor: c, directory: dir);
all.addAll(p.data.map((m) => m.id));
c = p.next;
} while (c != null);
print('----');
print('paged: ${seen.length} unique messages');
print('total: ${all.length} messages');
print('missing: ${all.difference(seen).length}');
final missing = all.difference(seen);
if (missing.isNotEmpty) print('first missing: ${missing.take(3).join(', ')}');
client.close();
exit(0);
}
+61
View File
@@ -0,0 +1,61 @@
// Creates a throwaway session, prompts it, and prints the live events for it:
// type, session id, assistant message id and payload keys. This is how the
// chat's streaming path is checked against a real server.
// dart run tool/live_probe.dart [seconds]
import 'dart:async';
import 'dart:io';
import 'package:openchamber/api/client.dart';
const types = [
'session.created', 'session.renamed', 'session.execution.started',
'session.execution.succeeded', 'session.execution.failed',
'session.execution.interrupted', 'session.step.started',
'session.step.ended', 'session.step.failed', 'session.text.started',
'session.text.delta', 'session.text.ended', 'session.reasoning.started',
'session.reasoning.delta', 'session.reasoning.ended',
'session.tool.called', 'session.tool.success', 'session.tool.failed',
'permission.asked', 'permission.replied',
];
Future<void> main(List<String> args) async {
final seconds = args.isEmpty ? 40 : int.tryParse(args[0]) ?? 40;
final dir = Directory.current.path;
final client = Client(Uri.parse('http://127.0.0.1:3000'));
final session = await client.createSession(title: 'event probe', directory: dir);
print('session ${session.id}');
final counts = <String, int>{};
final sub = client.streamEvents(types: types).listen((ev) {
final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {};
final sid = data['sessionID'];
if (sid != session.id) return;
counts[type] = (counts[type] ?? 0) + 1;
print('$type msg=${data['assistantMessageID'] ?? data['messageID']} '
'part=${data['partID']} keys=${data.keys.join(',')}');
}, onError: (Object e) => print('stream error: $e'));
await Future.delayed(const Duration(milliseconds: 500));
await client.prompt(session.id,
text: args.length > 1
? args.sublist(1).join(' ')
: 'Reply with the single word: pong',
directory: dir);
print('prompted');
await Future.delayed(Duration(seconds: seconds));
await sub.cancel();
final page = await client.listMessages(session.id, limit: 50, directory: dir);
print('---- messages: ${page.data.length}');
for (final m in page.data.reversed) {
final parts = m.content.map((p) => '${p.type}${p.name == null ? '' : '(${p.name})'}').join(',');
print('${m.id} ${m.type} parts=[$parts]');
}
print('---- event counts: $counts');
await client.deleteSession(session.id);
client.close();
exit(0);
}
+73
View File
@@ -0,0 +1,73 @@
// A probe for the Dart client's proxy support, run with:
// dart run tool/proxy_probe.dart
// It talks to a local OpenChamber server directly and through the local
// SOCKS5 (1080) and HTTP (8081) test proxies.
import 'dart:io';
import 'package:openchamber/api/client.dart';
Future<void> probe(String? proxy) async {
final label = proxy ?? 'direct';
final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy);
final sw = Stopwatch()..start();
try {
final status = await client.sessionStatus().timeout(const Duration(seconds: 15));
final page = await client
.listSessions(limit: 3)
.timeout(const Duration(seconds: 15));
print('OK $label auth=${status['authenticated']} '
'sessions=${page.data.length} ${sw.elapsedMilliseconds}ms');
} on Object catch (e) {
print('FAIL $label ${e.toString().split('\n').first}');
} finally {
client.close();
}
}
Future<void> probeRaw(String? proxy) async {
final label = proxy ?? 'direct';
final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy);
try {
final bytes = await client
.rawFile(
'/home/blumia/Sources/openchamber-android-native/resources/icon.png',
directory: '/home/blumia/Sources/openchamber-android-native',
)
.timeout(const Duration(seconds: 15));
print('OK raw $label bytes=${bytes.length}');
} on Object catch (e) {
print('FAIL raw $label ${e.toString().split('\n').first}');
} finally {
client.close();
}
}
Future<void> probeStream(String? proxy) async {
final label = proxy ?? 'direct';
final client = Client(Uri.parse('http://127.0.0.1:3000'), proxy: proxy);
try {
final ev = await client
.streamEvents(types: ['session.execution.started'])
.first
.timeout(const Duration(seconds: 10));
print('OK sse $label ${ev['type']}');
} on Object catch (e) {
print('FAIL sse $label ${e.toString().split('\n').first}');
} finally {
client.close();
}
}
Future<void> main() async {
await probe(null);
await probe('socks5://127.0.0.1:1080');
await probe('socks5h://127.0.0.1:1080');
await probe('http://127.0.0.1:8081');
await probe('socks5://127.0.0.1:1');
await probeStream('socks5://127.0.0.1:1080');
await probeStream('http://127.0.0.1:8081');
await probeRaw(null);
await probeRaw('socks5://127.0.0.1:1080');
await probeRaw('http://127.0.0.1:8081');
exit(0);
}
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Tiny SOCKS5 (1080) and HTTP CONNECT/absolute-URI (8081) proxies for the
proxy verification. No auth, TCP only.
"""
import select
import socket
import struct
import threading
def recv_exact(conn, n):
buf = b''
while len(buf) < n:
d = conn.recv(n - len(buf))
if not d:
raise ConnectionError('closed')
buf += d
return buf
def pump(a, b):
try:
while True:
r, _, _ = select.select([a, b], [], [], 300)
if not r:
continue
for s in r:
data = s.recv(65536)
if not data:
return
(b if s is a else a).sendall(data)
except OSError:
pass
finally:
for s in (a, b):
try:
s.close()
except OSError:
pass
def socks_conn(conn):
try:
ver, n = recv_exact(conn, 2)
recv_exact(conn, n)
conn.sendall(bytes([5, 0]))
ver, cmd, rsv, atyp = recv_exact(conn, 4)
if atyp == 1:
addr = socket.inet_ntoa(recv_exact(conn, 4))
elif atyp == 3:
ln = recv_exact(conn, 1)[0]
addr = recv_exact(conn, ln).decode()
elif atyp == 4:
addr = socket.inet_ntop(socket.AF_INET6, recv_exact(conn, 16))
else:
raise ValueError('atyp')
port = struct.unpack('!H', recv_exact(conn, 2))[0]
print(f'socks CONNECT {addr}:{port}', flush=True)
remote = socket.create_connection((addr, port), timeout=15)
conn.sendall(bytes([5, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
pump(conn, remote)
except Exception as e: # noqa: BLE001
print('socks error', e, flush=True)
conn.close()
def http_conn(conn):
try:
buf = b''
while b'\r\n\r\n' not in buf:
d = conn.recv(65536)
if not d:
return
buf += d
head, rest = buf.split(b'\r\n\r\n', 1)
lines = head.split(b'\r\n')
method, target, version = lines[0].split(b' ')
if method == b'CONNECT':
host, _, port = target.decode().partition(':')
remote = socket.create_connection((host, int(port or 443)), timeout=15)
conn.sendall(b'HTTP/1.1 200 Connection Established\r\n\r\n')
if rest:
remote.sendall(rest)
print(f'http CONNECT {host}:{port}', flush=True)
pump(conn, remote)
return
if not target.startswith(b'http://'):
conn.sendall(b'HTTP/1.1 400 Bad Request\r\n\r\n')
conn.close()
return
rest_of_url = target[len(b'http://'):]
hostport, _, path = rest_of_url.partition(b'/')
host, _, port = hostport.partition(b':')
port = int(port or b'80')
hdrs = [l for l in lines[1:]
if not l.lower().startswith(b'proxy-') and not l.lower().startswith(b'connection:')]
clen = 0
for l in hdrs:
if l.lower().startswith(b'content-length:'):
clen = int(l.split(b':', 1)[1].strip())
body = rest
while len(body) < clen:
d = conn.recv(65536)
if not d:
break
body += d
request = b' '.join([method, b'/' + path, version]) + b'\r\n' + \
b'\r\n'.join(hdrs) + b'\r\nConnection: close\r\n\r\n' + body[:clen]
remote = socket.create_connection((host.decode(), port), timeout=15)
remote.sendall(request)
print(f'http {method.decode()} {host.decode()}:{port}/{path.decode(errors="replace")}', flush=True)
pump(conn, remote)
except Exception as e: # noqa: BLE001
print('http error', e, flush=True)
conn.close()
def serve(port, handler):
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('127.0.0.1', port))
srv.listen(64)
print(f'listening on 127.0.0.1:{port}', flush=True)
while True:
conn, _ = srv.accept()
threading.Thread(target=handler, args=(conn,), daemon=True).start()
threading.Thread(target=serve, args=(1080, socks_conn), daemon=True).start()
threading.Thread(target=serve, args=(8081, http_conn), daemon=True).start()
threading.Event().wait()