Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cecf5517a5 | ||
|
|
4bd9256ef8 | ||
|
|
b372bce63f | ||
|
|
695d27cdd7 | ||
|
|
318276d3b9 | ||
|
|
ce944751b4 | ||
|
|
fedc4dd79c | ||
|
|
c2dabbe187 | ||
|
|
9ae1e9b97a | ||
|
|
ba3c820186 | ||
|
|
8ac36b1fb1 | ||
|
|
83e09e8e25 | ||
|
|
a7e4ed8dd7 | ||
|
|
c6b5a870c6 | ||
|
|
bd8afeb686 | ||
|
|
2e0308f232 | ||
|
|
b65498d73e | ||
|
|
a70e9290ef | ||
|
|
545778c6f3 | ||
|
|
511c3b006b | ||
|
|
7b5bccf28f | ||
|
|
da4bfb6826 | ||
|
|
2f5ce61692 | ||
|
|
2185054aab | ||
|
|
00564fe94b | ||
|
|
9564019a91 | ||
|
|
c4de5e84d8 | ||
|
|
809e0a747a | ||
|
|
5c0ea6f6f4 | ||
|
|
d533bc95ef | ||
|
|
0f850b6191 | ||
|
|
9cbd97d532 | ||
|
|
cebf09048e | ||
|
|
79221e57d7 | ||
|
|
91bf5e5b81 | ||
|
|
8f6fd99103 | ||
|
|
902f1e18bb | ||
|
|
a7bc380ac0 | ||
|
|
675d19d563 | ||
|
|
d25167de58 | ||
|
|
d72af036a1 | ||
|
|
ff0dbf1b37 | ||
|
|
73af9d851b | ||
|
|
6ced914757 | ||
|
|
d9d5424318 | ||
|
|
e646130d1f | ||
|
|
1aa84a53e5 | ||
|
|
ea3b1f0f5e | ||
|
|
7f2f454539 | ||
|
|
fff6562cbc | ||
|
|
5a371e4faf | ||
|
|
5f95e2da97 | ||
|
|
60d02083d3 |
No files matched your search
@@ -5,6 +5,617 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 0.7.4 已知项目只算 OpenChamber 的项目列表(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 列表 | 0.7.3 用 `app.projects` 做过滤,但这个列表同时包含 OpenCode 发现的所有目录(`~/.config/pitchfork`、`~/Downloads` 等),所以那些端口仍被当成「已知项目」显示。现在只把带 OpenChamber 设置记录的项目(`metaId` 非空)加上当前项目当作已知工作区,和网页端的项目列表一致;没有目录的 announced 端口(9090)仍显示。手机列表恢复为网页端看到的 8080、9090 |
|
||||||
|
| 版本 | **0.7.4(code 704)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.7.3 开发服务器列表与网页端同一套过滤(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 列表 | 0.7.2 放开了项目目录过滤,结果把 `~/.config/pitchfork`、`~/Downloads` 等不在项目列表里的端口也列了出来(手机 7 个,网页只有 2 个)。现在按网页端的规则:只列出「返回了网页」且目录属于已知项目(含当前目录)或没有目录(announced)的端口;不在任何项目里的端口像网页端一样隐藏在「显示已隐藏端口」之后。Telegram 的 8080 属于已知项目、9090 没有目录,两者都会显示 |
|
||||||
|
| 版本 | **0.7.3(code 703)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.7.2 开发服务器列表改为全机器范围(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 列表 | 网页端的「正在运行的开发服务器」是整台宿主机的列表,不按当前项目过滤;手机端之前多了一层「当前项目目录」过滤,导致 `telegram-antispam-bot` 的 8080 在手机上不显示。现在同样列出服务端发现的所有「返回了网页」的端口(无页面的 adb/模拟器端口仍隐藏),与网页端一致 |
|
||||||
|
| 版本 | **0.7.2(code 702)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.7.1 浏览器通过服务端 dev tunnel 预览(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 网络 | 不再是手机本机网络:`localhost` / `127.0.0.1` 地址改为在手机本地绑定一个随机端口的 TCP 监听器,每条连接通过 Relay/直连的 WebSocket 连到服务端 `/api/dev-tunnel?port=…&oc_url_token=…`,由服务端连接它自己 loopback 上的 dev server;页面 origin 是本地监听器,绝对路径、Cookie、HMR WebSocket 都按这个 origin 工作 |
|
||||||
|
| dev server 列表 | 从 `/api/dev-servers` 读取服务端发现且返回了网页的项目 dev server(按当前项目目录过滤,过滤掉 adb/模拟器等没有页面的端口);空状态列出标题 / URL / 命令,点击即可预览;也可以手动输入 URL |
|
||||||
|
| 地址栏 | 显示原始 `http://localhost:端口/...`,内部加载本地隧道地址;页面里的同源链接会重写到隧道,跳到另一个 loopback 端口会为新端口开隧道;历史记录保存原始地址 |
|
||||||
|
| 鉴权 | Relay 由 `RelayTransport` 自动 mint `oc_url_token`;直连时客户端 `POST /auth/url-token` 取短期 token 并缓存,WebSocket 同时带 bearer;服务端仍只允许它发现列表里的端口 |
|
||||||
|
| 版本 | **0.7.1(code 701)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.7.0 浏览器地址栏菜单与网络说明(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 地址栏 | 后退 / 前进 / 在系统浏览器中打开 / 历史记录收进右上角「三个点」菜单;历史记录是二级菜单(最近 20 条,空时显示「暂无历史记录」)。地址栏只保留网址输入、停止/刷新和菜单,手机宽度下输入区明显变宽 |
|
||||||
|
| 网络 | 嵌入式 WebView 运行在**手机本机**,`localhost` 是手机而不是 OpenChamber 服务端;OpenChamber 网页端的浏览器面板同样在客户端渲染,服务端没有通用 URL 代理。空状态明确提示:要预览 OpenChamber 主机上的开发服务器,请输入主机的局域网地址(或让服务监听 0.0.0.0) |
|
||||||
|
| 版本 | **0.7.0(code 700)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.7 右侧栏浏览器与图标标签(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 浏览器 | 右侧栏新增【浏览器】页:地址栏(后退 / 前进 / 输入网址 / 前进按钮 / 停止或刷新)、历史记录、在系统浏览器中打开;空状态提供 `localhost:3000`、`5173`、`8080` 快捷入口;页面用嵌入式 WebView 打开(Android/iOS),桌面显示仅移动端可用的提示 |
|
||||||
|
| 地址栏 | 自动补 `http://`(localhost/回环地址)或 `https://`,加载错误时显示错误条和重试;地址字段把光标放在末尾,窄栏也能看到刚访问的部分 |
|
||||||
|
| 标签 | 右侧栏顶部由文字标签改为**图标 + tooltip**(文件、项目知识、终端、浏览器),项目多/栏窄时不再截断文字;四个页签用懒加载的 Offstage 栈保持各自状态(浏览器页面切走再切回不会重新加载) |
|
||||||
|
| 明文 | Android 允许 WebView 加载 HTTP(`usesCleartextTraffic`),本地开发服务器可直接预览 |
|
||||||
|
| 版本 | **0.6.7(code 607)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.6 图片查看器:保存/分享与隐藏顶栏(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 保存/分享 | 查看器右上角新增保存到相册、分享(Android):保存通过 MediaStore 写入 `Pictures/Chamber Go`(Android 10+ 无需权限,旧版本按需申请存储权限),分享用 FileProvider 生成临时文件并打开系统分享面板;非 Android 平台不显示这两个按钮 |
|
||||||
|
| 顶栏 | dsh-Go 的查看器顶栏(返回、文件名)是**始终显示**的;按你的建议,我们改为单指点击图片切换顶栏和底部页码的显示/隐藏,再点一次恢复,避免标题和按钮挡住图片;双击仍用于 2.5 倍缩放,未放大时左右滑动翻页,放大后单指拖动平移 |
|
||||||
|
| 版本 | **0.6.6(code 606)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.5 会话图片全屏查看(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 查看器 | 会话内图片(用户附件、工具生成/读取的图片、生成图片)从对话框改为全屏查看:黑底、返回 + 标题 + 页码;双指缩放最大 8 倍,双击在 2.5 倍与原始大小间切换,缩放后可单指拖动查看局部;多张图片可左右滑动 |
|
||||||
|
| 翻页与拖动 | 未缩放时单指左右滑动翻页;一旦放大,单指拖动用于平移图片,翻页被禁用,缩回原始大小后恢复翻页 |
|
||||||
|
| 参考 | dsh-Go 的图片查看器就是这种相册式行为(`ImageViewerPage` + `ImagePager` + `ZoomableImage`:双指 8 倍、双击 2.5 倍、缩放时禁用翻页),本次按同样的交互实现 |
|
||||||
|
| 版本 | **0.6.5(code 605)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.4 Relay 错误横幅在后台恢复后不消失(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 原因 | 从后台恢复时,Relay 隧道第一次请求可能因 DNS/网络尚未就绪失败,`refreshSessions` 把「无法连接 Relay…」写进 `AppState.error`;后续会话列表或事件流成功后没有清除它(事件流只清除固定的「Connection lost, reconnecting…」文案)。侧栏的「重试」只调用 `refreshSessions`,成功也不清错误,所以看起来没有反应,尽管会话、文件和实时更新都已恢复 |
|
||||||
|
| 修复 | 区分传输错误与会话操作错误:会话列表、搜索、加载更多、归档、活动状态、权限、聊天设置、项目、文件主页、模型等任一成功请求,以及事件流恢复后的任意事件,都会清除传输错误;置顶/归档等动作错误不会被例行刷新清掉。侧栏「重试」改为 `retryConnection()`:没有客户端时重连已保存的连接,否则重新拉取会话列表并清掉过期的传输错误 |
|
||||||
|
| 版本 | **0.6.4(code 604)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.3 文件侧栏的 gitignore 开关改用服务端值(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 服务端存储 | OpenChamber 的设置文档里有 `filesViewShowGitignored`(profile scope,网页端也用它),没有该键时默认不显示被 git 忽略的文件。客户端现在从 `/api/config/settings` 读取它,不再写死本地默认值 |
|
||||||
|
| 切换 | 文件侧栏的【显示被 git 忽略的文件】勾选/取消勾选后立即刷新列表,并通过 `PUT /api/config/settings` 写回服务端(`surface=mobile`);保存失败时恢复原值并显示错误 |
|
||||||
|
| 同步 | 侧栏打开期间如果服务端值变化(例如网页端改了同一设置),监听 `AppState` 后按新值重新加载列表 |
|
||||||
|
| 版本 | **0.6.3(code 603)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.2 归档选择器只列有归档的项目(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 筛选范围 | 归档页打开的项目选择器只列出**实际有已归档会话**的项目(按名字排序),不再显示全部项目;同时隐藏「添加项目」按钮(归档页不会新增归档,添加项目在此无意义)。聊天归档仍通过「聊天」行进入 |
|
||||||
|
| 版本 | **0.6.2(code 602)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.1 归档筛选改用共享项目选择器(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 项目筛选 | 归档页顶部原来的横向项目 chips 改为与新建会话 / 计划任务 / 统计一致的项目选择行:点击打开共享项目 bottomsheet(含「所有项目」「聊天」与全部项目、图标、路径、当前选中标记),选完立即筛选归档列表;项目很多时不会再横向挤在一起 |
|
||||||
|
| 选择器搜索 | 共享项目 bottomsheet 新增搜索框,按项目名或路径过滤,项目很多时也能快速定位;无匹配时显示「没有匹配的项目」 |
|
||||||
|
| 版本 | **0.6.1(code 601)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.6.0 归档页面(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 归档页面 | 全部功能新增【归档】:标题下显示已归档会话数量,支持按标题 / 会话 ID / 项目名搜索,顶部按项目分组的 chips 可筛选(全部 + 各项目及数量),点击行打开会话,行尾可取消归档(恢复)或打开菜单(打开 / 取消归档 / 复制会话 ID / 删除)。页面参考 OpenChamber 手机端归档页 |
|
||||||
|
| 侧栏 | 去掉【显示已归档】按钮和侧栏里的归档列表;侧栏只保留活动会话,归档统一从【全部功能 → 归档】进入 |
|
||||||
|
| 列表 | 归档会话按归档时间(缺失时按更新时间)倒序;项目分组按最近归档时间排序;取消归档后该行从归档页移回侧栏的活动列表 |
|
||||||
|
| 版本 | **0.6.0(code 600)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.7 添加项目与上下文环回退(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 添加项目 | 项目选择器右上角新增【添加项目】:从服务器用户主目录开始浏览文件夹(可输入路径、上一级、新建文件夹),选中后写入 OpenChamber 项目列表并立即作为当前目标;新建会话、计划任务、统计的项目列表共享同一入口 |
|
||||||
|
| 项目列表 | `/api/project` 只在项目里有会话后才返回该项;`refreshProjects` 现在合并设置文档里的项目(按 `addedAt` 新的在前),所以刚添加、还没有会话的项目也能在选择器里出现 |
|
||||||
|
| 上下文环 | 旧会话的模型可能已从服务器模型目录移除,`usageReading` 找不到上下文窗口时不再隐藏输入框底部的环:按 200K 窗口估算并显示 `~百分比`;用量弹层注明「该模型不在模型目录中,上下文窗口为估算值」 |
|
||||||
|
| 版本 | **0.5.7(code 507)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.6 统计页面与 Chamber Go(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 统计 | 全部功能里新增【统计】:时间范围(今天 / 7 天 / 30 天 / 90 天 / 全部)、项目筛选(所有项目或某个检出)、会话 / 提示词 / 令牌 / 费用 / 活跃天数 / 连续天数、每日(超过 92 天按周)活动柱状图、令牌构成、效率指标、模型排行(按令牌 / 费用 / 步数)、按需加载的工具调用统计(调用次数、成功率、失败、中位耗时)。数据来自 `/api/experimental/session/stats`;时区取设备的 IANA 名称(Android 平台通道,桌面回退 UTC) |
|
||||||
|
| 命名 | 客户端显示名改为 **Chamber Go**(Android 启动器、iOS、Linux 窗口、关于页),包名不变。配对兑换上报的 `clientLabel` / `deviceName`、登录标签与请求 user-agent(`chamber-go/<版本>`)一并改名 |
|
||||||
|
| 名称来源 | 网页端「连接到此服务器」列表显示服务器保存的 client label:操作员建配对链接时填的名字优先;否则沿用同设备(dedupeKey)已有的名字;第一次配对且都没填时才用客户端自报的 `clientLabel` / `deviceName`。因此老设备改名后仍显示旧名,要在列表里重命名,或撤销后重新配对 |
|
||||||
|
| 版本 | **0.5.6(code 506)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.5 项目选择与计划任务运行位置(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 空白选项 | 服务器会把根目录 `/` 也列成一个项目;`pathLeaf('/')` 取最后一段时得到空串,标签就成了空白。根路径现在用自己的路径作名称(`/`);同一个 checkout 被服务器列两次(项目记录 + sandbox)时也合并成一行 |
|
||||||
|
| 新建会话 | 点项目名不再先等项目接口:bottomsheet 立即弹出,列表为空时显示「正在加载项目…」,刷新完成(或已有缓存)后展示列表;确实没有项目时显示「没有可用的项目」 |
|
||||||
|
| 计划任务 | 运行位置改用与新建会话相同的项目 bottomsheet(含「聊天」scope、图标、路径与当前选中标记),不再用长列表下拉框 |
|
||||||
|
| 版本 | **0.5.5(code 505)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.4 文件下载进度(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 进度 | 下载对话框的进度条改为确定进度:用 `fs/stat` 取到的文件大小当总量,服务器给出 `Content-Length` 时以服务器为准;显示「已下载 / 总大小 (百分比)」。Relay 把响应体按 chunked 转发、不带 `Content-Length` 时也能看到百分比 |
|
||||||
|
| 取消 | 取消仍然中断请求并丢弃已下载的数据;完全没有大小信息时保持不确定进度条,并显示已下载字节数 |
|
||||||
|
| 版本 | **0.5.4(code 504)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.3 英文为源、按范围选择文本(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 语言 | 默认跟随系统(中文系统用中文,其它语言用英文),可在 设置 → 常规 → 语言 里固定「中文 / English」;选择保存在本机,启动时先读取再出第一帧,系统语言变化时「跟随系统」会立即重绘 |
|
||||||
|
| 文案 | 代码里直接写英文;`tr()` / `trArgs()` 查中文表 `lib/l10n/zh.dart`,`AppText` 同理。没有对应表的语言(西班牙语等)按英文显示,缺条目也回退英文,不会出现空文案。服务器与用户数据(会话标题、消息、任务名、文件内容等)用 `Text` 原样显示 |
|
||||||
|
| 系统组件 | 接入 `flutter_localizations`,日期/时间选择器、文本选择菜单等系统文案随语言切换 |
|
||||||
|
| 选择文本 | 只有会话内容可选中:消息气泡、回答正文、展开后的工具调用详情(命令/参数/输出)、一轮结束后的「模型 · 模式 · 耗时」行。未展开的工具调用行与「已完成 · X 次工具调用」等状态提示不可选中 |
|
||||||
|
| 会话同步 | 事件流断开期间开始的回合,其开始事件收不到:收到未知助手消息的事件时先拉取一次尾部,补齐用户消息与完整答复,而不是只拼出后续增量 |
|
||||||
|
| 测试 | `test/l10n_test.dart`:中文查表与回退、无表的系统语言读英文、`AppText` 跟随语言、代码里每处 `AppText`/`tr`/`trArgs` 字面量都有中文条目 |
|
||||||
|
| 验证 | 模拟器:系统英文 → 全英文;切中文后整页与系统时间选择器立即变中文,重启保持;切回「跟随系统」;中文与英文下逐页检查;长按消息文本出现选择菜单,长按未展开的工具行与状态提示不再触发选择;断网重连后从网页端继续会话,手机端自动补齐新回合 |
|
||||||
|
| 版本 | **0.5.3(code 503)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.2 中英双语与长按选择文本(分支 `flutter`,已被 0.5.3 调整)
|
||||||
|
|
||||||
|
- 初版:界面文案以中文写在代码里、查英文表;会话消息区整体包进 `SelectionArea`,长按任意位置都能选文本;接入 `flutter_localizations`。
|
||||||
|
- 0.5.3 起改为英文为源、按范围选择文本,见上。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.1 计划任务与「全部功能」入口(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 入口 | 侧栏底部、设置按钮左侧新增「全部功能」按钮,打开一个功能页;目前里面只有【计划任务】一张卡片(图标 + 一句说明) |
|
||||||
|
| 计划任务 | 对照网页端:顶部选择运行位置(已注册项目 + 「聊天」scope,默认取当前会话所在项目),下面列出该项目的任务。每张卡片显示名称、计划、上次运行/状态、下次运行、模型行与错误;开关直接暂停/启用,菜单里可立即运行、编辑、删除;下拉刷新 |
|
||||||
|
| 编辑器 | 底部弹层:任务名称(≤80)、提示词(≤20000)、计划类型(每天 / 每周 / 一次性 / Cron)、时间点(可加多个)、星期、日期与时间(中文的日期/时间选择器)、Cron 示例、是否启用;默认「使用默认模型与智能体」,关闭后可选模型(复用模型选择器)与智能体 |
|
||||||
|
| 接口 | `GET/PUT /api/projects/:id/scheduled-tasks`、`DELETE …/:taskId`、`POST …/:taskId/run`,与网页端同一份数据;`openchamber:chats` 作为聊天 scope;服务器没有该接口(404)时页面写明「服务器不支持计划任务」。时间按服务器时区 |
|
||||||
|
| 中文化 | 应用整体指定中文(`flutter_localizations`),系统自带的日期/时间选择器、文本选择菜单随之是中文 |
|
||||||
|
| 测试 | 新增 `test/scheduled_tasks_test.dart`:四种计划的解析与展示文案、保存时只带该类型用到的字段、默认模型判断、状态与相对时间、功能页入口、编辑器的必填校验与草稿;`sidebar_footer_test` 覆盖新按钮;95 项全过 |
|
||||||
|
| 验证 | 模拟器(真实服务端):侧栏「全部功能」→ 计划任务;默认运行位置取当前会话所在项目(聊天目录与 chats 根不出现在项目列表里,统一归到末尾的「聊天」scope)。新建「Daily time report」(每天 09:00)后列表显示「下次:8 小时 45 分钟后」;「立即运行」→ 服务端 `lastStatus: sent` 并新建一个 scheduled 会话,卡片显示「上次运行 00:16 · 成功」;编辑弹层带出原值;关掉开关变「已暂停」;删除 → 确认 → 列表为空、服务端任务为空(运行产生的会话也已删除);切到「聊天」scope 正常加载 |
|
||||||
|
| 版本 | **0.5.1(code 501)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.5.0 设置「常规」分组与「通用」页(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 分组 | 原来的【通用】分组改名【常规】,其下第一项新增【通用】页(智能体工具与记忆),第二项仍是【聊天】 |
|
||||||
|
| 通用页 | 对照网页端的「通用」页补齐:**在聊天中** —— 图表和原型、图像(开启时可选图像模型)、密钥、通知;**智能体知道的内容** —— 记忆(服务端支持时才出现;开启时带「整理记忆」勾选、模型与思考级别)、项目知识、用量限额。每项都有与网页端一致的一句说明 |
|
||||||
|
| 数据 | 全部走 `/api/config/settings?surface=mobile`,与网页端读写同一份设置;服务器未返回的键用网页端的默认值(图表/密钥/项目知识默认开,图像/通知/记忆/用量/整理记忆默认关),保存后以服务器返回的设置回填 |
|
||||||
|
| 模型选择 | 图像模型取 `/api/model?types=image`,整理记忆模型取会话的模型列表,都在底部弹层里选;可以清空回「不指定 / 默认模型」;换模型会清空思考级别 |
|
||||||
|
| 版本 | 版本号改为 **0.5.0(code 500)**,之后按 0.5.x 递增 |
|
||||||
|
| 测试 | `test/settings_screen_test.dart` 增加「通用」页:分组标题、六个开关与网页端一致的默认值(记忆需要服务端能力才显示);88 项全过 |
|
||||||
|
| 验证 | 模拟器(真实服务端):常规 → 通用;开关显示服务端当前值(图表关、图像开 + 图像模型 SenseNova U1.5 Lite、密钥开、通知关、记忆开、项目知识开、用量限额关)。开「图表和原型」后服务端 `agentRenderToolEnabled` 变 true;勾「整理记忆」出现模型行(AxonHub::deepseek-flash / 默认);图像模型弹层列出 Grok Imagine 与 SenseNova 并可清空回「不指定」;整理记忆弹层列出会话模型与「默认模型」。验证后把这两项改回原值 |
|
||||||
|
| 版本 | **0.5.0(code 500)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.17 设置按分组拆页,新增「关于」(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 分组 | 设置页改成索引,对齐 dsh-Go 的组织方式:【通用】聊天;【外观】主题、宠物;【帮助与关于】关于。每行带图标、一句说明与右箭头,点开是独立子页;原来的全部控件搬进各自子页,索引里只留入口 |
|
||||||
|
| 版本 | 应用版本改为运行时从平台读取(`package_info_plus` 的 `version`;不含 Android build 号,因为 ABI 拆分会给它加一位、四个 APK 各不相同),`pubspec.yaml` 成为唯一出处;配对/relay 握手里的 `appVersion` 也用它,不再有写死的常量(之前还停在 0.4.14) |
|
||||||
|
| 关于 | 新增「关于」子页:应用图标与名称、版本号、开源许可入口、服务端 OpenCode 版本(`/api/info`)与 OpenChamber 版本(`/api/version`),右上角可重新获取;开源许可按包列出,点开看完整许可证文本(自绘中文页,不用英文的 `LicensePage`);未连接或取不到时明确写「未连接」「未获取到」 |
|
||||||
|
| 测试 | `test/settings_screen_test.dart` 重写:索引分组、聊天/主题/宠物/关于四个子页、版本与许可入口;87 项全过 |
|
||||||
|
| 验证 | 模拟器:设置索引三个分组四行;主题页模式/主题色可用;宠物页显示已导入的「Deepy 小鲸鱼」、启用开关与大小;关于页版本「0.4.17」、OpenCode「2.4.0」、OpenChamber「2.8.0」(取自当前服务器),许可页按包列出、点开显示完整许可证文本 |
|
||||||
|
| 版本 | **0.4.17(code 417)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.16 回到前台后重新对账运行状态(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 问题 | 会话进行到一半把应用切到后台,期间这一轮结束了:回到前台时对话区会刷新出新内容,但输入框上方的运行状态条还停在切走时的样子(该消失却没消失)。侧栏的运行标记同样只看事件流,漏掉结束事件后也会一直转 |
|
||||||
|
| 会话状态条 | 回前台时不再只重载转录,还会读一次 `GET /api/session/active`,再按服务器答复重新算「这一轮是否在跑」:在跑就显示、结束就收起。服务器没答上来时退回转录尾部(最新一条 assistant 消息还没有 `completed` 时间就是在跑),不会把一次失败的请求当成「全部空闲」 |
|
||||||
|
| 侧栏 | 回前台时刷新活动会话集合(`refreshActive`),侧栏的运行标记与后台会话的嵌套标记随之更新;服务器明确答复后才覆盖本地集合,请求失败保留原状态 |
|
||||||
|
| 事件流重连 | 同一套对账也挂在事件流恢复后的第一个事件上:socket 静默断过(不一定切过后台)而漏掉「这一轮结束」时,状态条和侧栏同样会自愈 |
|
||||||
|
| 打开会话 | 打开一个已经在中途的会话时也问一次服务器,状态条从第一帧就是对的(以前要等下一批事件才知道在跑) |
|
||||||
|
| 测试 | 新增 `test/running_state_test.dart`:服务器说空闲/在跑、服务器无答复时按转录尾部判断(有未完成的 assistant 消息算在跑,全部完成则不算);83 项全过 |
|
||||||
|
| 验证 | 模拟器:另一个会话里跑一轮长命令 → 切到后台 → 等这一轮结束 → 回到前台:状态条不再出现,侧栏该会话的运行标记消失;再验回前台时仍在进行的一轮保持显示 |
|
||||||
|
| 版本 | **0.4.16(code 416)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.15 后台任务条细节:外观一致、停止移到弹层、宠物站位(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 外观一致 | 后台任务条改为与运行状态胶囊同一套形状:8 边距、14 水平内边距、36 最小高度、Stadium 圆角、相同的文字大小与基线,两条叠在一起时读作一组;多条任务在同一条胶囊里逐行排列 |
|
||||||
|
| 停止 | 按反馈去掉任务条上的「停止」按钮:它会把右侧对齐从计时挤开,与上方运行条的右端对不齐。现在点任意一行打开弹层,停止与复制都在弹层里(确认框「停止这个任务?」不变) |
|
||||||
|
| 弹层状态行 | 不再写「运行中」(弹层开着就是在跑,计时已经说明),也没有会让人误以为「点我刷新」的 `sync` 图标:左边只有计时;「停止」改成带方块停止图标的按钮;命令结束后才显示「已结束」 |
|
||||||
|
| 弹层关闭 | 去掉右侧的 x:拖动把手下滑和点遮罩都能关,x 是多余的 |
|
||||||
|
| 宠物 | 宠物站在最上方那条胶囊的边沿:有运行条或后台任务条时按它的 4px 上边距收脚,都不在时按输入框的 6px;之前会陷进胶囊顶边 2px |
|
||||||
|
| 测试 | `test/shell_jobs_test.dart`:任务条不再有「停止」、点行回调打开弹层、计时仍在;80 项全过 |
|
||||||
|
| 验证 | 模拟器:运行中 + 一条后台任务,两条胶囊等高同圆角;点任务行打开弹层:计时、带图标的「停止」与「复制」、实时输出与跟随,没有「运行中」字样与 x;首次读取时显示「读取输出…」转圈,不会误报「等待输出」;弹层内停止 → 确认 → shell 消失,弹层转为「已结束」并保留最后输出;从弹层头部下滑确实能关闭(x 去掉的前提);宠物在只有运行条、只有任务条、两者都有时都踩在胶囊上沿 |
|
||||||
|
| 版本 | **0.4.15(code 415)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.14 后台任务:状态条、实时输出与停止(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 状态条 | 输入框上方新增后台任务条(在运行状态胶囊之下):1 条时直接显示命令、计时、`停止`;多条折叠成「正在执行 N 条命令」,默认 N ≤ 3 展开;子代理会话的任务标「子代理」 |
|
||||||
|
| 输出 | 点状态条任意一行打开底部弹层:完整命令、运行状态与计时、实时输出(1 秒轮询 `GET /api/shell/:id/output`,cursor 续读、尾部 256KB 封顶)、自动跟随与「回到最新」、复制、停止 |
|
||||||
|
| 工具行 | 起后台命令的 `bash` 行带「后台」标签;展开后显示「后台输出」预览(最后 8 行,仅展开时轮询)+「查看全部」+「停止」 |
|
||||||
|
| 数据来源 | 首选 `GET /api/experimental/job?sessionID=…&descendants=true&status=running` 里的 `kind=shell`(opencode 自己的后台记录:`shellID`、`command`、`sessionID`、`time.started`,覆盖子会话,不会混入前台命令);老服务端 404 时退回 `GET /api/shell` + 转录里 `{status:running, shellID}` 的标记 |
|
||||||
|
| 停止 | 确认框「停止这个任务?」→ `DELETE /api/shell/:id` → 向启动它的会话写一条 synthetic 说明(“用户停止了这条后台命令,随后的 Shell.NotFoundError 不是失败,不要因此重跑”,与上游口径一致),然后刷新列表 |
|
||||||
|
| 结束后 | 命令结束后,工具行与弹层不再轮询,改用会话里 synthetic `<background-result kind="shell" …>` 的最终输出(shell 被删除后仍能看);如果是用户在 App 里停的,显示「用户停止了这条命令。」而不是 Shell.NotFoundError |
|
||||||
|
| 刷新 | 打开会话立即刷新,之后 3 秒一次;会话消息变化时也刷新(新任务立刻出现);服务端无该接口时停止轮询 |
|
||||||
|
| 测试 | 新增 `test/shell_jobs_test.dart`:后台标记识别(前台命令不算)、转录/任务/外壳列表解析、输出页、完成说明与停止标记、计时格式、停止说明,以及状态条 1 条/2 条/多条折叠的布局;80 项全过 |
|
||||||
|
| 验证 | 模拟器(真实任务):`sleep 900` 单条任务条 → 第二条命令变为「正在执行 2 条命令」+ 两条行;弹层实时输出(每秒 tick);弹层内「停止」→ 确认 → 任务与 shell 消失、模型收到 synthetic 停止说明;工具行「后台」标签 + 展开后的最终输出/「用户停止了这条命令。」。后台进程可用前台命令超时后「移到后台」的方式启动(`timeout` 5 秒、不加 background),这样不会像 `background: true` 那样在超时点被 SIGKILL,任务会一直跑到手动停止 |
|
||||||
|
| 版本 | **0.4.14(code 414)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.13 相对路径与生成图片的行内展示(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 路径显示 | 折叠状态下 `read` / `write` / `edit` 等文件工具只显示相对于会话目录的路径(如 `lib/screens/chat_screen.dart`),不再被 `/home/...` 前缀挤掉文件名;会话目录之外的路径(如 `/tmp/...`)仍显示完整路径。diff 展开后的多文件标题同样去前缀 |
|
||||||
|
| 生成图片 | 对照上游确认:`openchamber_image`(`action=image.generate`,结果 JSON 里 `data.images[].path`)在 `isShownInPlace` 为真时会从 Activity 折叠里**提升**出来,由 `ShownToolCard → GeneratedImages` 在对话中直接显示图片(懒加载、点开画廊、上方有下载)。现在我们也把它从工具运行段里提出来:运行段在它之前结束,图片以卡片形式出现在原位置,最大高度 380,点击打开既有的全屏预览;运行中仍是「正在生成图片」的普通步骤,失败则留在运行段显示错误 |
|
||||||
|
| 图片缓存 | 卡片与全屏预览共用一份内存缓存(最多 8 张),列表重建不重复请求 `/api/fs/raw` |
|
||||||
|
| 测试 | 新增 `test/generated_images_test.dart`:结果 JSON 解析多图、未完成/失败/其它工具/非 JSON 不显示,`relativePath` 去前缀、目录外保留、尾斜杠与相似前缀;65 项全过 |
|
||||||
|
| 版本 | **0.4.13(code 413)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.12 编辑工具的 diff 显示(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 展开为 diff | `edit` / `write` / `patch` 等文件修改工具展开后不再显示一整段 old/new 纯文本,而是逐行 diff:新增行绿色底、删除行红色底、`@@` hunk 头浅色标记、`---/+++` 等元信息变灰;长行软换行,整块可选中复制(对齐 dsh-Go / 上游 `ToolPartDiffPreview`) |
|
||||||
|
| 数据来源 | 优先用服务端 `state.metadata.files[].patch`(可能多文件,按文件显示标题),其次 `metadata.patch` / `metadata.diff`;老服务端没有 patch 时用输入的 `oldString`/`newString` 做行级 LCS,`write` 只有 `content` 时显示为全新增行 |
|
||||||
|
| 行尾统计 | 工具行右侧显示 `+N −M`(与 dsh-Go 一致),失败/运行中不显示 |
|
||||||
|
| 大 diff | 最多渲染 600 行,超出显示「仅显示前 600 行,共 N 行」,避免聊天列表一次构建过多行 |
|
||||||
|
| 结果行 | diff 下方保留一行工具自身结果(如「Edited PLAN.md (1 replacement)」),错误仍用错误色 |
|
||||||
|
| 测试 | 新增 `test/diff_view_test.dart`:metadata patch 解析与增删计数、无 patch 的 old/new 回退、`write` 内容回退、失败/非文件工具不显示、DiffView 渲染增删行;57 项全过 |
|
||||||
|
| 验证 | 桌面快速验证:`PATH=$HOME/SDK/flutter/bin:$HOME/SDK/localbin:$PATH CC=clang CXX=clang++ PKG_CONFIG_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu/pkgconfig:$HOME/SDK/linuxdev/usr/share/pkgconfig flutter build linux --release`,然后 `DISPLAY=:99 build/linux/x64/release/bundle/openchamber` + `ffmpeg -f x11grab` 截图。跑之前先 `pkill -f build/linux`:残留的旧 debug 实例会占着窗口,点到的其实是旧代码(界面看着"不是最新版"就是这个原因)。最终效果仍在模拟器上用触摸验证 |
|
||||||
|
| 版本 | **0.4.12(code 412)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.11 侧栏对齐调整(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 折叠箭头对齐 | 项目分组带内部 contentPadding 归零(外层仍为 8):分组折叠箭头与有子代理会话行的箭头在同一条竖线上 |
|
||||||
|
| 左右边距 | 会话行左右均为 8;项目带的 + 与会话行的 ⋮ 也都在右侧 8 的同一竖线上,标题可用宽度更大 |
|
||||||
|
| 标题起点 | 所有顶层会话行都保留固定 18px 的箭头列(无子代理时留空),标题横向起点一致;子代理行缩进 32 并保留竖线 |
|
||||||
|
| 测试 | 新增「分组箭头/子代理箭头同列、有无子代理的标题同起点」用例;52 项全过 |
|
||||||
|
| 版本 | **0.4.11(code 411)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.10 子代理树折叠、Agent Task 行与只读输入(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 侧栏树 | 子代理行默认折叠:有子代理的父行左侧出现展开/收起箭头(tooltip「展开子代理/收起子代理」),展开后子行缩进并带一条竖线;父行副标题仍显示「N 个子代理」。当前打开的子代理会自动展开它的父行,手动收起后不会被重新展开 |
|
||||||
|
| Agent Task | 父会话的工具步骤识别 `subagent` / `task`(上游 Agent Task),显示子代理图标和描述;点击整行直接打开对应子会话(`state.metadata.sessionID`,旧结果从 `sessionID: ses_…` 文本解析)。会话不在当前分页时用 `GET /api/session/{id}` 取回 |
|
||||||
|
| 只读输入 | 普通子代理会话默认只读,底部显示「无法向子智能体会话发送提示。」;服务端 `allowPromptingSubagentSessions` 为 true 时才显示输入框。Lead 的 operator-child(`metadata.openchamber.kind = 'operator-child'`)始终只读,显示「此会话由 Lead 管理,接管后才能继续。」,直到后续实现接管 |
|
||||||
|
| 返回父会话 | 0.4.9 的父会话返回保留 |
|
||||||
|
| 测试 | `test/subagent_readonly_test.dart`(默认只读、设置放开、operator-child 即使放开也只读);侧栏测试改为默认折叠→点箭头展开→打开子行;51 项全过 |
|
||||||
|
| 版本 | **0.4.10(code 410)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.9 浏览子代理会话(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 侧栏嵌套 | 子代理会话(`parentID` 指向父会话)不再被过滤掉:父行下面缩进显示一个子代理行(robot 图标,副标题以「子代理 ·」开头),父行的副标题显示「N 个子代理」;父会话在置顶区也带出它的子代理。子代理行可以点开查看完整会话内容,⋮ 菜单与普通会话一致 |
|
||||||
|
| 按需加载 | 打开父会话时并行请求 `GET /api/session?parentID=<id>`(每个父会话一次),把不在当前分页里的旧子代理补进列表;断开连接时清空缓存 |
|
||||||
|
| 父会话返回 | 子代理会话的 AppBar 左侧改为返回箭头(tooltip「返回父会话」),标题前有 robot 标记;点击回到父会话。侧栏点父行也能回去 |
|
||||||
|
| 测试 | `test/sidebar_rows_test.dart` 新增:父子会话同时显示、缩进/robot 图标、「1 个子代理」副标题、点击子行打开该会话;46 项全过 |
|
||||||
|
| 版本 | **0.4.9(code 409)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.8 项目图标与聊天图标(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 元数据 | `refreshProjects` 同时读 `/api/config/settings?surface=mobile` 的 `projects`,把 label / icon / color / iconBackground / iconImage 按路径合并到 `/api/project` 的条目上(自定义 data dir、Windows 大小写/分隔符都按路径匹配) |
|
||||||
|
| 项目图标 | 聊天组改用聊天气泡图标;项目组、项目选择器、草稿的项目 chip 统一用 `ProjectIcon`:OpenChamber 的 46 个 icon key 映射到 Material 图标,`color` 支持 hex 与旧主题 key(primary/error/comment/keyword/string/…),无自定义图标时显示对应颜色的图标/文件夹 |
|
||||||
|
| 自定义图标 | `iconImage` 存在时经 `GET /api/projects/<settingsId>/icon?theme=…&iconColor=…` 取图(带认证,走 Transport/Relay);SVG 用 `flutter_svg` 渲染,PNG/favicon 用 `Image.memory`;有 `iconBackground` 时加圆角底色;加载失败回退字形,按 theme+updatedAt 缓存 |
|
||||||
|
| 测试 | 现有 46 项全过;模拟器上确认聊天组是气泡、项目组带各自的颜色/图标、选择器与草稿 chip 一致 |
|
||||||
|
| 版本 | **0.4.8(code 408)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.7 聊天分组与「聊天」新建目标(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 聊天分组 | 连接后读 `GET /api/fs/home` 的 `chatsRoot` / `canonicalChatsRoot` / 旧版 `.config/openchamber/chats`,所有位于这些根下的会话(`chats/<日期>/session-…`)合并成一个「聊天」组;修复此前按目录 leaf 分组、每个聊天各显示成 `session-xxxxx` 的问题。自定义 data dir、Windows 分隔符/盘符大小写都按路径边界匹配 |
|
||||||
|
| 新建目标 | 新会话的项目选择器新增「聊天」:选择后草稿 chip 显示聊天图标和「聊天」;首次发送时先在 `chatsRoot/YYYY-MM-DD/session-<id>` 建目录(`POST /api/fs/mkdir`),再在该目录创建会话。已有聊天里点新会话会得到一个新的聊天目录,不会复用旧的 |
|
||||||
|
| 侧栏 | 聊天组的「+」提示「新建聊天」,直接打开以聊天为目标的草稿;项目选择器不再把聊天目录当作项目列出 |
|
||||||
|
| 测试 | `test/paths_test.dart` 增加聊天根边界(POSIX/Windows、`chats-other` 不误判);`test/sidebar_rows_test.dart` 增加多个聊天目录合并为唯一「聊天」组、不出现 `session-xxxxx` 的断言;本地服务器上用 curl 验证了在 chatsRoot 下 mkdir + 建会话 + 删除 |
|
||||||
|
| 版本 | **0.4.7(code 407)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.6 扫码无反应的修复与诊断(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 原因候选 | 0.4.5 以 480p 取流,配对二维码很密(网页端 1024px、L 级纠错、只有 2 个模块的静区),模块在画面里可能小于 zxing 能识别的尺寸;另外部分设备的 Y 平面最后一帧不含行尾 padding(长度为 `rowStride*(h-1)+w`),旧代码会直接丢弃所有帧 |
|
||||||
|
| 取流 | 先请求 720p(`ResolutionPreset.high`),失败才退回 480p;取流失败不再静默显示预览,而是显示错误;4 秒没有帧时提示「没有收到相机画面」 |
|
||||||
|
| 解码 | zxing 加 `tryHarder`;正常解码失败后再用 `InvertedLuminanceSource` 试一次反色(深色卡片上的浅色二维码);Y 平面允许最后一帧缺少 padding |
|
||||||
|
| 诊断 | 扫描页底部显示「1280×720 yuv420 · 已扫描 N 帧 / 解码 M 次」;首帧通过 `debugPrint` 记录分辨率/planes/rowStride/像素步长/字节数,解码异常也会记录一次 |
|
||||||
|
| 测试 | `test/qr_scan_test.dart` 增加最后一帧无 padding、反色二维码两项;全部通过 |
|
||||||
|
| 版本 | **0.4.6(code 406)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.5 扫码配对(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 扫码入口 | 「配对链接」对话框新增「扫码」:全屏相机 + 取景框 + 手电筒;扫到配对链接直接开始配对,不再要求按第二个按钮 |
|
||||||
|
| 解码 | 用 `camera` 0.12 + `zxing2` 0.2(纯 Dart,不依赖 ML Kit / Google Play 服务)。Android 取 YUV420 的 Y 平面直接作为亮度;BGRA(iOS/部分相机)按绿加权转亮度。解码放在 `compute` isolate,每帧不阻塞 UI,同一时间只解一帧 |
|
||||||
|
| 取景 | 后置相机优先、480p 预览、覆盖率/圆角遮罩 + 四角标记;非配对二维码提示「这不是 OpenChamber 配对二维码」并继续扫;无相机/权限被拒给出说明与重试 |
|
||||||
|
| 权限 | AndroidManifest 增加 CAMERA 权限;camera 硬件声明为非必需,没相机的设备仍可安装 |
|
||||||
|
| 测试 | `test/qr_scan_test.dart`:用 `qr` 生成配对链接二维码,渲染成 Y 平面(含 rowStride 内边距)后由 `decodeQrLuminance` 解出原文;空白帧、过短/非法尺寸返回 null |
|
||||||
|
| 版本 | **0.4.5(code 405)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 配对链接 | 服务器列表新增「配对链接」:粘贴 `openchamber://connect?v=2&p=…`,解析一次性密钥与候选地址(lan / tunnel / relay,按 priority 先直连后 Relay),用第一个能连上的候选兑换设备 token 并保存 |
|
||||||
|
| 端到端加密 | 新增 `relay_crypto.dart`:P-256 ECDH + HKDF-SHA256(salt = 握手 nonce,info = `openchamber-relay-v1`)派生两条 AES-256-GCM 方向密钥;帧 = 版本 + 12 字节 IV(4 随机前缀 + 8 字节计数器)+ 密文 + GCM tag,计数器严格递增,失败即关闭。与官方 `packages/ui/src/lib/relay/crypto.ts` 字节兼容 |
|
||||||
|
| 隧道 | 新增 `relay_tunnel.dart`:连 `wss://…/ws?v=1&role=client&serverId=…`,明文 hello/ready 握手,之后是加密的 mux 帧(HttpRequest/Body/Response/StreamEnd/Abort、WsOpen/Opened/Text/Binary/Close、Ping/Pong)。大消息按 64 KiB 分片与重组,断线不自动重拉(下一次请求重连,SSE 自己的重试循环会恢复) |
|
||||||
|
| Transport | `Transport.webSocket` 改为返回 `TransportSocket`(直连包装 WebSocket,Relay 用子流);新增 `RelayTransport` 实现同一接口,所有 HTTP/SSE 走隧道。Relay 下的终端 WebSocket 先经隧道 `POST /auth/url-token` 换取短时 token,附到 `oc_url_token` 查询参数 |
|
||||||
|
| 连接模型 | `Connection` 增加 `relayUrl/serverId/hostKey/grant` 与 `isRelay`;直连字段不变。配对成功的连接与设备 token 一起保存,之后启动/重连直接用 token,不再需要配对链接 |
|
||||||
|
| 未协商 | 不声明 batch、下行 flow control 与响应 gzip,走宿主端的 legacy 路径(一帧一条消息、明文响应体),先保证正确性 |
|
||||||
|
| 切换 | 已连接时配对会先断开旧服务器(关闭旧 shell、事件流),再切到新连接;`ChatScreen` 现在持有自己的 `ChatState`,不再在 dispose/计时器里读已清空的 `app.chat!`(修掉切换服务器时的一个空指针崩溃) |
|
||||||
|
| 测试 | `test/relay_crypto_test.dart`(JWK 往返、双方派生一致、方向密钥、重放/篡改失败、base64url)、`test/pairing_test.dart`(直连优先、relay-only、grant、过期/非法/裸 payload);`tool/relay_probe.dart` 对真实 relay 做了握手、兑换、/api/version、会话列表、SSE 与终端快照的端到端验证;模拟器上从「配对链接」粘贴 relay-only 链接、重启后自动重连、终端命令输入输出都通过 |
|
||||||
|
| 版本 | **0.4.4(code 404)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.3 终端多标签:下拉切换、新建、按标签恢复(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 多标签 | 每个目录一个 `TerminalWorkspace`,持有多个 `TerminalTab`(各自的 xterm 模型与 socket)。切换标签时旧标签 detach、新标签 attach,不同时占用多条 WebSocket;后台输出由服务端 snapshot 在切回时重放 |
|
||||||
|
| 下拉 | 状态条左侧变成标签下拉:显示「终端 N · 运行中」,菜单列出所有标签(当前项打勾)与「新建终端」。新建的标签自动用最小的空闲编号(终端 1、终端 2…) |
|
||||||
|
| 关闭/重启 | ⋮ 菜单改为「关闭此终端」,关掉当前标签并 DELETE;关掉最后一个会自动留一个新标签。重启只作用于当前标签,死会话在原标签内换成新会话 |
|
||||||
|
| 恢复 | 本机按连接 + 目录保存标签列表(id + 名称 + 活动标签)。启动后首次打开:`GET /api/terminal/sessions?cwd=` 与服务端对账,仍存在的会话按保存的顺序和名称还原,服务端新出现的会话(网页端开的)按创建时间追加成标签,服务端已没有的标签丢弃;一个都没有才新建。兼容 0.4.2 的单会话存档 |
|
||||||
|
| 过滤 | 只把 interactive 会话算作标签,project-action 的命令运行器不显示 |
|
||||||
|
| 测试 | `test/terminal_restore_test.dart`:标签对账(顺序、名称、丢弃、列表失败的兜底、过滤 action)、编号复用、按连接+目录保存标签与活动项、0.4.2 存档迁移 |
|
||||||
|
| 版本 | **0.4.3(code 403)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.2 终端恢复:重启后接回原来的 shell(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 问题 | 之前 `sessionId` 只在内存里:每次启动 App 后第一次打开终端都走 `POST /api/terminal/create`,旧 shell 还留在服务器上(无连接时 30 分钟空闲回收),只是再也接不回去 |
|
||||||
|
| 恢复 | 按连接 + 目录记住最后一次的终端 id(`openchamber.terminalSessions.<connId>`)。首次打开终端先 `GET /api/terminal/sessions?cwd=`:记得的 id 还在就直接 attach(服务端 snapshot 重放历史);不在了就采用该目录最新的运行中会话;一个都没有才新建 |
|
||||||
|
| 关闭 | 「关闭终端」先 DELETE 并忘掉记录,再用 `fresh` 新建,避免又接回刚关掉的会话;断开连接/切换服务器时照旧关闭 shell |
|
||||||
|
| 失效 | attach 收到 fatal `SESSION_NOT_FOUND`(例如服务端在中间重启过)时清掉记录并自动新建,不留死面板 |
|
||||||
|
| 单终端 | 仍是每个目录一个终端视图,不是多标签;同目录的其它会话保留给网页端,不会被删除 |
|
||||||
|
| 测试 | `test/terminal_restore_test.dart`:恢复优先级(记得的 > 最新运行中 > 最新)、按连接+目录保存与清除 |
|
||||||
|
| 版本 | **0.4.2(code 402)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 不再占位 | `PetSlot` 换成 `PetLayer`:宠物画在消息列表的 Stack 上层,列表恢复完整高度,字会从宠物四周透出来,不再有一条空白带把最后一行截掉 |
|
||||||
|
| 透明 | 只有精灵本身作画;画布其余部分不填充。命中测试只认 `contentBox`(外扩 4px),点空白处仍然滚动/点消息 |
|
||||||
|
| 拖动 | 按住身体左右拖,脚沿输入框上沿移动;松手保存在本机(`pet.x.v1`,0–1 的比例),重启后回到同一位置,窄屏/旋转按比例换算并夹在两端内 |
|
||||||
|
| 拖动反馈 | 拖动时抬升 6px,并播放包里的 `drag`(`react-drag`)动画;没有该动画就保持当前状态,松手回到聊天状态 |
|
||||||
|
| 点击 | 从 `onTapDown` 改为 `onTapUp`,拖动不再误触发左右半区的 `tapLeft/tapRight` |
|
||||||
|
| 测试 | `test/pet_layer_test.dart`:空白处点击穿透、身体吃掉点击、拖动改位置并写入 prefs、无宠物时不画 |
|
||||||
|
| 版本 | **0.4.1(code 401)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.4.0 输入框宠物:导入宠物包、精灵动画与状态(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 默认无宠物 | 不内置任何宠物;设置 → 宠物 显示「尚未导入宠物」和导入按钮,导入后才启用 |
|
||||||
|
| 宠物包 | 兼容 dsh-Go 的 PNG 精灵包:zip 内 `pack.json` + 各动画的 sprite sheet。解析 canvas / anchor / contentBox / animations(frames, cols, box) / states / reactions;导入时校验 `pack.json` 与每张精灵图,解压到应用文档目录 `pets/<id>/`,支持更换、启用/关闭、大小(40 / 52 / 64)与移除 |
|
||||||
|
| 渲染 | 新增 `PetSlot` / `PetSprite`:按 `anchor` 让宠物站在输入框上方(运行时有活动条则站在活动条顶边);按状态播放 `idle / thinking / working / error`;点击左右半区播放 `react-left / react-right`。图片一次只解码当前动画,切换时释放上一张 |
|
||||||
|
| 状态 | 活动条是「思考中」→ thinking,其余运行状态(回复中、调用工具)→ working,最后一轮失败 → error,空闲 → idle;草稿页显示 idle |
|
||||||
|
| 示例包 | `dist/deepy-whale-pet.zip`(dsh-Go 的 Deepy 小鲸鱼,保留包内 name/author/license) |
|
||||||
|
| 测试 | `test/pet_pack_test.dart`(真实 deepy pack 解析、帧与状态映射)、`test/pet_import_test.dart`(zip 解包、嵌套目录、缺少 pack.json 拒绝) |
|
||||||
|
| 版本 | **0.4.0(code 400)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.21 侧栏行更紧凑(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 行高 | 项目条和会话行都改为 `dense: true` + `minTileHeight: 56`,实测都是 54(此前是 72);标题 14 / 项目名 14.5,路径与副标题保持较小字号 |
|
||||||
|
| 对齐 | 仍然等高等宽;`+` 与会话 `⋮` 的 x 中心保持对齐(测试断言) |
|
||||||
|
| 版本 | **0.3.21(code 321)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.20 侧栏项目/会话行等高与右对齐、活动条改为 dsh-Go 胶囊(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 侧栏等高 | 项目分组头改用与会话行相同的 `ListTile`(标题 + 副标题),两者高度都是 72;分组的 8px 外边距由 ListTile 的内边距补偿,`+` 与会话的 `⋮` 落在同一竖线上 |
|
||||||
|
| 活动条 | 改为 dsh-Go 风格的全宽胶囊:左侧「标题 + 步骤摘要」,右侧等宽数字计时 `m:ss`(不足一分钟也显示 `0:03`),半透明 surface 背景,最小高度 36;去掉条内的转圈。胶囊顶边就是之后输入框宠物的栖息位置 |
|
||||||
|
| 版本 | **0.3.20(code 320)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.19 输入框环居中、运行状态条、侧栏项目层级与 Windows 路径(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 上下文环 | 单行输入框用 `CrossAxisAlignment.end`,16px 的环贴着底部而按键是 36px;给环加 10px 底边距,与按键同一中轴(有焦点时的两行布局本来就是居中,未改) |
|
||||||
|
| 运行中的尾部 | 运行中不再显示上一轮的 footer(模型 · 模式 · 用时,以及“复制回答 / 从这里分叉”菜单):`_turnRows` 在 `chat.running` 为真时不加 footer。改为在输入框上方显示 dsh-Go 风格的活动条:「思考中 / 正在回复 / 正在读取 · …」加当前步骤摘要和秒表,每秒刷新 |
|
||||||
|
| 侧栏项目 | 项目分组头改成带底色的圆角条,最小高度 56,加文件夹图标;标题 13.5 粗体、路径作副标题,与会话行的层级更清楚 |
|
||||||
|
| Windows 路径 | 项目名只取路径最后一段,`/` 与 `\` 都识别;同一项目的比较统一分隔符(盘符路径忽略大小写),分组键也统一分隔符,避免一个项目被拆成两组 |
|
||||||
|
| 版本 | **0.3.19(code 319)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.18 需要密码的服务器无法输入密码(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 问题 | 「添加服务器」表单的密码框只在编辑已保存服务器时显示(`!_editNew`)。新服务器首次连接被 401 拒绝后只提示「需要密码或已保存的凭据」,却没有输入密码的地方 |
|
||||||
|
| 修复 | 密码框始终显示,文案为「密码(如果需要)」,提示服务器未设置可留空;连接失败且错误提示需要密码时自动聚焦密码框;服务端返回 `Invalid credentials` 时显示为「密码错误,请重试」。新增 `test/servers_form_test.dart` 覆盖新服务器表单含密码框 |
|
||||||
|
| 版本 | **0.3.18(code 318)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.17 设置页、侧栏底部服务器栏与追问处理行为(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 设置页 | 新增 `lib/screens/settings_screen.dart`,分「外观 / 聊天 / 宠物」三组 |
|
||||||
|
| 侧栏 | 服务器切换从顶部移到底部:左侧是当前服务器名(点击打开服务器面板),右侧齿轮进入设置页,和原版手机端侧栏一致 |
|
||||||
|
| 外观 | 主题模式(跟随系统 / 浅色 / 深色)与主题色(8 个种子色);`lib/appearance_prefs.dart` 存本机 `shared_preferences`,明确不同步服务端;`main.dart` 的 `ThemeData` 读取它 |
|
||||||
|
| 聊天 | 「追问处理行为」:转向 / 排队。读写服务端 `GET/PUT /api/config/settings?surface=mobile` 的 `followUpBehavior`(profile 级、跨 surface 共享,默认 queue)。运行中短按发送按该设置执行,长按「发送方式」可临时选另一种并标出默认项。连接成功、设置页打开、应用回到前台时重新读取 |
|
||||||
|
| 宠物 | 仅占位,显示「暂未提供设置」 |
|
||||||
|
| 版本 | **0.3.17(code 317)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.16 输入法收起、模式面板与排队消息(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 输入框收起 | 手机返回手势关闭输入法(焦点仍在)时,输入框也收回单行:dsh-Go 用键盘高度判断;`Scaffold` 会从 body 去掉底部 viewInsets,所以由 `HomeScreen`(Scaffold 之上)读取键盘高度,经 `ChatScreen` / `NewSessionScreen` 传给 `ComposerBox`。键盘升到过的峰值一半以下即视为收起,再次唤起时展开。新增 `test/composer_box_test.dart` 覆盖 |
|
||||||
|
| 模式面板 | 「模式」(Build / Plan)chip 由下拉框改为底部面板:标题、图标、说明、当前项打勾;仍与模型/思考强度分开 |
|
||||||
|
| 排队消息 | 运行中短按发送默认「转向」(`delivery: steer`),长按发送键弹出「转向当前回合 / 排队」,只用服务端支持的 steer/queue。排队或转向的消息不乐观写入对话,而是显示为末尾的待发气泡(半透明 + 状态:正在转入 / 已排队 / 未发送),可「改为排队 / 转为转向」与「撤回」(`DELETE /api/session/:id/inbox/:id`,文本放回输入框)。打开会话与前台恢复时 `GET /api/session/:id/inbox`;订阅 `session.inbox.enqueued / delivered / cancelled / delivery.changed`,送达时刷新尾部。运行且输入框有文字时发送键显示为发送(dsh-Go 行为),空输入时才显示停止 |
|
||||||
|
| 版本 | **0.3.16(code 316)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.15 输入框两行折叠、模型与思考成组、模式独立(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 输入框折叠动画 | 新增 `lib/widgets/composer_box.dart`:未获焦点时是单行(附件键在左、输入框、上下文环、发送键在右),获得焦点时平滑展开为两行(上为输入框,下为附件键/模型/模式/环/发送键),失焦后收回单行;输入框用 `GlobalKey` 在两种布局间搬移,保留焦点与输入连接。参照 dsh-Go `Composer` 的 `footer` + `_ComposerRows` + `AnimationController` 做法 |
|
||||||
|
| 模型与思考强度成组 | 模型 chip 直接显示 `模型 · 思考档位`(如 `deepseek-flash · 高`),点开同一个面板:选模型后若该模型有 variants,底部出现思考强度选择,选完一次提交;最近使用的档位记在本机。草稿页与聊天页共用 `ModelPill` |
|
||||||
|
| 模式独立 | 原「智能体」chip 改为独立的 `ModeChip`(Build / Plan),与模型 chip 并列,不再把智能体与模型放在同一行组里;仍通过 `switchAgent` / 草稿的 `agent` 提交 |
|
||||||
|
| 草稿页 | 同样使用两行折叠 `ComposerBox`;项目 chip 单独在输入框上方始终可见(草稿页没有会话,模型/模式放在折叠的第二行);斜杠面板、快捷键保持不变 |
|
||||||
|
| 版本 | **0.3.15(code 315)** |
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.14 模型切换修复、输入框模型行、思考强度与模型面板(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 切换模型报错 | `POST /api/session/:id/model` 的 body 应为 `{model: {id, providerID, variant?}}`,之前把模型对象直接放在顶层,服务端报 `Missing key at ["model"]`;已修正并实测切换成功 |
|
||||||
|
| 输入框模型行 | 参照 dsh-Go:聊天页把模型/智能体从顶栏移到输入框上方,输入框获得焦点、有草稿文字或正在生成时显示;草稿页始终显示同一行(左侧多一个项目 chip)。聊天顶栏只留文件按钮 |
|
||||||
|
| 思考强度 | `/api/model` 的每个模型带 `variants`(v2 的 `{id, settings.reasoningEffort}`)。输入框行在模型有档位时显示「思考·默认/低/中/高/极高」,点开选档;选择以 `ModelRef.variant` 随 `POST /session/:id/model` 或建会话时提交,实测会话的 `model.variant` 变为 `high`。每个模型上次的档位记在本机 |
|
||||||
|
| 模型面板 | 重做 `lib/widgets/model_picker.dart`:按 provider 分组(可折叠)、「收藏」「最近」分组(本机 `shared_preferences`,收藏用星标切换)、每个模型标注上下文大小(如 `200K 上下文`)、推理能力标记、搜索、当前项打勾;智能体分段保留 |
|
||||||
|
| 草稿斜杠 | 斜杠面板抽成共享的 `lib/widgets/slash_palette.dart`(匹配、排序、面板、快捷键),草稿页与聊天页共用;草稿只列 `/api/command` 与 `/api/skill` 的结果,不含需要已有会话的客户端内置 `/compact`;无参命令选中即发送(先建会话再执行命令),带参命令补全名称 |
|
||||||
|
| 版本 | **0.3.14(code 314)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.13 草稿会话与分组侧栏(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 新会话 = 草稿 | 左侧栏 `+` 不再弹「标题」底部框,而是进入 `NewSessionScreen`:大标题「我们今天要做什么?」、项目 chip(`GET /api/project`,按 canonical 去重)、模型/智能体 chip(与聊天共用新的 `lib/widgets/model_picker.dart`)、附件与输入框。**发送前不创建会话**:第一次发送才 `POST /api/session`(带 `location.directory`、`model`、`agent`),随后 `openChat` 并发出这条消息 |
|
||||||
|
| 草稿生命周期 | 草稿只存内存(`AppState.draft` + `draftOpen`):未发送就离开时保留,侧栏顶部出现「草稿 · 项目名」一行(笔图标、首行、× 丢弃),点它回到草稿;发送成功即清空,创建失败留在草稿并显示错误。第二期接服务端 `/api/session-drafts`(已记入项目待办) |
|
||||||
|
| 侧栏分组 | 会话按 `location.directory` 分组(`.openchamber/chats` 归为「聊天」),组头是项目名 + 路径 + 折叠 + 「在此项目新会话」;组内按 `updated` 倒序并插「今天 / 昨天 / 本周早些时候 / 更早」小标题;默认过滤子会话(`parentID`),父会话的运行点会带上子会话的活动 |
|
||||||
|
| 置顶 | 写进 `session.metadata.openchamber.pinned`(`PATCH /api/session/:id {metadata}`,合并原有 metadata),跨客户端可见;置顶的会话收进顶部「已置顶」区,不再重复出现在项目组里 |
|
||||||
|
| 归档 | 主列表请求 `archived=false`;底部「显示已归档」按需拉 `archived=true`,展开后可取消归档(事件 `session.archived/unarchived` 同步) |
|
||||||
|
| 行操作 | 左滑(`flutter_slidable`,DrawerMotion)露出置顶 / 归档 / 删除;`⋮` 菜单有重命名、置顶、归档、删除、复制会话 ID;选中行有底色与加粗 |
|
||||||
|
| 其它 | 会话列表支持「载入更多」(cursor 分页);聊天页标题改为跟随 `AppState.sessions`,服务端根据首条消息生成的标题会即时显示;附件选择与缩略图抽到 `lib/widgets/composer_attachment.dart`,与草稿页共用 |
|
||||||
|
| 版本 | **0.3.13(code 313)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.12 侧栏头部、Termux 按键栏、键盘避让与记忆(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 侧栏头部 | 顶部一行改成「标签组 + 关闭按钮」,标题/目录副标题去掉(目录本来就在面包屑里);文件/项目知识/终端各自的功能按钮下沉到标签自己的头部行——文件页是面包屑右侧的「+ / ⋯」(预览时是「编辑 / 下载」),项目知识页是搜索框 + 刷新,终端页是状态 + 键盘/重启/菜单 |
|
||||||
|
| 按键栏 | 按 Termux 改成两行七列等宽:`ESC / — HOME ↑ END PGUP`、`TAB CTRL ALT ← ↓ → PGDN`(左下角是 **TAB**,不是收起按钮);CTRL/ALT 修饰对手机输入法的字符仍然生效 |
|
||||||
|
| 键盘避让 | 侧栏是对话框,不会自己随输入法缩小;现在给底部加上 `MediaQuery.viewInsets.bottom` 的内边距,终端连同按键栏一起抬到键盘上方,`TerminalView` 随之减少行数并把新尺寸回传给 PTY |
|
||||||
|
| 记忆 | 项目知识新增「记忆」标签:`GET /api/agent-memory/all` 一次取全局与项目两份,服务端把功能关掉时(404)整个标签不出现;卡片显示标题、类型(事实/偏好/参考)、内容,可编辑(标题/类型/正文)与删除,搜索也覆盖记忆 |
|
||||||
|
| 顺带修复 | 文件预览的编辑框 `expands: true` 缺 `minLines: null`,进编辑会触发断言 |
|
||||||
|
| 版本 | **0.3.12(code 312)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.11 终端、项目知识与下载进度(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 终端 | 右侧栏「终端」页:`POST /api/terminal/create` 建 PTY(cwd = 会话目录),`/api/terminal/ws` 走二进制控制帧(`0x01` + JSON:hello/attach/write/ping,snapshot/output/restart/exit/error)。渲染用 **xterm 4.0.0**(`Terminal` 模型 + `TerminalView`),断线按 500ms 起指数退避重连、重连后按服务端快照重放(先 `resize` 到快照尺寸再写历史);`/api/terminal/:id/resize` 做 250ms 去抖;App 回前台时自动重连 |
|
||||||
|
| 底栏 | 仿 Termux 的按键条(横向滚动):CTRL / ALT / SHIFT 修饰键,ESC、TAB、方向键、HOME/END/PGUP/PGDN/DEL,以及 `/ - \| ~ * $ # _ = + : ; " ' ( ) [ ] { } < > ? ! & \ ^ % @`;修饰键对**手机输入法**输入的字符同样生效(在 `onOutput` 里把下一个可打印字符映射成控制字符/ESC 前缀),按一次即清除 |
|
||||||
|
| 状态 | 状态条显示「运行中 / 正在连接 / 已退出(退出码)/ 连接失败」,并提供键盘、重启、清屏、关闭终端;终端会话按目录保存在 `AppState.terminals`,关面板不断 shell,切换服务器时显式关闭 |
|
||||||
|
| 项目知识 | 右侧栏「项目知识」页:`/api/project-context/:projectId`(projectId = `path_` + 目录 base64url);笔记(新建/编辑/置顶/删除)、待办(勾选、新建、删除,完成项沉底)、计划(新建、置顶、删除、打开全文);搜索框跨三种记录即时过滤;计划详情是全屏页(Markdown 渲染 + 编辑原文 + 保存) |
|
||||||
|
| 下载进度 | `/api/fs/raw` 改为流式:`downloadFile` 带 `onProgress` 与 `CancelToken`,请求头 `accept-encoding: identity` 以拿到 `Content-Length`(gzip 会让响应变成 chunked,进度只能是不确定态);下载中弹「正在下载」对话框显示已下载/总量/百分比,取消即中止连接并丢弃结果;完成后才弹保存对话框 |
|
||||||
|
| 修复 | `MarkdownView` 里的任务列表不再用 `material_ui` 的 Checkbox(它会找 `material_ui` 的 Material 祖先,应用里没有),改为 `✅`/`⬜` 文本;对话框里的 `TextEditingController` 改由对话框自身持有,避免关闭动画期间 dispose 触发框架断言 |
|
||||||
|
| 版本 | **0.3.11(code 311)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| Transport | 新增 `lib/api/transport.dart`:`TransportRequest`(method/path/query/rawQuery/headers/body)、`TransportResponse`(状态码/头/`Stream<List<int>>`,SSE 与文件下载仍可流式读)、`abstract Transport`;`DirectTransport` 就是原来的直连实现(HTTP CONNECT、SOCKS5/socks5h、自签与指纹固定、SHA-256 内置实现),`Client` 只保留业务方法,构造时可注入别的 Transport。行为与之前逐字节一致,后续 Private Relay 只需再加一个 `RelayTransport` |
|
||||||
|
| 历史图片 | 用户消息里的 `files` 现在从服务端读 `data`(base64)并缓存解码结果;气泡内显示缩略图,点按打开图片预览(与工具行读图共用同一个对话框)。无内联图片时仍回退到刚发送时的本地路径 |
|
||||||
|
| 原生表单 | `FormInfo`/`AgentFormField`/`FormOption`/`FormWhen` 按 `@opencode/client` 2.2.7 的 schema 建模;`GET /api/session/:id/form` 拉取待答问题,`POST …/form/:fid/reply` 提交、`DELETE …/form/:fid` 取消;订阅 `form.created/replied/cancelled`。输入框上方是表单卡片:string(带 options 时用 chip + 「其他…」)、multiselect、boolean(开关)、number/integer、external(链接确认);`when` 控制字段显隐,必填项(含「必须打开」的开关)不满足时提示并阻止发送,最多 360 px 内部滚动 |
|
||||||
|
| 左右分栏 | 新增 `lib/screens/home_screen.dart`:手机(< 840 px)把会话列表放进左侧 Drawer、聊天占满屏幕、顶栏是菜单键;宽屏(平板/桌面)左侧常驻 320 px 会话列 + 聊天。两者共用同一个 `SessionListPane`(会话选中高亮、搜索、新建、服务器、重命名/归档/删除)。启动时若还没有打开的会话,自动打开最新一条(与官方手机端一致) |
|
||||||
|
| 版本 | **0.3.10(code 310)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
|
## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
|
||||||
|
|
||||||
**背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo;
|
**背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo;
|
||||||
|
|||||||
@@ -1,27 +1,76 @@
|
|||||||
# OpenChamber Native
|
# Chamber Go
|
||||||
|
|
||||||
A lightweight OpenChamber client for phones, written in **Flutter** (Dart).
|
Chamber Go is a lightweight OpenChamber client for phones, written in
|
||||||
|
**Flutter** (Dart).
|
||||||
Android first. This branch (`flutter`) is a framework evaluation: the same
|
Android first. This branch (`flutter`) is a framework evaluation: the same
|
||||||
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
||||||
Flutter to compare mobile UI maturity.
|
Flutter to compare mobile UI maturity.
|
||||||
|
|
||||||
Status: 0.3.9 — servers (passwordless / password login, HTTP/HTTPS and
|
Status: 0.7.4 — servers (passwordless / password login, HTTP/HTTPS and
|
||||||
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
|
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
|
||||||
|
over the OpenChamber private relay with end-to-end encryption; the pairing
|
||||||
|
link is pasted or scanned with the camera), session list with search and live
|
||||||
events, chat with streaming Markdown and full history paging, tool steps
|
events, chat with streaming Markdown and full history paging, tool steps
|
||||||
grouped per turn (icon, one-line summary, foldable run) with image previews, a
|
grouped per turn (icon, one-line summary, foldable run) with image previews, a
|
||||||
context usage ring with a detail sheet, model/agent switching (Build/Plan only,
|
context usage ring with a detail sheet (an estimated window when the session's
|
||||||
current one checked), copy / fork / revert, attachments (photos/files),
|
model has left the server catalog), model/agent switching (Build/Plan only,
|
||||||
permissions. Android 7.0 (API 24)+, plus a Linux desktop target used for local
|
current one checked), copy / fork / revert, attachments (photos/files, kept
|
||||||
testing.
|
after a reload), the agent's native forms, permissions. The project picker can
|
||||||
|
add a folder from the server: it browses from the server user's home, renames
|
||||||
|
paths and creates folders, and keeps a project that exists only in OpenChamber's
|
||||||
|
settings (no session yet) in the list. The files sidebar also
|
||||||
|
carries the project knowledge (notes, todos, plans, and agent memory when the
|
||||||
|
server enables it) and a full terminal with a Termux-style key bar; downloads
|
||||||
|
show their progress and can be cancelled. The terminal holds several tabs per
|
||||||
|
project, switched from a dropdown next to the status (new tab included), and
|
||||||
|
remembers them per connection and directory: reopening after an app restart
|
||||||
|
attaches to the shells the server still holds instead of starting new ones. The panel is a tab row with its own
|
||||||
|
close button, and each tab has its own header row. Starting a session opens a
|
||||||
|
draft that only creates the session on the first send; the session list is
|
||||||
|
grouped by project with date captions, pins, archive and swipe actions;
|
||||||
|
subagent sessions nest under the session that started them (collapsed until
|
||||||
|
expanded) and open from the sidebar or the parent's Agent Task row; a subagent
|
||||||
|
chat is read-only unless the server allows prompting subagents; edit, write
|
||||||
|
and patch calls open as tinted line diffs with +N −M counts and show their
|
||||||
|
file path relative to the session directory; a finished image-generation call
|
||||||
|
shows the picture in the conversation instead of folding it away; commands
|
||||||
|
running in the background get a strip above the composer with their clock and
|
||||||
|
a stop, and their live output opens from there; the
|
||||||
|
server's managed chat folders are one 聊天 group, and a new session can target
|
||||||
|
聊天 instead of a project. Project rows use the icon and colour chosen in
|
||||||
|
OpenChamber (including an uploaded/auto icon image), and the chat group has a
|
||||||
|
chat icon. The
|
||||||
|
composer folds to one line when unfocused (or when the keyboard is dismissed)
|
||||||
|
and opens into two rows on focus, as in dsh-Go: the model and its thinking level
|
||||||
|
form one pill, the Build/Plan mode a separate chip (picked from a sheet). A
|
||||||
|
message sent while a turn runs can steer it or queue for its end, and waits as a
|
||||||
|
pending bubble that can be withdrawn; while a turn runs, an activity strip above
|
||||||
|
the input names the current step and its clock instead of the finished turn's
|
||||||
|
footer. Pets are opt-in: nothing is built in, and a dsh-Go sprite pack (a zip
|
||||||
|
with pack.json) is imported from Settings → 宠物 to stand above the input and
|
||||||
|
react to the turn's mood. The pet floats over the messages (only its body
|
||||||
|
takes touches) and can be dragged along the input's top edge; the spot is
|
||||||
|
remembered on the device. The picker groups providers, favourites,
|
||||||
|
recents and context size. The sidebar footer names the connected server (tap to
|
||||||
|
switch) beside a settings key; settings holds appearance (theme mode and seed
|
||||||
|
colour, device-local), the server's follow-up behavior (steer or queue on a send
|
||||||
|
while a turn runs) and a pet placeholder. A
|
||||||
|
phone opens the session list as the left drawer and a wide window (tablet,
|
||||||
|
desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop
|
||||||
|
target used for local testing.
|
||||||
|
|
||||||
## What is here
|
## What is here
|
||||||
|
|
||||||
| Path | What |
|
| Path | What |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback` |
|
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, forms, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; every request goes through `Transport` (today `DirectTransport`: HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback`), so a relay tunnel only adds an implementation |
|
||||||
| `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) |
|
| `lib/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/state.dart` | The app state: connections, live sessions, the open chat, the server's follow-up behavior, and SSE event folding |
|
||||||
| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets); the message list is reversed so older pages grow above without moving the viewport |
|
| `lib/appearance_prefs.dart` | Device-local theme mode and seed colour (`shared_preferences`) |
|
||||||
|
| `lib/pets/` | Imported pet packs: the dsh-Go `pack.json` sprite format, unpacked into the app's documents, plus the one-sheet image cache |
|
||||||
|
| `lib/widgets/pet_sprite.dart` | The pet strip above the composer and its sprite player (frames, moods, tap reactions) |
|
||||||
|
| `lib/terminal_state.dart` | Terminal workspaces and tabs: each tab is an xterm model plus its `/api/terminal/ws` socket; switching detaches the old tab, the saved tab list lets a restart reattach |
|
||||||
|
| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar with the knowledge and terminal tabs); the message list is reversed so older pages grow above without moving the viewport |
|
||||||
| `lib/widgets/` | The context usage ring |
|
| `lib/widgets/` | The context usage ring |
|
||||||
|
|
||||||
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
|
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
|
||||||
|
|||||||
@@ -42,6 +42,10 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation("androidx.core:core-ktx:1.13.1")
|
||||||
|
}
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
compilerOptions {
|
compilerOptions {
|
||||||
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
|
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
|
||||||
|
|||||||
@@ -1,9 +1,21 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
<uses-permission android:name="android.permission.CAMERA"/>
|
||||||
|
<!-- Saving to the gallery; Android 10+ uses MediaStore without this. -->
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||||
|
android:maxSdkVersion="28"/>
|
||||||
|
<!-- The camera plugin declares audio for video; the scanner only reads
|
||||||
|
frames, so the app must not end up asking for the microphone. -->
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove"/>
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false"/>
|
||||||
|
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
|
||||||
<application
|
<application
|
||||||
android:label="OpenChamber"
|
android:label="Chamber Go"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher">
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:usesCleartextTraffic="true">
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
@@ -26,6 +38,16 @@
|
|||||||
<category android:name="android.intent.category.LAUNCHER"/>
|
<category android:name="android.intent.category.LAUNCHER"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
<!-- Pictures the image viewer shares out of the app's cache. -->
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths"/>
|
||||||
|
</provider>
|
||||||
<!-- Don't delete the meta-data below.
|
<!-- Don't delete the meta-data below.
|
||||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||||
<meta-data
|
<meta-data
|
||||||
|
|||||||
@@ -1,5 +1,227 @@
|
|||||||
package net.blumia.openchamber.flutter
|
package net.blumia.openchamber.flutter
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.media.MediaScannerConnection
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
|
import io.flutter.plugin.common.MethodChannel
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
class MainActivity : FlutterActivity()
|
class MainActivity : FlutterActivity() {
|
||||||
|
private data class PendingSave(
|
||||||
|
val bytes: ByteArray,
|
||||||
|
val name: String,
|
||||||
|
val mime: String,
|
||||||
|
val result: MethodChannel.Result,
|
||||||
|
)
|
||||||
|
|
||||||
|
private var pendingSave: PendingSave? = null
|
||||||
|
|
||||||
|
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||||
|
super.configureFlutterEngine(flutterEngine)
|
||||||
|
// The app's private files directory, for imported pet packs. A small
|
||||||
|
// channel instead of path_provider, whose JNI binding does not load
|
||||||
|
// on this engine.
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/appdir")
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"documents" -> result.success(filesDir.absolutePath)
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The statistics API buckets days by an IANA zone; Dart only knows the
|
||||||
|
// abbreviation, so the platform reports the real id.
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/device")
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"ianaTimeZone" -> result.success(java.util.TimeZone.getDefault().id)
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The right sidebar's browser hands a page to the system browser.
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/browser")
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"openUrl" -> {
|
||||||
|
val url = call.argument<String>("url")
|
||||||
|
if (url.isNullOrBlank()) {
|
||||||
|
result.error("bad_args", "Missing URL", null)
|
||||||
|
return@setMethodCallHandler
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
|
||||||
|
result.success(true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
result.error("open_failed", e.message ?: "Could not open the URL", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Saving a conversation picture to the gallery and sharing it: both
|
||||||
|
// need Android APIs (MediaStore, FileProvider) that a Dart package
|
||||||
|
// would pull in another native dependency for.
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/media")
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"saveImage" -> {
|
||||||
|
val bytes = call.argument<ByteArray>("bytes")
|
||||||
|
val name = call.argument<String>("name")
|
||||||
|
val mime = call.argument<String>("mime") ?: "image/png"
|
||||||
|
if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) {
|
||||||
|
result.error("bad_args", "Missing image data", null)
|
||||||
|
return@setMethodCallHandler
|
||||||
|
}
|
||||||
|
saveImage(bytes, name, mime, result)
|
||||||
|
}
|
||||||
|
"shareImage" -> {
|
||||||
|
val bytes = call.argument<ByteArray>("bytes")
|
||||||
|
val name = call.argument<String>("name")
|
||||||
|
val mime = call.argument<String>("mime") ?: "image/png"
|
||||||
|
if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) {
|
||||||
|
result.error("bad_args", "Missing image data", null)
|
||||||
|
return@setMethodCallHandler
|
||||||
|
}
|
||||||
|
shareImage(bytes, name, mime, result)
|
||||||
|
}
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveImage(
|
||||||
|
bytes: ByteArray,
|
||||||
|
name: String,
|
||||||
|
mime: String,
|
||||||
|
result: MethodChannel.Result,
|
||||||
|
) {
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
|
||||||
|
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
|
||||||
|
PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
if (pendingSave != null) {
|
||||||
|
result.error("busy", "Another picture is being saved", null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pendingSave = PendingSave(bytes, name, mime, result)
|
||||||
|
requestPermissions(
|
||||||
|
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
|
||||||
|
REQUEST_SAVE,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeImage(bytes, name, mime, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeImage(
|
||||||
|
bytes: ByteArray,
|
||||||
|
name: String,
|
||||||
|
mime: String,
|
||||||
|
result: MethodChannel.Result,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(MediaStore.Images.Media.DISPLAY_NAME, name)
|
||||||
|
put(MediaStore.Images.Media.MIME_TYPE, mime)
|
||||||
|
put(
|
||||||
|
MediaStore.Images.Media.RELATIVE_PATH,
|
||||||
|
"${Environment.DIRECTORY_PICTURES}/Chamber Go",
|
||||||
|
)
|
||||||
|
put(MediaStore.Images.Media.IS_PENDING, 1)
|
||||||
|
}
|
||||||
|
val collection = MediaStore.Images.Media.getContentUri(
|
||||||
|
MediaStore.VOLUME_EXTERNAL_PRIMARY,
|
||||||
|
)
|
||||||
|
val uri = contentResolver.insert(collection, values)
|
||||||
|
?: throw IllegalStateException("Could not create the picture")
|
||||||
|
contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||||
|
?: throw IllegalStateException("Could not open the picture")
|
||||||
|
values.clear()
|
||||||
|
values.put(MediaStore.Images.Media.IS_PENDING, 0)
|
||||||
|
contentResolver.update(uri, values, null, null)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||||
|
?: throw IllegalStateException("Could not decode the picture")
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val uri = MediaStore.Images.Media.insertImage(
|
||||||
|
contentResolver, bitmap, name, null,
|
||||||
|
) ?: throw IllegalStateException("Could not save the picture")
|
||||||
|
bitmap.recycle()
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
MediaScannerConnection.scanFile(
|
||||||
|
this,
|
||||||
|
arrayOf(Uri.parse(uri).path ?: ""),
|
||||||
|
arrayOf(mime),
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
result.success(true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
result.error("save_failed", e.message ?: "Could not save the picture", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shareImage(
|
||||||
|
bytes: ByteArray,
|
||||||
|
name: String,
|
||||||
|
mime: String,
|
||||||
|
result: MethodChannel.Result,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
val directory = File(cacheDir, "shared_images").apply { mkdirs() }
|
||||||
|
val file = File(directory, name)
|
||||||
|
file.writeBytes(bytes)
|
||||||
|
val uri = FileProvider.getUriForFile(
|
||||||
|
this, "$packageName.fileprovider", file,
|
||||||
|
)
|
||||||
|
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||||
|
type = mime
|
||||||
|
putExtra(Intent.EXTRA_STREAM, uri)
|
||||||
|
clipData = ClipData.newRawUri("image", uri)
|
||||||
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
startActivity(Intent.createChooser(intent, "Share image"))
|
||||||
|
result.success(true)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
result.error("share_failed", e.message ?: "Could not share the picture", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onRequestPermissionsResult(
|
||||||
|
requestCode: Int,
|
||||||
|
permissions: Array<out String>,
|
||||||
|
grantResults: IntArray,
|
||||||
|
) {
|
||||||
|
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||||
|
if (requestCode != REQUEST_SAVE) return
|
||||||
|
val pending = pendingSave ?: return
|
||||||
|
pendingSave = null
|
||||||
|
if (grantResults.isNotEmpty() &&
|
||||||
|
grantResults[0] == PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
writeImage(pending.bytes, pending.name, pending.mime, pending.result)
|
||||||
|
} else {
|
||||||
|
pending.result.error(
|
||||||
|
"permission",
|
||||||
|
"Storage permission is required to save the picture",
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val REQUEST_SAVE = 701
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths>
|
||||||
|
<!-- Pictures the viewer writes before sharing them. -->
|
||||||
|
<cache-path name="shared_images" path="shared_images/" />
|
||||||
|
</paths>
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
<key>CFBundleDevelopmentRegion</key>
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||||
<key>CFBundleDisplayName</key>
|
<key>CFBundleDisplayName</key>
|
||||||
<string>Openchamber</string>
|
<string>Chamber Go</string>
|
||||||
<key>CFBundleExecutable</key>
|
<key>CFBundleExecutable</key>
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
<key>CFBundleIdentifier</key>
|
<key>CFBundleIdentifier</key>
|
||||||
|
|||||||
+766
-245
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
|||||||
|
// A loopback TCP listener that carries each accepted connection through the
|
||||||
|
// OpenChamber host's dev-server tunnel. The WebView loads
|
||||||
|
// http://127.0.0.1:<localPort>, so a dev server running on the host (its own
|
||||||
|
// localhost) can be previewed from the phone; the original URL stays in the
|
||||||
|
// address bar.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import '../state.dart';
|
||||||
|
import 'transport.dart';
|
||||||
|
|
||||||
|
/// True for an address that means "the host running the dev server".
|
||||||
|
bool isLoopbackDevHost(String host) {
|
||||||
|
final h = host.trim().toLowerCase();
|
||||||
|
return h == 'localhost' ||
|
||||||
|
h == '127.0.0.1' ||
|
||||||
|
h == '::1' ||
|
||||||
|
h == '[::1]' ||
|
||||||
|
h == '0.0.0.0' ||
|
||||||
|
h == '::';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The port a dev-server URL names (80/443 when it has none), or null.
|
||||||
|
int? devServerPort(Uri uri) {
|
||||||
|
if (!isLoopbackDevHost(uri.host)) return null;
|
||||||
|
if (uri.hasPort) return uri.port > 0 ? uri.port : null;
|
||||||
|
return uri.scheme == 'https' ? 443 : 80;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The URL the WebView loads: the same path on the tunnel's local port.
|
||||||
|
Uri localTunnelUri(Uri original, int localPort) => original.replace(
|
||||||
|
scheme: 'http',
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: localPort,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Maps a URL the WebView reports back to the original host's URL, so the
|
||||||
|
/// address bar and history show the dev server's address, not the listener's.
|
||||||
|
String displayUrlFor(String webUrl, int localPort, String displayOrigin) {
|
||||||
|
final local = 'http://127.0.0.1:$localPort';
|
||||||
|
if (webUrl == local) return displayOrigin;
|
||||||
|
if (webUrl.startsWith('$local/')) {
|
||||||
|
return '$displayOrigin${webUrl.substring(local.length)}';
|
||||||
|
}
|
||||||
|
return webUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A local TCP listener for [remotePort] on the OpenChamber host.
|
||||||
|
class DevTunnel {
|
||||||
|
final AppState app;
|
||||||
|
final int remotePort;
|
||||||
|
|
||||||
|
ServerSocket? _server;
|
||||||
|
final Set<_Pipe> _pipes = {};
|
||||||
|
bool _closed = false;
|
||||||
|
|
||||||
|
DevTunnel(this.app, this.remotePort);
|
||||||
|
|
||||||
|
int get localPort => _server?.port ?? 0;
|
||||||
|
|
||||||
|
Future<int> start() async {
|
||||||
|
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
if (_closed) {
|
||||||
|
await server.close();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
_server = server;
|
||||||
|
server.listen(_accept);
|
||||||
|
return server.port;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _accept(Socket socket) async {
|
||||||
|
if (_closed) {
|
||||||
|
socket.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
TransportSocket? tunnel;
|
||||||
|
try {
|
||||||
|
tunnel = await app.openDevTunnel(remotePort);
|
||||||
|
} catch (_) {
|
||||||
|
socket.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_closed) {
|
||||||
|
socket.destroy();
|
||||||
|
await tunnel.close().catchError((Object _) {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
late final _Pipe pipe;
|
||||||
|
pipe = _Pipe(socket, tunnel, () => _pipes.remove(pipe));
|
||||||
|
_pipes.add(pipe);
|
||||||
|
socket.listen(
|
||||||
|
pipe.toTunnel,
|
||||||
|
onError: (_) => pipe.close(),
|
||||||
|
onDone: () => pipe.close(),
|
||||||
|
);
|
||||||
|
tunnel.messages.listen(
|
||||||
|
pipe.toSocket,
|
||||||
|
onError: (_) => pipe.close(),
|
||||||
|
onDone: () => pipe.close(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> close() async {
|
||||||
|
if (_closed) return;
|
||||||
|
_closed = true;
|
||||||
|
await _server?.close();
|
||||||
|
_server = null;
|
||||||
|
for (final pipe in [..._pipes]) {
|
||||||
|
await pipe.close();
|
||||||
|
}
|
||||||
|
_pipes.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Pipe {
|
||||||
|
final Socket socket;
|
||||||
|
final TransportSocket tunnel;
|
||||||
|
final void Function() onClosed;
|
||||||
|
bool _closed = false;
|
||||||
|
|
||||||
|
_Pipe(this.socket, this.tunnel, this.onClosed);
|
||||||
|
|
||||||
|
void toTunnel(List<int> data) {
|
||||||
|
if (_closed) return;
|
||||||
|
try {
|
||||||
|
tunnel.add(data);
|
||||||
|
} catch (_) {
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void toSocket(List<int> data) {
|
||||||
|
if (_closed) return;
|
||||||
|
try {
|
||||||
|
socket.add(data);
|
||||||
|
} catch (_) {
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> close() async {
|
||||||
|
if (_closed) return;
|
||||||
|
_closed = true;
|
||||||
|
try {
|
||||||
|
socket.destroy();
|
||||||
|
} catch (_) {}
|
||||||
|
try {
|
||||||
|
await tunnel.close();
|
||||||
|
} catch (_) {}
|
||||||
|
onClosed();
|
||||||
|
}
|
||||||
|
}
|
||||||
+784
-4
@@ -1,6 +1,10 @@
|
|||||||
// OpenChamber API models, ported from the Go client's protocol knowledge.
|
// OpenChamber API models, ported from the Go client's protocol knowledge.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
class ModelRef {
|
class ModelRef {
|
||||||
final String id;
|
final String id;
|
||||||
final String providerId;
|
final String providerId;
|
||||||
@@ -52,34 +56,247 @@ class Location {
|
|||||||
|
|
||||||
class Session {
|
class Session {
|
||||||
final String id;
|
final String id;
|
||||||
|
final String? parentID;
|
||||||
|
final String projectID;
|
||||||
final String title;
|
final String title;
|
||||||
final String agent;
|
final String agent;
|
||||||
final ModelRef? model;
|
final ModelRef? model;
|
||||||
final Location? location;
|
final Location? location;
|
||||||
|
final Map<String, dynamic> metadata;
|
||||||
final int created;
|
final int created;
|
||||||
final int updated;
|
final int updated;
|
||||||
|
final int viewed;
|
||||||
|
final int archived;
|
||||||
|
|
||||||
Session({
|
Session({
|
||||||
required this.id,
|
required this.id,
|
||||||
required this.title,
|
required this.title,
|
||||||
|
this.parentID,
|
||||||
|
this.projectID = '',
|
||||||
this.agent = '',
|
this.agent = '',
|
||||||
this.model,
|
this.model,
|
||||||
this.location,
|
this.location,
|
||||||
|
this.metadata = const {},
|
||||||
this.created = 0,
|
this.created = 0,
|
||||||
this.updated = 0,
|
this.updated = 0,
|
||||||
|
this.viewed = 0,
|
||||||
|
this.archived = 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
factory Session.fromJson(Map<String, dynamic> j) {
|
factory Session.fromJson(Map<String, dynamic> j) {
|
||||||
final t = j['time'] as Map<String, dynamic>? ?? {};
|
final t = j['time'] as Map<String, dynamic>? ?? {};
|
||||||
return Session(
|
return Session(
|
||||||
id: j['id'] as String,
|
id: j['id'] as String,
|
||||||
|
parentID: j['parentID'] as String?,
|
||||||
|
projectID: j['projectID'] as String? ?? '',
|
||||||
title: j['title'] as String? ?? '',
|
title: j['title'] as String? ?? '',
|
||||||
agent: j['agent'] as String? ?? '',
|
agent: j['agent'] as String? ?? '',
|
||||||
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
|
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
|
||||||
location: j['location'] == null ? null : Location.fromJson(j['location'] as Map<String, dynamic>),
|
location: j['location'] == null ? null : Location.fromJson(j['location'] as Map<String, dynamic>),
|
||||||
|
metadata: j['metadata'] is Map<String, dynamic>
|
||||||
|
? Map<String, dynamic>.from(j['metadata'] as Map<String, dynamic>)
|
||||||
|
: const {},
|
||||||
created: (t['created'] as num?)?.toInt() ?? 0,
|
created: (t['created'] as num?)?.toInt() ?? 0,
|
||||||
updated: (t['updated'] as num?)?.toInt() ?? 0,
|
updated: (t['updated'] as num?)?.toInt() ?? 0,
|
||||||
|
viewed: (t['viewed'] as num?)?.toInt() ?? 0,
|
||||||
|
archived: (t['archived'] as num?)?.toInt() ?? 0,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
String get directory => location?.directory ?? '';
|
String get directory => location?.directory ?? '';
|
||||||
|
|
||||||
|
bool get isChild => parentID != null && parentID!.isNotEmpty;
|
||||||
|
bool get isArchived => archived > 0;
|
||||||
|
|
||||||
|
/// Pins live in the session's metadata (`openchamber.pinned`), so every
|
||||||
|
/// client of the server sees them.
|
||||||
|
bool get isPinned {
|
||||||
|
final openchamber = metadata['openchamber'];
|
||||||
|
return openchamber is Map && openchamber['pinned'] is Map;
|
||||||
|
}
|
||||||
|
|
||||||
|
int get pinnedAt {
|
||||||
|
final openchamber = metadata['openchamber'];
|
||||||
|
if (openchamber is! Map) return 0;
|
||||||
|
final pinned = openchamber['pinned'];
|
||||||
|
return pinned is Map && pinned['at'] is num ? (pinned['at'] as num).toInt() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Session copyWith({
|
||||||
|
String? title,
|
||||||
|
ModelRef? model,
|
||||||
|
String? agent,
|
||||||
|
Map<String, dynamic>? metadata,
|
||||||
|
int? viewed,
|
||||||
|
int? archived,
|
||||||
|
int? updated,
|
||||||
|
}) =>
|
||||||
|
Session(
|
||||||
|
id: id,
|
||||||
|
parentID: parentID,
|
||||||
|
projectID: projectID,
|
||||||
|
title: title ?? this.title,
|
||||||
|
agent: agent ?? this.agent,
|
||||||
|
model: model ?? this.model,
|
||||||
|
location: location,
|
||||||
|
metadata: metadata ?? this.metadata,
|
||||||
|
created: created,
|
||||||
|
updated: updated ?? this.updated,
|
||||||
|
viewed: viewed ?? this.viewed,
|
||||||
|
archived: archived ?? this.archived,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The server's home and managed chats roots (`GET /api/fs/home`).
|
||||||
|
class FsHomeInfo {
|
||||||
|
final String home;
|
||||||
|
final String chatsRoot;
|
||||||
|
final String? canonicalChatsRoot;
|
||||||
|
final String? canonicalLegacyChatsRoot;
|
||||||
|
|
||||||
|
const FsHomeInfo({
|
||||||
|
required this.home,
|
||||||
|
required this.chatsRoot,
|
||||||
|
this.canonicalChatsRoot,
|
||||||
|
this.canonicalLegacyChatsRoot,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory FsHomeInfo.fromJson(Map<String, dynamic> j) {
|
||||||
|
String? nonEmpty(Object? value) =>
|
||||||
|
value is String && value.trim().isNotEmpty ? value.trim() : null;
|
||||||
|
return FsHomeInfo(
|
||||||
|
home: nonEmpty(j['home']) ?? '',
|
||||||
|
chatsRoot: nonEmpty(j['chatsRoot']) ?? '',
|
||||||
|
canonicalChatsRoot: nonEmpty(j['canonicalChatsRoot']),
|
||||||
|
canonicalLegacyChatsRoot: nonEmpty(j['canonicalLegacyChatsRoot']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A project the server knows: a checkout (or chat folder) an agent can work
|
||||||
|
/// in. [canonical] is the directory a session there carries.
|
||||||
|
class ProjectInfo {
|
||||||
|
final String id;
|
||||||
|
final String canonical;
|
||||||
|
final String name;
|
||||||
|
final String vcs;
|
||||||
|
|
||||||
|
/// The OpenChamber settings row this project was decorated from. The icon
|
||||||
|
/// endpoint keys on this id, not the opencode project id.
|
||||||
|
final String metaId;
|
||||||
|
final String icon;
|
||||||
|
final String color;
|
||||||
|
final String iconBackground;
|
||||||
|
final String iconImageMime;
|
||||||
|
final int iconImageUpdatedAt;
|
||||||
|
|
||||||
|
const ProjectInfo({
|
||||||
|
required this.id,
|
||||||
|
required this.canonical,
|
||||||
|
this.name = '',
|
||||||
|
this.vcs = '',
|
||||||
|
this.metaId = '',
|
||||||
|
this.icon = '',
|
||||||
|
this.color = '',
|
||||||
|
this.iconBackground = '',
|
||||||
|
this.iconImageMime = '',
|
||||||
|
this.iconImageUpdatedAt = 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProjectInfo.fromJson(Map<String, dynamic> j) => ProjectInfo(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
canonical: j['canonical'] as String? ?? '',
|
||||||
|
name: j['name'] as String? ?? '',
|
||||||
|
vcs: j['vcs'] as String? ?? '',
|
||||||
|
);
|
||||||
|
|
||||||
|
bool get hasIconImage => metaId.isNotEmpty && iconImageUpdatedAt > 0;
|
||||||
|
|
||||||
|
/// Decorates the opencode project with its OpenChamber settings row: the
|
||||||
|
/// operator's label, icon key, colour and uploaded/auto icon image.
|
||||||
|
ProjectInfo withMeta(Map<String, dynamic>? meta) {
|
||||||
|
if (meta == null) return this;
|
||||||
|
String text(Object? value) => value is String ? value.trim() : '';
|
||||||
|
final label = text(meta['label']);
|
||||||
|
final image = meta['iconImage'];
|
||||||
|
var mime = '';
|
||||||
|
var updatedAt = 0;
|
||||||
|
if (image is Map) {
|
||||||
|
mime = text(image['mime']);
|
||||||
|
final updated = image['updatedAt'];
|
||||||
|
if (updated is num) updatedAt = updated.toInt();
|
||||||
|
}
|
||||||
|
return ProjectInfo(
|
||||||
|
id: id,
|
||||||
|
canonical: canonical,
|
||||||
|
name: label.isNotEmpty ? label : name,
|
||||||
|
vcs: vcs,
|
||||||
|
metaId: text(meta['id']),
|
||||||
|
icon: text(meta['icon']),
|
||||||
|
color: text(meta['color']),
|
||||||
|
iconBackground: text(meta['iconBackground']),
|
||||||
|
iconImageMime: mime,
|
||||||
|
iconImageUpdatedAt: updatedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String get label {
|
||||||
|
if (name.trim().isNotEmpty) return name.trim();
|
||||||
|
return pathLeaf(canonical);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last segment of a path, treating `\` and `/` alike: a Windows server
|
||||||
|
/// sends `C:\...` and a project has to read as its folder name, not the path.
|
||||||
|
String pathLeaf(String path) {
|
||||||
|
final trimmed = path.replaceAll(RegExp(r'[/\\]+$'), '');
|
||||||
|
// A filesystem root ("/", "C:\") has no last segment; its own path is the
|
||||||
|
// only name left, and an empty one would render a blank row and menu entry.
|
||||||
|
if (trimmed.isEmpty) return path.trim();
|
||||||
|
final index = trimmed.lastIndexOf(RegExp(r'[/\\]'));
|
||||||
|
return index >= 0 ? trimmed.substring(index + 1) : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A path with `\` written as `/` and no trailing slash, for comparing and
|
||||||
|
/// grouping directory names from a Windows or a POSIX server.
|
||||||
|
String slashPath(String path) =>
|
||||||
|
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), '');
|
||||||
|
|
||||||
|
/// A file inside [directory] shown without it: the tool row says
|
||||||
|
/// `lib/screens/chat_screen.dart`, as the first-party client does, so a phone
|
||||||
|
/// still sees the part of the path that matters. Paths elsewhere stay whole.
|
||||||
|
String relativePath(String path, String directory) {
|
||||||
|
final file = path.trim();
|
||||||
|
final dir = slashPath(directory.trim());
|
||||||
|
if (file.isEmpty || dir.isEmpty) return file;
|
||||||
|
final normalized = slashPath(file);
|
||||||
|
if (normalized == dir) return '.';
|
||||||
|
if (normalized.startsWith('$dir/')) return normalized.substring(dir.length + 1);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether [directory] is [root] or inside it. Separators are unified and a
|
||||||
|
/// Windows drive path compares case-insensitively, as [samePath] does.
|
||||||
|
bool isUnderDirectory(String directory, String root) {
|
||||||
|
final d = slashPath(directory);
|
||||||
|
final r = slashPath(root);
|
||||||
|
if (d.isEmpty || r.isEmpty) return false;
|
||||||
|
final windows = RegExp(r'^[A-Za-z]:').hasMatch(d) ||
|
||||||
|
RegExp(r'^[A-Za-z]:').hasMatch(r);
|
||||||
|
final dd = windows ? d.toLowerCase() : d;
|
||||||
|
final rr = windows ? r.toLowerCase() : r;
|
||||||
|
return dd == rr || dd.startsWith('$rr/');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether two directory paths name the same place. Separators are unified;
|
||||||
|
/// a drive-letter path compares case-insensitively, as Windows does.
|
||||||
|
bool samePath(String a, String b) {
|
||||||
|
final x = slashPath(a);
|
||||||
|
final y = slashPath(b);
|
||||||
|
if (x == y) return true;
|
||||||
|
final windows = RegExp(r'^[A-Za-z]:').hasMatch(x) ||
|
||||||
|
RegExp(r'^[A-Za-z]:').hasMatch(y);
|
||||||
|
return windows && x.toLowerCase() == y.toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
class ContentPart {
|
class ContentPart {
|
||||||
@@ -232,6 +449,10 @@ class Message {
|
|||||||
final String reason;
|
final String reason;
|
||||||
/// Compaction messages: the summary the model wrote for the new history.
|
/// Compaction messages: the summary the model wrote for the new history.
|
||||||
final String summary;
|
final String summary;
|
||||||
|
|
||||||
|
/// What the server attached to the message: a synthetic note carries why it
|
||||||
|
/// was written (a stopped shell, a job report), the chat UI reads that.
|
||||||
|
final Map<String, dynamic>? metadata;
|
||||||
Message({
|
Message({
|
||||||
required this.id,
|
required this.id,
|
||||||
required this.type,
|
required this.type,
|
||||||
@@ -249,6 +470,7 @@ class Message {
|
|||||||
this.status = '',
|
this.status = '',
|
||||||
this.reason = '',
|
this.reason = '',
|
||||||
this.summary = '',
|
this.summary = '',
|
||||||
|
this.metadata,
|
||||||
});
|
});
|
||||||
factory Message.fromJson(Map<String, dynamic> j) {
|
factory Message.fromJson(Map<String, dynamic> j) {
|
||||||
final t = j['time'] as Map<String, dynamic>? ?? {};
|
final t = j['time'] as Map<String, dynamic>? ?? {};
|
||||||
@@ -277,6 +499,7 @@ class Message {
|
|||||||
status: j['status'] as String? ?? '',
|
status: j['status'] as String? ?? '',
|
||||||
reason: j['reason'] as String? ?? '',
|
reason: j['reason'] as String? ?? '',
|
||||||
summary: j['summary'] as String? ?? '',
|
summary: j['summary'] as String? ?? '',
|
||||||
|
metadata: j['metadata'] as Map<String, dynamic>?,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
String get partText {
|
String get partText {
|
||||||
@@ -291,9 +514,466 @@ class Message {
|
|||||||
class FileAttachment {
|
class FileAttachment {
|
||||||
final String name;
|
final String name;
|
||||||
final String mime;
|
final String mime;
|
||||||
FileAttachment(this.name, this.mime);
|
|
||||||
factory FileAttachment.fromJson(Map<String, dynamic> j) =>
|
/// Base64 of the file the user attached, as the server stores it.
|
||||||
FileAttachment(j['name'] as String? ?? '', j['mime'] as String? ?? '');
|
final String data;
|
||||||
|
|
||||||
|
/// 'inline' | 'path' — where the bytes came from, when the server says.
|
||||||
|
final String source;
|
||||||
|
|
||||||
|
FileAttachment(this.name, this.mime, {this.data = '', this.source = ''});
|
||||||
|
|
||||||
|
bool get isImage => mime.startsWith('image/') && data.isNotEmpty;
|
||||||
|
|
||||||
|
factory FileAttachment.fromJson(Map<String, dynamic> j) => FileAttachment(
|
||||||
|
j['name'] as String? ?? '',
|
||||||
|
j['mime'] as String? ?? '',
|
||||||
|
data: j['data'] as String? ?? '',
|
||||||
|
// Stored messages carry `{type: 'inline'}` here; keep only text.
|
||||||
|
source: j['source'] is String ? j['source'] as String : '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A prompt the server holds in the session's inbox until it is delivered:
|
||||||
|
/// `queue` waits for the running turn to end, `steer` joins it at its next
|
||||||
|
/// step. The message only enters the transcript when it is delivered.
|
||||||
|
class InboxItem {
|
||||||
|
final String id;
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
/// 'steer' | 'queue'.
|
||||||
|
final String delivery;
|
||||||
|
final int created;
|
||||||
|
final List<FileAttachment> files;
|
||||||
|
|
||||||
|
const InboxItem({
|
||||||
|
required this.id,
|
||||||
|
required this.text,
|
||||||
|
required this.delivery,
|
||||||
|
this.created = 0,
|
||||||
|
this.files = const [],
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Non-user inbox entries (compaction, moves, synthetic context) are the
|
||||||
|
/// server's own; only what the person typed is shown.
|
||||||
|
factory InboxItem.fromJson(Map<String, dynamic> j) {
|
||||||
|
final time = j['time'] as Map<String, dynamic>? ?? {};
|
||||||
|
final payload = j['payload'] as Map<String, dynamic>? ?? {};
|
||||||
|
return InboxItem(
|
||||||
|
id: j['id'] as String,
|
||||||
|
text: payload['text'] as String? ?? '',
|
||||||
|
delivery: j['delivery'] as String? ?? 'queue',
|
||||||
|
created: (time['created'] as num?)?.toInt() ?? 0,
|
||||||
|
files: (payload['files'] as List?)
|
||||||
|
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList() ??
|
||||||
|
const [],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An `enqueued` event carries the payload under `item` and the id beside
|
||||||
|
/// it, rather than in the item.
|
||||||
|
factory InboxItem.fromEvent(String id, Map<String, dynamic> j, int created) {
|
||||||
|
final payload = j['payload'] as Map<String, dynamic>? ?? {};
|
||||||
|
return InboxItem(
|
||||||
|
id: id,
|
||||||
|
text: payload['text'] as String? ?? '',
|
||||||
|
delivery: j['delivery'] as String? ?? 'queue',
|
||||||
|
created: created,
|
||||||
|
files: (payload['files'] as List?)
|
||||||
|
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList() ??
|
||||||
|
const [],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
InboxItem withDelivery(String value) => InboxItem(
|
||||||
|
id: id,
|
||||||
|
text: text,
|
||||||
|
delivery: value,
|
||||||
|
created: created,
|
||||||
|
files: files,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One row of a native form's choice control.
|
||||||
|
class FormOption {
|
||||||
|
final String value;
|
||||||
|
final String label;
|
||||||
|
final String? description;
|
||||||
|
const FormOption(this.value, this.label, [this.description]);
|
||||||
|
factory FormOption.fromJson(Map<String, dynamic> j) => FormOption(
|
||||||
|
j['value'] as String? ?? '',
|
||||||
|
j['label'] as String? ?? j['value'] as String? ?? '',
|
||||||
|
j['description'] as String?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `when` makes a field visible only while another field holds a value.
|
||||||
|
class FormWhen {
|
||||||
|
final String key;
|
||||||
|
final String op; // eq | neq
|
||||||
|
final Object? value;
|
||||||
|
const FormWhen(this.key, this.op, this.value);
|
||||||
|
factory FormWhen.fromJson(Map<String, dynamic> j) => FormWhen(
|
||||||
|
j['key'] as String? ?? '',
|
||||||
|
j['op'] as String? ?? 'eq',
|
||||||
|
j['value'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A field of a form request: string, number, integer, boolean, multiselect
|
||||||
|
/// or external (a link the user acknowledges).
|
||||||
|
class AgentFormField {
|
||||||
|
final String key;
|
||||||
|
final String type;
|
||||||
|
final String? title;
|
||||||
|
final String? description;
|
||||||
|
final String? placeholder;
|
||||||
|
final String? format;
|
||||||
|
final String? url;
|
||||||
|
final bool required;
|
||||||
|
final bool hidden;
|
||||||
|
final bool custom;
|
||||||
|
final Object? defaultValue;
|
||||||
|
final num? minimum;
|
||||||
|
final num? maximum;
|
||||||
|
final int? minLength;
|
||||||
|
final int? maxLength;
|
||||||
|
final int? minItems;
|
||||||
|
final int? maxItems;
|
||||||
|
final List<FormOption> options;
|
||||||
|
final List<FormWhen> when;
|
||||||
|
|
||||||
|
const AgentFormField({
|
||||||
|
required this.key,
|
||||||
|
required this.type,
|
||||||
|
this.title,
|
||||||
|
this.description,
|
||||||
|
this.placeholder,
|
||||||
|
this.format,
|
||||||
|
this.url,
|
||||||
|
this.required = false,
|
||||||
|
this.hidden = false,
|
||||||
|
this.custom = false,
|
||||||
|
this.defaultValue,
|
||||||
|
this.minimum,
|
||||||
|
this.maximum,
|
||||||
|
this.minLength,
|
||||||
|
this.maxLength,
|
||||||
|
this.minItems,
|
||||||
|
this.maxItems,
|
||||||
|
this.options = const [],
|
||||||
|
this.when = const [],
|
||||||
|
});
|
||||||
|
|
||||||
|
factory AgentFormField.fromJson(Map<String, dynamic> j) {
|
||||||
|
num? numOf(Object? v) => v is num ? v : null;
|
||||||
|
return AgentFormField(
|
||||||
|
key: j['key'] as String? ?? '',
|
||||||
|
type: j['type'] as String? ?? 'string',
|
||||||
|
title: j['title'] as String?,
|
||||||
|
description: j['description'] as String?,
|
||||||
|
placeholder: j['placeholder'] as String?,
|
||||||
|
format: j['format'] as String?,
|
||||||
|
url: j['url'] as String?,
|
||||||
|
required: j['required'] as bool? ?? false,
|
||||||
|
hidden: j['hidden'] as bool? ?? false,
|
||||||
|
custom: j['custom'] as bool? ?? false,
|
||||||
|
defaultValue: j['default'],
|
||||||
|
minimum: numOf(j['minimum']),
|
||||||
|
maximum: numOf(j['maximum']),
|
||||||
|
minLength: (j['minLength'] as num?)?.toInt(),
|
||||||
|
maxLength: (j['maxLength'] as num?)?.toInt(),
|
||||||
|
minItems: (j['minItems'] as num?)?.toInt(),
|
||||||
|
maxItems: (j['maxItems'] as num?)?.toInt(),
|
||||||
|
options: [
|
||||||
|
for (final o in (j['options'] as List? ?? []))
|
||||||
|
if (o is Map<String, dynamic>) FormOption.fromJson(o),
|
||||||
|
],
|
||||||
|
when: [
|
||||||
|
for (final w in (j['when'] as List? ?? []))
|
||||||
|
if (w is Map<String, dynamic>) FormWhen.fromJson(w),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String get label => (title == null || title!.isEmpty) ? key : title!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A blocking question from the agent. The client answers every visible field
|
||||||
|
/// at once; the answer map is keyed by field key.
|
||||||
|
class FormInfo {
|
||||||
|
final String id;
|
||||||
|
final String sessionID;
|
||||||
|
final String title;
|
||||||
|
final List<AgentFormField> fields;
|
||||||
|
const FormInfo({
|
||||||
|
required this.id,
|
||||||
|
required this.sessionID,
|
||||||
|
required this.title,
|
||||||
|
required this.fields,
|
||||||
|
});
|
||||||
|
factory FormInfo.fromJson(Map<String, dynamic> j) => FormInfo(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
sessionID: j['sessionID'] as String? ?? '',
|
||||||
|
title: j['title'] as String? ?? '',
|
||||||
|
fields: [
|
||||||
|
for (final f in (j['fields'] as List? ?? []))
|
||||||
|
if (f is Map<String, dynamic>) AgentFormField.fromJson(f),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------- project knowledge
|
||||||
|
|
||||||
|
/// A saved note, as `/api/project-context` stores it.
|
||||||
|
class ProjectNote {
|
||||||
|
final String id;
|
||||||
|
final String body;
|
||||||
|
final int createdAt;
|
||||||
|
final int updatedAt;
|
||||||
|
final String source; // manual | selection | agent
|
||||||
|
final bool pinned;
|
||||||
|
final String? planId;
|
||||||
|
|
||||||
|
const ProjectNote({
|
||||||
|
required this.id,
|
||||||
|
required this.body,
|
||||||
|
this.createdAt = 0,
|
||||||
|
this.updatedAt = 0,
|
||||||
|
this.source = 'manual',
|
||||||
|
this.pinned = false,
|
||||||
|
this.planId,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProjectNote.fromJson(Map<String, dynamic> j) => ProjectNote(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
body: j['body'] as String? ?? '',
|
||||||
|
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||||
|
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
|
||||||
|
source: j['source'] as String? ?? 'manual',
|
||||||
|
pinned: j['pinned'] as bool? ?? false,
|
||||||
|
planId: j['planId'] as String?,
|
||||||
|
);
|
||||||
|
|
||||||
|
String get firstLine {
|
||||||
|
final line = body.split('\n').firstWhere((l) => l.trim().isNotEmpty,
|
||||||
|
orElse: () => '');
|
||||||
|
return line.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A todo item. [planId] links it to a plan; [dependsOn] lists the todos of
|
||||||
|
/// the same plan that must be completed first.
|
||||||
|
class ProjectTodo {
|
||||||
|
final String id;
|
||||||
|
final String text;
|
||||||
|
final bool completed;
|
||||||
|
final int createdAt;
|
||||||
|
final String? planId;
|
||||||
|
final List<String> dependsOn;
|
||||||
|
|
||||||
|
const ProjectTodo({
|
||||||
|
required this.id,
|
||||||
|
required this.text,
|
||||||
|
this.completed = false,
|
||||||
|
this.createdAt = 0,
|
||||||
|
this.planId,
|
||||||
|
this.dependsOn = const [],
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProjectTodo.fromJson(Map<String, dynamic> j) => ProjectTodo(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
text: j['text'] as String? ?? '',
|
||||||
|
completed: j['completed'] as bool? ?? false,
|
||||||
|
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||||
|
planId: j['planId'] as String?,
|
||||||
|
dependsOn: [
|
||||||
|
for (final d in (j['dependsOn'] as List? ?? []))
|
||||||
|
if (d is String) d,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plan the project lists: a manifest entry (personal) or a file from the
|
||||||
|
/// team's shared folder.
|
||||||
|
class ProjectPlanLink {
|
||||||
|
final String id;
|
||||||
|
final String file;
|
||||||
|
final String title;
|
||||||
|
final int createdAt;
|
||||||
|
final bool pinned;
|
||||||
|
final String source; // personal | shared
|
||||||
|
final int progressDone;
|
||||||
|
final int progressTotal;
|
||||||
|
final String? sessionId;
|
||||||
|
|
||||||
|
const ProjectPlanLink({
|
||||||
|
required this.id,
|
||||||
|
required this.file,
|
||||||
|
required this.title,
|
||||||
|
this.createdAt = 0,
|
||||||
|
this.pinned = false,
|
||||||
|
this.source = 'personal',
|
||||||
|
this.progressDone = 0,
|
||||||
|
this.progressTotal = 0,
|
||||||
|
this.sessionId,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProjectPlanLink.fromJson(Map<String, dynamic> j) {
|
||||||
|
final progress = j['progress'];
|
||||||
|
final session = j['session'];
|
||||||
|
return ProjectPlanLink(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
file: j['file'] as String? ?? '',
|
||||||
|
title: j['title'] as String? ?? '',
|
||||||
|
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||||
|
pinned: j['pinned'] as bool? ?? false,
|
||||||
|
source: j['source'] as String? ?? 'personal',
|
||||||
|
progressDone:
|
||||||
|
progress is Map ? (progress['done'] as num?)?.toInt() ?? 0 : 0,
|
||||||
|
progressTotal:
|
||||||
|
progress is Map ? (progress['total'] as num?)?.toInt() ?? 0 : 0,
|
||||||
|
sessionId: session is Map ? session['sessionId'] as String? : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get hasProgress => progressTotal > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything the project knowledge panel shows for one directory.
|
||||||
|
class ProjectContext {
|
||||||
|
final List<ProjectNote> notes;
|
||||||
|
final List<ProjectTodo> todos;
|
||||||
|
final List<ProjectPlanLink> plans;
|
||||||
|
final String? sharedPlansDir;
|
||||||
|
|
||||||
|
const ProjectContext({
|
||||||
|
this.notes = const [],
|
||||||
|
this.todos = const [],
|
||||||
|
this.plans = const [],
|
||||||
|
this.sharedPlansDir,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProjectContext.fromJson(Map<String, dynamic> j) => ProjectContext(
|
||||||
|
notes: [
|
||||||
|
for (final n in (j['notes'] as List? ?? []))
|
||||||
|
if (n is Map<String, dynamic>) ProjectNote.fromJson(n),
|
||||||
|
],
|
||||||
|
todos: [
|
||||||
|
for (final t in (j['todos'] as List? ?? []))
|
||||||
|
if (t is Map<String, dynamic>) ProjectTodo.fromJson(t),
|
||||||
|
],
|
||||||
|
plans: [
|
||||||
|
for (final p in (j['plans'] as List? ?? []))
|
||||||
|
if (p is Map<String, dynamic>) ProjectPlanLink.fromJson(p),
|
||||||
|
],
|
||||||
|
sharedPlansDir: j['sharedPlansDir'] as String?,
|
||||||
|
);
|
||||||
|
|
||||||
|
bool get isEmpty => notes.isEmpty && todos.isEmpty && plans.isEmpty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One remembered fact, preference or reference. The agent writes these
|
||||||
|
/// through its memory tool; the panel reads, corrects and deletes them.
|
||||||
|
class AgentMemoryEntry {
|
||||||
|
final String id;
|
||||||
|
final String title;
|
||||||
|
final String body;
|
||||||
|
final String type; // fact | preference | reference
|
||||||
|
final int createdAt;
|
||||||
|
final int updatedAt;
|
||||||
|
final bool flagged;
|
||||||
|
final String? sessionId;
|
||||||
|
|
||||||
|
const AgentMemoryEntry({
|
||||||
|
required this.id,
|
||||||
|
required this.title,
|
||||||
|
required this.body,
|
||||||
|
this.type = 'fact',
|
||||||
|
this.createdAt = 0,
|
||||||
|
this.updatedAt = 0,
|
||||||
|
this.flagged = false,
|
||||||
|
this.sessionId,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory AgentMemoryEntry.fromJson(Map<String, dynamic> j) => AgentMemoryEntry(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
title: j['title'] as String? ?? '',
|
||||||
|
body: j['body'] as String? ?? '',
|
||||||
|
type: j['type'] as String? ?? 'fact',
|
||||||
|
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
|
||||||
|
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
|
||||||
|
flagged: j['flagged'] == true,
|
||||||
|
sessionId: j['sessionId'] as String?,
|
||||||
|
);
|
||||||
|
|
||||||
|
String get typeLabel => switch (type) {
|
||||||
|
'preference' => tr('Preference'),
|
||||||
|
'reference' => tr('Reference'),
|
||||||
|
_ => tr('Fact'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Both memory scopes in one read, as `/api/agent-memory/all` answers.
|
||||||
|
class AgentMemorySnapshot {
|
||||||
|
final List<AgentMemoryEntry> global;
|
||||||
|
final List<AgentMemoryEntry> project;
|
||||||
|
final bool globalFailed;
|
||||||
|
final bool projectFailed;
|
||||||
|
|
||||||
|
const AgentMemorySnapshot({
|
||||||
|
this.global = const [],
|
||||||
|
this.project = const [],
|
||||||
|
this.globalFailed = false,
|
||||||
|
this.projectFailed = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory AgentMemorySnapshot.fromJson(Map<String, dynamic> j) =>
|
||||||
|
AgentMemorySnapshot(
|
||||||
|
global: [
|
||||||
|
for (final m in (j['global'] as List? ?? []))
|
||||||
|
if (m is Map<String, dynamic>) AgentMemoryEntry.fromJson(m),
|
||||||
|
],
|
||||||
|
project: [
|
||||||
|
for (final m in (j['project'] as List? ?? []))
|
||||||
|
if (m is Map<String, dynamic>) AgentMemoryEntry.fromJson(m),
|
||||||
|
],
|
||||||
|
globalFailed: j['globalFailed'] == true,
|
||||||
|
projectFailed: j['projectFailed'] == true,
|
||||||
|
);
|
||||||
|
|
||||||
|
bool get isEmpty => global.isEmpty && project.isEmpty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plan as the server reads it back: the link plus its Markdown.
|
||||||
|
class ProjectPlanContent {
|
||||||
|
final String id;
|
||||||
|
final String title;
|
||||||
|
final String body;
|
||||||
|
final String raw;
|
||||||
|
final String? path;
|
||||||
|
final String source;
|
||||||
|
|
||||||
|
const ProjectPlanContent({
|
||||||
|
required this.id,
|
||||||
|
required this.title,
|
||||||
|
required this.body,
|
||||||
|
this.raw = '',
|
||||||
|
this.path,
|
||||||
|
this.source = 'personal',
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProjectPlanContent.fromJson(Map<String, dynamic> j) =>
|
||||||
|
ProjectPlanContent(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
title: j['title'] as String? ?? '',
|
||||||
|
body: j['body'] as String? ?? '',
|
||||||
|
raw: j['raw'] as String? ?? '',
|
||||||
|
path: j['path'] as String?,
|
||||||
|
source: j['source'] as String? ?? 'personal',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
class Page<T> {
|
class Page<T> {
|
||||||
@@ -316,17 +996,36 @@ class ModelInfo {
|
|||||||
final String name;
|
final String name;
|
||||||
final int context;
|
final int context;
|
||||||
final int output;
|
final int output;
|
||||||
ModelInfo(this.id, this.providerId, this.name, this.context, this.output);
|
|
||||||
|
/// Thinking levels this model offers (`minimal`, `low`, `medium`, …), as
|
||||||
|
/// v2's model variants. Empty means the model has no effort choice.
|
||||||
|
final List<String> variants;
|
||||||
|
|
||||||
|
/// The provider says the model reasons; worth a mark in the picker.
|
||||||
|
final bool reasoning;
|
||||||
|
|
||||||
|
ModelInfo(this.id, this.providerId, this.name, this.context, this.output,
|
||||||
|
{this.variants = const [], this.reasoning = false});
|
||||||
|
|
||||||
factory ModelInfo.fromJson(Map<String, dynamic> j) {
|
factory ModelInfo.fromJson(Map<String, dynamic> j) {
|
||||||
final lim = j['limit'] as Map<String, dynamic>? ?? {};
|
final lim = j['limit'] as Map<String, dynamic>? ?? {};
|
||||||
|
final capabilities = j['capabilities'];
|
||||||
return ModelInfo(
|
return ModelInfo(
|
||||||
j['id'] as String,
|
j['id'] as String,
|
||||||
j['providerID'] as String? ?? '',
|
j['providerID'] as String? ?? '',
|
||||||
j['name'] as String? ?? (j['id'] as String? ?? ''),
|
j['name'] as String? ?? (j['id'] as String? ?? ''),
|
||||||
(lim['context'] as num?)?.toInt() ?? 0,
|
(lim['context'] as num?)?.toInt() ?? 0,
|
||||||
(lim['output'] as num?)?.toInt() ?? 0,
|
(lim['output'] as num?)?.toInt() ?? 0,
|
||||||
|
variants: [
|
||||||
|
for (final v in (j['variants'] as List? ?? []))
|
||||||
|
if (v is Map && v['id'] is String) v['id'] as String,
|
||||||
|
],
|
||||||
|
reasoning:
|
||||||
|
capabilities is Map && capabilities['reasoning'] == true,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool get hasEffort => variants.isNotEmpty;
|
||||||
}
|
}
|
||||||
|
|
||||||
class AgentInfo {
|
class AgentInfo {
|
||||||
@@ -361,3 +1060,84 @@ String _jsonString(Object? o) {
|
|||||||
if (o is String) return o;
|
if (o is String) return o;
|
||||||
return o.toString();
|
return o.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The images an `openchamber_image` call saved. The first-party client lifts
|
||||||
|
/// such a call out of the folded run and shows the pictures in the chat; this
|
||||||
|
/// reads the call's result envelope (`{ok, action: image.generate, data:
|
||||||
|
/// {images: [{path}]}}`) to know which files those are.
|
||||||
|
List<String> generatedImagePaths(ContentPart part) {
|
||||||
|
const empty = <String>[];
|
||||||
|
if (part.type != 'tool' || part.name != 'openchamber_image') return empty;
|
||||||
|
final state = part.state;
|
||||||
|
if (state == null || state.status != 'completed') return empty;
|
||||||
|
final text = state.content
|
||||||
|
.where((c) => c.type == 'text')
|
||||||
|
.map((c) => c.text)
|
||||||
|
.join()
|
||||||
|
.trim();
|
||||||
|
if (text.isEmpty) return empty;
|
||||||
|
Object? decoded;
|
||||||
|
try {
|
||||||
|
decoded = jsonDecode(text);
|
||||||
|
} catch (_) {
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
if (decoded is! Map) return empty;
|
||||||
|
if (decoded['ok'] != true || decoded['action'] != 'image.generate') {
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
final data = decoded['data'];
|
||||||
|
if (data is! Map) return empty;
|
||||||
|
final images = data['images'];
|
||||||
|
if (images is! List) return empty;
|
||||||
|
final out = <String>[];
|
||||||
|
for (final image in images) {
|
||||||
|
if (image is! Map) continue;
|
||||||
|
final path = image['path'];
|
||||||
|
if (path is String && path.trim().isNotEmpty) out.add(path.trim());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the server says it runs: OpenCode itself (`/api/info`) and the
|
||||||
|
/// OpenChamber web layer in front of it (`/api/version`). Either may be
|
||||||
|
/// empty on older servers.
|
||||||
|
class ServerVersions {
|
||||||
|
final String opencode;
|
||||||
|
final String openchamber;
|
||||||
|
const ServerVersions({this.opencode = '', this.openchamber = ''});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A dev server the OpenChamber host discovered (`GET /api/dev-servers`).
|
||||||
|
/// [url] is the address to preview (usually a loopback URL on the host); the
|
||||||
|
/// browser tunnels its port through `/api/dev-tunnel`.
|
||||||
|
class DevServerInfo {
|
||||||
|
final int port;
|
||||||
|
final String url;
|
||||||
|
final String command;
|
||||||
|
final String directory;
|
||||||
|
final String title;
|
||||||
|
|
||||||
|
const DevServerInfo({
|
||||||
|
this.port = 0,
|
||||||
|
this.url = '',
|
||||||
|
this.command = '',
|
||||||
|
this.directory = '',
|
||||||
|
this.title = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
factory DevServerInfo.fromJson(Map<String, dynamic> j) {
|
||||||
|
final page = j['page'];
|
||||||
|
return DevServerInfo(
|
||||||
|
port: (j['port'] as num?)?.toInt() ?? 0,
|
||||||
|
url: j['url'] as String? ?? '',
|
||||||
|
command: j['command'] as String? ?? '',
|
||||||
|
directory: j['directory'] as String? ?? '',
|
||||||
|
title: page is Map && page['title'] is String
|
||||||
|
? (page['title'] as String).trim()
|
||||||
|
: '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String get label => title.isNotEmpty ? title : (url.isNotEmpty ? url : ':$port');
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
// The pairing link the desktop shows as a QR code: `openchamber://connect?v=2`
|
||||||
|
// with a base64url JSON payload. It carries the one-time secret and the ways
|
||||||
|
// to reach the server — direct URLs and, when enabled, the private relay with
|
||||||
|
// the host's encryption key (the E2EE trust anchor).
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
const _maxPayloadLength = 16384;
|
||||||
|
|
||||||
|
class PairingCandidate {
|
||||||
|
final String type; // lan | tunnel | relay
|
||||||
|
final String url; // direct candidates
|
||||||
|
final String relayUrl; // relay candidates
|
||||||
|
final String serverId;
|
||||||
|
final Map<String, dynamic>? hostKey;
|
||||||
|
final String? grant;
|
||||||
|
final int priority;
|
||||||
|
|
||||||
|
const PairingCandidate.direct({
|
||||||
|
required this.type,
|
||||||
|
required this.url,
|
||||||
|
this.priority = 100,
|
||||||
|
}) : relayUrl = '',
|
||||||
|
serverId = '',
|
||||||
|
hostKey = null,
|
||||||
|
grant = null;
|
||||||
|
|
||||||
|
const PairingCandidate.relay({
|
||||||
|
required String this.relayUrl,
|
||||||
|
required this.serverId,
|
||||||
|
required Map<String, dynamic> this.hostKey,
|
||||||
|
this.grant,
|
||||||
|
this.priority = 100,
|
||||||
|
}) : type = 'relay',
|
||||||
|
url = '';
|
||||||
|
|
||||||
|
bool get isRelay => type == 'relay';
|
||||||
|
}
|
||||||
|
|
||||||
|
class PairingPayload {
|
||||||
|
final String pairingId;
|
||||||
|
final String secret;
|
||||||
|
final String? label;
|
||||||
|
final String? fingerprint;
|
||||||
|
final DateTime? expiresAt;
|
||||||
|
final List<PairingCandidate> candidates;
|
||||||
|
|
||||||
|
const PairingPayload({
|
||||||
|
required this.pairingId,
|
||||||
|
required this.secret,
|
||||||
|
this.label,
|
||||||
|
this.fingerprint,
|
||||||
|
this.expiresAt,
|
||||||
|
required this.candidates,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a link or payload. Returns null when it is not a valid, unexpired
|
||||||
|
/// pairing link. Direct candidates come before relay, each by priority, so a
|
||||||
|
/// reachable LAN address is tried before the tunnel.
|
||||||
|
PairingPayload? parsePairingLink(String raw) {
|
||||||
|
final text = raw.trim();
|
||||||
|
if (text.isEmpty || text.length > _maxPayloadLength) return null;
|
||||||
|
|
||||||
|
String? encoded;
|
||||||
|
final start = text.indexOf('?');
|
||||||
|
if (start >= 0) {
|
||||||
|
final head = text.substring(0, start);
|
||||||
|
if (RegExp(r'^openchamber://connect/?$', caseSensitive: false)
|
||||||
|
.hasMatch(head)) {
|
||||||
|
for (final part in text.substring(start + 1).split('&')) {
|
||||||
|
final eq = part.indexOf('=');
|
||||||
|
if (eq < 0) continue;
|
||||||
|
final key = part.substring(0, eq);
|
||||||
|
final value = part.substring(eq + 1);
|
||||||
|
if (key == 'p') encoded = value;
|
||||||
|
if (key == 'v' && value != '2') return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
encoded ??= text;
|
||||||
|
if (encoded.length > _maxPayloadLength) return null;
|
||||||
|
final Object? decoded;
|
||||||
|
try {
|
||||||
|
decoded = jsonDecode(utf8.decode(_base64UrlDecode(encoded)));
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (decoded is! Map) return null;
|
||||||
|
final pairingId = decoded['pairingId'];
|
||||||
|
final secret = decoded['secret'];
|
||||||
|
if (decoded['v'] != 2 || pairingId is! String || secret is! String) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (pairingId.trim().isEmpty || secret.trim().isEmpty) return null;
|
||||||
|
|
||||||
|
DateTime? expiresAt;
|
||||||
|
final rawExpiry = decoded['expiresAt'];
|
||||||
|
if (rawExpiry is String && rawExpiry.isNotEmpty) {
|
||||||
|
expiresAt = DateTime.tryParse(rawExpiry);
|
||||||
|
if (expiresAt != null && !expiresAt.isAfter(DateTime.now())) return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final rawCandidates = decoded['candidates'];
|
||||||
|
final candidates = <PairingCandidate>[];
|
||||||
|
if (rawCandidates is List) {
|
||||||
|
for (final raw in rawCandidates) {
|
||||||
|
final candidate = _candidate(raw);
|
||||||
|
if (candidate != null) candidates.add(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (candidates.isEmpty) return null;
|
||||||
|
candidates.sort((a, b) {
|
||||||
|
if (a.isRelay != b.isRelay) return a.isRelay ? 1 : -1;
|
||||||
|
return a.priority.compareTo(b.priority);
|
||||||
|
});
|
||||||
|
final label = decoded['label'];
|
||||||
|
final fingerprint = decoded['fingerprint'];
|
||||||
|
return PairingPayload(
|
||||||
|
pairingId: pairingId.trim(),
|
||||||
|
secret: secret.trim(),
|
||||||
|
label: label is String && label.trim().isNotEmpty ? label.trim() : null,
|
||||||
|
fingerprint: fingerprint is String && fingerprint.trim().isNotEmpty
|
||||||
|
? fingerprint.trim()
|
||||||
|
: null,
|
||||||
|
expiresAt: expiresAt,
|
||||||
|
candidates: candidates,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
PairingCandidate? _candidate(Object? raw) {
|
||||||
|
if (raw is! Map) return null;
|
||||||
|
final priority = raw['priority'] is num
|
||||||
|
? (raw['priority'] as num).toInt()
|
||||||
|
: 100;
|
||||||
|
final type = raw['type'];
|
||||||
|
if (type == 'lan' || type == 'tunnel') {
|
||||||
|
final url = _httpUrl(raw['url']);
|
||||||
|
if (url == null) return null;
|
||||||
|
return PairingCandidate.direct(type: type as String, url: url, priority: priority);
|
||||||
|
}
|
||||||
|
if (type == 'relay') {
|
||||||
|
final relayUrl = _wsUrl(raw['relayUrl']);
|
||||||
|
final serverId = raw['serverId'];
|
||||||
|
final key = _ecPublicJwk(raw['hostEncPubJwk']);
|
||||||
|
if (relayUrl == null ||
|
||||||
|
serverId is! String ||
|
||||||
|
serverId.trim().isEmpty ||
|
||||||
|
key == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final grant = raw['grant'];
|
||||||
|
return PairingCandidate.relay(
|
||||||
|
relayUrl: relayUrl,
|
||||||
|
serverId: serverId.trim(),
|
||||||
|
hostKey: key,
|
||||||
|
grant: grant is String && grant.trim().isNotEmpty ? grant.trim() : null,
|
||||||
|
priority: priority,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _httpUrl(Object? raw) {
|
||||||
|
if (raw is! String) return null;
|
||||||
|
final uri = Uri.tryParse(raw.trim());
|
||||||
|
if (uri == null || (uri.scheme != 'http' && uri.scheme != 'https')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (uri.host.isEmpty) return null;
|
||||||
|
return uri.removeFragment().toString().replaceAll(RegExp(r'/+$'), '');
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _wsUrl(Object? raw) {
|
||||||
|
if (raw is! String) return null;
|
||||||
|
final uri = Uri.tryParse(raw.trim());
|
||||||
|
if (uri == null || (uri.scheme != 'ws' && uri.scheme != 'wss')) return null;
|
||||||
|
if (uri.host.isEmpty) return null;
|
||||||
|
return uri.removeFragment().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic>? _ecPublicJwk(Object? raw) {
|
||||||
|
if (raw is! Map) return null;
|
||||||
|
if (raw['kty'] != 'EC' || raw['crv'] != 'P-256') return null;
|
||||||
|
final x = raw['x'];
|
||||||
|
final y = raw['y'];
|
||||||
|
if (x is! String || y is! String || x.isEmpty || y.isEmpty) return null;
|
||||||
|
return {'kty': 'EC', 'crv': 'P-256', 'x': x, 'y': y};
|
||||||
|
}
|
||||||
|
|
||||||
|
List<int> _base64UrlDecode(String value) {
|
||||||
|
final padded = value.padRight((value.length + 3) ~/ 4 * 4, '=');
|
||||||
|
return base64Url.decode(padded);
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// QR decoding for the pairing scanner. The camera hands us a Y plane (YUV420
|
||||||
|
// on Android) that is already luminance; zxing2's QR reader does the rest. Kept
|
||||||
|
// free of Flutter so a frame can be decoded in a background isolate and a unit
|
||||||
|
// test can feed it a generated QR image.
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:zxing2/qrcode.dart';
|
||||||
|
import 'package:zxing2/zxing2.dart';
|
||||||
|
|
||||||
|
/// One grayscale frame: [rowStride] may exceed [width] (camera padding).
|
||||||
|
class QrFrame {
|
||||||
|
final Uint8List luminance;
|
||||||
|
final int width;
|
||||||
|
final int height;
|
||||||
|
final int rowStride;
|
||||||
|
|
||||||
|
const QrFrame({
|
||||||
|
required this.luminance,
|
||||||
|
required this.width,
|
||||||
|
required this.height,
|
||||||
|
required this.rowStride,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The payload of the QR code in [frame], or null when there is none.
|
||||||
|
String? decodeQrFrame(QrFrame frame) => decodeQrLuminance(
|
||||||
|
frame.luminance,
|
||||||
|
frame.width,
|
||||||
|
frame.height,
|
||||||
|
frame.rowStride,
|
||||||
|
);
|
||||||
|
|
||||||
|
String? decodeQrLuminance(
|
||||||
|
Uint8List luminance, int width, int height, int rowStride) {
|
||||||
|
if (width <= 0 || height <= 0 || rowStride < width) return null;
|
||||||
|
// The camera's Y plane may omit the padding of its last row, so the buffer
|
||||||
|
// can be one row shorter than rowStride * height.
|
||||||
|
if (luminance.length < rowStride * (height - 1) + width) return null;
|
||||||
|
final source = _PlaneLuminanceSource(luminance, width, height, rowStride);
|
||||||
|
final direct = _read(source);
|
||||||
|
if (direct != null) return direct;
|
||||||
|
// A pairing QR drawn light-on-dark (a dark card in the web UI) is still a
|
||||||
|
// QR: try the inverted frame before giving up on it.
|
||||||
|
return _read(InvertedLuminanceSource(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _read(LuminanceSource source) {
|
||||||
|
try {
|
||||||
|
final bitmap = BinaryBitmap(HybridBinarizer(source));
|
||||||
|
final hints = DecodeHints()..put(DecodeHintType.tryHarder);
|
||||||
|
return QRCodeReader().decode(bitmap, hints: hints).text;
|
||||||
|
} on ReaderException {
|
||||||
|
return null;
|
||||||
|
} catch (_) {
|
||||||
|
// A torn or malformed frame must not stop the scanner.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// BGRA8888 (iOS and some cameras): green-weighted luminance, as zxing2's
|
||||||
|
/// RGBLuminanceSource computes it.
|
||||||
|
Uint8List bgraToLuminance(
|
||||||
|
Uint8List bytes, int width, int height, int rowStride) {
|
||||||
|
final out = Uint8List(width * height);
|
||||||
|
for (var y = 0; y < height; y++) {
|
||||||
|
final row = y * rowStride;
|
||||||
|
final target = y * width;
|
||||||
|
for (var x = 0; x < width; x++) {
|
||||||
|
final i = row + x * 4;
|
||||||
|
if (i + 2 >= bytes.length) break;
|
||||||
|
final b = bytes[i];
|
||||||
|
final g = bytes[i + 1];
|
||||||
|
final r = bytes[i + 2];
|
||||||
|
out[target + x] = (r + 2 * g + b) >> 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PlaneLuminanceSource extends LuminanceSource {
|
||||||
|
final Uint8List data;
|
||||||
|
final int rowStride;
|
||||||
|
|
||||||
|
_PlaneLuminanceSource(this.data, int width, int height, this.rowStride)
|
||||||
|
: super(width, height);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Int8List getRow(int y, Int8List? row) {
|
||||||
|
final out = (row != null && row.length >= width) ? row : Int8List(width);
|
||||||
|
final base = y * rowStride;
|
||||||
|
final available = data.length - base;
|
||||||
|
final count = available < width ? available : width;
|
||||||
|
for (var x = 0; x < count; x++) {
|
||||||
|
out[x] = data[base + x].toSigned(8);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Int8List getMatrix() {
|
||||||
|
final out = Int8List(width * height);
|
||||||
|
for (var y = 0; y < height; y++) {
|
||||||
|
final base = y * rowStride;
|
||||||
|
final target = y * width;
|
||||||
|
final available = data.length - base;
|
||||||
|
final count = available < width ? available : width;
|
||||||
|
for (var x = 0; x < count; x++) {
|
||||||
|
out[target + x] = data[base + x].toSigned(8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
// E2EE for the OpenChamber private relay (Layer 2). The host holds a
|
||||||
|
// long-lived P-256 key; its public JWK reaches us in the pairing link and is
|
||||||
|
// the trust anchor. An ephemeral P-256 key and a 16-byte nonce per connection
|
||||||
|
// derive two AES-256-GCM keys, one per direction; frames carry a version, a
|
||||||
|
// 12-byte IV (4-byte random prefix + 8-byte counter) and the GCM tag.
|
||||||
|
//
|
||||||
|
// The wire format is the first-party one (packages/ui/src/lib/relay/crypto.ts),
|
||||||
|
// so this must stay byte-compatible.
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:pointycastle/export.dart';
|
||||||
|
|
||||||
|
const relayHkdfInfo = 'openchamber-relay-v1';
|
||||||
|
const encryptedFrameVersion = 1;
|
||||||
|
const _ivPrefixBytes = 4;
|
||||||
|
const _ivCounterBytes = 8;
|
||||||
|
const _ivBytes = _ivPrefixBytes + _ivCounterBytes;
|
||||||
|
const _tagBytes = 16;
|
||||||
|
const _frameHeaderBytes = 1 + _ivBytes;
|
||||||
|
const _nonceBytes = 16;
|
||||||
|
const _sessionKeyBytes = 32;
|
||||||
|
const _maxPlaintextBytes = 64 * 1024;
|
||||||
|
|
||||||
|
class RelayCryptoError implements Exception {
|
||||||
|
final String message;
|
||||||
|
const RelayCryptoError(this.message);
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
ECDomainParameters get _p256 => ECCurve_prime256v1();
|
||||||
|
|
||||||
|
class RelayKeyPair {
|
||||||
|
final ECPrivateKey privateKey;
|
||||||
|
final ECPublicKey publicKey;
|
||||||
|
RelayKeyPair(this.privateKey, this.publicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
final Random _secureRandom = Random.secure();
|
||||||
|
Uint8List randomBytes(int length) =>
|
||||||
|
Uint8List.fromList(List<int>.generate(length, (_) => _secureRandom.nextInt(256)));
|
||||||
|
|
||||||
|
RelayKeyPair newRelayKeyPair() {
|
||||||
|
final random = FortunaRandom()
|
||||||
|
..seed(KeyParameter(randomBytes(32)));
|
||||||
|
final generator = ECKeyGenerator()
|
||||||
|
..init(ParametersWithRandom(
|
||||||
|
ECKeyGeneratorParameters(_p256), random));
|
||||||
|
final pair = generator.generateKeyPair();
|
||||||
|
return RelayKeyPair(pair.privateKey, pair.publicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The four public members only, as the protocol's JWK.
|
||||||
|
Map<String, String> publicJwk(ECPublicKey key) {
|
||||||
|
final point = key.Q;
|
||||||
|
if (point == null || point.isInfinity) {
|
||||||
|
throw const RelayCryptoError('invalid public key');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
'kty': 'EC',
|
||||||
|
'crv': 'P-256',
|
||||||
|
'x': _base64Url(_bigIntBytes(point.x!.toBigInteger()!, 32)),
|
||||||
|
'y': _base64Url(_bigIntBytes(point.y!.toBigInteger()!, 32)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
ECPublicKey importPublicJwk(Map<String, dynamic> jwk) {
|
||||||
|
if (jwk['kty'] != 'EC' || jwk['crv'] != 'P-256') {
|
||||||
|
throw const RelayCryptoError('invalid ECDH public key JWK');
|
||||||
|
}
|
||||||
|
final x = jwk['x'];
|
||||||
|
final y = jwk['y'];
|
||||||
|
if (x is! String || y is! String) {
|
||||||
|
throw const RelayCryptoError('invalid ECDH public key JWK');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final point = _p256.curve.createPoint(
|
||||||
|
_bytesBigInt(_base64UrlDecode(x)),
|
||||||
|
_bytesBigInt(_base64UrlDecode(y)),
|
||||||
|
);
|
||||||
|
return ECPublicKey(point, _p256);
|
||||||
|
} catch (_) {
|
||||||
|
throw const RelayCryptoError('invalid ECDH public key JWK');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String jwkFingerprint(Map<String, dynamic> jwk) =>
|
||||||
|
jsonEncode({'crv': jwk['crv'], 'kty': jwk['kty'], 'x': jwk['x'], 'y': jwk['y']});
|
||||||
|
|
||||||
|
/// The two 32-byte AES keys. The nonce is the handshake salt; the info string
|
||||||
|
/// is fixed, so the host derives the same pair.
|
||||||
|
({Uint8List clientToHost, Uint8List hostToClient}) deriveSessionKeys(
|
||||||
|
ECPrivateKey ownPrivate, ECPublicKey peer, Uint8List nonce) {
|
||||||
|
if (nonce.length != _nonceBytes) {
|
||||||
|
throw const RelayCryptoError('invalid handshake nonce length');
|
||||||
|
}
|
||||||
|
final agreement = ECDHBasicAgreement()..init(ownPrivate);
|
||||||
|
final shared = _bigIntBytes(agreement.calculateAgreement(peer), 32);
|
||||||
|
final hkdf = HKDFKeyDerivator(SHA256Digest())
|
||||||
|
..init(HkdfParameters(
|
||||||
|
shared,
|
||||||
|
_sessionKeyBytes * 2,
|
||||||
|
nonce,
|
||||||
|
Uint8List.fromList(utf8.encode(relayHkdfInfo)),
|
||||||
|
));
|
||||||
|
final material = hkdf.process(Uint8List(0));
|
||||||
|
return (
|
||||||
|
clientToHost: Uint8List.sublistView(material, 0, _sessionKeyBytes),
|
||||||
|
hostToClient: Uint8List.sublistView(material, _sessionKeyBytes),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class RelayEncryptor {
|
||||||
|
final Uint8List _key;
|
||||||
|
final Uint8List _prefix;
|
||||||
|
int _counter = 0;
|
||||||
|
|
||||||
|
RelayEncryptor(this._key) : _prefix = randomBytes(_ivPrefixBytes);
|
||||||
|
|
||||||
|
Uint8List encrypt(Uint8List plaintext) {
|
||||||
|
if (plaintext.length > _maxPlaintextBytes) {
|
||||||
|
throw const RelayCryptoError('plaintext frame exceeds maximum size');
|
||||||
|
}
|
||||||
|
_counter += 1;
|
||||||
|
final iv = Uint8List(_ivBytes)..setAll(0, _prefix);
|
||||||
|
var counter = _counter;
|
||||||
|
for (var i = _ivCounterBytes - 1; i >= 0; i--) {
|
||||||
|
iv[_ivPrefixBytes + i] = counter & 0xff;
|
||||||
|
counter >>= 8;
|
||||||
|
}
|
||||||
|
final cipher = GCMBlockCipher(AESEngine())
|
||||||
|
..init(true, AEADParameters(KeyParameter(_key), _tagBytes * 8, iv, Uint8List(0)));
|
||||||
|
final ciphertext = cipher.process(plaintext);
|
||||||
|
final frame = Uint8List(_frameHeaderBytes + ciphertext.length)
|
||||||
|
..[0] = encryptedFrameVersion
|
||||||
|
..setAll(1, iv)
|
||||||
|
..setAll(_frameHeaderBytes, ciphertext);
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RelayDecryptor {
|
||||||
|
final Uint8List _key;
|
||||||
|
int _lastCounter = 0;
|
||||||
|
|
||||||
|
RelayDecryptor(this._key);
|
||||||
|
|
||||||
|
Uint8List decrypt(Uint8List frame) {
|
||||||
|
if (frame.length < _frameHeaderBytes + _tagBytes) {
|
||||||
|
throw const RelayCryptoError('encrypted frame too short');
|
||||||
|
}
|
||||||
|
if (frame[0] != encryptedFrameVersion) {
|
||||||
|
throw const RelayCryptoError('unsupported encrypted frame version');
|
||||||
|
}
|
||||||
|
final iv = Uint8List.sublistView(frame, 1, _frameHeaderBytes);
|
||||||
|
var counter = 0;
|
||||||
|
for (var i = 0; i < _ivCounterBytes; i++) {
|
||||||
|
counter = (counter << 8) | iv[_ivPrefixBytes + i];
|
||||||
|
}
|
||||||
|
if (counter <= _lastCounter) {
|
||||||
|
throw const RelayCryptoError('frame counter regression');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final cipher = GCMBlockCipher(AESEngine())
|
||||||
|
..init(false,
|
||||||
|
AEADParameters(KeyParameter(_key), _tagBytes * 8, iv, Uint8List(0)));
|
||||||
|
final plaintext =
|
||||||
|
cipher.process(Uint8List.sublistView(frame, _frameHeaderBytes));
|
||||||
|
_lastCounter = counter;
|
||||||
|
return plaintext;
|
||||||
|
} catch (_) {
|
||||||
|
throw const RelayCryptoError('frame decryption failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Uint8List _bigIntBytes(BigInt value, int length) {
|
||||||
|
final out = Uint8List(length);
|
||||||
|
var v = value;
|
||||||
|
for (var i = length - 1; i >= 0; i--) {
|
||||||
|
out[i] = (v & BigInt.from(0xff)).toInt();
|
||||||
|
v >>= 8;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInt _bytesBigInt(Uint8List bytes) {
|
||||||
|
var value = BigInt.zero;
|
||||||
|
for (final b in bytes) {
|
||||||
|
value = (value << 8) | BigInt.from(b);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
String _base64Url(Uint8List bytes) =>
|
||||||
|
base64Url.encode(bytes).replaceAll('=', '');
|
||||||
|
|
||||||
|
Uint8List _base64UrlDecode(String value) {
|
||||||
|
if (!RegExp(r'^[A-Za-z0-9_-]*$').hasMatch(value)) {
|
||||||
|
throw const RelayCryptoError('invalid base64url input');
|
||||||
|
}
|
||||||
|
final padded = value.padRight((value.length + 3) ~/ 4 * 4, '=');
|
||||||
|
return base64Url.decode(padded);
|
||||||
|
}
|
||||||
|
|
||||||
|
String base64UrlEncodeBytes(Uint8List bytes) => _base64Url(bytes);
|
||||||
|
Uint8List base64UrlDecodeBytes(String value) => _base64UrlDecode(value);
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// The server as reached through the private relay: every request and socket
|
||||||
|
// rides the E2EE tunnel started from the pairing link's relay candidate.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../l10n.dart';
|
||||||
|
import '../version.dart';
|
||||||
|
import 'relay_tunnel.dart';
|
||||||
|
import 'transport.dart';
|
||||||
|
|
||||||
|
class RelayTransport implements Transport {
|
||||||
|
final RelayTunnel _tunnel;
|
||||||
|
String? _bearer;
|
||||||
|
String? _urlToken;
|
||||||
|
DateTime _urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
|
Future<String>? _minting;
|
||||||
|
|
||||||
|
RelayTransport({
|
||||||
|
required String relayUrl,
|
||||||
|
required String serverId,
|
||||||
|
required Map<String, dynamic> hostKey,
|
||||||
|
String? grant,
|
||||||
|
String? version,
|
||||||
|
}) : _tunnel = RelayTunnel(
|
||||||
|
relayUrl: relayUrl,
|
||||||
|
serverId: serverId,
|
||||||
|
hostKey: hostKey,
|
||||||
|
grant: grant,
|
||||||
|
// Read at construction: the version is known once the app has
|
||||||
|
// started, which is after this default would have been fixed.
|
||||||
|
appVersion: version ?? appVersion,
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest request) =>
|
||||||
|
_tunnel.send(request);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async {
|
||||||
|
final token = await _mintUrlToken();
|
||||||
|
final query = [
|
||||||
|
if (rawQuery != null && rawQuery.isNotEmpty) rawQuery,
|
||||||
|
if (token.isNotEmpty) 'oc_url_token=${Uri.encodeQueryComponent(token)}',
|
||||||
|
].join('&');
|
||||||
|
return _tunnel.openWebSocket(path, rawQuery: query, headers: headers);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {
|
||||||
|
if (_bearer != token) {
|
||||||
|
_bearer = token;
|
||||||
|
_urlToken = null;
|
||||||
|
_urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// WebSocket upgrades cannot carry headers, so the host expects a short-lived
|
||||||
|
/// URL-scoped token minted over the same tunnel with the bearer.
|
||||||
|
Future<String> _mintUrlToken() async {
|
||||||
|
final bearer = _bearer;
|
||||||
|
if (bearer == null || bearer.isEmpty) return '';
|
||||||
|
if (_urlToken != null && _urlToken!.isNotEmpty &&
|
||||||
|
DateTime.now().isBefore(_urlTokenExpiresAt)) {
|
||||||
|
return _urlToken!;
|
||||||
|
}
|
||||||
|
final inFlight = _minting;
|
||||||
|
if (inFlight != null) return inFlight;
|
||||||
|
final future = _mint(bearer);
|
||||||
|
_minting = future;
|
||||||
|
try {
|
||||||
|
return await future;
|
||||||
|
} finally {
|
||||||
|
_minting = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String> _mint(String bearer) async {
|
||||||
|
final response = await _tunnel.send(TransportRequest(
|
||||||
|
method: 'POST',
|
||||||
|
path: '/auth/url-token',
|
||||||
|
headers: {'authorization': 'Bearer $bearer', 'accept': 'application/json'},
|
||||||
|
));
|
||||||
|
final bytes = await response.body
|
||||||
|
.fold<List<int>>(<int>[], (all, chunk) => all..addAll(chunk));
|
||||||
|
if (response.status < 200 || response.status >= 300) {
|
||||||
|
throw RelayTunnelException(trArgs('Could not get a WebSocket token ({0})', [response.status]));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(utf8.decode(bytes, allowMalformed: true));
|
||||||
|
if (decoded is! Map) return '';
|
||||||
|
final token = decoded['token'];
|
||||||
|
if (token is! String) return '';
|
||||||
|
final expiresIn = decoded['expiresIn'];
|
||||||
|
final expiresAt = decoded['expiresAt'];
|
||||||
|
final lifetime = expiresIn is num
|
||||||
|
? Duration(seconds: expiresIn.toInt())
|
||||||
|
: expiresAt is num && expiresAt > 0
|
||||||
|
? Duration(milliseconds: expiresAt.toInt())
|
||||||
|
: const Duration(minutes: 4);
|
||||||
|
_urlToken = token.trim();
|
||||||
|
_urlTokenExpiresAt = DateTime.now()
|
||||||
|
.add(lifetime)
|
||||||
|
.subtract(const Duration(seconds: 20));
|
||||||
|
return _urlToken!;
|
||||||
|
} catch (_) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => _tunnel.close();
|
||||||
|
}
|
||||||
@@ -0,0 +1,634 @@
|
|||||||
|
// The OpenChamber private relay, client side: one outbound WebSocket to the
|
||||||
|
// relay, an end-to-end encrypted channel to the host (P-256 ECDH + HKDF +
|
||||||
|
// AES-256-GCM), and a small mux that carries the app's HTTP/SSE requests and
|
||||||
|
// WebSockets. The relay only forwards ciphertext; the host key from the
|
||||||
|
// pairing link is the trust anchor.
|
||||||
|
//
|
||||||
|
// Wire-compatible with packages/ui/src/lib/relay/ (protocol v1). Batching,
|
||||||
|
// downstream flow control and response gzip are not negotiated: the host's
|
||||||
|
// legacy path sends one plain frame per message and plain bodies.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import '../l10n.dart';
|
||||||
|
import 'relay_crypto.dart';
|
||||||
|
import 'transport.dart';
|
||||||
|
|
||||||
|
const _relayProtocolVersion = 1;
|
||||||
|
const _tunnelFrameHeaderBytes = 5;
|
||||||
|
const _tunnelFragmentFlag = 0x80;
|
||||||
|
const _maxPlaintextFrameBytes = 64 * 1024;
|
||||||
|
const _maxTunnelPayloadBytes = _maxPlaintextFrameBytes - _tunnelFrameHeaderBytes - 5;
|
||||||
|
const _connectTimeout = Duration(seconds: 20);
|
||||||
|
const _handshakeTimeout = Duration(seconds: 30);
|
||||||
|
const _keepAliveEvery = Duration(seconds: 30);
|
||||||
|
const _keepAliveDeadAfter = Duration(seconds: 70);
|
||||||
|
|
||||||
|
class RelayFrameType {
|
||||||
|
static const httpRequest = 1;
|
||||||
|
static const httpBody = 2;
|
||||||
|
static const httpResponse = 3;
|
||||||
|
static const streamEnd = 4;
|
||||||
|
static const streamAbort = 5;
|
||||||
|
static const wsOpen = 6;
|
||||||
|
static const wsOpened = 7;
|
||||||
|
static const wsText = 8;
|
||||||
|
static const wsBinary = 9;
|
||||||
|
static const wsClose = 10;
|
||||||
|
static const ping = 11;
|
||||||
|
static const pong = 12;
|
||||||
|
static const deliveryAck = 13;
|
||||||
|
}
|
||||||
|
|
||||||
|
class RelayTunnelException implements Exception {
|
||||||
|
final String message;
|
||||||
|
const RelayTunnelException(this.message);
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request over the tunnel. [path] is relative to the server root, [query]
|
||||||
|
/// the encoded query string (without `?`). The reply's body streams.
|
||||||
|
class RelayTunnel {
|
||||||
|
final String relayUrl;
|
||||||
|
final String serverId;
|
||||||
|
final Map<String, dynamic> hostKey;
|
||||||
|
final String? grant;
|
||||||
|
final String appVersion;
|
||||||
|
final String platform;
|
||||||
|
final HttpClient _http = HttpClient()
|
||||||
|
..connectionTimeout = const Duration(seconds: 20);
|
||||||
|
|
||||||
|
_RelayChannel? _channel;
|
||||||
|
Future<_RelayChannel>? _connecting;
|
||||||
|
bool _closed = false;
|
||||||
|
int _failures = 0;
|
||||||
|
DateTime _retryAfter = DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
|
|
||||||
|
RelayTunnel({
|
||||||
|
required this.relayUrl,
|
||||||
|
required this.serverId,
|
||||||
|
required this.hostKey,
|
||||||
|
this.grant,
|
||||||
|
this.appVersion = '0.4.4',
|
||||||
|
this.platform = 'android',
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<TransportResponse> send(TransportRequest request) async {
|
||||||
|
final channel = await _ensureChannel();
|
||||||
|
final streamId = channel.nextStreamId();
|
||||||
|
final body = request.body;
|
||||||
|
final controller = StreamController<List<int>>();
|
||||||
|
final response = Completer<TransportResponse>();
|
||||||
|
var finished = false;
|
||||||
|
|
||||||
|
void cleanup() {
|
||||||
|
channel.streams.remove(streamId);
|
||||||
|
channel.dropFragments(streamId);
|
||||||
|
}
|
||||||
|
|
||||||
|
void finish({Object? error}) {
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
|
cleanup();
|
||||||
|
if (error != null) {
|
||||||
|
if (!response.isCompleted) {
|
||||||
|
response.completeError(error);
|
||||||
|
} else {
|
||||||
|
controller.addError(error);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void deliveredHead(int status, Map<String, String> headers) {
|
||||||
|
final noBody = status == 204 || status == 205 || status == 304;
|
||||||
|
if (noBody) {
|
||||||
|
finished = true;
|
||||||
|
cleanup();
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
response.complete(TransportResponse(
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
controller.stream,
|
||||||
|
abort: () {
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
|
cleanup();
|
||||||
|
channel.sendJson(RelayFrameType.streamAbort, streamId, {'reason': 'aborted'});
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
channel.streams[streamId] = _TunnelStream(
|
||||||
|
onFrame: (type, payload) {
|
||||||
|
switch (type) {
|
||||||
|
case RelayFrameType.httpResponse:
|
||||||
|
if (finished || response.isCompleted) return;
|
||||||
|
final dynamic decoded;
|
||||||
|
try {
|
||||||
|
decoded = jsonDecode(utf8.decode(payload));
|
||||||
|
} catch (_) {
|
||||||
|
finish(error: RelayTunnelException(tr('Invalid response headers')));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (decoded is! Map) {
|
||||||
|
finish(error: RelayTunnelException(tr('Invalid response headers')));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final status = (decoded['status'] as num?)?.toInt() ?? 0;
|
||||||
|
final rawHeaders = decoded['headers'];
|
||||||
|
final headers = <String, String>{};
|
||||||
|
if (rawHeaders is Map) {
|
||||||
|
for (final entry in rawHeaders.entries) {
|
||||||
|
if (entry.key is String && entry.value is String) {
|
||||||
|
headers[(entry.key as String).toLowerCase()] = entry.value as String;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
deliveredHead(status, headers);
|
||||||
|
break;
|
||||||
|
case RelayFrameType.httpBody:
|
||||||
|
if (!finished) controller.add(Uint8List.fromList(payload));
|
||||||
|
break;
|
||||||
|
case RelayFrameType.streamEnd:
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
|
cleanup();
|
||||||
|
controller.close();
|
||||||
|
break;
|
||||||
|
case RelayFrameType.streamAbort:
|
||||||
|
var reason = tr('Transfer interrupted');
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(utf8.decode(payload));
|
||||||
|
if (decoded is Map && decoded['reason'] is String) {
|
||||||
|
reason = decoded['reason'] as String;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
finish(error: RelayTunnelException(reason));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onFail: (error) => finish(error: error),
|
||||||
|
);
|
||||||
|
|
||||||
|
final query = request.rawQuery ??
|
||||||
|
Uri(queryParameters: request.query.isEmpty ? null : request.query).query;
|
||||||
|
channel.sendJson(RelayFrameType.httpRequest, streamId, {
|
||||||
|
'method': request.method,
|
||||||
|
'path': request.path,
|
||||||
|
'query': query,
|
||||||
|
'headers': request.headers,
|
||||||
|
'hasBody': body != null,
|
||||||
|
});
|
||||||
|
if (body != null) {
|
||||||
|
if (body.isEmpty) {
|
||||||
|
channel.send(RelayFrameType.httpBody, streamId, Uint8List(0));
|
||||||
|
} else {
|
||||||
|
for (var offset = 0; offset < body.length; offset += _maxTunnelPayloadBytes) {
|
||||||
|
final end = (offset + _maxTunnelPayloadBytes).clamp(0, body.length);
|
||||||
|
channel.send(RelayFrameType.httpBody, streamId,
|
||||||
|
Uint8List.fromList(body.sublist(offset, end)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
channel.send(RelayFrameType.streamEnd, streamId, Uint8List(0));
|
||||||
|
return response.future;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens a server WebSocket over the tunnel. [path] carries no query;
|
||||||
|
/// [rawQuery] is sent as-is. Outgoing frames are held until the host reports
|
||||||
|
/// the loopback socket open.
|
||||||
|
Future<TransportSocket> openWebSocket(
|
||||||
|
String path, {
|
||||||
|
String rawQuery = '',
|
||||||
|
Map<String, String> headers = const {},
|
||||||
|
}) async {
|
||||||
|
final channel = await _ensureChannel();
|
||||||
|
final streamId = channel.nextStreamId();
|
||||||
|
final socket = _RelaySocket(
|
||||||
|
channel: channel,
|
||||||
|
streamId: streamId,
|
||||||
|
path: path,
|
||||||
|
query: rawQuery,
|
||||||
|
);
|
||||||
|
channel.streams[streamId] = _TunnelStream(
|
||||||
|
onFrame: socket.onFrame,
|
||||||
|
onFail: socket.onFail,
|
||||||
|
);
|
||||||
|
channel.sendJson(RelayFrameType.wsOpen, streamId, {
|
||||||
|
'path': path,
|
||||||
|
'query': rawQuery,
|
||||||
|
});
|
||||||
|
return socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_RelayChannel> _ensureChannel() async {
|
||||||
|
if (_closed) throw const RelayTunnelException('relay tunnel closed');
|
||||||
|
final current = _channel;
|
||||||
|
if (current != null && !current.dead) return current;
|
||||||
|
final connecting = _connecting;
|
||||||
|
if (connecting != null) return connecting;
|
||||||
|
final wait = _retryAfter.difference(DateTime.now());
|
||||||
|
if (wait > Duration.zero) await Future<void>.delayed(wait);
|
||||||
|
final future = _connect();
|
||||||
|
_connecting = future;
|
||||||
|
try {
|
||||||
|
final channel = await future;
|
||||||
|
_channel = channel;
|
||||||
|
_failures = 0;
|
||||||
|
return channel;
|
||||||
|
} catch (error) {
|
||||||
|
_failures += 1;
|
||||||
|
final delay = Duration(
|
||||||
|
milliseconds: (500 * (1 << (_failures.clamp(0, 4)))).clamp(500, 8000));
|
||||||
|
_retryAfter = DateTime.now().add(delay);
|
||||||
|
rethrow;
|
||||||
|
} finally {
|
||||||
|
_connecting = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_RelayChannel> _connect() async {
|
||||||
|
final keyPair = newRelayKeyPair();
|
||||||
|
final nonce = randomBytes(16);
|
||||||
|
final hello = jsonEncode({
|
||||||
|
't': 'hello',
|
||||||
|
'v': _relayProtocolVersion,
|
||||||
|
'clientPubJwk': publicJwk(keyPair.publicKey),
|
||||||
|
'nonce': base64UrlEncodeBytes(nonce),
|
||||||
|
});
|
||||||
|
|
||||||
|
final uri = _relayUri();
|
||||||
|
final WebSocket ws;
|
||||||
|
try {
|
||||||
|
ws = await WebSocket.connect(uri.toString(), customClient: _http)
|
||||||
|
.timeout(_connectTimeout);
|
||||||
|
} catch (error) {
|
||||||
|
throw RelayTunnelException(trArgs('Could not connect to the relay: {0}', [error]));
|
||||||
|
}
|
||||||
|
final channel = _RelayChannel(ws);
|
||||||
|
final ready = Completer<void>();
|
||||||
|
var finished = false;
|
||||||
|
Timer? helloTimer;
|
||||||
|
Timer? deadline;
|
||||||
|
StreamSubscription<dynamic>? subscription;
|
||||||
|
|
||||||
|
void closeWith(Object error) {
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
|
helloTimer?.cancel();
|
||||||
|
deadline?.cancel();
|
||||||
|
channel.dead = true;
|
||||||
|
channel.failAll(error);
|
||||||
|
subscription?.cancel();
|
||||||
|
try {
|
||||||
|
ws.close();
|
||||||
|
} catch (_) {}
|
||||||
|
if (!ready.isCompleted) ready.completeError(error);
|
||||||
|
_channel = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void onData(dynamic raw) {
|
||||||
|
if (finished) return;
|
||||||
|
if (raw is String) {
|
||||||
|
if (raw.contains('relay-retire')) {
|
||||||
|
// The relay asks the peer to close instead of closing its side.
|
||||||
|
var code = 1011;
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is Map) {
|
||||||
|
final parsed = decoded['code'];
|
||||||
|
if (parsed is num) code = parsed.toInt();
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
closeWith(RelayTunnelException('relay closed the tunnel ($code)'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!ready.isCompleted) {
|
||||||
|
dynamic decoded;
|
||||||
|
try {
|
||||||
|
decoded = jsonDecode(raw);
|
||||||
|
} catch (_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (decoded is Map && decoded['t'] == 'ready') {
|
||||||
|
try {
|
||||||
|
final keys = deriveSessionKeys(
|
||||||
|
keyPair.privateKey, importPublicJwk(hostKey), nonce);
|
||||||
|
channel.encryptor = RelayEncryptor(keys.clientToHost);
|
||||||
|
channel.decryptor = RelayDecryptor(keys.hostToClient);
|
||||||
|
helloTimer?.cancel();
|
||||||
|
deadline?.cancel();
|
||||||
|
ready.complete();
|
||||||
|
} catch (error) {
|
||||||
|
closeWith(RelayTunnelException(trArgs('Key exchange failed: {0}', [error])));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// After the channel is up the host may repeat `ready` for a retried
|
||||||
|
// hello; anything else plaintext is a protocol violation.
|
||||||
|
if (raw.contains('"ready"')) return;
|
||||||
|
closeWith(RelayTunnelException(tr('Received a plaintext frame after the handshake')));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (raw is! List<int>) return;
|
||||||
|
channel.lastReceived = DateTime.now();
|
||||||
|
if (!ready.isCompleted) return;
|
||||||
|
try {
|
||||||
|
final plaintext = channel.decryptor.decrypt(Uint8List.fromList(raw));
|
||||||
|
channel.handlePlaintext(plaintext);
|
||||||
|
} catch (error) {
|
||||||
|
closeWith(RelayTunnelException(trArgs('Decryption failed: {0}', [error])));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
subscription = ws.listen(
|
||||||
|
onData,
|
||||||
|
onError: (Object error) => closeWith(RelayTunnelException(trArgs('Relay connection error: {0}', [error]))),
|
||||||
|
onDone: () {
|
||||||
|
if (!finished) {
|
||||||
|
closeWith(RelayTunnelException(trArgs(
|
||||||
|
'Relay connection closed ({0} {1})',
|
||||||
|
[ws.closeCode ?? '-', ws.closeReason ?? ''])));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
cancelOnError: true,
|
||||||
|
);
|
||||||
|
channel.onClosed = () =>
|
||||||
|
closeWith(RelayTunnelException(tr('Relay connection closed')));
|
||||||
|
|
||||||
|
void sendHello() {
|
||||||
|
if (finished) return;
|
||||||
|
try {
|
||||||
|
ws.add(hello);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendHello();
|
||||||
|
helloTimer = Timer.periodic(const Duration(seconds: 1), (_) => sendHello());
|
||||||
|
deadline = Timer(_handshakeTimeout, () {
|
||||||
|
closeWith(RelayTunnelException(tr('Relay handshake timed out')));
|
||||||
|
});
|
||||||
|
|
||||||
|
await ready.future;
|
||||||
|
if (channel.dead) {
|
||||||
|
throw RelayTunnelException(trArgs(
|
||||||
|
'Relay connection closed ({0} {1})',
|
||||||
|
[ws.closeCode ?? '-', ws.closeReason ?? '']));
|
||||||
|
}
|
||||||
|
channel.startKeepAlive();
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
Uri _relayUri() {
|
||||||
|
final base = Uri.parse(relayUrl);
|
||||||
|
final params = <String, String>{
|
||||||
|
...base.queryParameters,
|
||||||
|
'v': '$_relayProtocolVersion',
|
||||||
|
'role': 'client',
|
||||||
|
'serverId': serverId,
|
||||||
|
'appId': 'openchamber',
|
||||||
|
'appVersion': appVersion,
|
||||||
|
'platform': platform,
|
||||||
|
};
|
||||||
|
final relayGrant = grant;
|
||||||
|
if (relayGrant != null && relayGrant.isNotEmpty) {
|
||||||
|
params['grant'] = relayGrant;
|
||||||
|
}
|
||||||
|
return base.replace(queryParameters: params);
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
if (_closed) return;
|
||||||
|
_closed = true;
|
||||||
|
final channel = _channel;
|
||||||
|
_channel = null;
|
||||||
|
if (channel != null) {
|
||||||
|
channel.dead = true;
|
||||||
|
channel.failAll(const RelayTunnelException('relay tunnel closed'));
|
||||||
|
channel.close();
|
||||||
|
}
|
||||||
|
_http.close(force: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _TunnelStream {
|
||||||
|
final void Function(int type, Uint8List payload) onFrame;
|
||||||
|
final void Function(Object error) onFail;
|
||||||
|
_TunnelStream({required this.onFrame, required this.onFail});
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RelayChannel {
|
||||||
|
final WebSocket ws;
|
||||||
|
late final RelayEncryptor encryptor;
|
||||||
|
late final RelayDecryptor decryptor;
|
||||||
|
final Map<int, _TunnelStream> streams = {};
|
||||||
|
final Map<String, BytesBuilder> _fragments = {};
|
||||||
|
Timer? _keepAlive;
|
||||||
|
DateTime lastReceived = DateTime.now();
|
||||||
|
int _nextStreamId = -1;
|
||||||
|
bool dead = false;
|
||||||
|
void Function()? onClosed;
|
||||||
|
|
||||||
|
_RelayChannel(this.ws);
|
||||||
|
|
||||||
|
int nextStreamId() {
|
||||||
|
_nextStreamId += 2;
|
||||||
|
return _nextStreamId;
|
||||||
|
}
|
||||||
|
|
||||||
|
void startKeepAlive() {
|
||||||
|
_keepAlive?.cancel();
|
||||||
|
_keepAlive = Timer.periodic(_keepAliveEvery, (_) {
|
||||||
|
if (dead) return;
|
||||||
|
if (DateTime.now().difference(lastReceived) > _keepAliveDeadAfter) {
|
||||||
|
dead = true;
|
||||||
|
_keepAlive?.cancel();
|
||||||
|
onClosed?.call();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
send(RelayFrameType.ping, 0, Uint8List(0));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void send(int type, int streamId, Uint8List payload, {bool more = false}) {
|
||||||
|
if (dead) return;
|
||||||
|
final frame = Uint8List(_tunnelFrameHeaderBytes + payload.length);
|
||||||
|
frame[0] = more ? type | _tunnelFragmentFlag : type;
|
||||||
|
frame[1] = (streamId >> 24) & 0xff;
|
||||||
|
frame[2] = (streamId >> 16) & 0xff;
|
||||||
|
frame[3] = (streamId >> 8) & 0xff;
|
||||||
|
frame[4] = streamId & 0xff;
|
||||||
|
frame.setAll(_tunnelFrameHeaderBytes, payload);
|
||||||
|
try {
|
||||||
|
ws.add(encryptor.encrypt(frame));
|
||||||
|
} catch (_) {
|
||||||
|
dead = true;
|
||||||
|
onClosed?.call();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendJson(int type, int streamId, Object value) =>
|
||||||
|
send(type, streamId, Uint8List.fromList(utf8.encode(jsonEncode(value))));
|
||||||
|
|
||||||
|
void sendFragmented(int type, int streamId, Uint8List payload) {
|
||||||
|
if (payload.isEmpty) {
|
||||||
|
send(type, streamId, Uint8List(0));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (var offset = 0; offset < payload.length; offset += _maxTunnelPayloadBytes) {
|
||||||
|
final end = (offset + _maxTunnelPayloadBytes).clamp(0, payload.length);
|
||||||
|
send(type, streamId, Uint8List.sublistView(payload, offset, end),
|
||||||
|
more: end < payload.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void dropFragments(int streamId) {
|
||||||
|
_fragments.removeWhere((key, _) => key.startsWith('$streamId:'));
|
||||||
|
}
|
||||||
|
|
||||||
|
void handlePlaintext(Uint8List plaintext) {
|
||||||
|
if (dead || plaintext.length < _tunnelFrameHeaderBytes) return;
|
||||||
|
final rawType = plaintext[0];
|
||||||
|
final more = (rawType & _tunnelFragmentFlag) != 0;
|
||||||
|
final type = rawType & ~_tunnelFragmentFlag;
|
||||||
|
final streamId = (plaintext[1] << 24) |
|
||||||
|
(plaintext[2] << 16) |
|
||||||
|
(plaintext[3] << 8) |
|
||||||
|
plaintext[4];
|
||||||
|
var payload = Uint8List.sublistView(plaintext, _tunnelFrameHeaderBytes);
|
||||||
|
lastReceived = DateTime.now();
|
||||||
|
|
||||||
|
if (type == RelayFrameType.ping) {
|
||||||
|
send(RelayFrameType.pong, streamId, Uint8List(0));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (type == RelayFrameType.pong) return;
|
||||||
|
if (type == RelayFrameType.deliveryAck) return;
|
||||||
|
|
||||||
|
if (type == RelayFrameType.wsText || type == RelayFrameType.wsBinary) {
|
||||||
|
if (more || _fragments.containsKey('$streamId:$type')) {
|
||||||
|
final key = '$streamId:$type';
|
||||||
|
final builder = _fragments.putIfAbsent(key, BytesBuilder.new);
|
||||||
|
builder.add(payload);
|
||||||
|
if (builder.length > 16 * 1024 * 1024) {
|
||||||
|
dead = true;
|
||||||
|
onClosed?.call();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (more) return;
|
||||||
|
payload = builder.takeBytes();
|
||||||
|
_fragments.remove(key);
|
||||||
|
}
|
||||||
|
} else if (more) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final stream = streams[streamId];
|
||||||
|
if (stream == null) return;
|
||||||
|
stream.onFrame(type, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
void failAll(Object error) {
|
||||||
|
final all = List.of(streams.values);
|
||||||
|
streams.clear();
|
||||||
|
for (final stream in all) {
|
||||||
|
try {
|
||||||
|
stream.onFail(error);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
_keepAlive?.cancel();
|
||||||
|
try {
|
||||||
|
ws.close();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RelaySocket implements TransportSocket {
|
||||||
|
final _RelayChannel channel;
|
||||||
|
final int streamId;
|
||||||
|
final String path;
|
||||||
|
final String query;
|
||||||
|
final StreamController<List<int>> _messages = StreamController<List<int>>();
|
||||||
|
final List<Uint8List> _pending = [];
|
||||||
|
bool _open = false;
|
||||||
|
bool _closed = false;
|
||||||
|
|
||||||
|
_RelaySocket({
|
||||||
|
required this.channel,
|
||||||
|
required this.streamId,
|
||||||
|
required this.path,
|
||||||
|
required this.query,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<List<int>> get messages => _messages.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void add(List<int> data) {
|
||||||
|
if (_closed) return;
|
||||||
|
final bytes = Uint8List.fromList(data);
|
||||||
|
if (!_open) {
|
||||||
|
_pending.add(bytes);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
channel.sendFragmented(RelayFrameType.wsBinary, streamId, bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
void onFrame(int type, Uint8List payload) {
|
||||||
|
switch (type) {
|
||||||
|
case RelayFrameType.wsOpened:
|
||||||
|
if (_open) return;
|
||||||
|
_open = true;
|
||||||
|
for (final frame in _pending) {
|
||||||
|
channel.sendFragmented(RelayFrameType.wsBinary, streamId, frame);
|
||||||
|
}
|
||||||
|
_pending.clear();
|
||||||
|
break;
|
||||||
|
case RelayFrameType.wsText:
|
||||||
|
if (!_closed) _messages.add(payload);
|
||||||
|
break;
|
||||||
|
case RelayFrameType.wsBinary:
|
||||||
|
if (!_closed) _messages.add(payload);
|
||||||
|
break;
|
||||||
|
case RelayFrameType.wsClose:
|
||||||
|
_finish();
|
||||||
|
break;
|
||||||
|
case RelayFrameType.streamAbort:
|
||||||
|
_finish(error: RelayTunnelException(tr('WebSocket substream interrupted')));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void onFail(Object error) => _finish(error: error);
|
||||||
|
|
||||||
|
void _finish({Object? error}) {
|
||||||
|
if (_closed) return;
|
||||||
|
_closed = true;
|
||||||
|
channel.streams.remove(streamId);
|
||||||
|
channel.dropFragments(streamId);
|
||||||
|
if (error != null) {
|
||||||
|
_messages.addError(error);
|
||||||
|
}
|
||||||
|
_messages.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close([int code = 1000, String reason = '']) async {
|
||||||
|
if (_closed) return;
|
||||||
|
// Even before `wsOpened`: the host may be dialing the loopback socket
|
||||||
|
// already, and this frame tells it to abandon that sub-stream.
|
||||||
|
channel.sendJson(
|
||||||
|
RelayFrameType.wsClose, streamId, {'code': code, 'reason': reason});
|
||||||
|
_finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
// Scheduled tasks: prompts the server sends on a schedule, into a new session
|
||||||
|
// or an existing one. The wire shape follows the web client
|
||||||
|
// (`/api/projects/:projectId/scheduled-tasks`), which reads the same tasks.
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
class ScheduledTask {
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final bool enabled;
|
||||||
|
|
||||||
|
/// 'daily' | 'weekly' | 'once' | 'cron'.
|
||||||
|
final String kind;
|
||||||
|
|
||||||
|
/// Daily and weekly: the `HH:mm` times it runs at.
|
||||||
|
final List<String> times;
|
||||||
|
|
||||||
|
/// Weekly: 0 is Sunday, as the server counts.
|
||||||
|
final List<int> weekdays;
|
||||||
|
|
||||||
|
/// Once: `YYYY-MM-DD` and `HH:mm`.
|
||||||
|
final String date;
|
||||||
|
final String time;
|
||||||
|
|
||||||
|
/// Cron: the expression.
|
||||||
|
final String cron;
|
||||||
|
|
||||||
|
/// IANA name; empty means the server's own zone.
|
||||||
|
final String timezone;
|
||||||
|
|
||||||
|
/// What a run does: the prompt, and whether the session's defaults are used
|
||||||
|
/// instead of a fixed model and agent.
|
||||||
|
final String prompt;
|
||||||
|
final bool useDefaults;
|
||||||
|
final String providerId;
|
||||||
|
final String modelId;
|
||||||
|
final String variant;
|
||||||
|
final String agent;
|
||||||
|
|
||||||
|
/// Sends into this session instead of a new one; empty means a new session.
|
||||||
|
final String targetSessionId;
|
||||||
|
|
||||||
|
final String lastStatus;
|
||||||
|
final String lastError;
|
||||||
|
final int lastRunAt;
|
||||||
|
final int nextRunAt;
|
||||||
|
final int lastDurationMs;
|
||||||
|
final String lastSessionId;
|
||||||
|
|
||||||
|
const ScheduledTask({
|
||||||
|
this.id = '',
|
||||||
|
this.name = '',
|
||||||
|
this.enabled = true,
|
||||||
|
this.kind = 'daily',
|
||||||
|
this.times = const [],
|
||||||
|
this.weekdays = const [],
|
||||||
|
this.date = '',
|
||||||
|
this.time = '',
|
||||||
|
this.cron = '',
|
||||||
|
this.timezone = '',
|
||||||
|
this.prompt = '',
|
||||||
|
this.useDefaults = true,
|
||||||
|
this.providerId = '',
|
||||||
|
this.modelId = '',
|
||||||
|
this.variant = '',
|
||||||
|
this.agent = '',
|
||||||
|
this.targetSessionId = '',
|
||||||
|
this.lastStatus = '',
|
||||||
|
this.lastError = '',
|
||||||
|
this.lastRunAt = 0,
|
||||||
|
this.nextRunAt = 0,
|
||||||
|
this.lastDurationMs = 0,
|
||||||
|
this.lastSessionId = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ScheduledTask.fromJson(Map<String, dynamic> j) {
|
||||||
|
final schedule = j['schedule'] as Map<String, dynamic>? ?? const {};
|
||||||
|
final execution = j['execution'] as Map<String, dynamic>? ?? const {};
|
||||||
|
final state = j['state'] as Map<String, dynamic>? ?? const {};
|
||||||
|
String text(Object? value) => value is String ? value : '';
|
||||||
|
int number(Object? value) => (value is num) ? value.toInt() : 0;
|
||||||
|
return ScheduledTask(
|
||||||
|
id: text(j['id']),
|
||||||
|
name: text(j['name']),
|
||||||
|
enabled: j['enabled'] != false,
|
||||||
|
kind: text(schedule['kind']),
|
||||||
|
times: [
|
||||||
|
for (final value in schedule['times'] as List? ?? const [])
|
||||||
|
if (value is String) value,
|
||||||
|
],
|
||||||
|
weekdays: [
|
||||||
|
for (final value in schedule['weekdays'] as List? ?? const [])
|
||||||
|
if (value is num) value.toInt(),
|
||||||
|
],
|
||||||
|
date: text(schedule['date']),
|
||||||
|
time: text(schedule['time']),
|
||||||
|
cron: text(schedule['cron']),
|
||||||
|
timezone: text(schedule['timezone']),
|
||||||
|
prompt: text(execution['prompt']),
|
||||||
|
// The web client treats a task without a fixed model as using the
|
||||||
|
// session's defaults, whatever the flag says.
|
||||||
|
useDefaults: execution['useDefaults'] == true || text(execution['modelID']).isEmpty,
|
||||||
|
providerId: text(execution['providerID']),
|
||||||
|
modelId: text(execution['modelID']),
|
||||||
|
variant: text(execution['variant']),
|
||||||
|
agent: text(execution['agent']),
|
||||||
|
targetSessionId: text(j['targetSessionId']),
|
||||||
|
lastStatus: text(state['lastStatus']),
|
||||||
|
lastError: text(state['lastError']),
|
||||||
|
lastRunAt: number(state['lastRunAt']),
|
||||||
|
nextRunAt: number(state['nextRunAt']),
|
||||||
|
lastDurationMs: number(state['lastDurationMs']),
|
||||||
|
lastSessionId: text(state['lastSessionId']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the server is sent on save. State is the server's own; a task keeps
|
||||||
|
/// it unless it is deliberately replaced.
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
if (id.isNotEmpty) 'id': id,
|
||||||
|
'name': name,
|
||||||
|
'enabled': enabled,
|
||||||
|
'schedule': {
|
||||||
|
'kind': kind,
|
||||||
|
if (kind == 'daily' || kind == 'weekly') 'times': times,
|
||||||
|
if (kind == 'weekly') 'weekdays': weekdays,
|
||||||
|
if (kind == 'once') ...{'date': date, 'time': time},
|
||||||
|
if (kind == 'cron') 'cron': cron,
|
||||||
|
if (timezone.isNotEmpty) 'timezone': timezone,
|
||||||
|
},
|
||||||
|
'execution': {
|
||||||
|
'prompt': prompt,
|
||||||
|
'useDefaults': useDefaults,
|
||||||
|
if (!useDefaults && providerId.isNotEmpty) 'providerID': providerId,
|
||||||
|
if (!useDefaults && modelId.isNotEmpty) 'modelID': modelId,
|
||||||
|
if (!useDefaults && variant.isNotEmpty) 'variant': variant,
|
||||||
|
if (!useDefaults && agent.isNotEmpty) 'agent': agent,
|
||||||
|
},
|
||||||
|
if (targetSessionId.isNotEmpty) 'targetSessionId': targetSessionId,
|
||||||
|
};
|
||||||
|
|
||||||
|
ScheduledTask copyWith({bool? enabled}) => ScheduledTask(
|
||||||
|
id: id,
|
||||||
|
name: name,
|
||||||
|
enabled: enabled ?? this.enabled,
|
||||||
|
kind: kind,
|
||||||
|
times: times,
|
||||||
|
weekdays: weekdays,
|
||||||
|
date: date,
|
||||||
|
time: time,
|
||||||
|
cron: cron,
|
||||||
|
timezone: timezone,
|
||||||
|
prompt: prompt,
|
||||||
|
useDefaults: useDefaults,
|
||||||
|
providerId: providerId,
|
||||||
|
modelId: modelId,
|
||||||
|
variant: variant,
|
||||||
|
agent: agent,
|
||||||
|
targetSessionId: targetSessionId,
|
||||||
|
lastStatus: lastStatus,
|
||||||
|
lastError: lastError,
|
||||||
|
lastRunAt: lastRunAt,
|
||||||
|
nextRunAt: nextRunAt,
|
||||||
|
lastDurationMs: lastDurationMs,
|
||||||
|
lastSessionId: lastSessionId,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The model line: a fixed choice, or that the run uses the session's.
|
||||||
|
String get modelLabel {
|
||||||
|
if (useDefaults || modelId.isEmpty) return tr('Use default model and agent');
|
||||||
|
final model = [providerId, modelId].where((s) => s.isNotEmpty).join('/');
|
||||||
|
return agent.isEmpty ? model : '$model · $agent';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const scheduledWeekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||||
|
|
||||||
|
const scheduledTaskKindLabels = {
|
||||||
|
'daily': 'Daily',
|
||||||
|
'weekly': 'Weekly',
|
||||||
|
'once': 'Once',
|
||||||
|
'cron': 'Cron',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// '每天 09:00', '每周 周一、周三 09:00', '一次性 2026-12-01 09:00', …
|
||||||
|
String scheduledScheduleText(ScheduledTask task) {
|
||||||
|
final separator = tr(', ');
|
||||||
|
final times = task.times.isEmpty ? task.time : task.times.join(separator);
|
||||||
|
switch (task.kind) {
|
||||||
|
case 'daily':
|
||||||
|
return trArgs('Daily {0}', [times.isEmpty ? '--:--' : times]);
|
||||||
|
case 'weekly':
|
||||||
|
final days = [
|
||||||
|
for (final day in task.weekdays)
|
||||||
|
if (day >= 0 && day < scheduledWeekdays.length)
|
||||||
|
tr(scheduledWeekdays[day]),
|
||||||
|
].join(separator);
|
||||||
|
return trArgs('Weekly {0} {1}', [
|
||||||
|
days.isEmpty ? tr('no days') : days,
|
||||||
|
times.isEmpty ? '--:--' : times,
|
||||||
|
]);
|
||||||
|
case 'once':
|
||||||
|
return trArgs('Once {0} {1}', [
|
||||||
|
task.date.isEmpty ? tr('no date') : task.date,
|
||||||
|
task.time.isEmpty ? '--:--' : task.time,
|
||||||
|
]);
|
||||||
|
case 'cron':
|
||||||
|
return trArgs('Cron: {0}', [task.cron]);
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
String scheduledStatusLabel(String status) => switch (status) {
|
||||||
|
'success' || 'sent' => tr('Success'),
|
||||||
|
'error' || 'failed' => tr('Error'),
|
||||||
|
'running' => tr('Running'),
|
||||||
|
'queued' => tr('Queued'),
|
||||||
|
'skipped' => tr('Skipped'),
|
||||||
|
'cancelled' => tr('Cancelled'),
|
||||||
|
_ => tr('Idle'),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// How far away a moment is, in the words the web client uses.
|
||||||
|
String scheduledRelativeTime(int milliseconds) {
|
||||||
|
if (milliseconds <= 0) return '';
|
||||||
|
final diff = milliseconds - DateTime.now().millisecondsSinceEpoch;
|
||||||
|
final abs = diff.abs();
|
||||||
|
const minute = 60 * 1000;
|
||||||
|
const hour = 60 * minute;
|
||||||
|
const day = 24 * hour;
|
||||||
|
final future = diff >= 0;
|
||||||
|
if (abs < minute) return future ? tr('In less than a minute') : tr('Just now');
|
||||||
|
if (abs < hour) {
|
||||||
|
final m = (abs / minute).round();
|
||||||
|
return future
|
||||||
|
? trArgs('In {0} min', [m])
|
||||||
|
: trArgs('{0} min ago', [m]);
|
||||||
|
}
|
||||||
|
if (abs < day) {
|
||||||
|
final h = abs ~/ hour;
|
||||||
|
final m = ((abs % hour) / minute).round();
|
||||||
|
final body =
|
||||||
|
m > 0 ? trArgs('{0} hr {1} min', [h, m]) : trArgs('{0} hr', [h]);
|
||||||
|
return future ? trArgs('In {0}', [body]) : trArgs('{0} ago', [body]);
|
||||||
|
}
|
||||||
|
final d = abs ~/ day;
|
||||||
|
final h = ((abs % day) / hour).round();
|
||||||
|
final body = h > 0 ? trArgs('{0} days {1} hr', [d, h]) : trArgs('{0} days', [d]);
|
||||||
|
return future ? trArgs('In {0}', [body]) : trArgs('{0} ago', [body]);
|
||||||
|
}
|
||||||
|
|
||||||
|
String scheduledClock(int milliseconds) {
|
||||||
|
if (milliseconds <= 0) return '';
|
||||||
|
final at = DateTime.fromMillisecondsSinceEpoch(milliseconds);
|
||||||
|
String two(int n) => n.toString().padLeft(2, '0');
|
||||||
|
return '${two(at.hour)}:${two(at.minute)}';
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
// Background commands of a session (opencode's shells), as the first-party
|
||||||
|
// client shows them above the composer: the command, how long it has been
|
||||||
|
// running, and a way to stop it.
|
||||||
|
import '../l10n.dart';
|
||||||
|
import 'models.dart';
|
||||||
|
|
||||||
|
/// One running (or just ended) shell. `id` is the shell id opencode created
|
||||||
|
/// (`shellID` on a job); the tool call that detached it carries the same id.
|
||||||
|
class ShellTask {
|
||||||
|
final String id;
|
||||||
|
|
||||||
|
/// The session that started it (a subagent has its own).
|
||||||
|
final String sessionId;
|
||||||
|
final String command;
|
||||||
|
|
||||||
|
/// Epoch milliseconds.
|
||||||
|
final int startedAt;
|
||||||
|
final bool running;
|
||||||
|
|
||||||
|
const ShellTask({
|
||||||
|
required this.id,
|
||||||
|
required this.sessionId,
|
||||||
|
required this.command,
|
||||||
|
required this.startedAt,
|
||||||
|
this.running = true,
|
||||||
|
});
|
||||||
|
|
||||||
|
ShellTask copyWith({
|
||||||
|
String? command,
|
||||||
|
int? startedAt,
|
||||||
|
bool? running,
|
||||||
|
String? sessionId,
|
||||||
|
}) =>
|
||||||
|
ShellTask(
|
||||||
|
id: id,
|
||||||
|
sessionId: sessionId ?? this.sessionId,
|
||||||
|
command: command ?? this.command,
|
||||||
|
startedAt: startedAt ?? this.startedAt,
|
||||||
|
running: running ?? this.running,
|
||||||
|
);
|
||||||
|
|
||||||
|
static ShellTask? fromWire(Object? raw) {
|
||||||
|
if (raw is! Map) return null;
|
||||||
|
final id = raw['id'];
|
||||||
|
if (id is! String || id.isEmpty) return null;
|
||||||
|
final metadata = raw['metadata'];
|
||||||
|
final owner = metadata is Map ? metadata['sessionID'] : null;
|
||||||
|
final time = raw['time'];
|
||||||
|
final started = time is Map ? time['started'] : null;
|
||||||
|
return ShellTask(
|
||||||
|
id: id,
|
||||||
|
sessionId: owner is String ? owner : '',
|
||||||
|
command: (raw['command'] as String?) ?? '',
|
||||||
|
startedAt: (started as num?)?.toInt() ?? 0,
|
||||||
|
running: (raw['status'] as String?) == 'running',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One entry of `GET /api/experimental/job` when it is a shell job: its
|
||||||
|
/// `shellID` is the id the output and stop calls take.
|
||||||
|
static ShellTask? fromJob(Object? raw) {
|
||||||
|
if (raw is! Map || raw['kind'] != 'shell') return null;
|
||||||
|
final shellId = raw['shellID'];
|
||||||
|
if (shellId is! String || shellId.isEmpty) return null;
|
||||||
|
final time = raw['time'];
|
||||||
|
final started = time is Map ? time['started'] : null;
|
||||||
|
return ShellTask(
|
||||||
|
id: shellId,
|
||||||
|
sessionId: (raw['sessionID'] as String?) ?? '',
|
||||||
|
command: (raw['command'] as String?) ?? '',
|
||||||
|
startedAt: (started as num?)?.toInt() ?? 0,
|
||||||
|
running: (raw['status'] as String?) == 'running',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session's shells from `GET /api/shell`, running ones first as the
|
||||||
|
/// wire lists them. Shells that already exited stay in the answer (status
|
||||||
|
/// `exited`), so callers filter on [ShellTask.running].
|
||||||
|
List<ShellTask> shellTasksFromList(Map<String, dynamic> body) {
|
||||||
|
final data = body['data'];
|
||||||
|
if (data is! List) return const [];
|
||||||
|
return [
|
||||||
|
for (final raw in data) ?ShellTask.fromWire(raw),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The running shell jobs of `GET /api/experimental/job`: opencode's own
|
||||||
|
/// record of what it detached (a `bash` call that returned while the command
|
||||||
|
/// kept going). Unlike the transcript this also covers subagent sessions, and
|
||||||
|
/// it never contains a foreground command.
|
||||||
|
List<ShellTask> shellTasksFromJobs(Map<String, dynamic> body) {
|
||||||
|
final data = body['data'];
|
||||||
|
if (data is! List) return const [];
|
||||||
|
final out = <ShellTask>[];
|
||||||
|
for (final raw in data) {
|
||||||
|
final task = ShellTask.fromJob(raw);
|
||||||
|
if (task != null && task.running) out.add(task);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One page of a shell's output (`GET /api/shell/:id/output`): the text read
|
||||||
|
/// from [cursor], the cursor after it, and the total size so a first read can
|
||||||
|
/// start near the tail instead of the beginning.
|
||||||
|
class ShellOutputPage {
|
||||||
|
final String output;
|
||||||
|
final int cursor;
|
||||||
|
final int size;
|
||||||
|
|
||||||
|
/// The server cut this page (the requested span was larger than it serves
|
||||||
|
/// at once); the next read continues from [cursor].
|
||||||
|
final bool truncated;
|
||||||
|
|
||||||
|
const ShellOutputPage({
|
||||||
|
this.output = '',
|
||||||
|
this.cursor = 0,
|
||||||
|
this.size = 0,
|
||||||
|
this.truncated = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
static ShellOutputPage fromJson(Map<String, dynamic> body) {
|
||||||
|
final data = body['data'];
|
||||||
|
if (data is! Map) return const ShellOutputPage();
|
||||||
|
return ShellOutputPage(
|
||||||
|
output: (data['output'] as String?) ?? '',
|
||||||
|
cursor: (data['cursor'] as num?)?.toInt() ?? 0,
|
||||||
|
size: (data['size'] as num?)?.toInt() ?? 0,
|
||||||
|
truncated: data['truncated'] == true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A finished background command's report: the synthetic message opencode
|
||||||
|
/// writes into the session when the job ends (`<background-result …>`), which
|
||||||
|
/// also holds the output after the shell itself is gone.
|
||||||
|
class ShellCompletionNote {
|
||||||
|
final String shellId;
|
||||||
|
final String state;
|
||||||
|
final String output;
|
||||||
|
|
||||||
|
const ShellCompletionNote({
|
||||||
|
required this.shellId,
|
||||||
|
required this.state,
|
||||||
|
required this.output,
|
||||||
|
});
|
||||||
|
|
||||||
|
bool get failed => state == 'error' || state == 'cancelled';
|
||||||
|
}
|
||||||
|
|
||||||
|
final _backgroundResult = RegExp(
|
||||||
|
r'<background-result\b([^>]*)>([\s\S]*?)</background-result>');
|
||||||
|
|
||||||
|
/// The completion a synthetic message carries, or null for other notes.
|
||||||
|
ShellCompletionNote? shellCompletionNote(Message message) {
|
||||||
|
if (message.type != 'synthetic') return null;
|
||||||
|
final match = _backgroundResult.firstMatch(message.text);
|
||||||
|
if (match == null) return null;
|
||||||
|
final attrs = match.group(1) ?? '';
|
||||||
|
if (!attrs.contains('kind="shell"')) return null;
|
||||||
|
final id = RegExp(r'id="([^"]+)"').firstMatch(attrs)?.group(1);
|
||||||
|
if (id == null || id.isEmpty) return null;
|
||||||
|
final state =
|
||||||
|
RegExp(r'state="([^"]+)"').firstMatch(attrs)?.group(1) ?? '';
|
||||||
|
var output = match.group(2) ?? '';
|
||||||
|
if (output.startsWith('\n')) output = output.substring(1);
|
||||||
|
return ShellCompletionNote(
|
||||||
|
shellId: id, state: state, output: output.trimRight());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest completion note for [shellId], if the command has finished.
|
||||||
|
ShellCompletionNote? shellCompletionFor(
|
||||||
|
Iterable<Message> messages, String shellId) {
|
||||||
|
ShellCompletionNote? found;
|
||||||
|
for (final message in messages) {
|
||||||
|
final note = shellCompletionNote(message);
|
||||||
|
if (note != null && note.shellId == shellId) found = note;
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the app itself stopped [shellId]: the note it writes into the
|
||||||
|
/// session carries `metadata.openchamber.shellStop.shellIDs`.
|
||||||
|
bool shellWasStopped(Iterable<Message> messages, String shellId) {
|
||||||
|
for (final message in messages) {
|
||||||
|
if (message.type != 'synthetic') continue;
|
||||||
|
final openchamber = message.metadata?['openchamber'];
|
||||||
|
if (openchamber is! Map) continue;
|
||||||
|
final stop = openchamber['shellStop'];
|
||||||
|
if (stop is! Map) continue;
|
||||||
|
final ids = stop['shellIDs'];
|
||||||
|
if (ids is List && ids.contains(shellId)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shell id a *background* tool call detached, if this part is one. A
|
||||||
|
/// foreground command keeps `status: running` on the tool part itself; the
|
||||||
|
/// detached one is completed and its metadata says the shell still runs:
|
||||||
|
/// `{status: 'running', shellID: 'sh_…'}`, as the first-party client reads it.
|
||||||
|
String? backgroundShellId(ContentPart part) {
|
||||||
|
if (part.type != 'tool') return null;
|
||||||
|
const shells = {'bash', 'shell', 'pwsh', 'execute'};
|
||||||
|
if (!shells.contains(part.name ?? '')) return null;
|
||||||
|
final state = part.state;
|
||||||
|
if (state == null || state.status != 'completed') return null;
|
||||||
|
final metadata = state.metadata;
|
||||||
|
if (metadata == null || metadata['status'] != 'running') return null;
|
||||||
|
final id = metadata['shellID'];
|
||||||
|
return id is String && id.isNotEmpty ? id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A running background command is completed in the transcript (the call
|
||||||
|
/// returned at once) but still going; that is what the strip lists.
|
||||||
|
List<ShellTask> backgroundShellsFromMessages(
|
||||||
|
Iterable<Message> messages, String sessionId) {
|
||||||
|
final out = <ShellTask>[];
|
||||||
|
final seen = <String>{};
|
||||||
|
for (final message in messages) {
|
||||||
|
for (final part in message.content) {
|
||||||
|
final id = backgroundShellId(part);
|
||||||
|
if (id == null || !seen.add(id)) continue;
|
||||||
|
final input = part.state?.input ?? const <String, dynamic>{};
|
||||||
|
out.add(ShellTask(
|
||||||
|
id: id,
|
||||||
|
sessionId: sessionId,
|
||||||
|
command: '${input['command'] ?? ''}'.trim(),
|
||||||
|
startedAt: message.created,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep a shell under the report size: the first read asks for everything
|
||||||
|
/// and the UI shows only this much of the tail.
|
||||||
|
const shellOutputTailBytes = 256 * 1024;
|
||||||
|
|
||||||
|
/// `12秒`, `3分05秒`, `1:02:03`: the running clock a task row shows.
|
||||||
|
String formatElapsed(int milliseconds) {
|
||||||
|
final secs = milliseconds <= 0 ? 0 : milliseconds ~/ 1000;
|
||||||
|
if (secs < 60) return trArgs('{0}s', [secs]);
|
||||||
|
if (secs < 3600) {
|
||||||
|
final rest = secs % 60;
|
||||||
|
return trArgs(
|
||||||
|
'{0}m{1}s', [secs ~/ 60, rest.toString().padLeft(2, '0')]);
|
||||||
|
}
|
||||||
|
final hours = secs ~/ 3600;
|
||||||
|
final mins = (secs % 3600) ~/ 60;
|
||||||
|
final rest = secs % 60;
|
||||||
|
return '$hours:${mins.toString().padLeft(2, '0')}:'
|
||||||
|
'${rest.toString().padLeft(2, '0')}';
|
||||||
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
// The OpenChamber terminal protocol: HTTP commands (create, resize, restart,
|
||||||
|
// close) plus one WebSocket per host carrying binary control frames (a 0x01
|
||||||
|
// tag, then JSON). A socket can attach to several terminals; we attach to one.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'transport.dart';
|
||||||
|
|
||||||
|
/// What `POST /api/terminal/create` (and restart) answers.
|
||||||
|
class TerminalSessionInfo {
|
||||||
|
final String sessionId;
|
||||||
|
final int cols;
|
||||||
|
final int rows;
|
||||||
|
final String status;
|
||||||
|
|
||||||
|
const TerminalSessionInfo({
|
||||||
|
required this.sessionId,
|
||||||
|
this.cols = 80,
|
||||||
|
this.rows = 24,
|
||||||
|
this.status = 'running',
|
||||||
|
});
|
||||||
|
|
||||||
|
factory TerminalSessionInfo.fromJson(Map<String, dynamic> j) =>
|
||||||
|
TerminalSessionInfo(
|
||||||
|
sessionId: j['sessionId'] as String? ?? '',
|
||||||
|
cols: (j['cols'] as num?)?.toInt() ?? 80,
|
||||||
|
rows: (j['rows'] as num?)?.toInt() ?? 24,
|
||||||
|
status: j['status'] as String? ?? 'running',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A terminal the server still holds, from `GET /api/terminal/sessions`.
|
||||||
|
/// The id outlives this app process, so a restart can attach to the same
|
||||||
|
/// shell instead of making another one.
|
||||||
|
class ServerTerminal {
|
||||||
|
final String sessionId;
|
||||||
|
final String cwd;
|
||||||
|
final String status; // running | exited
|
||||||
|
final int? createdAt;
|
||||||
|
final String mode; // interactive | command
|
||||||
|
final String purpose; // terminal | project-action (or empty)
|
||||||
|
|
||||||
|
const ServerTerminal({
|
||||||
|
required this.sessionId,
|
||||||
|
this.cwd = '',
|
||||||
|
this.status = 'running',
|
||||||
|
this.createdAt,
|
||||||
|
this.mode = 'interactive',
|
||||||
|
this.purpose = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A terminal a person opened. A project action's command runner is also a
|
||||||
|
/// PTY, but it is not one of the user's tabs.
|
||||||
|
bool get interactive => mode != 'command' && purpose != 'project-action';
|
||||||
|
|
||||||
|
factory ServerTerminal.fromJson(Map<String, dynamic> j) {
|
||||||
|
final purposeJson = j['purpose'];
|
||||||
|
return ServerTerminal(
|
||||||
|
sessionId: j['sessionId'] as String? ?? '',
|
||||||
|
cwd: j['cwd'] as String? ?? '',
|
||||||
|
status: j['status'] as String? ?? 'running',
|
||||||
|
createdAt: (j['createdAt'] as num?)?.toInt(),
|
||||||
|
mode: j['mode'] as String? ?? 'interactive',
|
||||||
|
purpose: purposeJson is Map
|
||||||
|
? purposeJson['type'] as String? ?? ''
|
||||||
|
: '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One frame from the server: a snapshot (the authoritative screen), output,
|
||||||
|
/// an exit notice, or an error.
|
||||||
|
class TerminalEvent {
|
||||||
|
final String type; // snapshot | output | restarted | exit | error
|
||||||
|
final String data; // snapshot history / output text
|
||||||
|
final int sequence;
|
||||||
|
final int? cols;
|
||||||
|
final int? rows;
|
||||||
|
final String? status;
|
||||||
|
final int? exitCode;
|
||||||
|
final int? signal;
|
||||||
|
final String? code;
|
||||||
|
final String? message;
|
||||||
|
final bool fatal;
|
||||||
|
|
||||||
|
const TerminalEvent(
|
||||||
|
this.type, {
|
||||||
|
this.data = '',
|
||||||
|
this.sequence = 0,
|
||||||
|
this.cols,
|
||||||
|
this.rows,
|
||||||
|
this.status,
|
||||||
|
this.exitCode,
|
||||||
|
this.signal,
|
||||||
|
this.code,
|
||||||
|
this.message,
|
||||||
|
this.fatal = false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The socket's life, for the status bar.
|
||||||
|
enum TerminalLinkState { idle, creating, connecting, open, reconnecting, exited, error }
|
||||||
|
|
||||||
|
/// One attached terminal. Writes made while the socket is down wait in a
|
||||||
|
/// buffer; a dropped socket reconnects with backoff and reattaches, which
|
||||||
|
/// begins with a fresh snapshot.
|
||||||
|
class TerminalSocket {
|
||||||
|
final Transport transport;
|
||||||
|
final Map<String, String> headers;
|
||||||
|
final String sessionId;
|
||||||
|
final void Function(TerminalEvent event) onEvent;
|
||||||
|
final void Function(TerminalLinkState state, {String? detail}) onState;
|
||||||
|
|
||||||
|
TransportSocket? _socket;
|
||||||
|
Timer? _keepAlive;
|
||||||
|
Timer? _reconnect;
|
||||||
|
final StringBuffer _pending = StringBuffer();
|
||||||
|
int _failures = 0;
|
||||||
|
int _generation = 0;
|
||||||
|
bool _disposed = false;
|
||||||
|
bool _opened = false;
|
||||||
|
|
||||||
|
TerminalSocket({
|
||||||
|
required this.transport,
|
||||||
|
required this.headers,
|
||||||
|
required this.sessionId,
|
||||||
|
required this.onEvent,
|
||||||
|
required this.onState,
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<void> connect() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
final generation = ++_generation;
|
||||||
|
onState(_opened ? TerminalLinkState.reconnecting : TerminalLinkState.connecting);
|
||||||
|
try {
|
||||||
|
final socket = await transport.webSocket(
|
||||||
|
'/api/terminal/ws',
|
||||||
|
headers: headers,
|
||||||
|
);
|
||||||
|
if (_disposed || generation != _generation) {
|
||||||
|
await socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_socket = socket;
|
||||||
|
_failures = 0;
|
||||||
|
socket.messages.listen(
|
||||||
|
_handle,
|
||||||
|
onError: (_) => _drop(generation),
|
||||||
|
onDone: () => _drop(generation),
|
||||||
|
);
|
||||||
|
_send({'t': 'hello', 'v': 3});
|
||||||
|
_send({'t': 'attach', 'v': 3, 's': sessionId});
|
||||||
|
_opened = true;
|
||||||
|
_keepAlive?.cancel();
|
||||||
|
_keepAlive = Timer.periodic(
|
||||||
|
const Duration(seconds: 45), (_) => _send({'t': 'ping', 'v': 3}));
|
||||||
|
onState(TerminalLinkState.open);
|
||||||
|
_flushPending();
|
||||||
|
} catch (error) {
|
||||||
|
if (_disposed) return;
|
||||||
|
onState(TerminalLinkState.error, detail: '$error');
|
||||||
|
_scheduleReconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void write(String data) {
|
||||||
|
if (data.isEmpty) return;
|
||||||
|
if (_socket == null) {
|
||||||
|
_pending.write(data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_send({'t': 'write', 'v': 3, 's': sessionId, 'd': data});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> dispose() async {
|
||||||
|
_disposed = true;
|
||||||
|
_generation++;
|
||||||
|
_reconnect?.cancel();
|
||||||
|
_keepAlive?.cancel();
|
||||||
|
final socket = _socket;
|
||||||
|
_socket = null;
|
||||||
|
// Detaching leaves the session running on the server; closing the socket
|
||||||
|
// is enough for a panel that is going away.
|
||||||
|
try {
|
||||||
|
await socket?.close();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- internals
|
||||||
|
|
||||||
|
void _send(Map<String, Object?> message) {
|
||||||
|
final socket = _socket;
|
||||||
|
if (socket == null) return;
|
||||||
|
final bytes = <int>[1, ...utf8.encode(jsonEncode(message))];
|
||||||
|
try {
|
||||||
|
socket.add(bytes);
|
||||||
|
} catch (_) {
|
||||||
|
_drop(_generation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _flushPending() {
|
||||||
|
if (_pending.isEmpty) return;
|
||||||
|
final data = _pending.toString();
|
||||||
|
_pending.clear();
|
||||||
|
write(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _drop(int generation) {
|
||||||
|
if (_disposed || generation != _generation) return;
|
||||||
|
_generation++;
|
||||||
|
_keepAlive?.cancel();
|
||||||
|
_keepAlive = null;
|
||||||
|
final socket = _socket;
|
||||||
|
_socket = null;
|
||||||
|
try {
|
||||||
|
socket?.close();
|
||||||
|
} catch (_) {}
|
||||||
|
onState(TerminalLinkState.reconnecting);
|
||||||
|
_scheduleReconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleReconnect() {
|
||||||
|
if (_disposed || _reconnect != null) return;
|
||||||
|
_failures += 1;
|
||||||
|
final delay = Duration(
|
||||||
|
milliseconds: 500 * (1 << (_failures - 1).clamp(0, 4)));
|
||||||
|
_reconnect = Timer(delay, () {
|
||||||
|
_reconnect = null;
|
||||||
|
if (!_disposed) connect();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handle(dynamic raw) {
|
||||||
|
if (_disposed || raw is! List<int> || raw.isEmpty) return;
|
||||||
|
final Map<String, dynamic> message;
|
||||||
|
try {
|
||||||
|
final tag = raw.first;
|
||||||
|
final bytes = tag == 1 ? raw.sublist(1) : raw;
|
||||||
|
final decoded = jsonDecode(utf8.decode(bytes));
|
||||||
|
if (decoded is! Map<String, dynamic>) return;
|
||||||
|
message = decoded;
|
||||||
|
} catch (_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final type = message['t'] as String? ?? '';
|
||||||
|
final sequence = (message['q'] as num?)?.toInt() ?? 0;
|
||||||
|
switch (type) {
|
||||||
|
case 'snapshot':
|
||||||
|
onEvent(TerminalEvent(
|
||||||
|
'snapshot',
|
||||||
|
data: message['history'] as String? ?? '',
|
||||||
|
sequence: sequence,
|
||||||
|
cols: (message['cols'] as num?)?.toInt(),
|
||||||
|
rows: (message['rows'] as num?)?.toInt(),
|
||||||
|
status: message['status'] as String?,
|
||||||
|
exitCode: (message['exitCode'] as num?)?.toInt(),
|
||||||
|
signal: (message['signal'] as num?)?.toInt(),
|
||||||
|
));
|
||||||
|
break;
|
||||||
|
case 'output':
|
||||||
|
// `r` is the replay-safe text (terminal queries removed); `d` the raw
|
||||||
|
// bytes. Replay text is what the official client renders.
|
||||||
|
onEvent(TerminalEvent(
|
||||||
|
'output',
|
||||||
|
data: (message['r'] ?? message['d'] ?? '') as String,
|
||||||
|
sequence: sequence,
|
||||||
|
));
|
||||||
|
break;
|
||||||
|
case 'restarted':
|
||||||
|
onEvent(TerminalEvent(
|
||||||
|
'restarted',
|
||||||
|
data: message['history'] as String? ?? '',
|
||||||
|
sequence: sequence,
|
||||||
|
));
|
||||||
|
break;
|
||||||
|
case 'exit':
|
||||||
|
onState(TerminalLinkState.exited,
|
||||||
|
detail: '${(message['exitCode'] as num?)?.toInt() ?? ''}');
|
||||||
|
onEvent(TerminalEvent(
|
||||||
|
'exit',
|
||||||
|
sequence: sequence,
|
||||||
|
exitCode: (message['exitCode'] as num?)?.toInt(),
|
||||||
|
signal: (message['signal'] as num?)?.toInt(),
|
||||||
|
));
|
||||||
|
break;
|
||||||
|
case 'error':
|
||||||
|
onEvent(TerminalEvent(
|
||||||
|
'error',
|
||||||
|
sequence: sequence,
|
||||||
|
code: message['code'] as String?,
|
||||||
|
message: message['message'] as String?,
|
||||||
|
fatal: message['fatal'] as bool? ?? false,
|
||||||
|
));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
// How the client reaches the server. Today that is a direct HttpClient with
|
||||||
|
// the configured proxy and certificate rules; a relay transport can implement
|
||||||
|
// the same interface over its encrypted tunnel without any caller changing.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:socks5_proxy/socks_client.dart';
|
||||||
|
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// One request: a method, a path relative to the server root, its query, the
|
||||||
|
/// headers already decided by [Client] (auth, directory, accept, …) and an
|
||||||
|
/// optional complete body.
|
||||||
|
class TransportRequest {
|
||||||
|
final String method;
|
||||||
|
final String path;
|
||||||
|
final Map<String, String> query;
|
||||||
|
final Map<String, String> headers;
|
||||||
|
final List<int>? body;
|
||||||
|
|
||||||
|
/// When set, used verbatim as the query string (the event stream repeats
|
||||||
|
/// `types`, which a Map cannot express).
|
||||||
|
final String? rawQuery;
|
||||||
|
const TransportRequest({
|
||||||
|
required this.method,
|
||||||
|
required this.path,
|
||||||
|
this.query = const {},
|
||||||
|
this.headers = const {},
|
||||||
|
this.body,
|
||||||
|
this.rawQuery,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reply whose head is in hand and whose body still streams (SSE and file
|
||||||
|
/// downloads rely on that).
|
||||||
|
class TransportResponse {
|
||||||
|
final int status;
|
||||||
|
final Map<String, String> headers;
|
||||||
|
final Stream<List<int>> body;
|
||||||
|
|
||||||
|
/// Drops the connection while the body is still being read (a download the
|
||||||
|
/// user cancelled); null when the reply already finished.
|
||||||
|
final void Function()? abort;
|
||||||
|
const TransportResponse(this.status, this.headers, this.body, {this.abort});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A binary socket: a direct WebSocket, or one sub-stream of the relay tunnel.
|
||||||
|
/// The terminal speaks binary control frames, so text frames are not surfaced.
|
||||||
|
abstract class TransportSocket {
|
||||||
|
Stream<List<int>> get messages;
|
||||||
|
void add(List<int> data);
|
||||||
|
Future<void> close([int code = 1000, String reason = '']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one seam every request goes through.
|
||||||
|
abstract class Transport {
|
||||||
|
/// Sends [request], completing when the reply head arrives.
|
||||||
|
Future<TransportResponse> send(TransportRequest request);
|
||||||
|
|
||||||
|
/// Opens a WebSocket on [path] (the terminal stream). Through the same
|
||||||
|
/// sockets as [send], so proxies and certificates keep working.
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}});
|
||||||
|
|
||||||
|
/// The bearer the client authenticates with. A direct transport ignores it;
|
||||||
|
/// a relay must mint URL-scoped tokens from it for WebSocket upgrades, which
|
||||||
|
/// cannot carry headers.
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
/// Releases whatever sockets the transport holds.
|
||||||
|
void close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets a caller abandon a download: [cancel] aborts the request and makes the
|
||||||
|
/// reader stop at its next chunk.
|
||||||
|
class CancelToken {
|
||||||
|
bool _cancelled = false;
|
||||||
|
void Function()? _abort;
|
||||||
|
|
||||||
|
bool get isCancelled => _cancelled;
|
||||||
|
|
||||||
|
/// Called by the downloader once the request is in flight.
|
||||||
|
void attach(void Function() abort) {
|
||||||
|
_abort = abort;
|
||||||
|
if (_cancelled) abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
void detach() => _abort = null;
|
||||||
|
|
||||||
|
void cancel() {
|
||||||
|
if (_cancelled) return;
|
||||||
|
_cancelled = true;
|
||||||
|
_abort?.call();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thrown by a download the user cancelled.
|
||||||
|
class DownloadCancelled implements Exception {
|
||||||
|
const DownloadCancelled();
|
||||||
|
@override
|
||||||
|
String toString() => tr('Download cancelled');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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(trArgs('Invalid proxy address: {0}', [raw]));
|
||||||
|
}
|
||||||
|
final scheme = uri.scheme.toLowerCase();
|
||||||
|
final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h';
|
||||||
|
final http = scheme == 'http' || scheme == 'https';
|
||||||
|
if (!socks && !http) {
|
||||||
|
throw ArgumentError(trArgs(
|
||||||
|
'Unsupported proxy protocol: {0} (supported: http, https, socks5, socks5h)', [scheme]));
|
||||||
|
}
|
||||||
|
String? user;
|
||||||
|
String? pass;
|
||||||
|
if (uri.userInfo.isNotEmpty) {
|
||||||
|
final i = uri.userInfo.indexOf(':');
|
||||||
|
if (i >= 0) {
|
||||||
|
user = Uri.decodeComponent(uri.userInfo.substring(0, i));
|
||||||
|
pass = Uri.decodeComponent(uri.userInfo.substring(i + 1));
|
||||||
|
} else {
|
||||||
|
user = Uri.decodeComponent(uri.userInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080);
|
||||||
|
return ProxyConfig(scheme, uri.host, port, user, pass);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Direct HTTP: the server's own URL, optionally through an HTTP or SOCKS5
|
||||||
|
/// proxy, with the self-signed certificate rules.
|
||||||
|
class DirectTransport implements Transport {
|
||||||
|
final Uri base;
|
||||||
|
final bool insecure;
|
||||||
|
final String? fingerprint;
|
||||||
|
late final HttpClient _http;
|
||||||
|
ProxyConfig? _proxyConfig;
|
||||||
|
InternetAddress? _proxyAddress;
|
||||||
|
|
||||||
|
DirectTransport(
|
||||||
|
this.base, {
|
||||||
|
String? proxy,
|
||||||
|
this.insecure = false,
|
||||||
|
this.fingerprint,
|
||||||
|
}) {
|
||||||
|
_http = HttpClient()..connectionTimeout = const Duration(seconds: 20);
|
||||||
|
_proxyConfig = parseProxy(proxy);
|
||||||
|
if (_proxyConfig != null && _proxyConfig!.socks) {
|
||||||
|
// Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy
|
||||||
|
// package tunnels the socket and hands a Socket back to the client.
|
||||||
|
_http.connectionFactory = (uri, _, __) async {
|
||||||
|
final address = await _resolveProxyAddress();
|
||||||
|
final settings = ProxySettings(address, _proxyConfig!.port,
|
||||||
|
username: _proxyConfig!.username, password: _proxyConfig!.password);
|
||||||
|
final tunnel = SocksTCPClient.connect(
|
||||||
|
[settings],
|
||||||
|
// A unix-type address carries the host name, so the proxy resolves
|
||||||
|
// it (socks5h semantics) instead of resolving it here.
|
||||||
|
InternetAddress(uri.host, type: InternetAddressType.unix),
|
||||||
|
uri.port,
|
||||||
|
);
|
||||||
|
if (uri.scheme == 'https') {
|
||||||
|
final secure = tunnel.then(
|
||||||
|
(s) => s.secure(uri.host, onBadCertificate: _badCertificate));
|
||||||
|
return ConnectionTask.fromSocket(secure, () {});
|
||||||
|
}
|
||||||
|
return ConnectionTask.fromSocket(tunnel, () {});
|
||||||
|
};
|
||||||
|
} else if (_proxyConfig != null) {
|
||||||
|
_http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}';
|
||||||
|
}
|
||||||
|
_http.badCertificateCallback = (cert, host, port) => _badCertificate(cert);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<InternetAddress> _resolveProxyAddress() async {
|
||||||
|
if (_proxyAddress != null) return _proxyAddress!;
|
||||||
|
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
|
||||||
|
if (addresses.isEmpty) {
|
||||||
|
throw SocketException(tr('Could not resolve the proxy host'));
|
||||||
|
}
|
||||||
|
return _proxyAddress = addresses.first;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True for a certificate the app was told to accept: the user trusts any
|
||||||
|
/// (insecure), or its SHA-256 matches the pinned fingerprint.
|
||||||
|
bool _badCertificate(X509Certificate cert) {
|
||||||
|
if (insecure) return true;
|
||||||
|
final pinned = fingerprint?.replaceAll(':', '').toLowerCase();
|
||||||
|
if (pinned == null || pinned.isEmpty) return false;
|
||||||
|
return sha256Hex(cert.der) == pinned;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
final query = r.rawQuery ??
|
||||||
|
Uri(queryParameters: r.query.isEmpty ? null : r.query).query;
|
||||||
|
final uri = base.resolve(r.path).replace(query: query.isEmpty ? null : query);
|
||||||
|
final req = await _http.openUrl(r.method, uri);
|
||||||
|
// Every header must be set before the body, which finalizes them.
|
||||||
|
r.headers.forEach(req.headers.set);
|
||||||
|
if (r.body != null) req.add(r.body!);
|
||||||
|
final res = await req.close();
|
||||||
|
final headers = <String, String>{};
|
||||||
|
res.headers.forEach((name, values) {
|
||||||
|
headers[name.toLowerCase()] = values.join(', ');
|
||||||
|
});
|
||||||
|
return TransportResponse(res.statusCode, headers, res,
|
||||||
|
abort: req.abort);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async {
|
||||||
|
// ws:// is http:// with the upgrade; wss:// checks the same certificates,
|
||||||
|
// so the configured client is reused as it stands.
|
||||||
|
final base = this.base.replace(
|
||||||
|
scheme: this.base.scheme == 'https' ? 'wss' : 'ws');
|
||||||
|
final query = rawQuery ?? '';
|
||||||
|
final uri = base.resolve(path).replace(query: query.isEmpty ? null : query);
|
||||||
|
final socket = await WebSocket.connect(uri.toString(),
|
||||||
|
headers: headers, customClient: _http);
|
||||||
|
return _DirectSocket(socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => _http.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wraps a direct WebSocket in the transport-agnostic socket shape. The
|
||||||
|
/// terminal only speaks binary frames; text frames are ignored.
|
||||||
|
class _DirectSocket implements TransportSocket {
|
||||||
|
final WebSocket _socket;
|
||||||
|
_DirectSocket(this._socket);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<List<int>> get messages =>
|
||||||
|
_socket.where((event) => event is List<int>).cast<List<int>>();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void add(List<int> data) => _socket.add(data);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close([int code = 1000, String reason = '']) =>
|
||||||
|
_socket.close(code, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
String sha256Hex(List<int> bytes) => _Digest.sha256Hex(bytes);
|
||||||
|
|
||||||
|
// Minimal SHA-256, so the client has no native dependencies for pinning.
|
||||||
|
class _Digest {
|
||||||
|
static String sha256Hex(List<int> bytes) {
|
||||||
|
final h = List<int>.from(const [
|
||||||
|
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||||
|
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
||||||
|
]);
|
||||||
|
const k = [
|
||||||
|
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||||
|
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||||
|
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||||
|
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||||
|
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||||
|
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||||
|
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||||
|
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||||
|
];
|
||||||
|
final m = List<int>.from(bytes);
|
||||||
|
final bitLen = m.length * 8;
|
||||||
|
m.add(0x80);
|
||||||
|
while (m.length % 64 != 56) {
|
||||||
|
m.add(0);
|
||||||
|
}
|
||||||
|
for (var i = 7; i >= 0; i--) {
|
||||||
|
m.add((bitLen >> (8 * i)) & 0xff);
|
||||||
|
}
|
||||||
|
final words = List<int>.generate(m.length ~/ 4, (i) =>
|
||||||
|
(m[i * 4] << 24) | (m[i * 4 + 1] << 16) | (m[i * 4 + 2] << 8) | m[i * 4 + 3]);
|
||||||
|
var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
|
||||||
|
for (var i = 0; i < words.length; i += 16) {
|
||||||
|
final w = List<int>.filled(64, 0);
|
||||||
|
for (var j = 0; j < 16; j++) {
|
||||||
|
w[j] = words[i + j];
|
||||||
|
}
|
||||||
|
for (var j = 16; j < 64; j++) {
|
||||||
|
final s0 = _rotr(w[j - 15], 7) ^ _rotr(w[j - 15], 18) ^ (w[j - 15] >> 3);
|
||||||
|
final s1 = _rotr(w[j - 2], 17) ^ _rotr(w[j - 2], 19) ^ (w[j - 2] >> 10);
|
||||||
|
w[j] = (w[j - 16] + s0 + w[j - 7] + s1) & 0xffffffff;
|
||||||
|
}
|
||||||
|
var ta = a, tb = b, tc = c, td = d, te = e, tf = f, tg = g, th = hh;
|
||||||
|
for (var j = 0; j < 64; j++) {
|
||||||
|
final s1 = _rotr(te, 6) ^ _rotr(te, 11) ^ _rotr(te, 25);
|
||||||
|
final ch = (te & tf) ^ ((~te) & tg);
|
||||||
|
final t1 = (th + s1 + ch + k[j] + w[j]) & 0xffffffff;
|
||||||
|
final s0 = _rotr(ta, 2) ^ _rotr(ta, 13) ^ _rotr(ta, 22);
|
||||||
|
final maj = (ta & tb) ^ (ta & tc) ^ (tb & tc);
|
||||||
|
final t2 = (s0 + maj) & 0xffffffff;
|
||||||
|
th = tg;
|
||||||
|
tg = tf;
|
||||||
|
tf = te;
|
||||||
|
te = (td + t1) & 0xffffffff;
|
||||||
|
td = tc;
|
||||||
|
tc = tb;
|
||||||
|
tb = ta;
|
||||||
|
ta = (t1 + t2) & 0xffffffff;
|
||||||
|
}
|
||||||
|
a = (a + ta) & 0xffffffff;
|
||||||
|
b = (b + tb) & 0xffffffff;
|
||||||
|
c = (c + tc) & 0xffffffff;
|
||||||
|
d = (d + td) & 0xffffffff;
|
||||||
|
e = (e + te) & 0xffffffff;
|
||||||
|
f = (f + tf) & 0xffffffff;
|
||||||
|
g = (g + tg) & 0xffffffff;
|
||||||
|
hh = (hh + th) & 0xffffffff;
|
||||||
|
}
|
||||||
|
final out = List<int>.filled(32, 0);
|
||||||
|
final vals = [a, b, c, d, e, f, g, hh];
|
||||||
|
for (var i = 0; i < 8; i++) {
|
||||||
|
out[i * 4] = (vals[i] >> 24) & 0xff;
|
||||||
|
out[i * 4 + 1] = (vals[i] >> 16) & 0xff;
|
||||||
|
out[i * 4 + 2] = (vals[i] >> 8) & 0xff;
|
||||||
|
out[i * 4 + 3] = vals[i] & 0xff;
|
||||||
|
}
|
||||||
|
return out.map((e) => e.toRadixString(16).padLeft(2, '0')).join();
|
||||||
|
}
|
||||||
|
|
||||||
|
static int _rotr(int x, int n) => (x >> n) | ((x << (32 - n)) & 0xffffffff);
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
// The OpenCode session statistics report (`/experimental/session/stats`), as
|
||||||
|
// the OpenChamber web client's 统计 page reads it: prompts, steps, tokens,
|
||||||
|
// cost, activity, models and (on request) tool calls.
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// The ranges the page offers; the server only needs the start timestamp.
|
||||||
|
enum UsageRange { day, week, month, quarter, all }
|
||||||
|
|
||||||
|
extension UsageRangeX on UsageRange {
|
||||||
|
/// Days included, today counted; null for all time.
|
||||||
|
int? get days => switch (this) {
|
||||||
|
UsageRange.day => 1,
|
||||||
|
UsageRange.week => 7,
|
||||||
|
UsageRange.month => 30,
|
||||||
|
UsageRange.quarter => 90,
|
||||||
|
UsageRange.all => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Local midnight at the start of the range, in milliseconds; null for all
|
||||||
|
/// time (the server then starts at the oldest message).
|
||||||
|
int? startFrom(DateTime now) {
|
||||||
|
final days = this.days;
|
||||||
|
if (days == null) return null;
|
||||||
|
final today = DateTime(now.year, now.month, now.day);
|
||||||
|
return today.subtract(Duration(days: days - 1)).millisecondsSinceEpoch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageTokens {
|
||||||
|
final int input;
|
||||||
|
final int output;
|
||||||
|
final int reasoning;
|
||||||
|
final int cacheRead;
|
||||||
|
final int cacheWrite;
|
||||||
|
|
||||||
|
const UsageTokens({
|
||||||
|
this.input = 0,
|
||||||
|
this.output = 0,
|
||||||
|
this.reasoning = 0,
|
||||||
|
this.cacheRead = 0,
|
||||||
|
this.cacheWrite = 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Everything the model read or wrote, cache included.
|
||||||
|
int get total => input + output + reasoning + cacheRead + cacheWrite;
|
||||||
|
|
||||||
|
/// What the model produced: the answer plus its reasoning.
|
||||||
|
int get produced => output + reasoning;
|
||||||
|
|
||||||
|
factory UsageTokens.fromJson(Map<String, dynamic>? j) {
|
||||||
|
if (j == null) return const UsageTokens();
|
||||||
|
final cache = j['cache'] as Map<String, dynamic>? ?? const {};
|
||||||
|
int n(Object? v) => (v as num?)?.toInt() ?? 0;
|
||||||
|
return UsageTokens(
|
||||||
|
input: n(j['input']),
|
||||||
|
output: n(j['output']),
|
||||||
|
reasoning: n(j['reasoning']),
|
||||||
|
cacheRead: n(cache['read']),
|
||||||
|
cacheWrite: n(cache['write']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageModelStat {
|
||||||
|
final String providerId;
|
||||||
|
final String modelId;
|
||||||
|
final String? variant;
|
||||||
|
final int steps;
|
||||||
|
final UsageTokens tokens;
|
||||||
|
final double cost;
|
||||||
|
|
||||||
|
const UsageModelStat({
|
||||||
|
required this.providerId,
|
||||||
|
required this.modelId,
|
||||||
|
this.variant,
|
||||||
|
this.steps = 0,
|
||||||
|
this.tokens = const UsageTokens(),
|
||||||
|
this.cost = 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory UsageModelStat.fromJson(Map<String, dynamic> j) {
|
||||||
|
final model = j['model'] as Map<String, dynamic>? ?? const {};
|
||||||
|
final variant = model['variant'];
|
||||||
|
return UsageModelStat(
|
||||||
|
providerId: model['providerID'] as String? ?? '',
|
||||||
|
modelId: model['id'] as String? ?? '',
|
||||||
|
variant: variant is String && variant.isNotEmpty ? variant : null,
|
||||||
|
steps: (j['steps'] as num?)?.toInt() ?? 0,
|
||||||
|
tokens: UsageTokens.fromJson(j['tokens'] as Map<String, dynamic>?),
|
||||||
|
cost: (j['cost'] as num?)?.toDouble() ?? 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageToolStat {
|
||||||
|
final String name;
|
||||||
|
final int calls;
|
||||||
|
final int succeeded;
|
||||||
|
final int failed;
|
||||||
|
final int unfinished;
|
||||||
|
|
||||||
|
/// Median duration in milliseconds; null when the server did not measure it.
|
||||||
|
final double? durationP50;
|
||||||
|
|
||||||
|
const UsageToolStat({
|
||||||
|
required this.name,
|
||||||
|
this.calls = 0,
|
||||||
|
this.succeeded = 0,
|
||||||
|
this.failed = 0,
|
||||||
|
this.unfinished = 0,
|
||||||
|
this.durationP50,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory UsageToolStat.fromJson(Map<String, dynamic> j) => UsageToolStat(
|
||||||
|
name: j['name'] as String? ?? '',
|
||||||
|
calls: (j['calls'] as num?)?.toInt() ?? 0,
|
||||||
|
succeeded: (j['succeeded'] as num?)?.toInt() ?? 0,
|
||||||
|
failed: (j['failed'] as num?)?.toInt() ?? 0,
|
||||||
|
unfinished: (j['unfinished'] as num?)?.toInt() ?? 0,
|
||||||
|
durationP50: (j['durationP50'] as num?)?.toDouble(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageTools {
|
||||||
|
/// `none`, `summary` or `detail`.
|
||||||
|
final String mode;
|
||||||
|
final int calls;
|
||||||
|
final int succeeded;
|
||||||
|
final int failed;
|
||||||
|
final int unfinished;
|
||||||
|
final List<UsageToolStat> rows;
|
||||||
|
|
||||||
|
const UsageTools({
|
||||||
|
this.mode = 'none',
|
||||||
|
this.calls = 0,
|
||||||
|
this.succeeded = 0,
|
||||||
|
this.failed = 0,
|
||||||
|
this.unfinished = 0,
|
||||||
|
this.rows = const [],
|
||||||
|
});
|
||||||
|
|
||||||
|
bool get hasTotals => mode == 'summary' || mode == 'detail';
|
||||||
|
bool get hasDetail => mode == 'detail';
|
||||||
|
|
||||||
|
factory UsageTools.fromJson(Map<String, dynamic>? j) {
|
||||||
|
if (j == null) return const UsageTools();
|
||||||
|
final totals = j['totals'] as Map<String, dynamic>? ?? const {};
|
||||||
|
int n(Object? v) => (v as num?)?.toInt() ?? 0;
|
||||||
|
return UsageTools(
|
||||||
|
mode: j['mode'] as String? ?? 'none',
|
||||||
|
calls: n(totals['calls']),
|
||||||
|
succeeded: n(totals['succeeded']),
|
||||||
|
failed: n(totals['failed']),
|
||||||
|
unfinished: n(totals['unfinished']),
|
||||||
|
rows: [
|
||||||
|
for (final row in (j['usage'] as List?) ?? const [])
|
||||||
|
if (row is Map<String, dynamic>) UsageToolStat.fromJson(row),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageActivityDay {
|
||||||
|
final String date;
|
||||||
|
final int steps;
|
||||||
|
const UsageActivityDay(this.date, this.steps);
|
||||||
|
|
||||||
|
factory UsageActivityDay.fromJson(Map<String, dynamic> j) => UsageActivityDay(
|
||||||
|
j['date'] as String? ?? '',
|
||||||
|
(j['steps'] as num?)?.toInt() ?? 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageStats {
|
||||||
|
final int from;
|
||||||
|
final int to;
|
||||||
|
final int sessions;
|
||||||
|
final int subagents;
|
||||||
|
final int prompts;
|
||||||
|
final int steps;
|
||||||
|
final UsageTokens tokens;
|
||||||
|
final double cost;
|
||||||
|
final int activeDays;
|
||||||
|
final int streak;
|
||||||
|
final List<UsageActivityDay> activity;
|
||||||
|
final List<UsageModelStat> models;
|
||||||
|
final UsageTools tools;
|
||||||
|
|
||||||
|
const UsageStats({
|
||||||
|
this.from = 0,
|
||||||
|
this.to = 0,
|
||||||
|
this.sessions = 0,
|
||||||
|
this.subagents = 0,
|
||||||
|
this.prompts = 0,
|
||||||
|
this.steps = 0,
|
||||||
|
this.tokens = const UsageTokens(),
|
||||||
|
this.cost = 0,
|
||||||
|
this.activeDays = 0,
|
||||||
|
this.streak = 0,
|
||||||
|
this.activity = const [],
|
||||||
|
this.models = const [],
|
||||||
|
this.tools = const UsageTools(),
|
||||||
|
});
|
||||||
|
|
||||||
|
bool get isEmpty => prompts == 0 && steps == 0;
|
||||||
|
|
||||||
|
factory UsageStats.fromJson(Map<String, dynamic> j) {
|
||||||
|
final range = j['range'] as Map<String, dynamic>? ?? const {};
|
||||||
|
int n(Object? v) => (v as num?)?.toInt() ?? 0;
|
||||||
|
return UsageStats(
|
||||||
|
from: n(range['from']),
|
||||||
|
to: n(range['to']),
|
||||||
|
sessions: n(j['sessions']),
|
||||||
|
subagents: n(j['subagents']),
|
||||||
|
prompts: n(j['prompts']),
|
||||||
|
steps: n(j['steps']),
|
||||||
|
tokens: UsageTokens.fromJson(j['tokens'] as Map<String, dynamic>?),
|
||||||
|
cost: (j['cost'] as num?)?.toDouble() ?? 0,
|
||||||
|
activeDays: n(j['activeDays']),
|
||||||
|
streak: n(j['streak']),
|
||||||
|
activity: [
|
||||||
|
for (final day in (j['activity'] as List?) ?? const [])
|
||||||
|
if (day is Map<String, dynamic>) UsageActivityDay.fromJson(day),
|
||||||
|
],
|
||||||
|
models: [
|
||||||
|
for (final model in (j['models'] as List?) ?? const [])
|
||||||
|
if (model is Map<String, dynamic>) UsageModelStat.fromJson(model),
|
||||||
|
],
|
||||||
|
tools: UsageTools.fromJson(j['tools'] as Map<String, dynamic>?),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One column of the activity chart: a day, or a week once the range is too
|
||||||
|
/// long for daily bars.
|
||||||
|
class UsageBar {
|
||||||
|
final String start;
|
||||||
|
final String end;
|
||||||
|
final int steps;
|
||||||
|
const UsageBar(this.start, this.end, this.steps);
|
||||||
|
}
|
||||||
|
|
||||||
|
class UsageActivitySeries {
|
||||||
|
final bool weekly;
|
||||||
|
final List<UsageBar> bars;
|
||||||
|
final int max;
|
||||||
|
const UsageActivitySeries(this.weekly, this.bars, this.max);
|
||||||
|
}
|
||||||
|
|
||||||
|
const _maxDailyBars = 92;
|
||||||
|
|
||||||
|
String _dateKey(DateTime date) =>
|
||||||
|
'${date.year}-${date.month.toString().padLeft(2, '0')}-'
|
||||||
|
'${date.day.toString().padLeft(2, '0')}';
|
||||||
|
|
||||||
|
/// Fills the inactive days with zero so the chart shows the whole range, and
|
||||||
|
/// groups into weeks past 92 days so the bars stay readable.
|
||||||
|
UsageActivitySeries buildUsageActivity(UsageStats stats) {
|
||||||
|
if (stats.from <= 0 || stats.to <= 0) {
|
||||||
|
return const UsageActivitySeries(false, [], 0);
|
||||||
|
}
|
||||||
|
final stepsByDay = {
|
||||||
|
for (final day in stats.activity) day.date: day.steps,
|
||||||
|
};
|
||||||
|
final first = DateTime.fromMillisecondsSinceEpoch(stats.from);
|
||||||
|
final last = DateTime.fromMillisecondsSinceEpoch(stats.to - 1);
|
||||||
|
final lastKey = _dateKey(last);
|
||||||
|
final days = <UsageBar>[];
|
||||||
|
var cursor = DateTime(first.year, first.month, first.day);
|
||||||
|
while (true) {
|
||||||
|
final key = _dateKey(cursor);
|
||||||
|
days.add(UsageBar(key, key, stepsByDay[key] ?? 0));
|
||||||
|
if (key == lastKey) break;
|
||||||
|
cursor = DateTime(cursor.year, cursor.month, cursor.day + 1);
|
||||||
|
// A bogus timestamp must not spin forever.
|
||||||
|
if (days.length > 4000) break;
|
||||||
|
}
|
||||||
|
if (days.length <= _maxDailyBars) {
|
||||||
|
return UsageActivitySeries(
|
||||||
|
false, days, days.fold(0, (peak, day) => day.steps > peak ? day.steps : peak));
|
||||||
|
}
|
||||||
|
final weeks = <UsageBar>[];
|
||||||
|
for (var i = 0; i < days.length; i += 7) {
|
||||||
|
final chunk = days.sublist(i, (i + 7).clamp(0, days.length));
|
||||||
|
weeks.add(UsageBar(
|
||||||
|
chunk.first.start,
|
||||||
|
chunk.last.end,
|
||||||
|
chunk.fold(0, (sum, day) => sum + day.steps),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return UsageActivitySeries(
|
||||||
|
true, weeks, weeks.fold(0, (peak, week) => week.steps > peak ? week.steps : peak));
|
||||||
|
}
|
||||||
|
|
||||||
|
double? usageCacheHitRate(UsageTokens tokens) {
|
||||||
|
final misses = tokens.input + tokens.cacheWrite + tokens.cacheRead;
|
||||||
|
return misses > 0 ? tokens.cacheRead / misses : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
double? usageReasoningShare(UsageTokens tokens) {
|
||||||
|
final produced = tokens.produced;
|
||||||
|
return produced > 0 ? tokens.reasoning / produced : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
double? _average(int total, int count) => count > 0 ? total / count : null;
|
||||||
|
|
||||||
|
double? usageTokensPerSession(UsageStats stats) =>
|
||||||
|
_average(stats.tokens.total, stats.sessions);
|
||||||
|
|
||||||
|
double? usageStepsPerSession(UsageStats stats) =>
|
||||||
|
_average(stats.steps, stats.sessions);
|
||||||
|
|
||||||
|
double? usageCostPerSession(UsageStats stats) =>
|
||||||
|
stats.sessions > 0 ? stats.cost / stats.sessions : null;
|
||||||
|
|
||||||
|
double? usageCostPerMillionTokens(UsageStats stats) =>
|
||||||
|
stats.tokens.total > 0
|
||||||
|
? stats.cost / stats.tokens.total * 1000000
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const _monthNames = [
|
||||||
|
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||||
|
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
||||||
|
];
|
||||||
|
|
||||||
|
/// `Nov 5` for the chart's ends and `11月5日` in Chinese. Kept here so every
|
||||||
|
/// caller reads a day the same way.
|
||||||
|
String usageDayLabel(String day) {
|
||||||
|
final parts = day.split('-');
|
||||||
|
if (parts.length != 3) return day;
|
||||||
|
final month = int.tryParse(parts[1]);
|
||||||
|
final date = int.tryParse(parts[2]);
|
||||||
|
if (month == null || date == null) return day;
|
||||||
|
if (L10n.instance.isEnglish) return '${_monthNames[month - 1]} $date';
|
||||||
|
return '$month月$date日';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1.2K / 3.4M, as the web client compacts totals.
|
||||||
|
String usageCompactNumber(num value) {
|
||||||
|
if (value < 1000) return value.toStringAsFixed(0);
|
||||||
|
final (unit, suffix) = value < 1000000
|
||||||
|
? (1000.0, 'K')
|
||||||
|
: value < 1000000000
|
||||||
|
? (1000000.0, 'M')
|
||||||
|
: (1000000000.0, 'B');
|
||||||
|
final scaled = value / unit;
|
||||||
|
final text = scaled.toStringAsFixed(scaled >= 100 ? 0 : 1);
|
||||||
|
return '${text.endsWith('.0') ? text.substring(0, text.length - 2) : text}$suffix';
|
||||||
|
}
|
||||||
|
|
||||||
|
String usagePercent(double value) => '${(value * 100).toStringAsFixed(1)}%';
|
||||||
|
|
||||||
|
String usageCost(double value) => '\$${value.toStringAsFixed(2)}';
|
||||||
|
|
||||||
|
String usageDuration(double ms) {
|
||||||
|
if (ms < 1000) return '${ms.round()} ms';
|
||||||
|
final seconds = ms / 1000;
|
||||||
|
if (seconds < 60) return '${seconds.toStringAsFixed(1)} s';
|
||||||
|
final whole = seconds.floor();
|
||||||
|
return '${whole ~/ 60} min ${(whole % 60)} s';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The local calendar key the report's activity days use.
|
||||||
|
String usageDateKey(DateTime date) => _dateKey(date);
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// Appearance preferences: theme mode and seed colour. Device-local — the
|
||||||
|
// phone draws its own Material theme, so none of this is sent to the server.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
class AppearancePrefs extends ChangeNotifier {
|
||||||
|
AppearancePrefs._();
|
||||||
|
static final AppearancePrefs instance = AppearancePrefs._();
|
||||||
|
|
||||||
|
static const _modeKey = 'appearance.themeMode.v1';
|
||||||
|
static const _seedKey = 'appearance.seedColor.v1';
|
||||||
|
|
||||||
|
/// The first-party client's colour; a fresh install starts here.
|
||||||
|
static const defaultSeed = 0xFF6C5CE7;
|
||||||
|
|
||||||
|
ThemeMode _themeMode = ThemeMode.system;
|
||||||
|
int _seed = defaultSeed;
|
||||||
|
bool _loaded = false;
|
||||||
|
|
||||||
|
ThemeMode get themeMode => _themeMode;
|
||||||
|
Color get seedColor => Color(_seed);
|
||||||
|
|
||||||
|
Future<void> ensureLoaded() async {
|
||||||
|
if (_loaded) return;
|
||||||
|
_loaded = true;
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
_themeMode = switch (prefs.getString(_modeKey)) {
|
||||||
|
'light' => ThemeMode.light,
|
||||||
|
'dark' => ThemeMode.dark,
|
||||||
|
_ => ThemeMode.system,
|
||||||
|
};
|
||||||
|
_seed = prefs.getInt(_seedKey) ?? defaultSeed;
|
||||||
|
notifyListeners();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setThemeMode(ThemeMode mode) async {
|
||||||
|
if (mode == _themeMode) return;
|
||||||
|
_themeMode = mode;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString(_modeKey, mode.name);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setSeedColor(int value) async {
|
||||||
|
if (value == _seed) return;
|
||||||
|
_seed = value;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setInt(_seedKey, value);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The colours the appearance section offers; the first is the default.
|
||||||
|
const appearanceSeeds = <int>[
|
||||||
|
0xFF6C5CE7,
|
||||||
|
0xFF2F80ED,
|
||||||
|
0xFF00A884,
|
||||||
|
0xFF0FA3B1,
|
||||||
|
0xFFF2994A,
|
||||||
|
0xFFEB5757,
|
||||||
|
0xFFE84393,
|
||||||
|
0xFF6B7280,
|
||||||
|
];
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// Who is running in the background. opencode records detached commands as
|
||||||
|
// "shell" jobs (`GET /api/experimental/job`), session-scoped and covering
|
||||||
|
// subagents, so the list is right without reading the transcript. An older
|
||||||
|
// server without that endpoint falls back to the shell list, where only the
|
||||||
|
// transcript can say which commands were detached.
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import 'api/client.dart';
|
||||||
|
import 'api/shells.dart';
|
||||||
|
|
||||||
|
/// The background commands of the open session, refreshed while the chat is
|
||||||
|
/// on screen.
|
||||||
|
class ShellTasks extends ChangeNotifier {
|
||||||
|
ShellTasks(this.client, {required this.sessionId});
|
||||||
|
|
||||||
|
final Client client;
|
||||||
|
final String sessionId;
|
||||||
|
|
||||||
|
List<ShellTask> _tasks = const [];
|
||||||
|
List<ShellTask> get tasks => _tasks;
|
||||||
|
|
||||||
|
/// The shell list stopped answering (an opencode without the shell API):
|
||||||
|
/// polling stops so a chat does not keep asking.
|
||||||
|
bool available = true;
|
||||||
|
|
||||||
|
/// The job endpoint answered 404 once: this server only has `GET /api/shell`.
|
||||||
|
bool _jobs = true;
|
||||||
|
|
||||||
|
/// Fallback only: the detached calls the transcript knows about, with the
|
||||||
|
/// start time of the message that ran them.
|
||||||
|
final Map<String, ShellTask> _seeded = {};
|
||||||
|
|
||||||
|
/// Every task ever seen, for a tool row that wants its output after the
|
||||||
|
/// command has left the strip.
|
||||||
|
final Map<String, ShellTask> _known = {};
|
||||||
|
|
||||||
|
String _directory = '';
|
||||||
|
List<String> _sessionIds = const [];
|
||||||
|
Timer? _poll;
|
||||||
|
bool _busy = false;
|
||||||
|
bool _disposed = false;
|
||||||
|
|
||||||
|
/// The transcript's detached calls (fallback path). Called on every chat
|
||||||
|
/// change; cheap.
|
||||||
|
void seed(Iterable<ShellTask> tasks) {
|
||||||
|
var changed = false;
|
||||||
|
final ids = <String>{};
|
||||||
|
for (final task in tasks) {
|
||||||
|
if (!ids.add(task.id)) continue;
|
||||||
|
final old = _seeded[task.id];
|
||||||
|
if (old == null ||
|
||||||
|
old.command != task.command ||
|
||||||
|
old.startedAt != task.startedAt) {
|
||||||
|
_seeded[task.id] = task;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
_known[task.id] ??= task;
|
||||||
|
}
|
||||||
|
for (final id in _seeded.keys.toList()) {
|
||||||
|
if (!ids.contains(id)) {
|
||||||
|
_seeded.remove(id);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
_prune();
|
||||||
|
if (_poll != null) unawaited(refresh());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts (or re-arms) the refresh for [directory]. The job list does not
|
||||||
|
/// need it; the fallback shell list does.
|
||||||
|
void watch({required String directory, required Set<String> sessionIds}) {
|
||||||
|
final ids = sessionIds.toList()..sort();
|
||||||
|
if (_poll != null && directory == _directory && _same(ids, _sessionIds)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_directory = directory;
|
||||||
|
_sessionIds = ids;
|
||||||
|
_poll?.cancel();
|
||||||
|
_poll = Timer.periodic(const Duration(seconds: 3), (_) => refresh());
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-reads what is running now (after a stop, or when a tool transition
|
||||||
|
/// arrives).
|
||||||
|
Future<void> refresh() async {
|
||||||
|
if (_disposed || _busy) return;
|
||||||
|
_busy = true;
|
||||||
|
try {
|
||||||
|
if (available && _jobs) {
|
||||||
|
try {
|
||||||
|
final jobs = await client.listShellJobs(sessionId);
|
||||||
|
if (_disposed) return;
|
||||||
|
_set(jobs);
|
||||||
|
return;
|
||||||
|
} on ApiError catch (e) {
|
||||||
|
if (e.status != 404) rethrow;
|
||||||
|
_jobs = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (available) await _refreshShellList();
|
||||||
|
} on ApiError catch (e) {
|
||||||
|
if (e.status == 404) {
|
||||||
|
available = false;
|
||||||
|
_poll?.cancel();
|
||||||
|
_poll = null;
|
||||||
|
}
|
||||||
|
// A network hiccup keeps the last known tasks on screen.
|
||||||
|
} catch (_) {
|
||||||
|
// Same: the next tick tries again.
|
||||||
|
} finally {
|
||||||
|
_busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fallback: all running shells of the directory, narrowed to the
|
||||||
|
/// commands the transcript detached.
|
||||||
|
Future<void> _refreshShellList() async {
|
||||||
|
if (_seeded.isEmpty) {
|
||||||
|
_set(const []);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final listed = await client.listShells(directory: _directory);
|
||||||
|
if (_disposed) return;
|
||||||
|
final byId = {for (final shell in listed) shell.id: shell};
|
||||||
|
final next = <ShellTask>[];
|
||||||
|
for (final task in _seeded.values) {
|
||||||
|
final live = byId[task.id];
|
||||||
|
if (live == null || !live.running) continue;
|
||||||
|
next.add(task.copyWith(
|
||||||
|
command: live.command.isEmpty ? null : live.command,
|
||||||
|
startedAt: live.startedAt > 0 ? live.startedAt : null,
|
||||||
|
sessionId: live.sessionId.isEmpty ? null : live.sessionId,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
_set(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stops [task], then tells the model why its completion notice will look
|
||||||
|
/// like a failure, as the first-party client does.
|
||||||
|
Future<void> stop(ShellTask task, String directory) async {
|
||||||
|
await client.stopShell(task.id, directory: directory);
|
||||||
|
_seeded.remove(task.id);
|
||||||
|
_known.remove(task.id);
|
||||||
|
_set(_tasks.where((t) => t.id != task.id).toList());
|
||||||
|
// The notice goes to the session that started the command.
|
||||||
|
try {
|
||||||
|
await client.syntheticNote(
|
||||||
|
task.sessionId.isEmpty ? sessionId : task.sessionId,
|
||||||
|
text: stopNote(task.command),
|
||||||
|
description: 'Background command stopped by the user',
|
||||||
|
metadata: {
|
||||||
|
'openchamber': {
|
||||||
|
'shellStop': {
|
||||||
|
'shellIDs': [task.id],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
directory: directory,
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
// The command is stopped either way; the notice is a courtesy.
|
||||||
|
}
|
||||||
|
unawaited(refresh());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The task with this shell id, for a tool row opening its output.
|
||||||
|
ShellTask? task(String id) => _known[id];
|
||||||
|
|
||||||
|
void _prune() {
|
||||||
|
_set([
|
||||||
|
for (final task in _tasks)
|
||||||
|
if (_seeded.containsKey(task.id)) task,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _set(List<ShellTask> next) {
|
||||||
|
_tasks = List.unmodifiable(next);
|
||||||
|
for (final task in next) {
|
||||||
|
_known[task.id] = task;
|
||||||
|
}
|
||||||
|
if (!_disposed) notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool _same(List<String> a, List<String> b) {
|
||||||
|
if (a.length != b.length) return false;
|
||||||
|
for (var i = 0; i < a.length; i++) {
|
||||||
|
if (a[i] != b[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
|
_poll?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the model is told when a command is stopped from the app. Without it
|
||||||
|
/// the completion notice reads as a failure and the model may run it again.
|
||||||
|
String stopNote(String command) {
|
||||||
|
final shown = command.replaceAll(RegExp(r'\s+'), ' ').trim();
|
||||||
|
return 'The user stopped the background command `$shown`. '
|
||||||
|
'The completion notice that follows reports an error such as '
|
||||||
|
'Shell.NotFoundError or says that nothing ran; that is the stop, not a '
|
||||||
|
'failure of the command. Do not start it again just because of that '
|
||||||
|
'notice.';
|
||||||
|
}
|
||||||
+178
@@ -0,0 +1,178 @@
|
|||||||
|
// The app speaks English and Chinese. Code writes English; Chinese comes from
|
||||||
|
// the table in l10n/zh.dart through tr()/trArgs(), and AppText for the many
|
||||||
|
// Text leaves. 设置 → 常规 → 语言 chooses between the system language, Chinese
|
||||||
|
// and English; a language we have no table for reads English, and a missing
|
||||||
|
// entry falls back to the English source, so text never disappears.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:ui' show PlatformDispatcher;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import 'l10n/zh.dart';
|
||||||
|
|
||||||
|
enum AppLanguage { system, zh, en }
|
||||||
|
|
||||||
|
/// The language the UI is drawn in, and the lookup behind [tr] and [AppText].
|
||||||
|
class L10n extends ChangeNotifier {
|
||||||
|
L10n._();
|
||||||
|
static final L10n instance = L10n._();
|
||||||
|
|
||||||
|
/// Chinese until [ensureLoaded] has read the stored choice: tests and the
|
||||||
|
/// first frame before the app starts never see a half-changed language.
|
||||||
|
AppLanguage _choice = AppLanguage.zh;
|
||||||
|
|
||||||
|
AppLanguage get choice => _choice;
|
||||||
|
|
||||||
|
/// Reads the saved choice. No saved choice means follow the system, which
|
||||||
|
/// is what a fresh install does.
|
||||||
|
Future<void> ensureLoaded() async {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
_choice = switch (prefs.getString('language')) {
|
||||||
|
'zh' => AppLanguage.zh,
|
||||||
|
'en' => AppLanguage.en,
|
||||||
|
_ => AppLanguage.system,
|
||||||
|
};
|
||||||
|
} catch (_) {
|
||||||
|
_choice = AppLanguage.system;
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setLanguage(AppLanguage choice) async {
|
||||||
|
apply(choice);
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
if (choice == AppLanguage.system) {
|
||||||
|
await prefs.remove('language');
|
||||||
|
} else {
|
||||||
|
await prefs.setString('language', choice.name);
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// The choice still holds for this run.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes the language without touching the stored choice (tests, and the
|
||||||
|
/// first resolve before prefs are read).
|
||||||
|
void apply(AppLanguage choice) {
|
||||||
|
if (_choice == choice) return;
|
||||||
|
_choice = choice;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Locale get locale => switch (_choice) {
|
||||||
|
AppLanguage.zh => const Locale('zh', 'CN'),
|
||||||
|
AppLanguage.en => const Locale('en'),
|
||||||
|
// Only Chinese is translated; every other system language reads
|
||||||
|
// English.
|
||||||
|
AppLanguage.system =>
|
||||||
|
_systemIsChinese ? const Locale('zh', 'CN') : const Locale('en'),
|
||||||
|
};
|
||||||
|
|
||||||
|
bool get _systemIsChinese {
|
||||||
|
try {
|
||||||
|
return PlatformDispatcher.instance.locale.languageCode == 'zh';
|
||||||
|
} catch (_) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isEnglish => locale.languageCode == 'en';
|
||||||
|
|
||||||
|
/// What a language choice reads as: a language names itself.
|
||||||
|
String languageLabel(AppLanguage choice) => switch (choice) {
|
||||||
|
AppLanguage.system => tr('System'),
|
||||||
|
AppLanguage.zh => '中文',
|
||||||
|
AppLanguage.en => 'English',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The Chinese text for [en], or [en] when there is none.
|
||||||
|
String tr(String en) => isEnglish ? en : (chineseStrings[en] ?? en);
|
||||||
|
|
||||||
|
/// Same, for text built from parts: `trArgs('{0} subagents', [n])`. The
|
||||||
|
/// English template is filled as written; Chinese entries use the same
|
||||||
|
/// `{0}`, `{1}` placeholders.
|
||||||
|
String trArgs(String template, [List<Object?> args = const []]) {
|
||||||
|
var out = isEnglish ? template : (chineseStrings[template] ?? template);
|
||||||
|
for (var i = 0; i < args.length; i++) {
|
||||||
|
out = out.replaceAll('{$i}', '${args[i] ?? ''}');
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A system language change reaches the app while it runs; the choice
|
||||||
|
/// "follow the system" then has to redraw.
|
||||||
|
void systemLocaleChanged() {
|
||||||
|
if (_choice == AppLanguage.system) notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String tr(String en) => L10n.instance.tr(en);
|
||||||
|
|
||||||
|
String trArgs(String template, [List<Object?> args = const []]) =>
|
||||||
|
L10n.instance.trArgs(template, args);
|
||||||
|
|
||||||
|
/// [Text] that goes through the same lookup. It is const-constructible, so a
|
||||||
|
/// tree does not have to give up `const` to be translated. Content that comes
|
||||||
|
/// from the server (message text, titles) is drawn with plain [Text]: only
|
||||||
|
/// our own source strings are keys.
|
||||||
|
class AppText extends StatelessWidget {
|
||||||
|
final String data;
|
||||||
|
final TextStyle? style;
|
||||||
|
final StrutStyle? strutStyle;
|
||||||
|
final TextAlign? textAlign;
|
||||||
|
final TextDirection? textDirection;
|
||||||
|
final Locale? locale;
|
||||||
|
final bool? softWrap;
|
||||||
|
final TextOverflow? overflow;
|
||||||
|
final TextScaler? textScaler;
|
||||||
|
final int? maxLines;
|
||||||
|
final String? semanticsLabel;
|
||||||
|
final TextWidthBasis? textWidthBasis;
|
||||||
|
final TextHeightBehavior? textHeightBehavior;
|
||||||
|
final Color? selectionColor;
|
||||||
|
|
||||||
|
const AppText(
|
||||||
|
this.data, {
|
||||||
|
super.key,
|
||||||
|
this.style,
|
||||||
|
this.strutStyle,
|
||||||
|
this.textAlign,
|
||||||
|
this.textDirection,
|
||||||
|
this.locale,
|
||||||
|
this.softWrap,
|
||||||
|
this.overflow,
|
||||||
|
this.textScaler,
|
||||||
|
this.maxLines,
|
||||||
|
this.semanticsLabel,
|
||||||
|
this.textWidthBasis,
|
||||||
|
this.textHeightBehavior,
|
||||||
|
this.selectionColor,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
// Reading the resolved locale makes this widget depend on it: when the
|
||||||
|
// language changes, every AppText — including a const one whose widget
|
||||||
|
// instance the parent build reuses — is rebuilt in the new language.
|
||||||
|
final resolved = locale ?? Localizations.localeOf(context);
|
||||||
|
return Text(
|
||||||
|
tr(data),
|
||||||
|
style: style,
|
||||||
|
strutStyle: strutStyle,
|
||||||
|
textAlign: textAlign,
|
||||||
|
textDirection: textDirection,
|
||||||
|
locale: resolved,
|
||||||
|
softWrap: softWrap,
|
||||||
|
overflow: overflow,
|
||||||
|
textScaler: textScaler,
|
||||||
|
maxLines: maxLines,
|
||||||
|
semanticsLabel: semanticsLabel,
|
||||||
|
textWidthBasis: textWidthBasis,
|
||||||
|
textHeightBehavior: textHeightBehavior,
|
||||||
|
selectionColor: selectionColor,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,654 @@
|
|||||||
|
// Chinese text for every string the code writes in English. Keys are the
|
||||||
|
// English source, including {0}, {1} placeholders; a missing key falls back
|
||||||
|
// to the English itself, so an unsupported language simply reads English.
|
||||||
|
const Map<String, String> chineseStrings = {
|
||||||
|
'(No summary)': '(摘要为空)',
|
||||||
|
'(Untitled session)': '(无标题会话)',
|
||||||
|
', ': '、',
|
||||||
|
'1st of each month': '每月 1 日',
|
||||||
|
'A step failed · {0} tool calls': '有步骤失败 · {0} 次工具调用',
|
||||||
|
'About': '关于',
|
||||||
|
'Accent color': '主题色',
|
||||||
|
'Accent color {0}': '主题色 {0}',
|
||||||
|
'Add attachment': '添加附件',
|
||||||
|
'Add project': '添加项目',
|
||||||
|
'Add server': '添加服务器',
|
||||||
|
'Add this folder': '添加此文件夹',
|
||||||
|
'Add time': '添加时间',
|
||||||
|
'Agent': '智能体',
|
||||||
|
'Agent tools': '通用',
|
||||||
|
'Agent tools and memory': '智能体工具与记忆',
|
||||||
|
'All features': '全部功能',
|
||||||
|
'Allow once': '允许一次',
|
||||||
|
'Always allow': '总是允许',
|
||||||
|
'Animation {0} has no sprite sheet': '动画 {0} 没有精灵图',
|
||||||
|
'App': '应用',
|
||||||
|
'Appearance': '外观',
|
||||||
|
'Applies to this device only; not synced to the server': '仅当前设备生效,不同步到服务器',
|
||||||
|
'Archive': '归档',
|
||||||
|
'Attachment': '附件',
|
||||||
|
'Attachments cannot be larger than 10 MB': '附件不能超过 10MB',
|
||||||
|
'Back': '返回',
|
||||||
|
'Back to parent session': '返回父会话',
|
||||||
|
'Background': '后台',
|
||||||
|
'Background output': '后台输出',
|
||||||
|
'Build directly': '直接构建',
|
||||||
|
'Camera permission is required to scan. Allow OpenChamber to use the camera in system settings.': '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。',
|
||||||
|
'Attachments': '附件',
|
||||||
|
'Cancel': '取消',
|
||||||
|
'Canceling…': '正在取消…',
|
||||||
|
'Cancelled': '已取消',
|
||||||
|
'Cannot display image': '图片无法显示',
|
||||||
|
'Cannot open the subagent session': '无法打开子代理会话',
|
||||||
|
'Cannot preview: {0}': '无法预览:{0}',
|
||||||
|
'Cannot send prompts to a subagent session.': '无法向子智能体会话发送提示。',
|
||||||
|
'Change pet pack': '更换宠物包',
|
||||||
|
'Charts and prototypes': '图表和原型',
|
||||||
|
'Chat': '聊天',
|
||||||
|
'Chinese': '中文',
|
||||||
|
'Choose a session': '选择一个会话',
|
||||||
|
'Choose one': '请选择',
|
||||||
|
'Choose project': '选择项目',
|
||||||
|
'Clear screen': '清屏',
|
||||||
|
'Close': '关闭',
|
||||||
|
'Close sidebar': '关闭侧栏',
|
||||||
|
'Close this terminal': '关闭此终端',
|
||||||
|
'Collapse subagents': '收起子代理',
|
||||||
|
'Compact': '压缩',
|
||||||
|
'Compacting conversation': '正在压缩对话',
|
||||||
|
'Compaction failed: {0}': '压缩失败:{0}',
|
||||||
|
'Connect': '连接',
|
||||||
|
'Connect through Relay': '通过 Relay 连接',
|
||||||
|
'Connect to your OpenChamber server': '连接你的 OpenChamber 服务器',
|
||||||
|
'Connect to {0}': '连接 {0}',
|
||||||
|
'Connected': '已连接',
|
||||||
|
'Connecting…': '正在连接…',
|
||||||
|
'Connection closed: check whether the proxy works': '连接被断开:检查代理是否可用',
|
||||||
|
'Connection failed': '连接失败',
|
||||||
|
'Connection lost, reconnecting…': '连接中断,正在重连…',
|
||||||
|
'Connection refused: server or proxy not running, or wrong port': '连接被拒绝:服务器或代理未启动,或端口不对',
|
||||||
|
'Connection timed out: check the server and proxy address': '连接超时:检查服务器与代理地址',
|
||||||
|
'Content': '内容',
|
||||||
|
'Context limit': '上下文上限',
|
||||||
|
'Context usage': '上下文占用',
|
||||||
|
'Conversation compacted': '对话已压缩',
|
||||||
|
'Copied': '已复制',
|
||||||
|
'Copy': '复制',
|
||||||
|
'Copy answer': '复制回答',
|
||||||
|
'Copy message': '复制消息',
|
||||||
|
'Copy session ID': '复制会话 ID',
|
||||||
|
'Could not add the project: {0}': '无法添加项目:{0}',
|
||||||
|
'Could not attach: {0}': '选择失败:{0}',
|
||||||
|
'Could not connect to the relay: {0}': '无法连接 Relay:{0}',
|
||||||
|
'Could not create the chat directory: {0}': '无法创建聊天目录:{0}',
|
||||||
|
'Could not create the folder: {0}': '无法创建文件夹:{0}',
|
||||||
|
'Could not decode the QR code; try again': '二维码解码出错,请重试',
|
||||||
|
'Could not get a WebSocket token ({0})': '无法获取 WebSocket 令牌({0})',
|
||||||
|
'Could not load image: {0}': '图片加载失败:{0}',
|
||||||
|
'Could not load this folder: {0}': '无法加载此文件夹:{0}',
|
||||||
|
'Could not load, refresh to retry': '读取失败,请刷新',
|
||||||
|
'Could not open the camera: {0}': '无法打开相机:{0}',
|
||||||
|
'Could not open the subagent session: {0}': '无法打开子代理会话:{0}',
|
||||||
|
'Could not read output: {0}': '读取输出失败:{0}',
|
||||||
|
'Could not resolve address: check the server or proxy hostname': '无法解析地址:检查服务器或代理主机名',
|
||||||
|
'Could not resolve the proxy host': '无法解析代理主机',
|
||||||
|
'Could not stop: {0}': '停止失败:{0}',
|
||||||
|
'Couldn\'t delete task': '删除任务失败',
|
||||||
|
'Couldn\'t load scheduled tasks: {0}': '加载计划任务失败:{0}',
|
||||||
|
'Couldn\'t run task': '运行任务失败',
|
||||||
|
'Couldn\'t run task: {0}': '运行任务失败:{0}',
|
||||||
|
'Couldn\'t save': '保存失败',
|
||||||
|
'Couldn\'t save task': '保存任务失败',
|
||||||
|
'Couldn\'t save task: {0}': '保存任务失败:{0}',
|
||||||
|
'Couldn\'t save: {0}': '保存失败:{0}',
|
||||||
|
'Couldn\'t update task': '更新任务失败',
|
||||||
|
'Create': '创建',
|
||||||
|
'Creating…': '正在创建…',
|
||||||
|
'Cron expression': 'Cron 表达式',
|
||||||
|
'Cron expression is required': 'Cron 表达式为必填项',
|
||||||
|
'Cron: {0}': 'Cron:{0}',
|
||||||
|
'Current: {0}': '当前:{0}',
|
||||||
|
'Daily': '每天',
|
||||||
|
'Daily at 9': '每天 9 点',
|
||||||
|
'Daily sync': '每日同步',
|
||||||
|
'Daily {0}': '每天 {0}',
|
||||||
|
'Dark': '深色',
|
||||||
|
'Date': '日期',
|
||||||
|
'Decryption failed: {0}': '解密失败:{0}',
|
||||||
|
'Default': '默认',
|
||||||
|
'Default agent': '默认智能体',
|
||||||
|
'Default model': '默认模型',
|
||||||
|
'Delete': '删除',
|
||||||
|
'Delete scheduled task?': '删除计划任务?',
|
||||||
|
'Delete server?': '删除服务器?',
|
||||||
|
'Delete session?': '删除会话?',
|
||||||
|
'Delivery': '发送方式',
|
||||||
|
'Deny': '拒绝',
|
||||||
|
'Direct address or OpenChamber Relay': '直连地址或 OpenChamber Relay',
|
||||||
|
'Directory is empty': '目录为空',
|
||||||
|
'Discard draft': '丢弃草稿',
|
||||||
|
'Disconnect': '断开当前连接',
|
||||||
|
'Done': '完成',
|
||||||
|
'Done · {0} tool calls': '已完成 · {0} 次工具调用',
|
||||||
|
'Download': '下载',
|
||||||
|
'Download cancelled': '下载已取消',
|
||||||
|
'Downloaded {0}': '已下载 {0}',
|
||||||
|
'Downloading': '正在下载',
|
||||||
|
'Draft': '草稿',
|
||||||
|
'Draft · {0}': '草稿 · {0}',
|
||||||
|
'e.g. docs': '例如 docs',
|
||||||
|
'e.g. My computer': '如 我的电脑',
|
||||||
|
'e.g. notes.md': '例如 notes.md',
|
||||||
|
'Earlier': '更早',
|
||||||
|
'Earlier this week': '本周早些时候',
|
||||||
|
'Edit': '编辑',
|
||||||
|
'Edit memory': '编辑记忆',
|
||||||
|
'Edit note': '编辑笔记',
|
||||||
|
'Edit scheduled task': '编辑计划任务',
|
||||||
|
'Enable pet': '启用宠物',
|
||||||
|
'Enabled': '已启用',
|
||||||
|
'Enter a valid folder name': '请输入有效的文件夹名称',
|
||||||
|
'End-to-end encrypted; the server and device token stay the same': '端到端加密;服务器与设备令牌保持不变',
|
||||||
|
'Ended': '已结束',
|
||||||
|
'Error': '错误',
|
||||||
|
'Every 5 minutes': '每 5 分钟',
|
||||||
|
'Every hour': '每小时',
|
||||||
|
'Exit code {0}': '退出码 {0}',
|
||||||
|
'Exited': '已退出',
|
||||||
|
'Expand subagents': '展开子代理',
|
||||||
|
'Extra high': '极高',
|
||||||
|
'Extracted size exceeds 60 MB': '解压后超过 60MB',
|
||||||
|
'Fact': '事实',
|
||||||
|
'Favorites': '收藏',
|
||||||
|
'Feedback': '反馈',
|
||||||
|
'Fetch': '抓取',
|
||||||
|
'Fetch the server version again': '重新获取服务端版本',
|
||||||
|
'File is empty': '文件为空',
|
||||||
|
'File is large ({0}), download it to view': '文件较大({0}),请下载后查看',
|
||||||
|
'File {0}': '文件 {0}',
|
||||||
|
'Files': '文件',
|
||||||
|
'Flashlight': '手电筒',
|
||||||
|
'Folder name': '文件夹名称',
|
||||||
|
'Folder path': '文件夹路径',
|
||||||
|
'Follow system': '跟随系统',
|
||||||
|
'Follow the system, Chinese or English': '跟随系统、中文或 English',
|
||||||
|
'Follow-up behavior': '追问处理行为',
|
||||||
|
'Fork from here': '从这里分叉',
|
||||||
|
'Fri': '周五',
|
||||||
|
'General': '常规',
|
||||||
|
'Generate image': '生成图片',
|
||||||
|
'Generating summary…': '正在生成摘要…',
|
||||||
|
'Generating; you can still type…': '生成中,仍可输入…',
|
||||||
|
'Global memory': '全局记忆',
|
||||||
|
'Go': '前往',
|
||||||
|
'Goal': '目标',
|
||||||
|
'Got it': '知道了',
|
||||||
|
'Help & about': '帮助与关于',
|
||||||
|
'Hide archived': '隐藏已归档',
|
||||||
|
'Hide details': '收起详情',
|
||||||
|
'Hide summary': '隐藏摘要',
|
||||||
|
'High': '高',
|
||||||
|
'http://… or socks5://…': 'http://… 或 socks5://…',
|
||||||
|
'Idle': '空闲',
|
||||||
|
'Image': '图片',
|
||||||
|
'Image model': '图像模型',
|
||||||
|
'Images': '图像',
|
||||||
|
'Import a pet pack (.zip) and it will stand above the input box.': '导入一个宠物包(.zip)后,它会站在输入框上方。',
|
||||||
|
'Import failed: {0}': '导入失败:{0}',
|
||||||
|
'Import pet pack': '导入宠物包',
|
||||||
|
'Import, enable and size': '导入、启用与大小',
|
||||||
|
'Imported {0}': '已导入 {0}',
|
||||||
|
'In chat': '在聊天中',
|
||||||
|
'In less than a minute': '不到 1 分钟后',
|
||||||
|
'In the OpenChamber web app, open “Connect a device” and choose the QR code': '在 OpenChamber 网页端打开「连接设备」,选择二维码',
|
||||||
|
'In the OpenChamber web app, open “Connect a device”, then paste the link or scan the QR code. The link carries a one-time key and either a direct address or a private Relay.': '在 OpenChamber 网页端打开「连接设备」,粘贴链接或直接扫描二维码。链接里带一次性密钥,以及直连地址或私有 Relay。',
|
||||||
|
'In {0}': '{0}后',
|
||||||
|
'In {0} min': '{0} 分钟后',
|
||||||
|
'Init': '初始化',
|
||||||
|
'Invalid data URL': '无效的 data URL',
|
||||||
|
'Invalid proxy address: {0}': '代理地址无效:{0}',
|
||||||
|
'Invalid response headers': '响应头无效',
|
||||||
|
'Join at the next step; work continues': '在下一步加入,工作继续',
|
||||||
|
'Joining this turn…': '正在转入当前回合…',
|
||||||
|
'Jump to latest': '回到最新',
|
||||||
|
'Just now': '刚刚',
|
||||||
|
'Key exchange failed: {0}': '密钥协商失败:{0}',
|
||||||
|
'Keyboard': '键盘',
|
||||||
|
'Language': '语言',
|
||||||
|
'Large': '大',
|
||||||
|
'Large output, loading…': '输出较大,正在载入…',
|
||||||
|
'Last run {0} · {1}': '上次运行 {0} · {1}',
|
||||||
|
'Let the agent ask you for API keys, tokens or passwords on a private card in chat. Values never enter the conversation.': '允许智能体在聊天中的私密卡片上向你索取 API 密钥、令牌或密码。值不会进入对话。',
|
||||||
|
'Let the agent check each provider\'s limits and reset times.': '让智能体查看各提供商的限额及重置时间。',
|
||||||
|
'Let the agent generate and edit images with the model you choose; the model\'s provider charges for it.': '让智能体用你选择的模型生成和编辑图像,费用由该模型的提供商收取。',
|
||||||
|
'Let the agent read and update the project\'s notes, todos and plans.': '让智能体读取并更新项目的笔记、待办和计划。',
|
||||||
|
'Let the agent show charts, tables, diagrams and UI sketches in chat (isolated from your files) and ask you to pick one of them.': '让智能体在聊天中展示图表、表格、示意图和界面草图(与你的文件隔离),并请你在其中选择一个选项。',
|
||||||
|
'Light': '浅色',
|
||||||
|
'List': '列出',
|
||||||
|
'Loading projects…': '正在加载项目…',
|
||||||
|
'Load earlier messages': '载入更早的消息',
|
||||||
|
'Load more': '载入更多',
|
||||||
|
'Loading models…': '正在载入模型…',
|
||||||
|
'Loading…': '读取中…',
|
||||||
|
'Low': '低',
|
||||||
|
'Medium': '中',
|
||||||
|
'Memory': '记忆',
|
||||||
|
'Memory is not enabled': '记忆功能未启用',
|
||||||
|
'Memory is recorded by the agent during sessions; you can edit or delete it here.': '记忆由 agent 在会话中记录;你可以在这里修改或删除它。',
|
||||||
|
'Minimal': '极低',
|
||||||
|
'Missing sprite sheet {0}': '缺少精灵图 {0}',
|
||||||
|
'Mobile client': '手机客户端',
|
||||||
|
'Mode': '模式',
|
||||||
|
'Model': '模型',
|
||||||
|
'Model for tidying memory': '整理记忆使用的模型',
|
||||||
|
'Mon': '周一',
|
||||||
|
'Mondays at 9': '每周一 9 点',
|
||||||
|
'More': '更多',
|
||||||
|
'Name': '名称',
|
||||||
|
'Names cannot contain slashes': '名称里不能有斜杠',
|
||||||
|
'Network error: {0}': '网络错误:{0}',
|
||||||
|
'Network unreachable': '网络不可达',
|
||||||
|
'Never run': '从未运行',
|
||||||
|
'New': '新建',
|
||||||
|
'New chat': '新建聊天',
|
||||||
|
'New extension': '新建扩展',
|
||||||
|
'New file': '新建文件',
|
||||||
|
'New folder': '新建文件夹',
|
||||||
|
'New note': '新建笔记',
|
||||||
|
'New plan': '新建计划',
|
||||||
|
'New scheduled task': '新建计划任务',
|
||||||
|
'New session': '新会话',
|
||||||
|
'New session in this project': '在此项目新会话',
|
||||||
|
'New task': '新建任务',
|
||||||
|
'New terminal': '新建终端',
|
||||||
|
'New todo': '新建待办',
|
||||||
|
'Next: {0}': '下次:{0}',
|
||||||
|
'No archived sessions': '没有已归档的会话',
|
||||||
|
'No camera available': '没有可用的相机',
|
||||||
|
'No camera frames received; close and try again': '没有收到相机画面,请关闭后重试',
|
||||||
|
'No commands available': '没有可用的指令',
|
||||||
|
'No content': '无内容',
|
||||||
|
'no date': '未选日期',
|
||||||
|
'no days': '未选',
|
||||||
|
'No folders here': '此目录没有子文件夹',
|
||||||
|
'No matching files': '没有匹配的文件',
|
||||||
|
'No matching files in subdirectories': '子目录里没有匹配的文件',
|
||||||
|
'No matching memories': '没有匹配的记忆',
|
||||||
|
'No matching notes': '没有匹配的笔记',
|
||||||
|
'No matching plans': '没有匹配的计划',
|
||||||
|
'No matching sessions': '没有匹配的会话',
|
||||||
|
'No matching todos': '没有匹配的待办',
|
||||||
|
'No memories yet': '还没有记忆',
|
||||||
|
'No notes yet': '还没有笔记',
|
||||||
|
'No output': '无输出',
|
||||||
|
'No pet imported': '尚未导入宠物',
|
||||||
|
'No pet is included; pet packs stay on this device.': '默认不提供宠物;宠物包只存放在本机。',
|
||||||
|
'No plans yet': '还没有计划',
|
||||||
|
'No projects available': '没有可用的项目',
|
||||||
|
'No QR code yet; move closer or fill the frame with the code': '还没识别到二维码,试着靠近一点或让二维码占满取景框',
|
||||||
|
'No results': '没有结果',
|
||||||
|
'No scheduled tasks yet.': '暂无计划任务。',
|
||||||
|
'No sessions': '暂无会话',
|
||||||
|
'No todos yet': '还没有待办',
|
||||||
|
'None': '无',
|
||||||
|
'Not a valid zip file': '不是有效的 zip 文件',
|
||||||
|
'Not available': '未获取到',
|
||||||
|
'Not connected': '未连接',
|
||||||
|
'Not connected to a server': '未连接服务器',
|
||||||
|
'Not selected': '未选择',
|
||||||
|
'Not sent': '未发送',
|
||||||
|
'Not started': '未启动',
|
||||||
|
'Not tied to a project, saved in OpenChamber\'s chat directory': '不关联项目,保存在 OpenChamber 的聊天目录',
|
||||||
|
'Notes': '笔记',
|
||||||
|
'Nothing to copy': '没有可复制的文字',
|
||||||
|
'Notifications': '通知',
|
||||||
|
'Once': '一次性',
|
||||||
|
'Once a day, when no session is running, the agent tidies memory in the background: merging duplicates and removing entries that are obsolete or already in the project docs.': '每天一次,在没有会话运行时,智能体会在后台整理记忆:合并重复条目,删除已过时或项目文档中已有的内容。',
|
||||||
|
'Once {0} {1}': '一次性 {0} {1}',
|
||||||
|
'Open the session list': '打开会话列表',
|
||||||
|
'Open-source licenses': '开源许可',
|
||||||
|
'OpenCode could not send the message: {0}': 'OpenCode 发送消息失败:{0}',
|
||||||
|
'OpenCode could not send the message; retrying: {0}': 'OpenCode 发送消息失败,正在重试:{0}',
|
||||||
|
'Other': '其它',
|
||||||
|
'Other…': '其他…',
|
||||||
|
'Output copied': '已复制输出',
|
||||||
|
'pack.json is missing animations or states': 'pack.json 缺少动画或状态',
|
||||||
|
'pack.json is not a valid pet pack': 'pack.json 不是有效的宠物包',
|
||||||
|
'Pair and connect': '配对并连接',
|
||||||
|
'Pairing expired, please pair again': '配对已失效,请重新配对',
|
||||||
|
'Pairing failed': '配对失败',
|
||||||
|
'Pairing link': '配对链接',
|
||||||
|
'Pairing link is invalid or expired': '配对链接无效或已过期',
|
||||||
|
'Password': '需要密码',
|
||||||
|
'Password (if required)': '密码(如果需要)',
|
||||||
|
'Password or saved credentials required': '需要密码或已保存的凭据',
|
||||||
|
'Paste': '粘贴',
|
||||||
|
'Patch': '补丁',
|
||||||
|
'Paused': '已暂停',
|
||||||
|
'Paused tasks don\'t run on schedule but can still be run manually.': '暂停的任务不会按计划运行,但可以手动运行。',
|
||||||
|
'Permission': '权限',
|
||||||
|
'Permission requested: {0}': '请求权限: {0}',
|
||||||
|
'Personal': '个人',
|
||||||
|
'Pet': '宠物',
|
||||||
|
'Pet pack cannot exceed 40 MB': '宠物包不能超过 40MB',
|
||||||
|
'Pin': '置顶',
|
||||||
|
'Pinned': '已置顶',
|
||||||
|
'Plan body (Markdown)': '计划正文(Markdown)',
|
||||||
|
'Plan first without changing files': '先规划,不改动文件',
|
||||||
|
'Plan, build, or ask': '规划、构建或提问',
|
||||||
|
'Plans': '计划',
|
||||||
|
'Preference': '偏好',
|
||||||
|
'Preview': '预览',
|
||||||
|
'Project knowledge': '项目知识',
|
||||||
|
'Project memory': '项目记忆',
|
||||||
|
'Prompt': '提示词',
|
||||||
|
'Prompt can\'t exceed 20,000 characters': '提示词不能超过 20000 个字符',
|
||||||
|
'Prompt is required': '提示词为必填项',
|
||||||
|
'Proxy (optional)': '代理(可选)',
|
||||||
|
'Put the pairing QR code inside the frame': '把配对二维码放进框内',
|
||||||
|
'Queue': '排队',
|
||||||
|
'Queue instead': '改为排队',
|
||||||
|
'Queue: sends after the current turn ends.': '排队:等当前回合结束后再发送。',
|
||||||
|
'Queued': '已排队',
|
||||||
|
'Queued; sends after this turn': '已排队,本轮结束后发送',
|
||||||
|
'Read': '读取',
|
||||||
|
'Reading output…': '读取输出…',
|
||||||
|
'Received a plaintext frame after the handshake': '握手后收到明文帧',
|
||||||
|
'Recent': '最近',
|
||||||
|
'Reference': '参考',
|
||||||
|
'Refresh': '刷新',
|
||||||
|
'Relay connection closed': 'Relay 连接已关闭',
|
||||||
|
'Relay connection closed ({0} {1})': 'Relay 连接已关闭({0} {1})',
|
||||||
|
'Relay connection error: {0}': 'Relay 连接出错:{0}',
|
||||||
|
'Relay handshake timed out': 'Relay 握手超时',
|
||||||
|
'Relay server': 'Relay 服务器',
|
||||||
|
'Remember facts about you and each project across sessions.': '跨会话记住关于你和每个项目的事实。',
|
||||||
|
'Remove': '移除',
|
||||||
|
'Remove from favorites': '取消收藏',
|
||||||
|
'Remove pet?': '移除宠物?',
|
||||||
|
'Remove time': '移除时间',
|
||||||
|
'Rename': '重命名',
|
||||||
|
'Replying': '正在回复',
|
||||||
|
'Required: {0}': '请填写:{0}',
|
||||||
|
'Reserved output': '输出预留',
|
||||||
|
'Reserved output assumes at most 32K tokens, matching the official client.': '输出预留按最多 32K tokens 计算,与官方客户端一致。',
|
||||||
|
'Restart': '重新启动',
|
||||||
|
'Retry': '重试',
|
||||||
|
'Review': '审查',
|
||||||
|
'Run': '运行',
|
||||||
|
'Run now': '立即运行',
|
||||||
|
'Running': '运行中',
|
||||||
|
'Running {0} commands': '正在执行 {0} 条命令',
|
||||||
|
'Running · {0} tool calls': '执行中 · {0} 次工具调用',
|
||||||
|
'Runs in': '运行位置',
|
||||||
|
'Runs in: {0}': '运行位置:{0}',
|
||||||
|
'Sat': '周六',
|
||||||
|
'Save': '保存',
|
||||||
|
'Saved': '已保存',
|
||||||
|
'Saving…': '保存中…',
|
||||||
|
'Scan QR code': '扫码',
|
||||||
|
'Schedule type': '计划类型',
|
||||||
|
'Scheduled task deleted': '计划任务已删除',
|
||||||
|
'Scheduled task saved': '计划任务已保存',
|
||||||
|
'Scheduled tasks': '计划任务',
|
||||||
|
'Search': '搜索',
|
||||||
|
'Search notes, todos, and plans': '搜索笔记、待办与计划',
|
||||||
|
'Search notes, todos, plans, and memory': '搜索笔记、待办、计划与记忆',
|
||||||
|
'Search sessions': '搜索会话',
|
||||||
|
'Search subdirectories': '搜索子目录',
|
||||||
|
'Search this directory…': '搜索当前目录…',
|
||||||
|
'Searching subdirectories… ({0})': '正在搜索子目录…({0})',
|
||||||
|
'Secrets': '密钥',
|
||||||
|
'Select a model, or switch back to the default model': '请选择模型,或改回使用默认模型',
|
||||||
|
'Select a pet pack (.zip)': '选择宠物包(.zip)',
|
||||||
|
'Select at least one weekday': '请至少选择一个星期',
|
||||||
|
'Select model': '选择模型',
|
||||||
|
'Self-signed certificate fingerprint (optional)': '自签证书指纹(可选)',
|
||||||
|
'Send': '发送',
|
||||||
|
'Send a message…': '发消息…',
|
||||||
|
'Send after this turn ends': '等本轮结束后发送',
|
||||||
|
'Send prompts to sessions on a schedule': '按时间向会话发送提示词',
|
||||||
|
'Sends to an existing session': '发送到现有会话',
|
||||||
|
'Server': '服务端',
|
||||||
|
'Server address': '服务器地址',
|
||||||
|
'Server did not provide a chat directory': '服务器没有提供聊天目录',
|
||||||
|
'Server did not return a device token': '服务器没有返回设备令牌',
|
||||||
|
'Server password; leave empty if the server has none': '服务器密码;服务器未设置可留空',
|
||||||
|
'Servers': '服务器',
|
||||||
|
'Session ID copied': '已复制会话 ID',
|
||||||
|
'Sessions': '会话',
|
||||||
|
'Settings': '设置',
|
||||||
|
'System': '跟随系统',
|
||||||
|
'SHA-256 hex': 'SHA-256 十六进制',
|
||||||
|
'Shared': '团队共享',
|
||||||
|
'Show archived': '显示已归档',
|
||||||
|
'Show archived ({0})': '显示已归档 ({0})',
|
||||||
|
'Show details': '显示详情',
|
||||||
|
'Show git-ignored files': '显示被 git 忽略的文件',
|
||||||
|
'Show summary': '显示摘要',
|
||||||
|
'Showing the first {0} of {1} lines': '仅显示前 {0} 行,共 {1} 行',
|
||||||
|
'Signed in but no token was returned': '登录成功但没有返回令牌',
|
||||||
|
'Size': '大小',
|
||||||
|
'Skill': '技能',
|
||||||
|
'Skipped': '已跳过',
|
||||||
|
'Small': '小',
|
||||||
|
'Stands above the input box; off by default': '站在输入框上方,默认关闭',
|
||||||
|
'Steer': '转向',
|
||||||
|
'Steer instead': '转为转向',
|
||||||
|
'Steer into this turn': '转向当前回合',
|
||||||
|
'Steer: joins the current turn at the next step and work continues.': '转向:在下一步加入当前回合,工作继续。',
|
||||||
|
'Stop': '停止',
|
||||||
|
'Stop this task?': '停止这个任务?',
|
||||||
|
'Stopping…': '停止中…',
|
||||||
|
'Subagent': '子代理',
|
||||||
|
'Subagent · {0}': '子代理 · {0}',
|
||||||
|
'Subdirectory results': '子目录结果',
|
||||||
|
'Success': '成功',
|
||||||
|
'Summarize unfinished tasks and suggest next steps': '总结未完成任务并给出下一步建议',
|
||||||
|
'Sun': '周日',
|
||||||
|
'Switch terminal': '切换终端',
|
||||||
|
'Task': '任务',
|
||||||
|
'Task is already waiting in the queue': '任务已在队列中等待',
|
||||||
|
'Task name': '任务名称',
|
||||||
|
'Task name can\'t exceed 80 characters': '任务名称不能超过 80 个字符',
|
||||||
|
'Task name is required': '任务名称为必填项',
|
||||||
|
'Task started': '任务已启动',
|
||||||
|
'Terminal': '终端',
|
||||||
|
'Terminal 1': '终端 1',
|
||||||
|
'Terminal connection failed': '终端连接失败',
|
||||||
|
'Terminal {0}': '终端 {0}',
|
||||||
|
'The agent notifies you when work finishes or gets stuck.': '工作完成或卡住时,智能体会通知你。',
|
||||||
|
'The archive has no pack.json': '压缩包里没有 pack.json',
|
||||||
|
'The model failed to authenticate. Sign in again on the server or check the API key.': '模型的认证失败,请在服务端重新登录或检查 API Key。',
|
||||||
|
'The model is not in the catalog; the context window is estimated.': '该模型不在模型目录中,上下文窗口为估算值。',
|
||||||
|
'The pet pack stored on this device will be deleted.': '本机保存的宠物包会被删除。',
|
||||||
|
'The server doesn\'t support scheduled tasks': '服务器不支持计划任务',
|
||||||
|
'The theme is stored on this device only and does not sync with the server.': '主题只保存在本机,不随服务器同步。',
|
||||||
|
'The UI text switches together with the system\'s date and time pickers.': '界面文字与系统自带的日期、时间选择器会一起切换。',
|
||||||
|
'Theme': '主题',
|
||||||
|
'Theme mode': '主题模式',
|
||||||
|
'Theme mode and color': '主题模式与主题色',
|
||||||
|
'Thinking': '思考',
|
||||||
|
'Thinking effort': '思考强度',
|
||||||
|
'Thinking…': '正在思考…',
|
||||||
|
'Third-party components bundled with this app are listed below; tap one to read its full license.': '下面列出随本应用打包的第三方组件;点开可阅读完整许可证。',
|
||||||
|
'Third-party components used by this app and their licenses': '本应用使用的第三方组件与它们的许可证',
|
||||||
|
'This camera does not support the flashlight': '这个相机不支持手电筒',
|
||||||
|
'This component has no license text.': '该组件没有附带许可证文本。',
|
||||||
|
'This directory has no commands or skills yet': '这个目录还没有注册指令或技能',
|
||||||
|
'This file cannot be previewed': '这个文件无法预览',
|
||||||
|
'This is not an OpenChamber pairing QR code': '这不是 OpenChamber 配对二维码',
|
||||||
|
'This message and everything after it will be removed from the session and cannot be recovered.': '这条消息及其之后的内容会从会话中删除,且无法恢复。',
|
||||||
|
'This session has no directory': '这个会话没有关联目录',
|
||||||
|
'This session is managed by a Lead; take it over to continue.': '此会话由 Lead 管理,接管后才能继续。',
|
||||||
|
'This turn was stopped.': '本轮已停止。',
|
||||||
|
'Thought process': '思考过程',
|
||||||
|
'Thu': '周四',
|
||||||
|
'Tidy memory': '整理记忆',
|
||||||
|
'Time': '时间',
|
||||||
|
'Time must be in HH:mm format': '时间格式必须是 HH:mm',
|
||||||
|
'Times': '时间点',
|
||||||
|
'Times follow the server\'s time zone.': '时间按服务器所在时区。',
|
||||||
|
'Title': '标题',
|
||||||
|
'Today': '今天',
|
||||||
|
'Todos': '待办',
|
||||||
|
'Tokens used': '已用词元',
|
||||||
|
'Tool': '工具',
|
||||||
|
'Tools for servers and agents are collected here.': '服务器与智能体的工具都收在这里。',
|
||||||
|
'Transfer interrupted': '传输被中断',
|
||||||
|
'Trust self-signed certificates': '信任自签名证书',
|
||||||
|
'Tue': '周二',
|
||||||
|
'Turn cost': '本轮费用',
|
||||||
|
'Turn off to pin the model and agent this run uses.': '关闭后可固定这次运行使用的模型和智能体。',
|
||||||
|
'Unarchive': '取消归档',
|
||||||
|
'Unknown': '未知',
|
||||||
|
'Unknown error': '未知错误',
|
||||||
|
'Unpin': '取消置顶',
|
||||||
|
'Unsupported data URL': '不支持的 data URL',
|
||||||
|
'Unsupported proxy protocol: {0} (supported: http, https, socks5, socks5h)': '不支持的代理协议:{0}(支持 http、https、socks5、socks5h)',
|
||||||
|
'Untitled project': '未命名项目',
|
||||||
|
'Up one level': '上一级',
|
||||||
|
'Usage': '占用',
|
||||||
|
'Usage limits': '用量限额',
|
||||||
|
'Use AI to compact the session history and reduce context size': '使用 AI 压缩会话历史以减少上下文大小',
|
||||||
|
'Use default model and agent': '使用默认模型与智能体',
|
||||||
|
'Version': '版本',
|
||||||
|
'Version comes from the currently connected server': '版本取自当前连接的服务器',
|
||||||
|
'Version, server and open-source licenses': '版本、服务端与开源许可',
|
||||||
|
'Via Relay · {0}': '经由 Relay · {0}',
|
||||||
|
'Via {0}': '经由 {0}',
|
||||||
|
'View all': '查看全部',
|
||||||
|
'Waiting for output…': '等待输出…',
|
||||||
|
'WebSocket substream interrupted': 'WebSocket 子流被中断',
|
||||||
|
'Wed': '周三',
|
||||||
|
'Weekdays': '星期',
|
||||||
|
'Weekly': '每周',
|
||||||
|
'Weekly {0} {1}': '每周 {0} {1}',
|
||||||
|
'What are we building today?': '我们今天要做什么?',
|
||||||
|
'What happens by default when you press send while a run is in progress. Synced with the web client\'s setting.': '运行中按发送时,消息默认怎么处理。与网页端设置同步。',
|
||||||
|
'What needs doing': '要做什么',
|
||||||
|
'What the agent knows': '智能体知道的内容',
|
||||||
|
'Withdraw': '撤回',
|
||||||
|
'Withdraw message?': '撤回消息?',
|
||||||
|
'Withdraw this and later messages': '撤回此消息及之后',
|
||||||
|
'Write': '写入',
|
||||||
|
'Write something for later sessions to read': '记点什么,供之后的会话参考',
|
||||||
|
'Wrong password, try again': '密码错误,请重试',
|
||||||
|
'Yesterday': '昨天',
|
||||||
|
'You stopped this command.': '用户停止了这条命令。',
|
||||||
|
'Your provider has no image models': '你的提供商中没有图像模型',
|
||||||
|
'{0}\nvia {1}': '{0}\n经由 {1}',
|
||||||
|
'{0} ({1})': '{0}({1})',
|
||||||
|
'{0} / {1} ({2}%)': '{0} / {1}({2}%)',
|
||||||
|
'{0} ago': '{0}前',
|
||||||
|
'{0} context': '{0} 上下文',
|
||||||
|
'{0} days': '{0} 天',
|
||||||
|
'{0} days {1} hr': '{0} 天 {1} 小时',
|
||||||
|
'{0} hr': '{0} 小时',
|
||||||
|
'{0} hr {1} min': '{0} 小时 {1} 分钟',
|
||||||
|
'{0} in progress': '正在{0}',
|
||||||
|
'{0} min ago': '{0} 分钟前',
|
||||||
|
'{0} notes': '{0} 条笔记',
|
||||||
|
'{0} plans': '{0} 份计划',
|
||||||
|
'{0} subagents': '{0} 个子代理',
|
||||||
|
'{0} · {1} frames scanned / {2} decode attempts': '{0} · 已扫描 {1} 帧 / 解码 {2} 次',
|
||||||
|
'{0}/{1} done': '{0}/{1} 已完成',
|
||||||
|
'{0}m{1}s': '{0}分{1}秒',
|
||||||
|
'{0}s': '{0}秒',
|
||||||
|
'“{0}” and its schedule will be deleted.': '“{0}”及其计划会被删除。',
|
||||||
|
'“{0}” and its subagent sessions will be deleted permanently.': '“{0}”及其子会话将被删除,且无法恢复。',
|
||||||
|
'“{0}” will be removed from the list, and its device token will be deleted.': '“{0}”将从列表移除,设备令牌也会删除。',
|
||||||
|
'📎 {0} attachments': '📎 {0} 个附件',
|
||||||
|
|
||||||
|
// stats
|
||||||
|
'Stats': '统计',
|
||||||
|
'Prompts, tokens, cost and model activity': '提示词、词元、费用与模型活动',
|
||||||
|
'All projects': '所有项目',
|
||||||
|
'7 days': '7 天',
|
||||||
|
'30 days': '30 天',
|
||||||
|
'90 days': '90 天',
|
||||||
|
'All time': '全部时间',
|
||||||
|
"Couldn't load stats": '无法加载统计',
|
||||||
|
'Try again': '重试',
|
||||||
|
'No activity in this period': '这段时间没有活动',
|
||||||
|
'Sessions you run will show up here.': '你运行的会话会显示在这里。',
|
||||||
|
'No model usage in this period.': '这段时间没有模型使用。',
|
||||||
|
'Prompts': '提示词',
|
||||||
|
'Tokens': '词元',
|
||||||
|
'Cost': '费用',
|
||||||
|
'Active days': '活跃天数',
|
||||||
|
'Longest streak (days)': '最长连续天数',
|
||||||
|
'Weekly activity': '每周活动',
|
||||||
|
'Daily activity': '每日活动',
|
||||||
|
'Model steps per week': '每周的模型步数',
|
||||||
|
'Model steps per day': '每天的模型步数',
|
||||||
|
'Token composition': '词元构成',
|
||||||
|
'Efficiency': '效率',
|
||||||
|
'Cache hit rate': '缓存命中率',
|
||||||
|
'Cost / session': '每个会话费用',
|
||||||
|
'Cost per 1M tokens': '每百万词元费用',
|
||||||
|
'Tokens / session': '每个会话词元',
|
||||||
|
'Steps / session': '每个会话步数',
|
||||||
|
'Reasoning share': '推理占比',
|
||||||
|
'Input': '输入',
|
||||||
|
'Output + reasoning': '输出 + 推理',
|
||||||
|
'Cache reads': '缓存读取',
|
||||||
|
'Cache writes': '缓存写入',
|
||||||
|
'Models': '模型',
|
||||||
|
'Steps': '步数',
|
||||||
|
'Tool calls': '工具调用',
|
||||||
|
'Counting them reads every message in the period.': '统计工具调用需要读取这段时间的每条消息。',
|
||||||
|
'Calls': '调用次数',
|
||||||
|
'Success rate': '成功率',
|
||||||
|
'Failed': '失败',
|
||||||
|
'Unfinished': '未完成',
|
||||||
|
'Up': '上一级',
|
||||||
|
'Updated {0}': '更新于 {0}',
|
||||||
|
'Subagents: {0}': '子代理:{0}',
|
||||||
|
'In {0} · Out {1} · Cache {2}': '输入 {0} · 输出 {1} · 缓存 {2}',
|
||||||
|
'{0} · steps: {1}': '{0} · 步数 {1}',
|
||||||
|
'{0} steps': '{0} 步',
|
||||||
|
'calls: {0} · median: {1}': '调用 {0} · 中位耗时 {1}',
|
||||||
|
'calls: {0}': '调用 {0}',
|
||||||
|
'OpenChamber mobile client': 'OpenChamber 移动客户端',
|
||||||
|
|
||||||
|
// archive
|
||||||
|
'All': '全部',
|
||||||
|
'Open': '打开',
|
||||||
|
'1 archived session': '1 个已归档会话',
|
||||||
|
'{0} archived sessions': '{0} 个已归档会话',
|
||||||
|
'Search archived sessions': '搜索已归档会话',
|
||||||
|
'Search projects': '搜索项目',
|
||||||
|
'No matching archived sessions': '没有匹配的已归档会话',
|
||||||
|
'No matching projects': '没有匹配的项目',
|
||||||
|
'Browse archived sessions and restore them': '浏览已归档的会话并恢复',
|
||||||
|
'Session restored': '会话已恢复',
|
||||||
|
|
||||||
|
// image viewer
|
||||||
|
'Share': '分享',
|
||||||
|
'Share failed': '分享失败',
|
||||||
|
'Save to Photos': '保存到相册',
|
||||||
|
'Saved to Photos': '已保存到相册',
|
||||||
|
"Couldn't save the picture": '无法保存图片',
|
||||||
|
'Storage permission is required to save the picture': '保存图片需要存储权限',
|
||||||
|
|
||||||
|
// browser
|
||||||
|
'Browser': '浏览器',
|
||||||
|
'Enter a URL': '输入网址',
|
||||||
|
'Web browser': '网页浏览器',
|
||||||
|
'Enter a URL above to start browsing': '在上方输入网址开始浏览',
|
||||||
|
'Browser is only available on Android and iOS': '浏览器面板仅支持 Android 和 iOS',
|
||||||
|
'Open in system browser': '在系统浏览器中打开',
|
||||||
|
'Forward': '前进',
|
||||||
|
'Reload': '重新加载',
|
||||||
|
'History': '历史记录',
|
||||||
|
'Invalid URL': '无效的网址',
|
||||||
|
'Could not open the browser: {0}': '无法打开浏览器:{0}',
|
||||||
|
'No history': '暂无历史记录',
|
||||||
|
'Dev servers': '开发服务器',
|
||||||
|
'Enter a URL above, or open a dev server found on the OpenChamber host': '在上方输入网址,或打开在 OpenChamber 主机上发现的开发服务器',
|
||||||
|
'Could not list dev servers: {0}': '无法获取开发服务器列表:{0}',
|
||||||
|
'No dev servers found. Start one in the terminal, then refresh.': '没有发现开发服务器。请在终端启动一个,然后刷新。',
|
||||||
|
'Loopback dev servers (localhost) are previewed through the OpenChamber host; other addresses use this device\'s network.': '本机回环地址(localhost)的开发服务器会通过 OpenChamber 主机预览;其他地址使用手机网络。',
|
||||||
|
'Could not open the dev server: {0}': '无法打开开发服务器:{0}',
|
||||||
|
};
|
||||||
+37
-6
@@ -1,10 +1,21 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||||
|
|
||||||
|
import 'appearance_prefs.dart';
|
||||||
|
import 'l10n.dart';
|
||||||
|
import 'pets/pet_library.dart';
|
||||||
|
import 'screens/home_screen.dart';
|
||||||
import 'screens/servers_screen.dart';
|
import 'screens/servers_screen.dart';
|
||||||
import 'screens/sessions_screen.dart';
|
|
||||||
import 'state.dart';
|
import 'state.dart';
|
||||||
|
import 'version.dart';
|
||||||
|
|
||||||
void main() {
|
Future<void> main() async {
|
||||||
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
// The version goes into every connection's handshake; read it once here so
|
||||||
|
// nothing waits for it later. The language is read before the first frame
|
||||||
|
// for the same reason: a saved choice should never flash the other one.
|
||||||
|
await loadAppVersion();
|
||||||
|
await L10n.instance.ensureLoaded();
|
||||||
runApp(const OpenChamberApp());
|
runApp(const OpenChamberApp());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,6 +34,8 @@ class _OpenChamberAppState extends State<OpenChamberApp>
|
|||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
app.init();
|
app.init();
|
||||||
|
AppearancePrefs.instance.ensureLoaded();
|
||||||
|
PetLibrary.instance.ensureLoaded();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -31,6 +44,12 @@ class _OpenChamberAppState extends State<OpenChamberApp>
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeLocales(List<Locale>? locales) {
|
||||||
|
// "Follow the system" has to redraw when the system language changes.
|
||||||
|
L10n.instance.systemLocaleChanged();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
// The socket often dies while the app sits in the background; nothing
|
// The socket often dies while the app sits in the background; nothing
|
||||||
@@ -40,24 +59,36 @@ class _OpenChamberAppState extends State<OpenChamberApp>
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final look = AppearancePrefs.instance;
|
||||||
return ListenableBuilder(
|
return ListenableBuilder(
|
||||||
listenable: app,
|
listenable: Listenable.merge([app, look, L10n.instance]),
|
||||||
builder: (context, _) {
|
builder: (context, _) {
|
||||||
final home = app.client == null
|
final home = app.client == null
|
||||||
? ServersScreen(app: app)
|
? ServersScreen(app: app)
|
||||||
: SessionsScreen(app: app);
|
: HomeScreen(app: app);
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: 'OpenChamber',
|
title: 'OpenChamber',
|
||||||
|
// Chinese and English, picked in 设置 → 常规 → 语言 or followed
|
||||||
|
// from the system. The built-in pieces (date and time pickers,
|
||||||
|
// text selection menu) follow the same choice.
|
||||||
|
locale: L10n.instance.locale,
|
||||||
|
supportedLocales: const [Locale('en'), Locale('zh', 'CN')],
|
||||||
|
localizationsDelegates: const [
|
||||||
|
GlobalMaterialLocalizations.delegate,
|
||||||
|
GlobalWidgetsLocalizations.delegate,
|
||||||
|
GlobalCupertinoLocalizations.delegate,
|
||||||
|
],
|
||||||
|
themeMode: look.themeMode,
|
||||||
theme: ThemeData(
|
theme: ThemeData(
|
||||||
colorScheme: ColorScheme.fromSeed(
|
colorScheme: ColorScheme.fromSeed(
|
||||||
seedColor: const Color(0xFF6C5CE7),
|
seedColor: look.seedColor,
|
||||||
brightness: Brightness.light,
|
brightness: Brightness.light,
|
||||||
),
|
),
|
||||||
useMaterial3: true,
|
useMaterial3: true,
|
||||||
),
|
),
|
||||||
darkTheme: ThemeData(
|
darkTheme: ThemeData(
|
||||||
colorScheme: ColorScheme.fromSeed(
|
colorScheme: ColorScheme.fromSeed(
|
||||||
seedColor: const Color(0xFF6C5CE7),
|
seedColor: look.seedColor,
|
||||||
brightness: Brightness.dark,
|
brightness: Brightness.dark,
|
||||||
),
|
),
|
||||||
useMaterial3: true,
|
useMaterial3: true,
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// Model picker preferences: favorites, recently used models, and the effort
|
||||||
|
// last chosen for each. Device-local; the server has no say in them.
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import 'l10n.dart';
|
||||||
|
|
||||||
|
class ModelPrefs {
|
||||||
|
ModelPrefs._();
|
||||||
|
static final ModelPrefs instance = ModelPrefs._();
|
||||||
|
|
||||||
|
static const _favoritesKey = 'model.favorites.v1';
|
||||||
|
static const _recentsKey = 'model.recents.v1';
|
||||||
|
static const _effortsKey = 'model.efforts.v1';
|
||||||
|
static const _maxRecents = 6;
|
||||||
|
|
||||||
|
final Set<String> favorites = {};
|
||||||
|
final List<String> recents = [];
|
||||||
|
final Map<String, String> efforts = {};
|
||||||
|
bool _loaded = false;
|
||||||
|
|
||||||
|
static String keyFor(String providerId, String id) => '$providerId/$id';
|
||||||
|
|
||||||
|
Future<void> ensureLoaded() async {
|
||||||
|
if (_loaded) return;
|
||||||
|
_loaded = true;
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
favorites
|
||||||
|
..clear()
|
||||||
|
..addAll(prefs.getStringList(_favoritesKey) ?? const []);
|
||||||
|
recents
|
||||||
|
..clear()
|
||||||
|
..addAll(prefs.getStringList(_recentsKey) ?? const []);
|
||||||
|
final raw = prefs.getString(_effortsKey);
|
||||||
|
if (raw != null && raw.isNotEmpty) {
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is Map) {
|
||||||
|
efforts
|
||||||
|
..clear()
|
||||||
|
..addAll({
|
||||||
|
for (final entry in decoded.entries)
|
||||||
|
if (entry.value is String)
|
||||||
|
'${entry.key}': entry.value as String,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isFavorite(String key) => favorites.contains(key);
|
||||||
|
|
||||||
|
Future<void> toggleFavorite(String key) async {
|
||||||
|
if (!favorites.remove(key)) favorites.add(key);
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setStringList(_favoritesKey, favorites.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> rememberModel(String key) async {
|
||||||
|
recents.remove(key);
|
||||||
|
recents.insert(0, key);
|
||||||
|
if (recents.length > _maxRecents) recents.removeRange(_maxRecents, recents.length);
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setStringList(_recentsKey, recents);
|
||||||
|
}
|
||||||
|
|
||||||
|
String? effortFor(String key) => efforts[key];
|
||||||
|
|
||||||
|
Future<void> rememberEffort(String key, String? variant) async {
|
||||||
|
if (variant == null || variant.isEmpty) {
|
||||||
|
efforts.remove(key);
|
||||||
|
} else {
|
||||||
|
efforts[key] = variant;
|
||||||
|
}
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString(_effortsKey, jsonEncode(efforts));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `200000` reads as `200K`, `1000000` as `1M`.
|
||||||
|
String formatTokenCount(int tokens) {
|
||||||
|
if (tokens <= 0) return '';
|
||||||
|
String trim(String value) =>
|
||||||
|
value.endsWith('.0') ? value.substring(0, value.length - 2) : value;
|
||||||
|
if (tokens >= 1000000) {
|
||||||
|
return '${trim((tokens / 1000000).toStringAsFixed(1))}M';
|
||||||
|
}
|
||||||
|
if (tokens >= 1000) {
|
||||||
|
return '${(tokens / 1000).round()}K';
|
||||||
|
}
|
||||||
|
return '$tokens';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Chinese label for an effort variant; unknown ids keep their own name.
|
||||||
|
String effortLabel(String? variant) {
|
||||||
|
if (variant == null || variant.isEmpty) return tr('Default');
|
||||||
|
return switch (variant.toLowerCase()) {
|
||||||
|
'default' => tr('Default'),
|
||||||
|
'none' => tr('None'),
|
||||||
|
'minimal' => tr('Minimal'),
|
||||||
|
'low' => tr('Low'),
|
||||||
|
'medium' || 'mid' => tr('Medium'),
|
||||||
|
'high' => tr('High'),
|
||||||
|
'xhigh' || 'max' => tr('Extra high'),
|
||||||
|
_ => variant,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
// Imported pets live on the device: a zip's `pack.json` and sprite sheets are
|
||||||
|
// unpacked under the app's documents, and only this client reads them. There
|
||||||
|
// is no built-in pet; nothing shows until the person imports one.
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:ui' as ui;
|
||||||
|
|
||||||
|
import 'package:archive/archive.dart';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import '../l10n.dart';
|
||||||
|
import 'pet_pack.dart';
|
||||||
|
|
||||||
|
class PetImportException implements Exception {
|
||||||
|
final String message;
|
||||||
|
const PetImportException(this.message);
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
class PetLibrary extends ChangeNotifier {
|
||||||
|
PetLibrary._();
|
||||||
|
static final PetLibrary instance = PetLibrary._();
|
||||||
|
|
||||||
|
static const _activeKey = 'pet.active.v1';
|
||||||
|
static const _enabledKey = 'pet.enabled.v1';
|
||||||
|
static const _sizeKey = 'pet.size.v1';
|
||||||
|
static const _positionKey = 'pet.x.v1';
|
||||||
|
|
||||||
|
/// The canvas width a pet is drawn at; the list offers these.
|
||||||
|
static const sizes = <double>[40, 52, 64];
|
||||||
|
|
||||||
|
PetPack? pack;
|
||||||
|
bool enabled = false;
|
||||||
|
double size = 52;
|
||||||
|
|
||||||
|
/// Where the pet stands along its edge, 0 = left end, 1 = right end.
|
||||||
|
double position = 0.5;
|
||||||
|
|
||||||
|
String? _packDir;
|
||||||
|
bool _loaded = false;
|
||||||
|
|
||||||
|
// One decoded sheet at a time: a full sheet can be several megabytes, and
|
||||||
|
// only the current mood is on screen.
|
||||||
|
String? _imagePath;
|
||||||
|
ui.Image? _image;
|
||||||
|
Future<ui.Image?>? _loading;
|
||||||
|
|
||||||
|
bool get hasPet => pack != null;
|
||||||
|
bool get ready => pack != null && enabled;
|
||||||
|
|
||||||
|
Future<void> ensureLoaded() async {
|
||||||
|
if (_loaded) return;
|
||||||
|
_loaded = true;
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
enabled = prefs.getBool(_enabledKey) ?? false;
|
||||||
|
size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80);
|
||||||
|
position = (prefs.getDouble(_positionKey) ?? 0.5).clamp(0.0, 1.0);
|
||||||
|
final active = prefs.getString(_activeKey);
|
||||||
|
if (active != null && active.isNotEmpty) {
|
||||||
|
final root = await _petsRoot();
|
||||||
|
final dir = Directory('${root.path}/$active');
|
||||||
|
final manifest = File('${dir.path}/pack.json');
|
||||||
|
if (await manifest.exists()) {
|
||||||
|
final json = jsonDecode(await manifest.readAsString());
|
||||||
|
if (json is Map<String, dynamic>) {
|
||||||
|
final parsed = PetPack.fromJson(json);
|
||||||
|
if (parsed.isValid) {
|
||||||
|
pack = parsed;
|
||||||
|
_packDir = dir.path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// A corrupt or half-written pet must not keep the app from starting.
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setEnabled(bool value) async {
|
||||||
|
enabled = value;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool(_enabledKey, value);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setSize(double value) async {
|
||||||
|
size = value.clamp(32, 80);
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setDouble(_sizeKey, size);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> setPosition(double value) async {
|
||||||
|
position = value.clamp(0.0, 1.0);
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setDouble(_positionKey, position);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unpacks and activates a pet package. [root] is for tests; the app uses
|
||||||
|
/// the documents directory.
|
||||||
|
Future<PetPack> importZip(List<int> bytes, {Directory? root}) async {
|
||||||
|
if (bytes.isEmpty) throw PetImportException(tr('File is empty'));
|
||||||
|
if (bytes.length > 40 * 1024 * 1024) {
|
||||||
|
throw PetImportException(tr('Pet pack cannot exceed 40 MB'));
|
||||||
|
}
|
||||||
|
|
||||||
|
final Archive archive;
|
||||||
|
try {
|
||||||
|
archive = ZipDecoder().decodeBytes(bytes, verify: true);
|
||||||
|
} catch (_) {
|
||||||
|
throw PetImportException(tr('Not a valid zip file'));
|
||||||
|
}
|
||||||
|
|
||||||
|
ArchiveFile? manifest;
|
||||||
|
for (final file in archive.files) {
|
||||||
|
if (!file.isFile) continue;
|
||||||
|
final name = file.name.replaceAll('\\', '/');
|
||||||
|
if (name == 'pack.json' || name.endsWith('/pack.json')) {
|
||||||
|
if (manifest == null || name.length < manifest.name.length) {
|
||||||
|
manifest = file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (manifest == null) {
|
||||||
|
throw PetImportException(tr('The archive has no pack.json'));
|
||||||
|
}
|
||||||
|
|
||||||
|
final manifestName = manifest.name.replaceAll('\\', '/');
|
||||||
|
final base = manifestName == 'pack.json'
|
||||||
|
? ''
|
||||||
|
: manifestName.substring(0, manifestName.length - '/pack.json'.length);
|
||||||
|
|
||||||
|
final PetPack parsed;
|
||||||
|
try {
|
||||||
|
final text = utf8.decode(_content(manifest));
|
||||||
|
final json = jsonDecode(text);
|
||||||
|
if (json is! Map<String, dynamic>) throw const FormatException();
|
||||||
|
parsed = PetPack.fromJson(json);
|
||||||
|
} catch (_) {
|
||||||
|
throw PetImportException(tr('pack.json is not a valid pet pack'));
|
||||||
|
}
|
||||||
|
if (!parsed.isValid) {
|
||||||
|
throw PetImportException(tr('pack.json is missing animations or states'));
|
||||||
|
}
|
||||||
|
|
||||||
|
final id = _safeId(parsed.id.isNotEmpty ? parsed.id : parsed.name);
|
||||||
|
final rootDir = root ?? await _petsRoot();
|
||||||
|
await rootDir.create(recursive: true);
|
||||||
|
final staging = Directory('${rootDir.path}/.$id.importing');
|
||||||
|
if (await staging.exists()) await staging.delete(recursive: true);
|
||||||
|
await staging.create(recursive: true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
var extracted = 0;
|
||||||
|
for (final file in archive.files) {
|
||||||
|
if (!file.isFile) continue;
|
||||||
|
final name = file.name.replaceAll('\\', '/');
|
||||||
|
if (base.isNotEmpty && !name.startsWith('$base/')) continue;
|
||||||
|
final rel = base.isEmpty ? name : name.substring(base.length + 1);
|
||||||
|
if (rel.isEmpty || rel.startsWith('/')) continue;
|
||||||
|
final segments = rel.split('/');
|
||||||
|
if (segments.any((s) => s.isEmpty || s == '..' || s == '.')) continue;
|
||||||
|
final content = _content(file);
|
||||||
|
extracted += content.length;
|
||||||
|
if (extracted > 60 * 1024 * 1024) {
|
||||||
|
throw PetImportException(tr('Extracted size exceeds 60 MB'));
|
||||||
|
}
|
||||||
|
final target = File('${staging.path}/$rel');
|
||||||
|
await target.parent.create(recursive: true);
|
||||||
|
await target.writeAsBytes(content, flush: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final animation in parsed.animations.values) {
|
||||||
|
if (animation.sheet.isEmpty) {
|
||||||
|
throw PetImportException(trArgs('Animation {0} has no sprite sheet', [animation.name]));
|
||||||
|
}
|
||||||
|
final sheet = File('${staging.path}/${animation.sheet}');
|
||||||
|
if (!await sheet.exists()) {
|
||||||
|
throw PetImportException(trArgs('Missing sprite sheet {0}', [animation.sheet]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final destination = Directory('${rootDir.path}/$id');
|
||||||
|
if (await destination.exists()) await destination.delete(recursive: true);
|
||||||
|
await staging.rename(destination.path);
|
||||||
|
|
||||||
|
_clearImages();
|
||||||
|
pack = parsed;
|
||||||
|
_packDir = destination.path;
|
||||||
|
enabled = true;
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString(_activeKey, id);
|
||||||
|
await prefs.setBool(_enabledKey, true);
|
||||||
|
} catch (_) {}
|
||||||
|
notifyListeners();
|
||||||
|
return parsed;
|
||||||
|
} catch (_) {
|
||||||
|
if (await staging.exists()) {
|
||||||
|
try {
|
||||||
|
await staging.delete(recursive: true);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> remove() async {
|
||||||
|
final dir = _packDir;
|
||||||
|
pack = null;
|
||||||
|
_packDir = null;
|
||||||
|
enabled = false;
|
||||||
|
_clearImages();
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.remove(_activeKey);
|
||||||
|
await prefs.setBool(_enabledKey, false);
|
||||||
|
} catch (_) {}
|
||||||
|
if (dir != null) {
|
||||||
|
try {
|
||||||
|
await Directory(dir).delete(recursive: true);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decoded sheet for [animation], held one at a time.
|
||||||
|
Future<ui.Image?> imageFor(PetAnimation animation) {
|
||||||
|
final dir = _packDir;
|
||||||
|
if (dir == null || animation.sheet.isEmpty) return Future.value(null);
|
||||||
|
final path = '$dir/${animation.sheet}';
|
||||||
|
if (_imagePath == path) {
|
||||||
|
if (_image != null) return Future.value(_image);
|
||||||
|
if (_loading != null) return _loading!;
|
||||||
|
}
|
||||||
|
_imagePath = path;
|
||||||
|
_image?.dispose();
|
||||||
|
_image = null;
|
||||||
|
final loading = _decode(path);
|
||||||
|
_loading = loading;
|
||||||
|
return loading;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<ui.Image?> _decode(String path) async {
|
||||||
|
try {
|
||||||
|
final bytes = await File(path).readAsBytes();
|
||||||
|
final codec = await ui.instantiateImageCodec(bytes);
|
||||||
|
final frame = await codec.getNextFrame();
|
||||||
|
final image = frame.image;
|
||||||
|
if (_imagePath != path) {
|
||||||
|
image.dispose();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
_image = image;
|
||||||
|
return image;
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
if (_imagePath == path) _loading = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _clearImages() {
|
||||||
|
_image?.dispose();
|
||||||
|
_image = null;
|
||||||
|
_imagePath = null;
|
||||||
|
_loading = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const _appDirChannel = MethodChannel('openchamber/appdir');
|
||||||
|
|
||||||
|
Future<Directory> _petsRoot() async {
|
||||||
|
String? base;
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
// A tiny channel in MainActivity: enough to find the app's files dir
|
||||||
|
// without the JNI-based path_provider, which this engine cannot load.
|
||||||
|
try {
|
||||||
|
base = await _appDirChannel.invokeMethod<String>('documents');
|
||||||
|
} catch (_) {
|
||||||
|
// Fall through to the StateError below.
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
final env = Platform.environment;
|
||||||
|
final data = env['XDG_DATA_HOME'];
|
||||||
|
base = data != null && data.isNotEmpty
|
||||||
|
? '$data/openchamber'
|
||||||
|
: '${env['HOME'] ?? '.'}/.local/share/openchamber';
|
||||||
|
}
|
||||||
|
if (base == null || base.isEmpty) {
|
||||||
|
throw StateError('no writable directory for pets');
|
||||||
|
}
|
||||||
|
final root = Directory('$base/pets');
|
||||||
|
if (!await root.exists()) await root.create(recursive: true);
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<int> _content(ArchiveFile file) {
|
||||||
|
final content = file.content;
|
||||||
|
return content is List<int> ? content : List<int>.from(content as List);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _safeId(String raw) {
|
||||||
|
final id = raw
|
||||||
|
.toLowerCase()
|
||||||
|
.replaceAll(RegExp(r'[^a-z0-9._-]+'), '-')
|
||||||
|
.replaceAll(RegExp(r'^[-._]+|[-._]+$'), '');
|
||||||
|
return id.isEmpty ? 'pet' : id;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// A pet package, in the shape dsh-Go's packs already use: `pack.json` points
|
||||||
|
// at PNG sprite sheets, each frame cropped from a canvas of a few logical
|
||||||
|
// pixels, and names the animations for each mood.
|
||||||
|
import 'dart:ui';
|
||||||
|
|
||||||
|
/// One sheet frame in the play order, with how long it stays up.
|
||||||
|
class PetFrame {
|
||||||
|
final int index;
|
||||||
|
final int ms;
|
||||||
|
const PetFrame(this.index, this.ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
class PetAnimation {
|
||||||
|
final String name;
|
||||||
|
final String sheet;
|
||||||
|
final int frameW;
|
||||||
|
final int frameH;
|
||||||
|
final int cols;
|
||||||
|
final bool loop;
|
||||||
|
|
||||||
|
/// Where this animation sits on the pack's logical canvas.
|
||||||
|
final Rect box;
|
||||||
|
final List<PetFrame> frames;
|
||||||
|
|
||||||
|
const PetAnimation({
|
||||||
|
required this.name,
|
||||||
|
required this.sheet,
|
||||||
|
required this.frameW,
|
||||||
|
required this.frameH,
|
||||||
|
required this.cols,
|
||||||
|
required this.loop,
|
||||||
|
required this.box,
|
||||||
|
required this.frames,
|
||||||
|
});
|
||||||
|
|
||||||
|
int get totalMs => frames.fold(0, (sum, f) => sum + f.ms);
|
||||||
|
|
||||||
|
factory PetAnimation.fromJson(String name, Map<String, dynamic> j) {
|
||||||
|
final box = _rect(j['box'], const Rect.fromLTWH(0, 0, 1, 1));
|
||||||
|
final cols = _int(j['cols'], 1).clamp(1, 4096);
|
||||||
|
final total = _int(j['ms'], 50 * cols);
|
||||||
|
final frames = <PetFrame>[];
|
||||||
|
final raw = j['frames'];
|
||||||
|
if (raw is List) {
|
||||||
|
for (final e in raw) {
|
||||||
|
if (e is! Map) continue;
|
||||||
|
final ms = _int(e['ms'], 50);
|
||||||
|
frames.add(PetFrame(_int(e['i'], 0), ms <= 0 ? 50 : ms));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (frames.isEmpty) {
|
||||||
|
final each = (total / cols).round().clamp(16, 2000);
|
||||||
|
for (var i = 0; i < cols; i++) {
|
||||||
|
frames.add(PetFrame(i, each));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return PetAnimation(
|
||||||
|
name: name,
|
||||||
|
sheet: j['sheet'] as String? ?? '',
|
||||||
|
frameW: _int(j['frameW'], (box.width * 5).round()),
|
||||||
|
frameH: _int(j['frameH'], (box.height * 5).round()),
|
||||||
|
cols: cols,
|
||||||
|
loop: j['loop'] != false,
|
||||||
|
box: box,
|
||||||
|
frames: frames,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a pack says. Only the parts this client draws are kept; reactions
|
||||||
|
/// and idle pools are read as far as they can be played.
|
||||||
|
class PetPack {
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final String author;
|
||||||
|
final String license;
|
||||||
|
final String source;
|
||||||
|
final bool pixelArt;
|
||||||
|
|
||||||
|
/// The logical canvas the frames are placed on.
|
||||||
|
final Size canvas;
|
||||||
|
|
||||||
|
/// Where the pet's feet rest on that canvas.
|
||||||
|
final Offset anchor;
|
||||||
|
final Rect contentBox;
|
||||||
|
|
||||||
|
final Map<String, PetAnimation> animations;
|
||||||
|
final Map<String, List<String>> states;
|
||||||
|
|
||||||
|
/// tapLeft / tapRight / tickle / drag -> animation name.
|
||||||
|
final Map<String, String> reactions;
|
||||||
|
|
||||||
|
const PetPack({
|
||||||
|
required this.id,
|
||||||
|
required this.name,
|
||||||
|
required this.author,
|
||||||
|
required this.license,
|
||||||
|
required this.source,
|
||||||
|
required this.pixelArt,
|
||||||
|
required this.canvas,
|
||||||
|
required this.anchor,
|
||||||
|
required this.contentBox,
|
||||||
|
required this.animations,
|
||||||
|
required this.states,
|
||||||
|
required this.reactions,
|
||||||
|
});
|
||||||
|
|
||||||
|
bool get isValid =>
|
||||||
|
animations.isNotEmpty && states.values.any((list) => list.any(animations.containsKey));
|
||||||
|
|
||||||
|
String? get idleName {
|
||||||
|
for (final name in states['idle'] ?? const <String>[]) {
|
||||||
|
if (animations.containsKey(name)) return name;
|
||||||
|
}
|
||||||
|
return animations.keys.isEmpty ? null : animations.keys.first;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first animation of [state] the pack actually has, then idle.
|
||||||
|
String? animationForState(String state) {
|
||||||
|
for (final name in states[state] ?? const <String>[]) {
|
||||||
|
if (animations.containsKey(name)) return name;
|
||||||
|
}
|
||||||
|
return idleName;
|
||||||
|
}
|
||||||
|
|
||||||
|
PetAnimation? animation(String? name) =>
|
||||||
|
name == null ? null : animations[name];
|
||||||
|
|
||||||
|
factory PetPack.fromJson(Map<String, dynamic> j) {
|
||||||
|
final canvasJson = j['canvas'];
|
||||||
|
final cw = _double(canvasJson is Map ? canvasJson['w'] : null, 52);
|
||||||
|
final ch = _double(canvasJson is Map ? canvasJson['h'] : null, cw);
|
||||||
|
final anchorJson = j['anchor'];
|
||||||
|
final ax = _double(anchorJson is Map ? anchorJson['x'] : null, cw / 2);
|
||||||
|
final ay = _double(anchorJson is Map ? anchorJson['baseline'] : null, ch);
|
||||||
|
|
||||||
|
final animations = <String, PetAnimation>{};
|
||||||
|
final rawAnims = j['animations'];
|
||||||
|
if (rawAnims is Map) {
|
||||||
|
for (final e in rawAnims.entries) {
|
||||||
|
final value = e.value;
|
||||||
|
if (e.key is String && value is Map) {
|
||||||
|
animations[e.key as String] =
|
||||||
|
PetAnimation.fromJson(e.key as String, Map<String, dynamic>.from(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final states = <String, List<String>>{};
|
||||||
|
final rawStates = j['states'];
|
||||||
|
if (rawStates is Map) {
|
||||||
|
for (final e in rawStates.entries) {
|
||||||
|
final list = e.value;
|
||||||
|
if (e.key is String && list is List) {
|
||||||
|
states[e.key as String] = [
|
||||||
|
for (final v in list)
|
||||||
|
if (v is String) v,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final reactions = <String, String>{};
|
||||||
|
final rawReactions = j['reactions'];
|
||||||
|
if (rawReactions is Map) {
|
||||||
|
for (final key in const ['tapLeft', 'tapRight', 'tickle', 'drag']) {
|
||||||
|
final v = rawReactions[key];
|
||||||
|
if (v is String) {
|
||||||
|
reactions[key] = v;
|
||||||
|
} else if (v is Map) {
|
||||||
|
final file = v['file'];
|
||||||
|
final files = v['files'];
|
||||||
|
if (file is String) {
|
||||||
|
reactions[key] = file;
|
||||||
|
} else if (files is List && files.isNotEmpty && files.first is String) {
|
||||||
|
reactions[key] = files.first as String;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return PetPack(
|
||||||
|
id: j['id'] as String? ?? '',
|
||||||
|
name: j['name'] as String? ?? '',
|
||||||
|
author: j['author'] as String? ?? '',
|
||||||
|
license: j['license'] as String? ?? '',
|
||||||
|
source: j['source'] as String? ?? '',
|
||||||
|
pixelArt: j['pixelArt'] != false,
|
||||||
|
canvas: Size(cw, ch),
|
||||||
|
anchor: Offset(ax, ay),
|
||||||
|
contentBox: _rect(j['contentBox'], Rect.fromLTWH(0, 0, cw, ch)),
|
||||||
|
animations: animations,
|
||||||
|
states: states,
|
||||||
|
reactions: reactions,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int _int(Object? v, int fallback) =>
|
||||||
|
v is num ? v.toInt() : (v is String ? int.tryParse(v) ?? fallback : fallback);
|
||||||
|
|
||||||
|
double _double(Object? v, double fallback) =>
|
||||||
|
v is num ? v.toDouble() : (v is String ? double.tryParse(v) ?? fallback : fallback);
|
||||||
|
|
||||||
|
Rect _rect(Object? v, Rect fallback) {
|
||||||
|
if (v is! Map) return fallback;
|
||||||
|
return Rect.fromLTWH(
|
||||||
|
_double(v['x'], fallback.left),
|
||||||
|
_double(v['y'], fallback.top),
|
||||||
|
_double(v['w'], fallback.width),
|
||||||
|
_double(v['h'], fallback.height),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
// 归档: every archived session in one place, grouped by project and searchable.
|
||||||
|
// Archived sessions are no longer mixed into the sidebar; this page is the
|
||||||
|
// only list of them, mirroring OpenChamber's archive page (title, count,
|
||||||
|
// search, project chips, restore and delete).
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import '../widgets/project_icon.dart';
|
||||||
|
import '../widgets/project_picker.dart';
|
||||||
|
|
||||||
|
class ArchivedSessionsScreen extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
|
||||||
|
const ArchivedSessionsScreen({super.key, required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ArchivedSessionsScreen> createState() => _ArchivedSessionsScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ArchivedSessionsScreenState extends State<ArchivedSessionsScreen> {
|
||||||
|
final TextEditingController _searchCtrl = TextEditingController();
|
||||||
|
String _query = '';
|
||||||
|
|
||||||
|
/// The selected project bucket key; null is "all projects".
|
||||||
|
String? _bucket;
|
||||||
|
|
||||||
|
AppState get _app => widget.app;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
// The sidebar no longer fetches the archive; this page owns it.
|
||||||
|
if (!_app.archivedLoaded) _app.refreshArchived();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_searchCtrl.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _matches(String directory) {
|
||||||
|
final selected = _bucket;
|
||||||
|
if (selected == null) return true;
|
||||||
|
if (selected == AppState.chatTarget) {
|
||||||
|
return directory.isEmpty ||
|
||||||
|
directory == AppState.chatTarget ||
|
||||||
|
_app.isChatDirectory(directory);
|
||||||
|
}
|
||||||
|
return samePath(directory, selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Archived sessions matching the search and the selected project, newest
|
||||||
|
/// archived first (falling back to updated for old records).
|
||||||
|
List<Session> _filtered() {
|
||||||
|
final query = _query.trim().toLowerCase();
|
||||||
|
return [
|
||||||
|
for (final session in _app.archivedSessions)
|
||||||
|
if (_matches(session.directory) &&
|
||||||
|
(query.isEmpty ||
|
||||||
|
session.title.toLowerCase().contains(query) ||
|
||||||
|
session.id.toLowerCase().contains(query) ||
|
||||||
|
_app
|
||||||
|
.projectLabelFor(session.directory)
|
||||||
|
.toLowerCase()
|
||||||
|
.contains(query)))
|
||||||
|
session,
|
||||||
|
]..sort((a, b) => _time(b).compareTo(_time(a)));
|
||||||
|
}
|
||||||
|
|
||||||
|
static int _time(Session session) =>
|
||||||
|
session.archived > 0 ? session.archived : session.updated;
|
||||||
|
|
||||||
|
Future<void> _refresh() => _app.refreshArchived();
|
||||||
|
|
||||||
|
/// The projects the picker offers here: only checkouts that actually hold
|
||||||
|
/// archived sessions. This page never archives anything, so a project
|
||||||
|
/// without an archive would only get in the way.
|
||||||
|
List<ProjectInfo> _archiveProjects() {
|
||||||
|
final byPath = <String, ProjectInfo>{};
|
||||||
|
for (final session in _app.archivedSessions) {
|
||||||
|
final directory = session.directory;
|
||||||
|
if (directory.isEmpty || _app.isChatDirectory(directory)) continue;
|
||||||
|
final project = _app.projectFor(directory) ??
|
||||||
|
ProjectInfo(id: '', canonical: directory, name: pathLeaf(directory));
|
||||||
|
final key = slashPath(project.canonical).toLowerCase();
|
||||||
|
byPath.putIfAbsent(key, () => project);
|
||||||
|
}
|
||||||
|
final projects = byPath.values.toList()
|
||||||
|
..sort((a, b) => a.label.toLowerCase().compareTo(b.label.toLowerCase()));
|
||||||
|
return projects;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickProject() async {
|
||||||
|
final choice = await showProjectPicker(
|
||||||
|
context,
|
||||||
|
app: _app,
|
||||||
|
selected: _bucket ?? allProjectsTarget,
|
||||||
|
includeAll: true,
|
||||||
|
onlyProjects: _archiveProjects(),
|
||||||
|
);
|
||||||
|
if (choice == null || !mounted) return;
|
||||||
|
setState(() => _bucket = choice.isAll ? null : choice.canonical);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _scopeRow(ThemeData theme) {
|
||||||
|
final selected = _bucket;
|
||||||
|
final isChat = selected != null && _app.isChatDirectory(selected);
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
onTap: _pickProject,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
if (selected == null)
|
||||||
|
Icon(Icons.folder_copy_outlined,
|
||||||
|
size: 18, color: theme.hintColor)
|
||||||
|
else if (isChat)
|
||||||
|
ProjectIcon(app: _app, chat: true, size: 18)
|
||||||
|
else
|
||||||
|
ProjectIcon(
|
||||||
|
app: _app, project: _app.projectFor(selected), size: 18),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
selected == null
|
||||||
|
? tr('All projects')
|
||||||
|
: _app.projectLabelFor(selected),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(fontSize: 14),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _unarchive(Session session) async {
|
||||||
|
await _app.setArchived(session, false);
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: AppText(tr('Session restored'))));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _copy(Session session) {
|
||||||
|
Clipboard.setData(ClipboardData(text: session.id));
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: AppText(tr('Session ID copied'))));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _confirmDelete(Session session) {
|
||||||
|
showDialog(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
title: const AppText('Delete session?'),
|
||||||
|
content: AppText(trArgs(
|
||||||
|
'“{0}” and its subagent sessions will be deleted permanently.',
|
||||||
|
[session.title])),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
child: const AppText('Cancel')),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () {
|
||||||
|
Navigator.pop(context);
|
||||||
|
_app.client?.deleteSession(session.id);
|
||||||
|
_app.sessions.removeWhere((s) => s.id == session.id);
|
||||||
|
_app.archivedSessions.removeWhere((s) => s.id == session.id);
|
||||||
|
_app.touch();
|
||||||
|
},
|
||||||
|
child: const AppText('Delete'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _open(Session session) {
|
||||||
|
_app.openChat(session);
|
||||||
|
// The archive page sits above the all-features page and the shell; the
|
||||||
|
// chat opens on the shell.
|
||||||
|
Navigator.of(context).popUntil((route) => route.isFirst);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _subtitle(Session session, {required bool showProject}) {
|
||||||
|
final parts = <String>[];
|
||||||
|
if (showProject) parts.add(_app.projectLabelFor(session.directory));
|
||||||
|
if (session.isChild) parts.add(tr('Subagent'));
|
||||||
|
final time = _time(session);
|
||||||
|
if (time > 0) {
|
||||||
|
final d = DateTime.fromMillisecondsSinceEpoch(time);
|
||||||
|
parts.add('${d.month.toString().padLeft(2, '0')}-'
|
||||||
|
'${d.day.toString().padLeft(2, '0')} '
|
||||||
|
'${d.hour.toString().padLeft(2, '0')}:'
|
||||||
|
'${d.minute.toString().padLeft(2, '0')}');
|
||||||
|
}
|
||||||
|
return parts.join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _row(Session session, {required bool showProject}) {
|
||||||
|
return ListTile(
|
||||||
|
// Compact like the sidebar's session rows.
|
||||||
|
dense: true,
|
||||||
|
minTileHeight: 56,
|
||||||
|
contentPadding: const EdgeInsets.only(left: 16, right: 4),
|
||||||
|
title: Text(
|
||||||
|
session.title.isEmpty ? tr('(Untitled session)') : session.title,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(fontSize: 14),
|
||||||
|
),
|
||||||
|
subtitle: Text(
|
||||||
|
_subtitle(session, showProject: showProject),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
trailing: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.unarchive_outlined, size: 20),
|
||||||
|
tooltip: tr('Unarchive'),
|
||||||
|
onPressed: () => _unarchive(session),
|
||||||
|
),
|
||||||
|
PopupMenuButton<String>(
|
||||||
|
icon: const Icon(Icons.more_vert, size: 18),
|
||||||
|
onSelected: (value) {
|
||||||
|
switch (value) {
|
||||||
|
case 'open':
|
||||||
|
_open(session);
|
||||||
|
break;
|
||||||
|
case 'unarchive':
|
||||||
|
_unarchive(session);
|
||||||
|
break;
|
||||||
|
case 'copy':
|
||||||
|
_copy(session);
|
||||||
|
break;
|
||||||
|
case 'delete':
|
||||||
|
_confirmDelete(session);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
itemBuilder: (_) => [
|
||||||
|
const PopupMenuItem(value: 'open', child: AppText('Open')),
|
||||||
|
const PopupMenuItem(
|
||||||
|
value: 'unarchive', child: AppText('Unarchive')),
|
||||||
|
const PopupMenuItem(
|
||||||
|
value: 'copy', child: AppText('Copy session ID')),
|
||||||
|
const PopupMenuItem(value: 'delete', child: AppText('Delete')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
onTap: () => _open(session),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const AppText('Archive'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.refresh),
|
||||||
|
tooltip: tr('Refresh'),
|
||||||
|
onPressed: _app.archivedLoading ? null : _refresh,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: ListenableBuilder(
|
||||||
|
listenable: _app,
|
||||||
|
builder: (context, _) {
|
||||||
|
final shown = _filtered();
|
||||||
|
final all = _app.archivedSessions.length;
|
||||||
|
final count = shown.length == 1
|
||||||
|
? tr('1 archived session')
|
||||||
|
: trArgs('{0} archived sessions', [shown.length]);
|
||||||
|
return Column(
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 8, 16, 6),
|
||||||
|
child: TextField(
|
||||||
|
controller: _searchCtrl,
|
||||||
|
onChanged: (value) => setState(() => _query = value),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: tr('Search archived sessions'),
|
||||||
|
prefixIcon: const Icon(Icons.search),
|
||||||
|
isDense: true,
|
||||||
|
border: OutlineInputBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_scopeRow(theme),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 6, 16, 2),
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: AppText(
|
||||||
|
count,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 12, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: _app.archivedLoading && all == 0
|
||||||
|
? const Center(child: CircularProgressIndicator())
|
||||||
|
: RefreshIndicator(
|
||||||
|
onRefresh: _refresh,
|
||||||
|
child: shown.isEmpty
|
||||||
|
? ListView(
|
||||||
|
// Keep pull-to-refresh working on an empty
|
||||||
|
// archive.
|
||||||
|
physics:
|
||||||
|
const AlwaysScrollableScrollPhysics(),
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(32),
|
||||||
|
child: AppText(
|
||||||
|
all == 0
|
||||||
|
? 'No archived sessions'
|
||||||
|
: 'No matching archived sessions',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
: ListView(
|
||||||
|
physics:
|
||||||
|
const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.only(bottom: 24),
|
||||||
|
children: [
|
||||||
|
for (final session in shown)
|
||||||
|
_row(session,
|
||||||
|
showProject: _bucket == null),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,563 @@
|
|||||||
|
// The right sidebar's web browser: an address bar over an embedded WebView,
|
||||||
|
// with history navigation, reload/stop and opening the page in the system
|
||||||
|
// browser. A loopback URL (the host's dev server) is carried over the
|
||||||
|
// OpenChamber dev tunnel through a local TCP listener, so a dev server running
|
||||||
|
// on the host can be previewed from the phone; other addresses use the phone's
|
||||||
|
// network. The panel keeps its page while another tab is shown (the tab stack
|
||||||
|
// keeps it alive).
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:webview_flutter/webview_flutter.dart';
|
||||||
|
|
||||||
|
import '../api/dev_tunnel.dart';
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
|
||||||
|
class BrowserPanel extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
|
||||||
|
/// The session/project whose dev servers the empty state lists.
|
||||||
|
final String directory;
|
||||||
|
|
||||||
|
const BrowserPanel({super.key, required this.app, required this.directory});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<BrowserPanel> createState() => _BrowserPanelState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BrowserPanelState extends State<BrowserPanel> {
|
||||||
|
static const MethodChannel _channel = MethodChannel('openchamber/browser');
|
||||||
|
|
||||||
|
final TextEditingController _url = TextEditingController();
|
||||||
|
final List<String> _history = [];
|
||||||
|
WebViewController? _web;
|
||||||
|
DevTunnel? _tunnel;
|
||||||
|
int? _tunnelPort;
|
||||||
|
String? _displayOrigin;
|
||||||
|
List<DevServerInfo> _servers = const [];
|
||||||
|
bool _serversLoading = false;
|
||||||
|
String? _serversError;
|
||||||
|
bool _loading = false;
|
||||||
|
bool _hasPage = false;
|
||||||
|
bool _canBack = false;
|
||||||
|
bool _canForward = false;
|
||||||
|
int _progress = 0;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
bool get _supported => Platform.isAndroid || Platform.isIOS;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
if (!_supported) return;
|
||||||
|
_web = WebViewController()
|
||||||
|
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||||
|
..setBackgroundColor(Colors.transparent)
|
||||||
|
..setNavigationDelegate(NavigationDelegate(
|
||||||
|
onPageStarted: (url) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_hasPage = true;
|
||||||
|
_progress = 0;
|
||||||
|
_error = null;
|
||||||
|
_setUrl(_displayFor(url));
|
||||||
|
});
|
||||||
|
_syncNavigation();
|
||||||
|
},
|
||||||
|
onPageFinished: (url) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_progress = 100;
|
||||||
|
_setUrl(_displayFor(url));
|
||||||
|
});
|
||||||
|
_remember(_displayFor(url));
|
||||||
|
_syncNavigation();
|
||||||
|
},
|
||||||
|
onProgress: (value) {
|
||||||
|
if (mounted) setState(() => _progress = value);
|
||||||
|
},
|
||||||
|
onUrlChange: (change) {
|
||||||
|
final url = change.url;
|
||||||
|
if (url != null && mounted) setState(() => _setUrl(_displayFor(url)));
|
||||||
|
},
|
||||||
|
onNavigationRequest: (request) {
|
||||||
|
final rewritten = _rewriteNavigation(request.url);
|
||||||
|
if (rewritten == null) return NavigationDecision.prevent;
|
||||||
|
if (rewritten != request.url) {
|
||||||
|
_web?.loadRequest(Uri.parse(rewritten));
|
||||||
|
return NavigationDecision.prevent;
|
||||||
|
}
|
||||||
|
return NavigationDecision.navigate;
|
||||||
|
},
|
||||||
|
onWebResourceError: (error) {
|
||||||
|
if ((error.isForMainFrame ?? true) && mounted) {
|
||||||
|
setState(() => _error = error.description);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
));
|
||||||
|
_loadServers();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
unawaited(_tunnel?.close());
|
||||||
|
_url.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
String _displayFor(String url) {
|
||||||
|
final tunnel = _tunnel;
|
||||||
|
final origin = _displayOrigin;
|
||||||
|
if (tunnel == null || origin == null) return url;
|
||||||
|
return displayUrlFor(url, tunnel.localPort, origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _rewriteNavigation(String url) {
|
||||||
|
final tunnel = _tunnel;
|
||||||
|
final origin = _displayOrigin;
|
||||||
|
if (tunnel == null || origin == null) return url;
|
||||||
|
final local = 'http://127.0.0.1:${tunnel.localPort}';
|
||||||
|
if (url == local || url.startsWith('$local/')) return url;
|
||||||
|
final uri = Uri.tryParse(url);
|
||||||
|
if (uri == null) return url;
|
||||||
|
final originOfUrl =
|
||||||
|
'${uri.scheme}://${uri.host}${uri.hasPort ? ':${uri.port}' : ''}';
|
||||||
|
if (originOfUrl == origin) {
|
||||||
|
return localTunnelUri(uri, tunnel.localPort).toString();
|
||||||
|
}
|
||||||
|
final port = devServerPort(uri);
|
||||||
|
if (port != null) {
|
||||||
|
if (port == _tunnelPort) {
|
||||||
|
return localTunnelUri(uri, tunnel.localPort).toString();
|
||||||
|
}
|
||||||
|
// A loopback link to another dev port means another server on the host.
|
||||||
|
unawaited(_navigate(url));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _syncNavigation() async {
|
||||||
|
final web = _web;
|
||||||
|
if (web == null) return;
|
||||||
|
final back = await web.canGoBack();
|
||||||
|
final forward = await web.canGoForward();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_canBack = back;
|
||||||
|
_canForward = forward;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts [url] in the address field with the caret at its end, so the part
|
||||||
|
/// that was just visited stays visible in the narrow bar.
|
||||||
|
void _setUrl(String url) {
|
||||||
|
_url.value = TextEditingValue(
|
||||||
|
text: url,
|
||||||
|
selection: TextSelection.collapsed(offset: url.length),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _remember(String url) {
|
||||||
|
if (url.isEmpty) return;
|
||||||
|
_history.remove(url);
|
||||||
|
_history.insert(0, url);
|
||||||
|
if (_history.length > 20) _history.removeLast();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadServers() async {
|
||||||
|
final cl = widget.app.client;
|
||||||
|
if (cl == null) return;
|
||||||
|
setState(() {
|
||||||
|
_serversLoading = true;
|
||||||
|
_serversError = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final list = await cl.devServers(directory: widget.directory);
|
||||||
|
if (!mounted) return;
|
||||||
|
// Match the web client's "running dev servers": a port that answered
|
||||||
|
// with a page is listed when it belongs to a known project (or carries
|
||||||
|
// no directory, which is how announced servers arrive). Ports started
|
||||||
|
// outside every project stay behind the web client's "show hidden
|
||||||
|
// ports" too.
|
||||||
|
final known = <String>[
|
||||||
|
if (widget.directory.isNotEmpty) widget.directory,
|
||||||
|
// Only OpenChamber's own project list counts as work, as on the web;
|
||||||
|
// an OpenCode project that happens to exist under ~/Downloads or a
|
||||||
|
// tool's config directory is still outside the user's projects.
|
||||||
|
for (final project in widget.app.projects)
|
||||||
|
if (project.canonical.isNotEmpty && project.metaId.isNotEmpty)
|
||||||
|
project.canonical,
|
||||||
|
];
|
||||||
|
bool knownDirectory(String directory) {
|
||||||
|
if (directory.isEmpty || known.isEmpty) return true;
|
||||||
|
for (final root in known) {
|
||||||
|
if (samePath(root, directory) || isUnderDirectory(directory, root)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
final filtered = [
|
||||||
|
for (final server in list)
|
||||||
|
if (server.title.isNotEmpty && knownDirectory(server.directory))
|
||||||
|
server,
|
||||||
|
]..sort((a, b) => a.port.compareTo(b.port));
|
||||||
|
setState(() {
|
||||||
|
_servers = filtered;
|
||||||
|
_serversLoading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_serversError = '$e';
|
||||||
|
_serversLoading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<DevTunnel?> _ensureTunnel(Uri uri) async {
|
||||||
|
final port = devServerPort(uri);
|
||||||
|
if (port == null) {
|
||||||
|
await _tunnel?.close();
|
||||||
|
_tunnel = null;
|
||||||
|
_tunnelPort = null;
|
||||||
|
_displayOrigin = null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (_tunnel != null && _tunnelPort == port) return _tunnel;
|
||||||
|
await _tunnel?.close();
|
||||||
|
_tunnel = null;
|
||||||
|
_tunnelPort = null;
|
||||||
|
final tunnel = DevTunnel(widget.app, port);
|
||||||
|
await tunnel.start();
|
||||||
|
_tunnel = tunnel;
|
||||||
|
_tunnelPort = port;
|
||||||
|
_displayOrigin =
|
||||||
|
'${uri.scheme}://${uri.host}${uri.hasPort ? ':${uri.port}' : ''}';
|
||||||
|
return tunnel;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _navigate(String raw) async {
|
||||||
|
var text = raw.trim();
|
||||||
|
if (text.isEmpty) return;
|
||||||
|
if (!text.contains('://')) {
|
||||||
|
final host = text.split('/').first.split(':').first;
|
||||||
|
final local = host == 'localhost' ||
|
||||||
|
host == '127.0.0.1' ||
|
||||||
|
host == '[::1]' ||
|
||||||
|
host == '0.0.0.0';
|
||||||
|
text = '${local ? 'http' : 'https'}://$text';
|
||||||
|
}
|
||||||
|
final uri = Uri.tryParse(text);
|
||||||
|
if (uri == null || !uri.hasAuthority) {
|
||||||
|
_snack(tr('Invalid URL'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
FocusScope.of(context).unfocus();
|
||||||
|
_setUrl(text);
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final tunnel = await _ensureTunnel(uri);
|
||||||
|
if (!mounted) return;
|
||||||
|
final target = tunnel == null ? uri : localTunnelUri(uri, tunnel.localPort);
|
||||||
|
setState(() => _hasPage = true);
|
||||||
|
await _web?.loadRequest(target);
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_error = trArgs('Could not open the dev server: {0}', [e]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openExternal() async {
|
||||||
|
if (!Platform.isAndroid) return;
|
||||||
|
final url = _url.text.trim();
|
||||||
|
if (url.isEmpty) return;
|
||||||
|
try {
|
||||||
|
await _channel.invokeMethod<bool>('openUrl', {'url': url});
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) _snack(trArgs('Could not open the browser: {0}', [e]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _snack(String text) {
|
||||||
|
ScaffoldMessenger.of(context)
|
||||||
|
..hideCurrentSnackBar()
|
||||||
|
..showSnackBar(SnackBar(content: AppText(text)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
if (!_supported) {
|
||||||
|
return Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(32),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.public_off, size: 40, color: theme.hintColor),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
const AppText(
|
||||||
|
'Browser is only available on Android and iOS',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 13),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
_addressBar(theme),
|
||||||
|
if (_loading)
|
||||||
|
LinearProgressIndicator(
|
||||||
|
value: _progress > 0 && _progress < 100 ? _progress / 100 : null,
|
||||||
|
minHeight: 2,
|
||||||
|
),
|
||||||
|
if (_error != null) _errorBar(theme),
|
||||||
|
Expanded(
|
||||||
|
// Keep the WebView attached even before the first address: a
|
||||||
|
// loadRequest on a controller with no platform view is lost. The
|
||||||
|
// empty state is an overlay until a page starts.
|
||||||
|
child: Stack(
|
||||||
|
children: [
|
||||||
|
Positioned.fill(child: WebViewWidget(controller: _web!)),
|
||||||
|
if (!_hasPage)
|
||||||
|
Positioned.fill(
|
||||||
|
child: ColoredBox(
|
||||||
|
color: theme.colorScheme.surface,
|
||||||
|
child: _empty(theme),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _addressBar(ThemeData theme) {
|
||||||
|
final web = _web;
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(4, 6, 4, 6),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: TextField(
|
||||||
|
controller: _url,
|
||||||
|
keyboardType: TextInputType.url,
|
||||||
|
textInputAction: TextInputAction.go,
|
||||||
|
onSubmitted: _navigate,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
isDense: true,
|
||||||
|
hintText: tr('Enter a URL'),
|
||||||
|
prefixIcon: const Icon(Icons.public, size: 18),
|
||||||
|
suffixIcon: IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_forward, size: 18),
|
||||||
|
tooltip: tr('Go'),
|
||||||
|
onPressed: () => _navigate(_url.text),
|
||||||
|
),
|
||||||
|
border: OutlineInputBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(_loading ? Icons.stop : Icons.refresh, size: 20),
|
||||||
|
tooltip: _loading ? tr('Stop') : tr('Reload'),
|
||||||
|
onPressed: _loading
|
||||||
|
? () => web?.runJavaScript('window.stop()')
|
||||||
|
: web?.reload,
|
||||||
|
),
|
||||||
|
MenuAnchor(
|
||||||
|
builder: (context, controller, child) => IconButton(
|
||||||
|
icon: const Icon(Icons.more_vert, size: 20),
|
||||||
|
tooltip: tr('More'),
|
||||||
|
onPressed: () =>
|
||||||
|
controller.isOpen ? controller.close() : controller.open(),
|
||||||
|
),
|
||||||
|
menuChildren: [
|
||||||
|
MenuItemButton(
|
||||||
|
leadingIcon: const Icon(Icons.arrow_back, size: 18),
|
||||||
|
onPressed: _canBack ? () => web?.goBack() : null,
|
||||||
|
child: const AppText('Back'),
|
||||||
|
),
|
||||||
|
MenuItemButton(
|
||||||
|
leadingIcon: const Icon(Icons.arrow_forward, size: 18),
|
||||||
|
onPressed: _canForward ? () => web?.goForward() : null,
|
||||||
|
child: const AppText('Forward'),
|
||||||
|
),
|
||||||
|
if (Platform.isAndroid)
|
||||||
|
MenuItemButton(
|
||||||
|
leadingIcon: const Icon(Icons.open_in_browser, size: 18),
|
||||||
|
onPressed: _openExternal,
|
||||||
|
child: const AppText('Open in system browser'),
|
||||||
|
),
|
||||||
|
MenuItemButton(
|
||||||
|
leadingIcon: const Icon(Icons.dns_outlined, size: 18),
|
||||||
|
onPressed: () {
|
||||||
|
setState(() => _hasPage = false);
|
||||||
|
_loadServers();
|
||||||
|
},
|
||||||
|
child: const AppText('Dev servers'),
|
||||||
|
),
|
||||||
|
SubmenuButton(
|
||||||
|
leadingIcon: const Icon(Icons.history, size: 18),
|
||||||
|
menuChildren: _history.isEmpty
|
||||||
|
? [
|
||||||
|
const MenuItemButton(
|
||||||
|
onPressed: null,
|
||||||
|
child: AppText('No history'),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
for (final url in _history)
|
||||||
|
MenuItemButton(
|
||||||
|
onPressed: () {
|
||||||
|
_setUrl(url);
|
||||||
|
_navigate(url);
|
||||||
|
},
|
||||||
|
child: Text(url,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
child: const AppText('History'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _errorBar(ThemeData theme) {
|
||||||
|
return Container(
|
||||||
|
color: theme.colorScheme.errorContainer.withValues(alpha: 0.4),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.error_outline,
|
||||||
|
size: 16, color: theme.colorScheme.error),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_error!,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.colorScheme.error),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => _web?.reload(),
|
||||||
|
child: const AppText('Retry'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _empty(ThemeData theme) {
|
||||||
|
return SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.all(20),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.public, size: 40, color: theme.hintColor),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const AppText(
|
||||||
|
'Web browser',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
const AppText(
|
||||||
|
'Enter a URL above, or open a dev server found on the OpenChamber host',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 12),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 14),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
const Expanded(
|
||||||
|
child: AppText(
|
||||||
|
'Dev servers',
|
||||||
|
style: TextStyle(fontSize: 13.5, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.refresh, size: 18),
|
||||||
|
tooltip: tr('Refresh'),
|
||||||
|
onPressed: _serversLoading ? null : _loadServers,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (_serversLoading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.all(16),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_servers.isNotEmpty)
|
||||||
|
for (final server in _servers)
|
||||||
|
ListTile(
|
||||||
|
dense: true,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(horizontal: 4),
|
||||||
|
leading: Icon(Icons.lan_outlined,
|
||||||
|
size: 20, color: theme.hintColor),
|
||||||
|
title: Text(server.label,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
subtitle: Text(
|
||||||
|
[
|
||||||
|
if (server.url.isNotEmpty) server.url,
|
||||||
|
if (server.command.isNotEmpty) server.command,
|
||||||
|
].join(' · '),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
trailing: const Icon(Icons.chevron_right, size: 18),
|
||||||
|
onTap: () => _navigate(server.url.isEmpty
|
||||||
|
? 'http://localhost:${server.port}'
|
||||||
|
: server.url),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
child: AppText(
|
||||||
|
_serversError != null
|
||||||
|
? trArgs('Could not list dev servers: {0}', [_serversError!])
|
||||||
|
: 'No dev servers found. Start one in the terminal, then refresh.',
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
const AppText(
|
||||||
|
'Loopback dev servers (localhost) are previewed through the OpenChamber host; other addresses use this device\'s network.',
|
||||||
|
style: TextStyle(fontSize: 11.5),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1560
-717
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,120 @@
|
|||||||
|
// 全部功能: the tools the sidebar keeps behind one button, each opening its
|
||||||
|
// own page. Scheduled tasks so far; more entries go into the grid.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../state.dart';
|
||||||
|
import 'archived_sessions_screen.dart';
|
||||||
|
import 'scheduled_tasks_screen.dart';
|
||||||
|
import 'stats_screen.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
class FeaturesScreen extends StatelessWidget {
|
||||||
|
final AppState app;
|
||||||
|
const FeaturesScreen({super.key, required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(title: const AppText('All features')),
|
||||||
|
body: ListView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 32),
|
||||||
|
children: [
|
||||||
|
AppText('Tools for servers and agents are collected here.',
|
||||||
|
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
|
||||||
|
const SizedBox(height: 14),
|
||||||
|
GridView.count(
|
||||||
|
crossAxisCount: 2,
|
||||||
|
shrinkWrap: true,
|
||||||
|
physics: const NeverScrollableScrollPhysics(),
|
||||||
|
mainAxisSpacing: 12,
|
||||||
|
crossAxisSpacing: 12,
|
||||||
|
childAspectRatio: 1.25,
|
||||||
|
children: [
|
||||||
|
_FeatureTile(
|
||||||
|
icon: Icons.schedule,
|
||||||
|
title: 'Scheduled tasks',
|
||||||
|
caption: 'Send prompts to sessions on a schedule',
|
||||||
|
onTap: () => Navigator.of(context).push(MaterialPageRoute(
|
||||||
|
builder: (_) => ScheduledTasksScreen(app: app),
|
||||||
|
)),
|
||||||
|
),
|
||||||
|
_FeatureTile(
|
||||||
|
icon: Icons.query_stats,
|
||||||
|
title: 'Stats',
|
||||||
|
caption: 'Prompts, tokens, cost and model activity',
|
||||||
|
onTap: () => Navigator.of(context).push(MaterialPageRoute(
|
||||||
|
builder: (_) => StatsScreen(app: app),
|
||||||
|
)),
|
||||||
|
),
|
||||||
|
_FeatureTile(
|
||||||
|
icon: Icons.archive_outlined,
|
||||||
|
title: 'Archive',
|
||||||
|
caption: 'Browse archived sessions and restore them',
|
||||||
|
onTap: () => Navigator.of(context).push(MaterialPageRoute(
|
||||||
|
builder: (_) => ArchivedSessionsScreen(app: app),
|
||||||
|
)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FeatureTile extends StatelessWidget {
|
||||||
|
final IconData icon;
|
||||||
|
final String title;
|
||||||
|
final String caption;
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
const _FeatureTile({
|
||||||
|
required this.icon,
|
||||||
|
required this.title,
|
||||||
|
required this.caption,
|
||||||
|
required this.onTap,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Material(
|
||||||
|
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
width: 38,
|
||||||
|
height: 38,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.primaryContainer,
|
||||||
|
borderRadius: BorderRadius.circular(11),
|
||||||
|
),
|
||||||
|
child: Icon(icon,
|
||||||
|
size: 21, color: theme.colorScheme.onPrimaryContainer),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
AppText(title,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 14.5, fontWeight: FontWeight.w600)),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
AppText(
|
||||||
|
caption,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+392
-207
@@ -9,15 +9,20 @@ import 'package:flutter/material.dart';
|
|||||||
|
|
||||||
import '../api/client.dart';
|
import '../api/client.dart';
|
||||||
import '../api/models.dart';
|
import '../api/models.dart';
|
||||||
|
import '../api/transport.dart';
|
||||||
import '../state.dart';
|
import '../state.dart';
|
||||||
import '../widgets/markdown_view.dart';
|
import '../widgets/markdown_view.dart';
|
||||||
|
import 'browser_panel.dart';
|
||||||
|
import 'knowledge_panel.dart';
|
||||||
|
import 'terminal_panel.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
Future<void> showFilesPanel(
|
Future<void> showFilesPanel(
|
||||||
BuildContext context, AppState app, Session session) {
|
BuildContext context, AppState app, String directory) {
|
||||||
return showGeneralDialog<void>(
|
return showGeneralDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: true,
|
barrierDismissible: true,
|
||||||
barrierLabel: '文件',
|
barrierLabel: tr('Files'),
|
||||||
barrierColor: Colors.black54,
|
barrierColor: Colors.black54,
|
||||||
transitionDuration: const Duration(milliseconds: 220),
|
transitionDuration: const Duration(milliseconds: 220),
|
||||||
pageBuilder: (context, _, __) {
|
pageBuilder: (context, _, __) {
|
||||||
@@ -29,7 +34,7 @@ Future<void> showFilesPanel(
|
|||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
width: width * 0.92,
|
width: width * 0.92,
|
||||||
height: double.infinity,
|
height: double.infinity,
|
||||||
child: FilesPanel(app: app, session: session),
|
child: FilesPanel(app: app, directory: directory),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -44,8 +49,11 @@ Future<void> showFilesPanel(
|
|||||||
|
|
||||||
class FilesPanel extends StatefulWidget {
|
class FilesPanel extends StatefulWidget {
|
||||||
final AppState app;
|
final AppState app;
|
||||||
final Session session;
|
|
||||||
const FilesPanel({super.key, required this.app, required this.session});
|
/// The workspace directory this panel browses. A draft has one before it
|
||||||
|
/// has a session, so the panel never needs a session.
|
||||||
|
final String directory;
|
||||||
|
const FilesPanel({super.key, required this.app, required this.directory});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<FilesPanel> createState() => _FilesPanelState();
|
State<FilesPanel> createState() => _FilesPanelState();
|
||||||
@@ -64,7 +72,7 @@ const _skipDirs = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
class _FilesPanelState extends State<FilesPanel> {
|
class _FilesPanelState extends State<FilesPanel> {
|
||||||
String get _root => widget.session.directory;
|
String get _root => widget.directory;
|
||||||
Client? get _client => widget.app.client;
|
Client? get _client => widget.app.client;
|
||||||
|
|
||||||
String _path = '';
|
String _path = '';
|
||||||
@@ -73,8 +81,9 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
String? _error;
|
String? _error;
|
||||||
String _query = '';
|
String _query = '';
|
||||||
|
|
||||||
/// A project listing hides what git ignores; the menu can show it.
|
/// The last gitignore choice seen; the app's server-backed setting can
|
||||||
bool _showIgnored = false;
|
/// change while the panel is open (the switch writes it, a reload reads it).
|
||||||
|
bool _lastShowIgnored = false;
|
||||||
|
|
||||||
List<FsEntry> _deepResults = [];
|
List<FsEntry> _deepResults = [];
|
||||||
bool _deepDone = false;
|
bool _deepDone = false;
|
||||||
@@ -86,6 +95,11 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
bool _previewLoading = false;
|
bool _previewLoading = false;
|
||||||
String? _previewError;
|
String? _previewError;
|
||||||
Uint8List? _previewBytes;
|
Uint8List? _previewBytes;
|
||||||
|
|
||||||
|
/// The file's size from `fs/stat`, even when too large to preview: the
|
||||||
|
/// download dialog shows a determinate bar against it when the response
|
||||||
|
/// carries no Content-Length (the relay forwards bodies chunked).
|
||||||
|
int? _previewSize;
|
||||||
String? _previewText;
|
String? _previewText;
|
||||||
bool _previewBinary = false;
|
bool _previewBinary = false;
|
||||||
bool _previewImage = false;
|
bool _previewImage = false;
|
||||||
@@ -97,20 +111,36 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
|
|
||||||
int _tab = 0;
|
int _tab = 0;
|
||||||
|
|
||||||
|
/// Tabs built at least once. Kept alive (offstage) so the browser, terminal
|
||||||
|
/// and knowledge pages keep their state when another tab is shown.
|
||||||
|
final Set<int> _built = {0};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_lastShowIgnored = widget.app.showGitignored;
|
||||||
|
widget.app.addListener(_onApp);
|
||||||
_path = _root;
|
_path = _root;
|
||||||
if (_root.isNotEmpty) _load();
|
if (_root.isNotEmpty) _load();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
widget.app.removeListener(_onApp);
|
||||||
_editor.dispose();
|
_editor.dispose();
|
||||||
_search.dispose();
|
_search.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The gitignore setting is shared with the web UI; when it changes (here
|
||||||
|
/// or on another client), reload the listing with the new filter.
|
||||||
|
void _onApp() {
|
||||||
|
if (!mounted || widget.app.showGitignored == _lastShowIgnored) return;
|
||||||
|
_lastShowIgnored = widget.app.showGitignored;
|
||||||
|
setState(() {});
|
||||||
|
if (_previewPath == null) _load();
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------- files
|
// ------------------------------------------------------------- files
|
||||||
|
|
||||||
Future<void> _load([String? path]) async {
|
Future<void> _load([String? path]) async {
|
||||||
@@ -126,8 +156,8 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
_deepDone = false;
|
_deepDone = false;
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
final list = await client
|
final list = await client.fsList(target,
|
||||||
.fsList(target, directory: _root, respectGitignore: !_showIgnored)
|
directory: _root, respectGitignore: !widget.app.showGitignored)
|
||||||
..removeWhere((e) => e.name == '.git');
|
..removeWhere((e) => e.name == '.git');
|
||||||
list.sort((a, b) {
|
list.sort((a, b) {
|
||||||
if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
|
if (a.isDirectory != b.isDirectory) return a.isDirectory ? -1 : 1;
|
||||||
@@ -224,6 +254,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
_previewLoading = true;
|
_previewLoading = true;
|
||||||
_previewError = null;
|
_previewError = null;
|
||||||
_previewBytes = null;
|
_previewBytes = null;
|
||||||
|
_previewSize = null;
|
||||||
_previewText = null;
|
_previewText = null;
|
||||||
_previewBinary = false;
|
_previewBinary = false;
|
||||||
_previewImage = false;
|
_previewImage = false;
|
||||||
@@ -233,11 +264,15 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
if (client == null) return;
|
if (client == null) return;
|
||||||
try {
|
try {
|
||||||
final stat = await client.fsStat(entry.path, directory: _root);
|
final stat = await client.fsStat(entry.path, directory: _root);
|
||||||
|
if (stat != null && stat.size > 0 && mounted) {
|
||||||
|
setState(() => _previewSize = stat.size);
|
||||||
|
}
|
||||||
if (stat != null && stat.size > 2 * 1024 * 1024) {
|
if (stat != null && stat.size > 2 * 1024 * 1024) {
|
||||||
if (!mounted || _previewPath != entry.path) return;
|
if (!mounted || _previewPath != entry.path) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_previewLoading = false;
|
_previewLoading = false;
|
||||||
_previewError = '文件较大(${_fmtSize(stat.size)}),请下载后查看';
|
_previewError = trArgs(
|
||||||
|
'File is large ({0}), download it to view', [_fmtSize(stat.size)]);
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -277,7 +312,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
_previewText = _editor.text;
|
_previewText = _editor.text;
|
||||||
_previewBinary = false;
|
_previewBinary = false;
|
||||||
});
|
});
|
||||||
_toast('已保存');
|
_toast('Saved');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _saving = false);
|
setState(() => _saving = false);
|
||||||
@@ -289,16 +324,29 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
final client = _client;
|
final client = _client;
|
||||||
final path = _previewPath;
|
final path = _previewPath;
|
||||||
if (client == null || path == null) return;
|
if (client == null || path == null) return;
|
||||||
|
// A file already in memory needs no progress; the rest stream with one.
|
||||||
|
var bytes = _previewBytes;
|
||||||
|
if (bytes == null) {
|
||||||
|
bytes = await showDialog<Uint8List>(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false,
|
||||||
|
builder: (_) => _DownloadDialog(
|
||||||
|
name: _previewName,
|
||||||
|
expectedSize: _previewSize,
|
||||||
|
start: (onProgress, cancel) => client.downloadFile(path,
|
||||||
|
directory: _root, onProgress: onProgress, cancel: cancel),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (bytes == null || !mounted) return;
|
||||||
try {
|
try {
|
||||||
final bytes = _previewBytes ??
|
|
||||||
Uint8List.fromList(await client.rawFile(path, directory: _root));
|
|
||||||
final uri = await FilePicker.saveFile(
|
final uri = await FilePicker.saveFile(
|
||||||
fileName: _previewName,
|
fileName: _previewName,
|
||||||
bytes: bytes,
|
bytes: bytes,
|
||||||
);
|
);
|
||||||
if (uri != null) _toast('已保存');
|
if (uri != null) _toast('Saved');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
_toast('下载失败:$e');
|
_toast(trArgs('Couldn\'t save: {0}', [e]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,7 +355,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
Future<void> _newEntry({required bool directory}) async {
|
Future<void> _newEntry({required bool directory}) async {
|
||||||
final client = _client;
|
final client = _client;
|
||||||
if (client == null || _path.isEmpty) return;
|
if (client == null || _path.isEmpty) return;
|
||||||
final name = await _askName(directory ? '新建文件夹' : '新建文件');
|
final name = await _askName(directory ? 'New folder' : 'New file');
|
||||||
if (name == null) return;
|
if (name == null) return;
|
||||||
final target = '$_path/$name';
|
final target = '$_path/$name';
|
||||||
try {
|
try {
|
||||||
@@ -331,23 +379,23 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
final name = await showDialog<String>(
|
final name = await showDialog<String>(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => AlertDialog(
|
builder: (context) => AlertDialog(
|
||||||
title: Text(title),
|
title: AppText(title),
|
||||||
content: TextField(
|
content: TextField(
|
||||||
controller: controller,
|
controller: controller,
|
||||||
autofocus: true,
|
autofocus: true,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
labelText: '名称',
|
labelText: tr('Name'),
|
||||||
hintText: title == '新建文件夹' ? '例如 docs' : '例如 notes.md',
|
hintText: title == 'New folder' ? tr('e.g. docs') : tr('e.g. notes.md'),
|
||||||
),
|
),
|
||||||
onSubmitted: (v) => Navigator.of(context).pop(v),
|
onSubmitted: (v) => Navigator.of(context).pop(v),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
child: const Text('取消')),
|
child: const AppText('Cancel')),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||||
child: const Text('创建')),
|
child: const AppText('Create')),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -355,7 +403,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
final trimmed = name?.trim() ?? '';
|
final trimmed = name?.trim() ?? '';
|
||||||
if (trimmed.isEmpty) return null;
|
if (trimmed.isEmpty) return null;
|
||||||
if (trimmed.contains('/') || trimmed.contains('\\')) {
|
if (trimmed.contains('/') || trimmed.contains('\\')) {
|
||||||
_toast('名称里不能有斜杠');
|
_toast(tr('Names cannot contain slashes'));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return trimmed;
|
return trimmed;
|
||||||
@@ -363,7 +411,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
|
|
||||||
void _toast(String message) {
|
void _toast(String message) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: AppText(message)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------- build
|
// -------------------------------------------------------------- build
|
||||||
@@ -372,117 +420,79 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
child: Column(
|
child: Padding(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
// The panel is a dialog, so it does not shrink for the keyboard on its
|
||||||
children: [
|
// own: give the IME's height back here, or it covers the terminal's
|
||||||
_header(theme),
|
// key bar and its last lines.
|
||||||
_tabs(theme),
|
padding:
|
||||||
const Divider(height: 1),
|
EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
|
||||||
Expanded(child: _body(theme)),
|
child: Column(
|
||||||
],
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
_tabs(theme),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Expanded(
|
||||||
|
child: Stack(
|
||||||
|
children: [
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
if (_built.contains(i))
|
||||||
|
Positioned.fill(
|
||||||
|
child: Offstage(
|
||||||
|
offstage: _tab != i,
|
||||||
|
child: _tabBody(i, theme),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _header(ThemeData theme) {
|
/// The tab row is the panel's title now; the only global action left is
|
||||||
|
/// closing the panel. Everything else belongs to the tab's own header.
|
||||||
|
Widget _tabs(ThemeData theme) {
|
||||||
|
// Icons only: four labels no longer fit a phone's panel width. The
|
||||||
|
// tooltips keep them identifiable.
|
||||||
|
const tabs = [
|
||||||
|
(Icons.folder_outlined, 'Files'),
|
||||||
|
(Icons.menu_book_outlined, 'Project knowledge'),
|
||||||
|
(Icons.terminal, 'Terminal'),
|
||||||
|
(Icons.public, 'Browser'),
|
||||||
|
];
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
|
padding: const EdgeInsets.fromLTRB(12, 6, 2, 6),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
if (_previewPath != null)
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.arrow_back),
|
|
||||||
tooltip: '返回',
|
|
||||||
onPressed: () => setState(() => _previewPath = null),
|
|
||||||
)
|
|
||||||
else
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Column(
|
child: SegmentedButton<int>(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
showSelectedIcon: false,
|
||||||
children: [
|
style: const ButtonStyle(
|
||||||
Text(_previewPath != null ? _previewName : '文件',
|
visualDensity: VisualDensity.compact,
|
||||||
maxLines: 1,
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
overflow: TextOverflow.ellipsis,
|
),
|
||||||
style: const TextStyle(
|
segments: [
|
||||||
fontSize: 16, fontWeight: FontWeight.w600)),
|
for (var i = 0; i < tabs.length; i++)
|
||||||
if (_previewPath == null && _root.isNotEmpty)
|
ButtonSegment(
|
||||||
Text(_rootName,
|
value: i,
|
||||||
maxLines: 1,
|
icon: Tooltip(
|
||||||
overflow: TextOverflow.ellipsis,
|
message: tr(tabs[i].$2),
|
||||||
style: TextStyle(
|
child: Icon(tabs[i].$1, size: 19),
|
||||||
fontSize: 12, color: theme.hintColor)),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
|
selected: {_tab},
|
||||||
|
onSelectionChanged: (v) => setState(() {
|
||||||
|
_tab = v.first;
|
||||||
|
_built.add(v.first);
|
||||||
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
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(
|
IconButton(
|
||||||
icon: const Icon(Icons.close),
|
icon: const Icon(Icons.close),
|
||||||
tooltip: '关闭',
|
tooltip: tr('Close sidebar'),
|
||||||
onPressed: () => Navigator.of(context).maybePop(),
|
onPressed: () => Navigator.of(context).maybePop(),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -490,77 +500,36 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _tabs(ThemeData theme) {
|
Widget _tabBody(int index, 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) {
|
if (_root.isEmpty) {
|
||||||
return const Center(child: Text('这个会话没有关联目录'));
|
return const Center(child: AppText('This session has no directory'));
|
||||||
}
|
}
|
||||||
switch (_tab) {
|
switch (index) {
|
||||||
case 1:
|
case 1:
|
||||||
return _placeholder(theme, Icons.menu_book_outlined, '项目知识',
|
return KnowledgePanel(app: widget.app, directory: _root);
|
||||||
'笔记、待办与计划会在这里。');
|
|
||||||
case 2:
|
case 2:
|
||||||
return _placeholder(
|
return TerminalPanel(app: widget.app, directory: _root);
|
||||||
theme, Icons.terminal, '终端', '在服务器上运行的终端会在这里。');
|
case 3:
|
||||||
|
return BrowserPanel(app: widget.app, directory: _root);
|
||||||
default:
|
default:
|
||||||
if (_previewPath != null) return _previewBody(theme);
|
return Column(
|
||||||
return _browser(theme);
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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: [
|
children: [
|
||||||
Icon(icon, size: 40, color: theme.hintColor),
|
_pathBar(theme),
|
||||||
const SizedBox(height: 12),
|
Expanded(
|
||||||
Text(title,
|
child: _previewPath != null
|
||||||
style: const TextStyle(
|
? _previewBody(theme)
|
||||||
fontSize: 16, fontWeight: FontWeight.w600)),
|
: _browserBody(theme),
|
||||||
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) {
|
Widget _browserBody(ThemeData theme) {
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
_pathBar(theme),
|
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
|
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
|
||||||
child: Row(
|
child: Row(
|
||||||
@@ -577,12 +546,12 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
isDense: true,
|
isDense: true,
|
||||||
prefixIcon: const Icon(Icons.search, size: 20),
|
prefixIcon: const Icon(Icons.search, size: 20),
|
||||||
hintText: '搜索当前目录…',
|
hintText: tr('Search this directory…'),
|
||||||
suffixIcon: _query.trim().isEmpty
|
suffixIcon: _query.trim().isEmpty
|
||||||
? null
|
? null
|
||||||
: IconButton(
|
: IconButton(
|
||||||
icon: const Icon(Icons.travel_explore, size: 20),
|
icon: const Icon(Icons.travel_explore, size: 20),
|
||||||
tooltip: '搜索子目录',
|
tooltip: tr('Search subdirectories'),
|
||||||
onPressed: _searching ? null : _deepSearch,
|
onPressed: _searching ? null : _deepSearch,
|
||||||
),
|
),
|
||||||
border: OutlineInputBorder(
|
border: OutlineInputBorder(
|
||||||
@@ -605,7 +574,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
height: 14,
|
height: 14,
|
||||||
child: CircularProgressIndicator(strokeWidth: 2)),
|
child: CircularProgressIndicator(strokeWidth: 2)),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Text('正在搜索子目录…(${_deepResults.length})',
|
AppText(trArgs('Searching subdirectories… ({0})', [_deepResults.length]),
|
||||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -615,32 +584,121 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The tab's own header: where you are, plus what you can do here. The
|
||||||
|
/// panel's global actions (close) sit in the tab row above.
|
||||||
Widget _pathBar(ThemeData theme) {
|
Widget _pathBar(ThemeData theme) {
|
||||||
final crumbs = _crumbs;
|
final crumbs = _crumbs;
|
||||||
|
final preview = _previewPath != null;
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(4, 0, 8, 4),
|
padding: const EdgeInsets.fromLTRB(4, 0, 4, 4),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: const Icon(Icons.arrow_upward, size: 20),
|
icon: Icon(preview ? Icons.arrow_back : Icons.arrow_upward,
|
||||||
tooltip: '上一级',
|
size: 20),
|
||||||
onPressed: _path == _root ? null : _up,
|
tooltip: preview ? tr('Back') : tr('Up one level'),
|
||||||
|
onPressed: preview
|
||||||
|
? () => setState(() => _previewPath = null)
|
||||||
|
: (_path == _root ? null : _up),
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: SingleChildScrollView(
|
child: preview
|
||||||
scrollDirection: Axis.horizontal,
|
? Column(
|
||||||
child: Row(
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
_crumb(theme, _rootName, () => _load(_root), last: crumbs.isEmpty),
|
children: [
|
||||||
for (var i = 0; i < crumbs.length; i++) ...[
|
Text(_previewName,
|
||||||
Text(' / ', style: TextStyle(color: theme.hintColor)),
|
maxLines: 1,
|
||||||
_crumb(theme, crumbs[i], () => _goToCrumb(i),
|
overflow: TextOverflow.ellipsis,
|
||||||
last: i == crumbs.length - 1),
|
style: const TextStyle(
|
||||||
],
|
fontSize: 13.5, fontWeight: FontWeight.w600)),
|
||||||
],
|
Text(_previewPath!,
|
||||||
),
|
maxLines: 1,
|
||||||
),
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
: SingleChildScrollView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
_crumb(theme, _rootName, () => _load(_root),
|
||||||
|
last: crumbs.isEmpty),
|
||||||
|
for (var i = 0; i < crumbs.length; i++) ...[
|
||||||
|
AppText(' / ', style: TextStyle(color: theme.hintColor)),
|
||||||
|
_crumb(theme, crumbs[i], () => _goToCrumb(i),
|
||||||
|
last: i == crumbs.length - 1),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
|
if (preview) ...[
|
||||||
|
if (_previewText != null)
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(_editing
|
||||||
|
? Icons.visibility_outlined
|
||||||
|
: Icons.edit_outlined),
|
||||||
|
tooltip: _editing ? tr('Preview') : tr('Edit'),
|
||||||
|
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: tr('Save'),
|
||||||
|
onPressed: _saving ? null : _save,
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.download_outlined),
|
||||||
|
tooltip: tr('Download'),
|
||||||
|
onPressed: _download,
|
||||||
|
),
|
||||||
|
] else if (_root.isNotEmpty) ...[
|
||||||
|
PopupMenuButton<bool>(
|
||||||
|
icon: const Icon(Icons.add),
|
||||||
|
tooltip: tr('New'),
|
||||||
|
onSelected: (directory) => _newEntry(directory: directory),
|
||||||
|
itemBuilder: (_) => const [
|
||||||
|
PopupMenuItem(value: false, child: AppText('New file')),
|
||||||
|
PopupMenuItem(value: true, child: AppText('New folder')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
PopupMenuButton<String>(
|
||||||
|
icon: const Icon(Icons.more_horiz),
|
||||||
|
tooltip: tr('More'),
|
||||||
|
onSelected: (value) {
|
||||||
|
if (value == 'ignored') {
|
||||||
|
widget.app.setShowGitignored(!widget.app.showGitignored);
|
||||||
|
} else if (value == 'refresh') {
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
itemBuilder: (_) => [
|
||||||
|
CheckedPopupMenuItem(
|
||||||
|
value: 'ignored',
|
||||||
|
checked: widget.app.showGitignored,
|
||||||
|
child: const AppText('Show git-ignored files'),
|
||||||
|
),
|
||||||
|
const PopupMenuItem(
|
||||||
|
value: 'refresh',
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.refresh, size: 18),
|
||||||
|
SizedBox(width: 10),
|
||||||
|
AppText('Refresh'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -676,7 +734,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
children: [
|
children: [
|
||||||
Text(_error!, textAlign: TextAlign.center),
|
Text(_error!, textAlign: TextAlign.center),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextButton(onPressed: () => _load(), child: const Text('重试')),
|
TextButton(onPressed: () => _load(), child: const AppText('Retry')),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -690,7 +748,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
.toList();
|
.toList();
|
||||||
if (filtered.isEmpty && _deepResults.isEmpty) {
|
if (filtered.isEmpty && _deepResults.isEmpty) {
|
||||||
return Center(
|
return Center(
|
||||||
child: Text(_query.trim().isEmpty ? '目录为空' : '没有匹配的文件',
|
child: AppText(_query.trim().isEmpty ? 'Directory is empty' : 'No matching files',
|
||||||
style: TextStyle(color: theme.hintColor)),
|
style: TextStyle(color: theme.hintColor)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -701,7 +759,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
if (_query.trim().isNotEmpty && _deepResults.isNotEmpty) ...[
|
if (_query.trim().isNotEmpty && _deepResults.isNotEmpty) ...[
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
||||||
child: Text('子目录结果',
|
child: AppText('Subdirectory results',
|
||||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
),
|
),
|
||||||
for (final e in _deepResults) _tile(theme, e, showPath: true),
|
for (final e in _deepResults) _tile(theme, e, showPath: true),
|
||||||
@@ -713,7 +771,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
filtered.isNotEmpty)
|
filtered.isNotEmpty)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
|
||||||
child: Text('子目录里没有匹配的文件',
|
child: AppText('No matching files in subdirectories',
|
||||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -773,7 +831,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
Text(_previewError!, textAlign: TextAlign.center),
|
Text(_previewError!, textAlign: TextAlign.center),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
if (_previewBytes != null || _previewError != null)
|
if (_previewBytes != null || _previewError != null)
|
||||||
TextButton(onPressed: _download, child: const Text('下载')),
|
TextButton(onPressed: _download, child: const AppText('Download')),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -795,7 +853,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
Icon(Icons.insert_drive_file_outlined,
|
Icon(Icons.insert_drive_file_outlined,
|
||||||
size: 40, color: theme.hintColor),
|
size: 40, color: theme.hintColor),
|
||||||
const SizedBox(height: 10),
|
const SizedBox(height: 10),
|
||||||
Text('这个文件无法预览',
|
AppText('This file cannot be previewed',
|
||||||
style: TextStyle(color: theme.hintColor)),
|
style: TextStyle(color: theme.hintColor)),
|
||||||
const SizedBox(height: 6),
|
const SizedBox(height: 6),
|
||||||
Text(_fmtSize(_previewBytes?.length ?? 0),
|
Text(_fmtSize(_previewBytes?.length ?? 0),
|
||||||
@@ -804,7 +862,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
OutlinedButton.icon(
|
OutlinedButton.icon(
|
||||||
onPressed: _download,
|
onPressed: _download,
|
||||||
icon: const Icon(Icons.download_outlined, size: 18),
|
icon: const Icon(Icons.download_outlined, size: 18),
|
||||||
label: const Text('下载'),
|
label: const AppText('Download'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -816,6 +874,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
child: TextField(
|
child: TextField(
|
||||||
controller: _editor,
|
controller: _editor,
|
||||||
maxLines: null,
|
maxLines: null,
|
||||||
|
minLines: null,
|
||||||
expands: true,
|
expands: true,
|
||||||
style: const TextStyle(fontSize: 13, fontFamily: 'monospace', height: 1.4),
|
style: const TextStyle(fontSize: 13, fontFamily: 'monospace', height: 1.4),
|
||||||
textAlignVertical: TextAlignVertical.top,
|
textAlignVertical: TextAlignVertical.top,
|
||||||
@@ -935,3 +994,129 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Streams one download and shows its progress; 取消 aborts the request and
|
||||||
|
/// the dialog closes with no bytes, so nothing is saved.
|
||||||
|
class _DownloadDialog extends StatefulWidget {
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
/// The file's size from `fs/stat`; the progress bar is determinate against
|
||||||
|
/// it from the first byte when the response has no Content-Length.
|
||||||
|
final int? expectedSize;
|
||||||
|
final Future<Uint8List> Function(
|
||||||
|
void Function(int received, int? total) onProgress,
|
||||||
|
CancelToken cancel) start;
|
||||||
|
|
||||||
|
const _DownloadDialog(
|
||||||
|
{required this.name, this.expectedSize, required this.start});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_DownloadDialog> createState() => _DownloadDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DownloadDialogState extends State<_DownloadDialog> {
|
||||||
|
final CancelToken _cancel = CancelToken();
|
||||||
|
int _received = 0;
|
||||||
|
int? _total;
|
||||||
|
bool _cancelling = false;
|
||||||
|
String? _error;
|
||||||
|
int _lastPaint = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_total = (widget.expectedSize ?? 0) > 0 ? widget.expectedSize : null;
|
||||||
|
_run();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _run() async {
|
||||||
|
try {
|
||||||
|
final bytes = await widget.start((received, total) {
|
||||||
|
if (!mounted) return;
|
||||||
|
// The server's own total is more accurate than the stat we started
|
||||||
|
// with; keep the latter when the response is chunked.
|
||||||
|
if (total != null) _total = total;
|
||||||
|
// Chunks arrive every few dozen KB; repaint a few times a second at
|
||||||
|
// most, and always on the last one.
|
||||||
|
final now = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
final known = _total;
|
||||||
|
if (known != null && received < known && now - _lastPaint < 80) return;
|
||||||
|
_lastPaint = now;
|
||||||
|
setState(() {
|
||||||
|
_received = received;
|
||||||
|
});
|
||||||
|
}, _cancel);
|
||||||
|
if (mounted) Navigator.of(context).pop(bytes);
|
||||||
|
} on DownloadCancelled {
|
||||||
|
if (mounted) Navigator.of(context).pop();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _error = error is ApiError ? error.message : '$error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _size(int bytes) {
|
||||||
|
if (bytes < 1024) return '$bytes B';
|
||||||
|
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
|
||||||
|
return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final total = _total;
|
||||||
|
final fraction = total != null && total > 0
|
||||||
|
? (_received / total).clamp(0.0, 1.0)
|
||||||
|
: null;
|
||||||
|
return AlertDialog(
|
||||||
|
title: const AppText('Downloading'),
|
||||||
|
content: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(widget.name,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(fontSize: 13)),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
if (_error == null) ...[
|
||||||
|
LinearProgressIndicator(value: fraction),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
AppText(
|
||||||
|
total != null
|
||||||
|
? trArgs('{0} / {1} ({2}%)', [
|
||||||
|
_size(_received),
|
||||||
|
_size(total),
|
||||||
|
// Below 10% one decimal says the transfer is moving;
|
||||||
|
// whole numbers are enough above it.
|
||||||
|
(fraction! * 100).toStringAsFixed(fraction < 0.1 ? 1 : 0),
|
||||||
|
])
|
||||||
|
: trArgs('Downloaded {0}', [_size(_received)]),
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
] else
|
||||||
|
Text(_error!,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 12.5, color: theme.colorScheme.error)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
if (_error == null)
|
||||||
|
TextButton(
|
||||||
|
onPressed: _cancelling
|
||||||
|
? null
|
||||||
|
: () {
|
||||||
|
setState(() => _cancelling = true);
|
||||||
|
_cancel.cancel();
|
||||||
|
},
|
||||||
|
child: AppText(_cancelling ? 'Canceling…' : 'Cancel'),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: const AppText('Close'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
// The connected shell. A phone treats the session list as the left drawer and
|
||||||
|
// the chat as the screen; a wide layout shows both side by side, which is
|
||||||
|
// where a tablet or a desktop window lands.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../state.dart';
|
||||||
|
import 'chat_screen.dart';
|
||||||
|
import 'new_session_screen.dart';
|
||||||
|
import 'sessions_screen.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
class HomeScreen extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
const HomeScreen({super.key, required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<HomeScreen> createState() => _HomeScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HomeScreenState extends State<HomeScreen> {
|
||||||
|
final GlobalKey<ScaffoldState> _scaffold = GlobalKey();
|
||||||
|
bool _opening = false;
|
||||||
|
|
||||||
|
static const _wideBreakpoint = 840.0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.app.addListener(_maybeOpenFirst);
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) => _maybeOpenFirst());
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
widget.app.removeListener(_maybeOpenFirst);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like the first-party client, a phone lands in a conversation rather than
|
||||||
|
/// on an empty pane: open the newest one when nothing is open yet.
|
||||||
|
void _maybeOpenFirst() {
|
||||||
|
final app = widget.app;
|
||||||
|
if (!mounted || _opening) return;
|
||||||
|
if (app.draftOpen) return;
|
||||||
|
if (app.chat != null || app.sessions.isEmpty) return;
|
||||||
|
_opening = true;
|
||||||
|
app.openChat(app.sessions.first).whenComplete(() => _opening = false);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _closeDrawer() {
|
||||||
|
_scaffold.currentState?.closeDrawer();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
// Read above the shell's Scaffold: its body has the bottom inset removed.
|
||||||
|
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: widget.app,
|
||||||
|
builder: (context, _) {
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final wide = constraints.maxWidth >= _wideBreakpoint;
|
||||||
|
final app = widget.app;
|
||||||
|
final chat = app.chat;
|
||||||
|
final draftOpen = app.draftOpen && app.draft != null;
|
||||||
|
final content = draftOpen
|
||||||
|
? NewSessionScreen(
|
||||||
|
key: const ValueKey('draft'),
|
||||||
|
app: app,
|
||||||
|
keyboardInset: keyboardInset,
|
||||||
|
onOpenSessions: wide
|
||||||
|
? null
|
||||||
|
: () => _scaffold.currentState?.openDrawer(),
|
||||||
|
)
|
||||||
|
: chat == null
|
||||||
|
? _empty(wide)
|
||||||
|
: ChatScreen(
|
||||||
|
key: ValueKey(chat.session.id),
|
||||||
|
app: app,
|
||||||
|
session: chat.session,
|
||||||
|
keyboardInset: keyboardInset,
|
||||||
|
onOpenSessions: wide
|
||||||
|
? null
|
||||||
|
: () => _scaffold.currentState?.openDrawer(),
|
||||||
|
);
|
||||||
|
if (wide) {
|
||||||
|
return Scaffold(
|
||||||
|
body: Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 320,
|
||||||
|
child: SessionListPane(app: widget.app),
|
||||||
|
),
|
||||||
|
const VerticalDivider(width: 1),
|
||||||
|
Expanded(child: content),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Scaffold(
|
||||||
|
key: _scaffold,
|
||||||
|
drawer: Drawer(
|
||||||
|
width: constraints.maxWidth * 0.86 > 380
|
||||||
|
? 380
|
||||||
|
: constraints.maxWidth * 0.86,
|
||||||
|
child: SessionListPane(
|
||||||
|
app: widget.app,
|
||||||
|
onOpened: _closeDrawer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
body: content,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _empty(bool wide) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
return Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(32),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.forum_outlined, size: 40, color: scheme.onSurfaceVariant),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
AppText('Choose a session',
|
||||||
|
style: TextStyle(fontSize: 16, color: scheme.onSurfaceVariant)),
|
||||||
|
if (!wide) ...[
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => _scaffold.currentState?.openDrawer(),
|
||||||
|
child: const AppText('Open the session list'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,479 @@
|
|||||||
|
// The new-session draft. Nothing exists on the server until the first message
|
||||||
|
// creates the session; this screen only holds the project, the model and what
|
||||||
|
// has been typed.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../state.dart';
|
||||||
|
import '../widgets/composer_attachment.dart';
|
||||||
|
import '../widgets/composer_box.dart';
|
||||||
|
import '../widgets/model_controls.dart';
|
||||||
|
import '../widgets/pet_sprite.dart';
|
||||||
|
import '../widgets/project_icon.dart';
|
||||||
|
import '../widgets/project_picker.dart';
|
||||||
|
import '../widgets/slash_palette.dart';
|
||||||
|
import 'files_panel.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
class NewSessionScreen extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
|
||||||
|
/// Opens the session drawer; null where the list is always on screen.
|
||||||
|
final VoidCallback? onOpenSessions;
|
||||||
|
|
||||||
|
/// The soft keyboard's height, from above the shell's Scaffold.
|
||||||
|
final double keyboardInset;
|
||||||
|
|
||||||
|
const NewSessionScreen({
|
||||||
|
super.key,
|
||||||
|
required this.app,
|
||||||
|
this.onOpenSessions,
|
||||||
|
this.keyboardInset = 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<NewSessionScreen> createState() => _NewSessionScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _NewSessionScreenState extends State<NewSessionScreen> {
|
||||||
|
SessionDraft get _draft => widget.app.draft!;
|
||||||
|
final TextEditingController _text = TextEditingController();
|
||||||
|
final FocusNode _inputFocus = FocusNode();
|
||||||
|
List<ComposerAttachment> _attachments = [];
|
||||||
|
bool _attaching = false;
|
||||||
|
|
||||||
|
/// The `/` palette for the draft's directory. It carries commands and
|
||||||
|
/// skills, not the client-local `compact` that needs an existing session.
|
||||||
|
List<SlashItem> _slashItems = [];
|
||||||
|
bool _slashLoading = false;
|
||||||
|
bool _slashLoaded = false;
|
||||||
|
int _slashIndex = 0;
|
||||||
|
String? _slashDismissed;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_text.text = _draft.text;
|
||||||
|
_text.addListener(_syncText);
|
||||||
|
_attachments = [];
|
||||||
|
_draft.attachments = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_text.removeListener(_syncText);
|
||||||
|
_text.dispose();
|
||||||
|
_inputFocus.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _syncText() {
|
||||||
|
if (_draft.text == _text.text) return;
|
||||||
|
widget.app.updateDraftText(_text.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get _canSend =>
|
||||||
|
_text.text.trim().isNotEmpty || _attachments.isNotEmpty;
|
||||||
|
|
||||||
|
List<SlashItem>? _slashMatches() => matchSlashItems(
|
||||||
|
items: _slashItems,
|
||||||
|
text: _text.text,
|
||||||
|
dismissed: _slashDismissed,
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<void> _ensureSlash() async {
|
||||||
|
if (_slashLoaded || _slashLoading) return;
|
||||||
|
_slashLoading = true;
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
try {
|
||||||
|
_slashItems = await widget.app.slashItemsFor(_draft.directory,
|
||||||
|
includeLocal: false);
|
||||||
|
_slashLoaded = true;
|
||||||
|
} catch (_) {
|
||||||
|
// An empty palette; a send falls back to a plain prompt.
|
||||||
|
}
|
||||||
|
_slashLoading = false;
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _moveSlash(List<SlashItem> items, int delta) {
|
||||||
|
if (items.isEmpty) return;
|
||||||
|
setState(() {
|
||||||
|
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _dismissSlash() => setState(() => _slashDismissed = _text.text);
|
||||||
|
|
||||||
|
/// A row was picked: no-argument commands run at once (creating the session
|
||||||
|
/// on the spot), the rest complete the name and wait for arguments.
|
||||||
|
void _pickSlash(SlashItem item) {
|
||||||
|
HapticFeedback.selectionClick();
|
||||||
|
final text = _text.text;
|
||||||
|
final lead = text.length - text.trimLeft().length;
|
||||||
|
final rest = text.trimLeft();
|
||||||
|
final match = RegExp(r'\s').firstMatch(rest);
|
||||||
|
final suffix = match == null ? '' : rest.substring(match.start);
|
||||||
|
final completes = item.skill || item.takesArgs;
|
||||||
|
if (!completes) {
|
||||||
|
final command = '/${item.name}';
|
||||||
|
_text.value = TextEditingValue(
|
||||||
|
text: command,
|
||||||
|
selection: TextSelection.collapsed(offset: command.length),
|
||||||
|
);
|
||||||
|
widget.app.updateDraftText(command);
|
||||||
|
setState(() {});
|
||||||
|
_send();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final prefix = '${text.substring(0, lead)}/${item.name}';
|
||||||
|
final separator =
|
||||||
|
suffix.isEmpty || !RegExp(r'^\s').hasMatch(suffix) ? ' ' : '';
|
||||||
|
final next = '$prefix$separator$suffix';
|
||||||
|
_text.value = TextEditingValue(
|
||||||
|
text: next,
|
||||||
|
selection: TextSelection.collapsed(offset: prefix.length + 1),
|
||||||
|
);
|
||||||
|
widget.app.updateDraftText(next);
|
||||||
|
_inputFocus.requestFocus();
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _send() async {
|
||||||
|
if (!_canSend || widget.app.sendingDraft) return;
|
||||||
|
final text = _text.text.trim();
|
||||||
|
final files = [
|
||||||
|
for (final a in _attachments) {'uri': a.dataUrl, 'name': a.name}
|
||||||
|
];
|
||||||
|
final images = [
|
||||||
|
for (final a in _attachments)
|
||||||
|
if (a.isImage && a.path != null) a.path!
|
||||||
|
];
|
||||||
|
FocusScope.of(context).unfocus();
|
||||||
|
await widget.app.sendDraft(text: text, files: files, images: images);
|
||||||
|
if (!mounted) return;
|
||||||
|
final draft = widget.app.draft;
|
||||||
|
if (draft != null) {
|
||||||
|
// The create failed: the draft is still here, keep what was typed.
|
||||||
|
_text.text = draft.text;
|
||||||
|
} else {
|
||||||
|
HapticFeedback.lightImpact();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickFiles() async {
|
||||||
|
setState(() => _attaching = true);
|
||||||
|
try {
|
||||||
|
final picked = await pickComposerAttachments(context);
|
||||||
|
if (picked.isEmpty) return;
|
||||||
|
setState(() {
|
||||||
|
for (final file in picked) {
|
||||||
|
if (_attachments.length >= 5) break;
|
||||||
|
_attachments.add(file);
|
||||||
|
}
|
||||||
|
_draft.attachments = _attachments.length;
|
||||||
|
});
|
||||||
|
widget.app.touch();
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context)
|
||||||
|
.showSnackBar(SnackBar(content: AppText(trArgs('Could not attach: {0}', [e]))));
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _attaching = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _removeAttachment(int index) {
|
||||||
|
setState(() {
|
||||||
|
_attachments.removeAt(index);
|
||||||
|
_draft.attachments = _attachments.length;
|
||||||
|
});
|
||||||
|
widget.app.touch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final app = widget.app;
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: app,
|
||||||
|
builder: (context, _) {
|
||||||
|
final draft = app.draft;
|
||||||
|
if (draft == null) return const SizedBox.shrink();
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
leading: widget.onOpenSessions == null
|
||||||
|
? null
|
||||||
|
: IconButton(
|
||||||
|
icon: const Icon(Icons.menu),
|
||||||
|
tooltip: tr('Sessions'),
|
||||||
|
onPressed: widget.onOpenSessions,
|
||||||
|
),
|
||||||
|
title: const AppText('New session'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.folder_open_outlined),
|
||||||
|
tooltip: tr('Files'),
|
||||||
|
onPressed: () => showFilesPanel(context, app, draft.directory),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: Column(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Stack(
|
||||||
|
children: [
|
||||||
|
Positioned.fill(
|
||||||
|
child: Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(32),
|
||||||
|
child: AppText(
|
||||||
|
'What are we building today?',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 26,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: scheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Positioned.fill(child: PetLayer(state: 'idle')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (draft.error != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
|
child: Text(
|
||||||
|
draft.error!,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5, color: scheme.error),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: _projectChip(draft),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
if (_attachments.isNotEmpty)
|
||||||
|
AttachmentTray(
|
||||||
|
items: _attachments,
|
||||||
|
onRemove: _removeAttachment,
|
||||||
|
),
|
||||||
|
_composer(theme, widget.keyboardInset),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _projectChip(SessionDraft draft) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final isChat = draft.directory == AppState.chatTarget;
|
||||||
|
final label = widget.app.projectLabelFor(draft.directory);
|
||||||
|
return InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(18),
|
||||||
|
onTap: _pickProject,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
ProjectIcon(
|
||||||
|
app: widget.app,
|
||||||
|
project: isChat ? null : widget.app.projectFor(draft.directory),
|
||||||
|
chat: isChat,
|
||||||
|
size: 15,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 5),
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 170),
|
||||||
|
child: Text(
|
||||||
|
label.isEmpty ? tr('Choose project') : label,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(Icons.expand_more, size: 16, color: theme.hintColor),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _composer(ThemeData theme, double keyboardInset) {
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
final sending = widget.app.sendingDraft;
|
||||||
|
final slash = _slashMatches();
|
||||||
|
final slashRows = slash ?? const <SlashItem>[];
|
||||||
|
Widget body = ComposerBox(
|
||||||
|
controller: _text,
|
||||||
|
focusNode: _inputFocus,
|
||||||
|
hint: tr('Plan, build, or ask'),
|
||||||
|
maxLines: 5,
|
||||||
|
keyboardInset: keyboardInset,
|
||||||
|
textInputAction:
|
||||||
|
slash != null ? TextInputAction.send : TextInputAction.newline,
|
||||||
|
onSubmitted: slash == null || slashRows.isEmpty
|
||||||
|
? null
|
||||||
|
: (_) => _pickSlash(
|
||||||
|
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
|
||||||
|
onChanged: (v) {
|
||||||
|
widget.app.updateDraftText(v);
|
||||||
|
_slashIndex = 0;
|
||||||
|
if (_slashDismissed != null && v != _slashDismissed) {
|
||||||
|
_slashDismissed = null;
|
||||||
|
}
|
||||||
|
if (v.trimLeft().startsWith('/')) _ensureSlash();
|
||||||
|
setState(() {});
|
||||||
|
if (slash != null && v.endsWith('\n')) {
|
||||||
|
final trimmed = v.trimRight();
|
||||||
|
_text.value = TextEditingValue(
|
||||||
|
text: trimmed,
|
||||||
|
selection: TextSelection.collapsed(offset: trimmed.length),
|
||||||
|
);
|
||||||
|
widget.app.updateDraftText(trimmed);
|
||||||
|
final rows = _slashMatches() ?? const <SlashItem>[];
|
||||||
|
if (rows.isNotEmpty) {
|
||||||
|
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
leading: _roundKey(
|
||||||
|
icon: Icons.attach_file,
|
||||||
|
label: tr('Add attachment'),
|
||||||
|
onTap: _pickFiles,
|
||||||
|
busy: _attaching,
|
||||||
|
),
|
||||||
|
model: ModelPill(
|
||||||
|
app: widget.app,
|
||||||
|
model: _draft.model,
|
||||||
|
onModel: (m) => widget.app.updateDraftModel(m),
|
||||||
|
),
|
||||||
|
mode: ModeChip(
|
||||||
|
app: widget.app,
|
||||||
|
agent: _draft.agent,
|
||||||
|
onAgent: (a) => widget.app.updateDraftModel(null, agent: a),
|
||||||
|
),
|
||||||
|
trailing: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(18),
|
||||||
|
onTap: sending || !_canSend ? null : _send,
|
||||||
|
child: Container(
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: _canSend || sending ? scheme.primary : scheme.surface,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: sending
|
||||||
|
? SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: scheme.onPrimary))
|
||||||
|
: Icon(Icons.arrow_upward,
|
||||||
|
size: 20,
|
||||||
|
color: _canSend ? scheme.onPrimary : theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (slash != null) ...[
|
||||||
|
KeyedSubtree(
|
||||||
|
key: const ValueKey('draft-slash-palette'),
|
||||||
|
child: SlashPalette(
|
||||||
|
items: slashRows,
|
||||||
|
index: _slashIndex,
|
||||||
|
loading: _slashLoading,
|
||||||
|
onPick: _pickSlash,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
],
|
||||||
|
CallbackShortcuts(
|
||||||
|
bindings: slash == null
|
||||||
|
? const {}
|
||||||
|
: {
|
||||||
|
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
|
||||||
|
_moveSlash(slashRows, 1),
|
||||||
|
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
|
||||||
|
_moveSlash(slashRows, -1),
|
||||||
|
const SingleActivator(LogicalKeyboardKey.enter): () =>
|
||||||
|
_pickSlash(slashRows[
|
||||||
|
_slashIndex.clamp(0, slashRows.length - 1)]),
|
||||||
|
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
|
||||||
|
_pickSlash(slashRows[
|
||||||
|
_slashIndex.clamp(0, slashRows.length - 1)]),
|
||||||
|
const SingleActivator(LogicalKeyboardKey.escape):
|
||||||
|
_dismissSlash,
|
||||||
|
},
|
||||||
|
child: body,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _roundKey(
|
||||||
|
{required IconData icon,
|
||||||
|
required String label,
|
||||||
|
required VoidCallback onTap,
|
||||||
|
bool busy = false}) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Tooltip(
|
||||||
|
message: label,
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(18),
|
||||||
|
onTap: busy ? null : onTap,
|
||||||
|
child: Container(
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surface,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: busy
|
||||||
|
? const SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2))
|
||||||
|
: Icon(icon, size: 19, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickProject() async {
|
||||||
|
final app = widget.app;
|
||||||
|
final draft = app.draft;
|
||||||
|
if (draft == null) return;
|
||||||
|
// The sheet opens right away; it refreshes the project list inside.
|
||||||
|
final choice = await showProjectPicker(
|
||||||
|
context,
|
||||||
|
app: app,
|
||||||
|
selected: draft.directory,
|
||||||
|
);
|
||||||
|
if (choice == null || !mounted) return;
|
||||||
|
app.updateDraftTarget(choice.canonical);
|
||||||
|
_slashLoaded = false;
|
||||||
|
_slashItems = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
// Scans the QR code a pairing link is shown as in OpenChamber's "connect a
|
||||||
|
// device" dialog. The camera stream's Y plane goes to zxing2 in a background
|
||||||
|
// isolate; only a decoded `openchamber://connect` link ends the scan.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:camera/camera.dart';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../api/qr_scan.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// Opens the scanner and returns the pairing link, or null when cancelled.
|
||||||
|
Future<String?> scanPairingQr(BuildContext context) {
|
||||||
|
return Navigator.of(context).push<String>(MaterialPageRoute(
|
||||||
|
fullscreenDialog: true,
|
||||||
|
builder: (_) => const ScanQrScreen(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
class ScanQrScreen extends StatefulWidget {
|
||||||
|
const ScanQrScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ScanQrScreen> createState() => _ScanQrScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ScanQrScreenState extends State<ScanQrScreen> {
|
||||||
|
CameraController? _controller;
|
||||||
|
String? _error;
|
||||||
|
String? _hint;
|
||||||
|
bool _decoding = false;
|
||||||
|
bool _found = false;
|
||||||
|
bool _torch = false;
|
||||||
|
Timer? _hintTimer;
|
||||||
|
Timer? _watchdog;
|
||||||
|
Timer? _slowHint;
|
||||||
|
|
||||||
|
/// Frame diagnostics: a scanner that silently does nothing is impossible to
|
||||||
|
/// tell apart from a camera that sends no frames without these.
|
||||||
|
int _frames = 0;
|
||||||
|
int _decodeAttempts = 0;
|
||||||
|
int _decodeErrors = 0;
|
||||||
|
bool _loggedFrame = false;
|
||||||
|
String? _frameShape;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_hintTimer?.cancel();
|
||||||
|
_watchdog?.cancel();
|
||||||
|
_slowHint?.cancel();
|
||||||
|
_closeCamera();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _closeCamera() {
|
||||||
|
final controller = _controller;
|
||||||
|
_controller = null;
|
||||||
|
if (controller == null) return;
|
||||||
|
controller.stopImageStream().catchError((_) {});
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _start() async {
|
||||||
|
_closeCamera();
|
||||||
|
_watchdog?.cancel();
|
||||||
|
_hintTimer?.cancel();
|
||||||
|
_slowHint?.cancel();
|
||||||
|
_frames = 0;
|
||||||
|
_decodeAttempts = 0;
|
||||||
|
_decodeErrors = 0;
|
||||||
|
_loggedFrame = false;
|
||||||
|
_frameShape = null;
|
||||||
|
setState(() {
|
||||||
|
_error = null;
|
||||||
|
_hint = null;
|
||||||
|
_found = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
final List<CameraDescription> cameras;
|
||||||
|
try {
|
||||||
|
cameras = await availableCameras();
|
||||||
|
} on CameraException catch (error) {
|
||||||
|
if (mounted) setState(() => _error = _cameraError(error));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (cameras.isEmpty) {
|
||||||
|
if (mounted) setState(() => _error = tr('No camera available'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CameraDescription pick = cameras.first;
|
||||||
|
for (final camera in cameras) {
|
||||||
|
if (camera.lensDirection == CameraLensDirection.back) {
|
||||||
|
pick = camera;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A dense pairing QR needs pixels: 720p first, then 480p for cameras or
|
||||||
|
// devices that refuse the higher analysis size.
|
||||||
|
Object? lastError;
|
||||||
|
for (final preset in const [ResolutionPreset.high, ResolutionPreset.medium]) {
|
||||||
|
final controller = CameraController(
|
||||||
|
pick,
|
||||||
|
preset,
|
||||||
|
enableAudio: false,
|
||||||
|
imageFormatGroup: ImageFormatGroup.yuv420,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
await controller.initialize();
|
||||||
|
if (!mounted) {
|
||||||
|
await controller.dispose();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() => _controller = controller);
|
||||||
|
await controller.startImageStream(_onFrame);
|
||||||
|
_watchdog = Timer(const Duration(seconds: 4), () {
|
||||||
|
if (!mounted || _frames > 0 || _error != null) return;
|
||||||
|
setState(() => _hint = tr('No camera frames received; close and try again'));
|
||||||
|
});
|
||||||
|
_slowHint = Timer(const Duration(seconds: 12), () {
|
||||||
|
if (!mounted || _found || _frames == 0) return;
|
||||||
|
_showHint(tr('No QR code yet; move closer or fill the frame with the code'),
|
||||||
|
sticky: true);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
try {
|
||||||
|
await controller.stopImageStream();
|
||||||
|
} catch (_) {}
|
||||||
|
try {
|
||||||
|
await controller.dispose();
|
||||||
|
} catch (_) {}
|
||||||
|
if (mounted && _controller == controller) {
|
||||||
|
setState(() => _controller = null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mounted) setState(() => _error = _cameraError(lastError));
|
||||||
|
}
|
||||||
|
|
||||||
|
String _cameraError(Object? error) {
|
||||||
|
if (error is CameraException) {
|
||||||
|
if (error.code == 'CameraAccessDenied' ||
|
||||||
|
error.code == 'CameraAccessDeniedWithoutPrompt' ||
|
||||||
|
error.code == 'CameraAccessRestricted') {
|
||||||
|
return tr('Camera permission is required to scan. Allow OpenChamber to use the camera in system settings.');
|
||||||
|
}
|
||||||
|
return trArgs('Could not open the camera: {0}', [error.description ?? error.code]);
|
||||||
|
}
|
||||||
|
return trArgs('Could not open the camera: {0}', [error]);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onFrame(CameraImage image) {
|
||||||
|
_frames += 1;
|
||||||
|
if (!_loggedFrame && image.planes.isNotEmpty) {
|
||||||
|
_loggedFrame = true;
|
||||||
|
final plane = image.planes.first;
|
||||||
|
_frameShape =
|
||||||
|
'${image.width}×${image.height} ${image.format.group.name}';
|
||||||
|
debugPrint('qr: frame ${image.width}x${image.height} '
|
||||||
|
'${image.format.group.name} planes=${image.planes.length} '
|
||||||
|
'row=${plane.bytesPerRow} pixel=${plane.bytesPerPixel} '
|
||||||
|
'bytes=${plane.bytes.length}');
|
||||||
|
}
|
||||||
|
if (mounted && _frames % 10 == 0) {
|
||||||
|
// Refresh the small diagnostics line without rebuilding 30x a second.
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
if (_decoding || _found || !mounted) return;
|
||||||
|
final frame = _frameOf(image);
|
||||||
|
if (frame == null) return;
|
||||||
|
_decoding = true;
|
||||||
|
_decodeAttempts += 1;
|
||||||
|
// Decoding off the UI thread: frames arrive at 30/s and a decode is not
|
||||||
|
// free, so only one is in flight at a time.
|
||||||
|
compute(decodeQrFrame, frame).then((text) {
|
||||||
|
_decoding = false;
|
||||||
|
if (!mounted || text == null || _found) return;
|
||||||
|
if (text.trim().startsWith('openchamber://connect')) {
|
||||||
|
_accept(text.trim());
|
||||||
|
} else {
|
||||||
|
_showHint(tr('This is not an OpenChamber pairing QR code'));
|
||||||
|
}
|
||||||
|
}).catchError((Object error) {
|
||||||
|
_decoding = false;
|
||||||
|
_decodeErrors += 1;
|
||||||
|
if (_decodeErrors == 1) {
|
||||||
|
debugPrint('qr: decode failed: $error');
|
||||||
|
if (mounted) _showHint(tr('Could not decode the QR code; try again'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
QrFrame? _frameOf(CameraImage image) {
|
||||||
|
if (image.planes.isEmpty) return null;
|
||||||
|
final plane = image.planes.first;
|
||||||
|
final group = image.format.group;
|
||||||
|
if (group == ImageFormatGroup.bgra8888) {
|
||||||
|
// The packed BGRA plane is not luminance yet.
|
||||||
|
final luminance = bgraToLuminance(
|
||||||
|
plane.bytes, image.width, image.height, plane.bytesPerRow);
|
||||||
|
return QrFrame(
|
||||||
|
luminance: luminance,
|
||||||
|
width: image.width,
|
||||||
|
height: image.height,
|
||||||
|
rowStride: image.width,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return QrFrame(
|
||||||
|
luminance: plane.bytes,
|
||||||
|
width: image.width,
|
||||||
|
height: image.height,
|
||||||
|
rowStride: plane.bytesPerRow,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showHint(String text, {bool sticky = false}) {
|
||||||
|
_hintTimer?.cancel();
|
||||||
|
if (mounted) setState(() => _hint = text);
|
||||||
|
if (sticky) return;
|
||||||
|
_hintTimer = Timer(const Duration(seconds: 2), () {
|
||||||
|
if (mounted) setState(() => _hint = null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _accept(String text) async {
|
||||||
|
_found = true;
|
||||||
|
HapticFeedback.mediumImpact();
|
||||||
|
try {
|
||||||
|
await _controller?.stopImageStream();
|
||||||
|
} catch (_) {}
|
||||||
|
if (mounted) Navigator.of(context).pop(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _toggleTorch() async {
|
||||||
|
final controller = _controller;
|
||||||
|
if (controller == null) return;
|
||||||
|
try {
|
||||||
|
await controller.setFlashMode(_torch ? FlashMode.off : FlashMode.torch);
|
||||||
|
if (mounted) setState(() => _torch = !_torch);
|
||||||
|
} catch (_) {
|
||||||
|
if (mounted) _showHint(tr('This camera does not support the flashlight'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final controller = _controller;
|
||||||
|
final ready =
|
||||||
|
controller != null && controller.value.isInitialized && _error == null;
|
||||||
|
return Scaffold(
|
||||||
|
backgroundColor: Colors.black,
|
||||||
|
body: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: [
|
||||||
|
if (ready)
|
||||||
|
Center(child: CameraPreview(controller))
|
||||||
|
else if (_error != null)
|
||||||
|
Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(28),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
const Icon(Icons.no_photography_outlined,
|
||||||
|
size: 36, color: Colors.white70),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Text(_error!,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: const TextStyle(color: Colors.white70)),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
FilledButton.tonal(
|
||||||
|
onPressed: _start,
|
||||||
|
child: const AppText('Retry'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
const Center(child: CircularProgressIndicator()),
|
||||||
|
if (ready) const IgnorePointer(child: CustomPaint(painter: _ScanOverlay())),
|
||||||
|
SafeArea(
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: tr('Close'),
|
||||||
|
icon: const Icon(Icons.close),
|
||||||
|
color: Colors.white,
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
tooltip: tr('Flashlight'),
|
||||||
|
icon: Icon(_torch ? Icons.flash_on : Icons.flash_off),
|
||||||
|
color: Colors.white,
|
||||||
|
onPressed: _toggleTorch,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(24, 0, 24, 32),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
_hint ?? tr('Put the pairing QR code inside the frame'),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: const TextStyle(color: Colors.white, fontSize: 14),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
const AppText(
|
||||||
|
'In the OpenChamber web app, open “Connect a device” and choose the QR code',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(color: Colors.white60, fontSize: 12),
|
||||||
|
),
|
||||||
|
if (ready && _frames > 0)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 8),
|
||||||
|
child: Text(
|
||||||
|
trArgs('{0} · {1} frames scanned / {2} decode attempts',
|
||||||
|
[_frameShape ?? '', _frames, _decodeAttempts]),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white38,
|
||||||
|
fontSize: 11,
|
||||||
|
fontFeatures: [FontFeature.tabularFigures()],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dims everything but the scan square and marks its corners.
|
||||||
|
class _ScanOverlay extends CustomPainter {
|
||||||
|
const _ScanOverlay();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void paint(Canvas canvas, Size size) {
|
||||||
|
final side = math.min(size.width, size.height) * 0.68;
|
||||||
|
final square = Rect.fromCenter(
|
||||||
|
center: Offset(size.width / 2, size.height / 2),
|
||||||
|
width: side,
|
||||||
|
height: side,
|
||||||
|
);
|
||||||
|
final radius = Radius.circular(side * 0.05);
|
||||||
|
final shade = Path()
|
||||||
|
..fillType = PathFillType.evenOdd
|
||||||
|
..addRect(Offset.zero & size)
|
||||||
|
..addRRect(RRect.fromRectAndRadius(square, radius));
|
||||||
|
canvas.drawPath(shade, Paint()..color = const Color(0x99000000));
|
||||||
|
|
||||||
|
final border = Paint()
|
||||||
|
..style = PaintingStyle.stroke
|
||||||
|
..strokeWidth = 2
|
||||||
|
..color = Colors.white.withValues(alpha: 0.85);
|
||||||
|
canvas.drawRRect(RRect.fromRectAndRadius(square, radius), border);
|
||||||
|
|
||||||
|
final corner = Paint()
|
||||||
|
..style = PaintingStyle.stroke
|
||||||
|
..strokeWidth = 4
|
||||||
|
..strokeCap = StrokeCap.round
|
||||||
|
..color = const Color(0xFFC6BFFF);
|
||||||
|
const arm = 28.0;
|
||||||
|
for (final (dx, dy, sx, sy) in [
|
||||||
|
(square.left, square.top, 1.0, 1.0),
|
||||||
|
(square.right, square.top, -1.0, 1.0),
|
||||||
|
(square.left, square.bottom, 1.0, -1.0),
|
||||||
|
(square.right, square.bottom, -1.0, -1.0),
|
||||||
|
]) {
|
||||||
|
canvas.drawLine(Offset(dx, dy), Offset(dx + arm * sx, dy), corner);
|
||||||
|
canvas.drawLine(Offset(dx, dy), Offset(dx, dy + arm * sy), corner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(_ScanOverlay oldDelegate) => false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,503 @@
|
|||||||
|
// 计划任务: the server's scheduled prompts, one project (or the chats scope)
|
||||||
|
// at a time. The list follows the web client: name, schedule, last result,
|
||||||
|
// next run, and the actions it offers — run now, pause, edit, delete.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/client.dart';
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../api/scheduled_tasks.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import '../widgets/project_picker.dart';
|
||||||
|
import '../widgets/scheduled_task_editor.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// Where a task runs: a registered project, or the chats scope.
|
||||||
|
class _TaskScope {
|
||||||
|
final String id;
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// The checkout the tasks run in; empty for the chats scope.
|
||||||
|
final String directory;
|
||||||
|
|
||||||
|
const _TaskScope(this.id, this.label, [this.directory = '']);
|
||||||
|
}
|
||||||
|
|
||||||
|
class ScheduledTasksScreen extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
const ScheduledTasksScreen({super.key, required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ScheduledTasksScreen> createState() => _ScheduledTasksScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ScheduledTasksScreenState extends State<ScheduledTasksScreen> {
|
||||||
|
late final List<_TaskScope> _scopes;
|
||||||
|
late _TaskScope? _scope;
|
||||||
|
List<ScheduledTask> _tasks = const [];
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
String _busyId = '';
|
||||||
|
|
||||||
|
AppState get app => widget.app;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_scopes = _buildScopes();
|
||||||
|
_scope = _defaultScope();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<_TaskScope> _buildScopes() {
|
||||||
|
return [
|
||||||
|
for (final project in selectableProjects(app))
|
||||||
|
_scopeFor(project),
|
||||||
|
_chatsScope,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
static _TaskScope _scopeFor(ProjectInfo project) => _TaskScope(
|
||||||
|
project.metaId.isNotEmpty
|
||||||
|
? project.metaId
|
||||||
|
: Client.projectIdFor(project.canonical),
|
||||||
|
project.label,
|
||||||
|
project.canonical,
|
||||||
|
);
|
||||||
|
|
||||||
|
_TaskScope get _chatsScope =>
|
||||||
|
_TaskScope(Client.scheduledChatsScope, tr('Chat'));
|
||||||
|
|
||||||
|
_TaskScope? _defaultScope() {
|
||||||
|
if (_scopes.isEmpty) return null;
|
||||||
|
final directory = app.directory;
|
||||||
|
if (directory.isNotEmpty) {
|
||||||
|
// A session below the chats root schedules into the chats scope.
|
||||||
|
if (app.isChatDirectory(directory)) return _scopes.last;
|
||||||
|
for (final scope in _scopes) {
|
||||||
|
if (slashPath(scope.directory) == slashPath(directory)) return scope;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return _scopes.first;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
final scope = _scope;
|
||||||
|
final client = app.client;
|
||||||
|
if (scope == null || client == null) {
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_tasks = const [];
|
||||||
|
_error = client == null ? tr('Not connected to a server') : null;
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final tasks = await client.scheduledTasks(scope.id);
|
||||||
|
if (!mounted || _scope?.id != scope.id) return;
|
||||||
|
setState(() {
|
||||||
|
_tasks = tasks;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} on ApiError catch (e) {
|
||||||
|
if (!mounted || _scope?.id != scope.id) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_tasks = const [];
|
||||||
|
_error = e.status == 404
|
||||||
|
? 'The server doesn\'t support scheduled tasks'
|
||||||
|
: trArgs('Couldn\'t load scheduled tasks: {0}', [e.message]);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted || _scope?.id != scope.id) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_tasks = const [];
|
||||||
|
_error = trArgs('Couldn\'t load scheduled tasks: {0}', [e]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _say(String message) {
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context)
|
||||||
|
.showSnackBar(SnackBar(content: AppText(message)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openEditor([ScheduledTask? task]) async {
|
||||||
|
final scope = _scope;
|
||||||
|
if (scope == null) return;
|
||||||
|
await showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
useSafeArea: true,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (_) => ScheduledTaskEditor(
|
||||||
|
app: app,
|
||||||
|
scopeLabel: scope.label,
|
||||||
|
initial: task,
|
||||||
|
onSave: (draft) => _save(scope, draft),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> _save(_TaskScope scope, ScheduledTask draft) async {
|
||||||
|
final client = app.client;
|
||||||
|
if (client == null) {
|
||||||
|
_say(tr('Not connected to a server'));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final tasks = await client.saveScheduledTask(scope.id, draft);
|
||||||
|
if (!mounted) return true;
|
||||||
|
if (_scope?.id == scope.id) setState(() => _tasks = tasks);
|
||||||
|
_say('Scheduled task saved');
|
||||||
|
return true;
|
||||||
|
} on ApiError catch (e) {
|
||||||
|
_say(e.message.isEmpty ? 'Couldn\'t save task' : e.message);
|
||||||
|
return false;
|
||||||
|
} catch (e) {
|
||||||
|
_say(trArgs('Couldn\'t save task: {0}', [e]));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _toggle(ScheduledTask task, bool enabled) async {
|
||||||
|
final scope = _scope;
|
||||||
|
final client = app.client;
|
||||||
|
if (scope == null || client == null || _busyId.isNotEmpty) return;
|
||||||
|
setState(() => _busyId = task.id);
|
||||||
|
try {
|
||||||
|
final tasks =
|
||||||
|
await client.saveScheduledTask(scope.id, task.copyWith(enabled: enabled));
|
||||||
|
if (!mounted) return;
|
||||||
|
if (_scope?.id == scope.id) setState(() => _tasks = tasks);
|
||||||
|
} catch (e) {
|
||||||
|
_say(e is ApiError && e.message.isNotEmpty ? e.message : 'Couldn\'t update task');
|
||||||
|
await _load();
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _busyId = '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _runNow(ScheduledTask task) async {
|
||||||
|
final scope = _scope;
|
||||||
|
final client = app.client;
|
||||||
|
if (scope == null || client == null || _busyId.isNotEmpty) return;
|
||||||
|
setState(() => _busyId = task.id);
|
||||||
|
try {
|
||||||
|
await client.runScheduledTask(scope.id, task.id);
|
||||||
|
_say('Task started');
|
||||||
|
await _load();
|
||||||
|
} on ApiError catch (e) {
|
||||||
|
_say(e.status == 409 ? 'Task is already waiting in the queue' : (e.message.isEmpty ? 'Couldn\'t run task' : e.message));
|
||||||
|
} catch (e) {
|
||||||
|
_say(trArgs('Couldn\'t run task: {0}', [e]));
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _busyId = '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _delete(ScheduledTask task) async {
|
||||||
|
final scope = _scope;
|
||||||
|
final client = app.client;
|
||||||
|
if (scope == null || client == null) return;
|
||||||
|
final ok = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (dialog) => AlertDialog(
|
||||||
|
title: const AppText('Delete scheduled task?'),
|
||||||
|
content: AppText(trArgs('“{0}” and its schedule will be deleted.', [task.name])),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(dialog, false),
|
||||||
|
child: const AppText('Cancel')),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.pop(dialog, true),
|
||||||
|
child: const AppText('Delete')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (ok != true || !mounted) return;
|
||||||
|
setState(() => _busyId = task.id);
|
||||||
|
try {
|
||||||
|
final tasks = await client.deleteScheduledTask(scope.id, task.id);
|
||||||
|
if (!mounted) return;
|
||||||
|
if (_scope?.id == scope.id) setState(() => _tasks = tasks);
|
||||||
|
_say('Scheduled task deleted');
|
||||||
|
} catch (e) {
|
||||||
|
_say(e is ApiError && e.message.isNotEmpty ? e.message : 'Couldn\'t delete task');
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _busyId = '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const AppText('Scheduled tasks'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.refresh),
|
||||||
|
tooltip: tr('Refresh'),
|
||||||
|
onPressed: _loading ? null : _load,
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.add),
|
||||||
|
tooltip: tr('New task'),
|
||||||
|
onPressed: _scope == null ? null : () => _openEditor(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: Column(
|
||||||
|
children: [
|
||||||
|
_scopeBar(theme),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Expanded(child: _body(theme)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same sheet the new-session composer uses: checkouts and the Chat
|
||||||
|
/// scope, with the project list refreshed behind it.
|
||||||
|
Future<void> _pickScope() async {
|
||||||
|
final selected =
|
||||||
|
_scope == null || _scope!.directory.isEmpty ? AppState.chatTarget : _scope!.directory;
|
||||||
|
final choice = await showProjectPicker(
|
||||||
|
context,
|
||||||
|
app: app,
|
||||||
|
selected: selected,
|
||||||
|
);
|
||||||
|
if (choice == null || !mounted) return;
|
||||||
|
final next = choice.isChat ? _chatsScope : _scopeFor(choice.project!);
|
||||||
|
if (next.id == _scope?.id) return;
|
||||||
|
setState(() {
|
||||||
|
_scope = next;
|
||||||
|
_tasks = const [];
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _scopeBar(ThemeData theme) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 6, 8, 6),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.folder_outlined, size: 18, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
AppText('Runs in', style: TextStyle(fontSize: 13, color: theme.hintColor)),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
onTap: _pickScope,
|
||||||
|
child: Padding(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_scope?.label ?? tr('Choose project'),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13.5,
|
||||||
|
color: theme.colorScheme.onSurface),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _body(ThemeData theme) {
|
||||||
|
if (_loading) return const Center(child: CircularProgressIndicator());
|
||||||
|
if (_error != null) {
|
||||||
|
return Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Text(_error!, style: TextStyle(color: theme.hintColor)),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextButton(onPressed: _load, child: const AppText('Retry')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (_tasks.isEmpty) {
|
||||||
|
return Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.event_note_outlined, size: 36, color: theme.hintColor),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
AppText('No scheduled tasks yet.', style: TextStyle(color: theme.hintColor)),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
FilledButton.tonalIcon(
|
||||||
|
onPressed: () => _openEditor(),
|
||||||
|
icon: const Icon(Icons.add, size: 18),
|
||||||
|
label: const AppText('New task'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: _load,
|
||||||
|
child: ListView.builder(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 8, 12, 24),
|
||||||
|
itemCount: _tasks.length,
|
||||||
|
itemBuilder: (context, i) => _card(theme, _tasks[i]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _card(ThemeData theme, ScheduledTask task) {
|
||||||
|
final running = task.lastStatus == 'running' || task.lastStatus == 'queued';
|
||||||
|
final statusColor = switch (task.lastStatus) {
|
||||||
|
'success' || 'sent' => theme.colorScheme.primary,
|
||||||
|
'error' || 'failed' => theme.colorScheme.error,
|
||||||
|
'running' || 'queued' => theme.colorScheme.tertiary,
|
||||||
|
_ => theme.hintColor,
|
||||||
|
};
|
||||||
|
final next = task.nextRunAt > 0 && task.enabled
|
||||||
|
? trArgs('Next: {0}', [scheduledRelativeTime(task.nextRunAt)])
|
||||||
|
: (task.enabled ? '' : 'Paused');
|
||||||
|
final last = task.lastRunAt > 0
|
||||||
|
? trArgs('Last run {0} · {1}', [
|
||||||
|
scheduledClock(task.lastRunAt),
|
||||||
|
scheduledStatusLabel(task.lastStatus),
|
||||||
|
])
|
||||||
|
: 'Never run';
|
||||||
|
return Card(
|
||||||
|
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 2),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: () => _openEditor(task),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(14, 10, 6, 10),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
task.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 15.5, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_busyId == task.id)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(horizontal: 12),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 1.8)),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Switch(
|
||||||
|
value: task.enabled,
|
||||||
|
onChanged: (v) => _toggle(task, v),
|
||||||
|
),
|
||||||
|
PopupMenuButton<String>(
|
||||||
|
tooltip: tr('More'),
|
||||||
|
onSelected: (value) {
|
||||||
|
switch (value) {
|
||||||
|
case 'run':
|
||||||
|
_runNow(task);
|
||||||
|
case 'edit':
|
||||||
|
_openEditor(task);
|
||||||
|
case 'delete':
|
||||||
|
_delete(task);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
itemBuilder: (_) => [
|
||||||
|
const PopupMenuItem(value: 'run', child: AppText('Run now')),
|
||||||
|
const PopupMenuItem(value: 'edit', child: AppText('Edit')),
|
||||||
|
PopupMenuItem(
|
||||||
|
value: 'delete',
|
||||||
|
child: AppText('Delete',
|
||||||
|
style: TextStyle(color: theme.colorScheme.error)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Text(scheduledScheduleText(task),
|
||||||
|
style: TextStyle(fontSize: 13, color: theme.colorScheme.onSurfaceVariant)),
|
||||||
|
if (task.targetSessionId.isEmpty)
|
||||||
|
const SizedBox.shrink()
|
||||||
|
else
|
||||||
|
AppText('Sends to an existing session', style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
if (running) ...[
|
||||||
|
SizedBox(
|
||||||
|
width: 12,
|
||||||
|
height: 12,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 1.6, color: statusColor),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
] else ...[
|
||||||
|
Icon(Icons.circle, size: 8, color: statusColor),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
],
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
last,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (next.isNotEmpty)
|
||||||
|
Text(next,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 11.5, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (task.lastError.isNotEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 4),
|
||||||
|
child: Text(
|
||||||
|
task.lastError,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 11.5, color: theme.colorScheme.error),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
task.modelLabel,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+266
-67
@@ -1,7 +1,10 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
import '../state.dart';
|
import '../state.dart';
|
||||||
import '../storage.dart';
|
import '../storage.dart';
|
||||||
|
import 'scan_qr_screen.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
/// The first screen: the saved servers, or the connect form.
|
/// The first screen: the saved servers, or the connect form.
|
||||||
class ServersScreen extends StatefulWidget {
|
class ServersScreen extends StatefulWidget {
|
||||||
@@ -28,6 +31,9 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
String _password = '';
|
String _password = '';
|
||||||
bool _connecting = false;
|
bool _connecting = false;
|
||||||
String? _formError;
|
String? _formError;
|
||||||
|
// A server may ask for a password only after the first attempt; the field
|
||||||
|
// is always there, but this one takes the focus when it is what is missing.
|
||||||
|
final FocusNode _passwordFocus = FocusNode();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -35,6 +41,12 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
if (widget.startEditing) _editing = true;
|
if (widget.startEditing) _editing = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_passwordFocus.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return ListenableBuilder(
|
return ListenableBuilder(
|
||||||
@@ -59,11 +71,11 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text('OpenChamber',
|
AppText('OpenChamber',
|
||||||
style: theme.textTheme.headlineMedium
|
style: theme.textTheme.headlineMedium
|
||||||
?.copyWith(fontWeight: FontWeight.bold)),
|
?.copyWith(fontWeight: FontWeight.bold)),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text('连接你的 OpenChamber 服务器',
|
AppText('Connect to your OpenChamber server',
|
||||||
style: theme.textTheme.bodyMedium
|
style: theme.textTheme.bodyMedium
|
||||||
?.copyWith(color: theme.hintColor)),
|
?.copyWith(color: theme.hintColor)),
|
||||||
],
|
],
|
||||||
@@ -81,10 +93,24 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
children: [
|
children: [
|
||||||
for (final c in conns) _serverCard(c),
|
for (final c in conns) _serverCard(c),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
OutlinedButton.icon(
|
Row(
|
||||||
onPressed: () => _startEdit(null),
|
children: [
|
||||||
icon: const Icon(Icons.add),
|
Expanded(
|
||||||
label: const Text('添加服务器'),
|
child: OutlinedButton.icon(
|
||||||
|
onPressed: () => _startEdit(null),
|
||||||
|
icon: const Icon(Icons.add),
|
||||||
|
label: const AppText('Add server'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: FilledButton.tonalIcon(
|
||||||
|
onPressed: _pair,
|
||||||
|
icon: const Icon(Icons.qr_code_2, size: 18),
|
||||||
|
label: const AppText('Pairing link'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -105,9 +131,10 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
subtitle: Column(
|
subtitle: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
|
Text(c.isRelay ? trArgs('Via Relay · {0}', [c.serverId]) : c.url,
|
||||||
if (c.proxy.isNotEmpty)
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
Text('经由 ${c.proxy}',
|
if (!c.isRelay && c.proxy.isNotEmpty)
|
||||||
|
AppText(trArgs('Via {0}', [c.proxy]),
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
@@ -117,9 +144,9 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
if (connected)
|
if (connected)
|
||||||
Text('已连接', style: TextStyle(color: theme.colorScheme.primary))
|
AppText('Connected', style: TextStyle(color: theme.colorScheme.primary))
|
||||||
else
|
else
|
||||||
TextButton(onPressed: () => _connect(c), child: const Text('连接')),
|
TextButton(onPressed: () => _connect(c), child: const AppText('Connect')),
|
||||||
PopupMenuButton<String>(
|
PopupMenuButton<String>(
|
||||||
onSelected: (v) {
|
onSelected: (v) {
|
||||||
if (v == 'edit') {
|
if (v == 'edit') {
|
||||||
@@ -129,8 +156,8 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
itemBuilder: (_) => const [
|
itemBuilder: (_) => const [
|
||||||
PopupMenuItem(value: 'edit', child: Text('编辑')),
|
PopupMenuItem(value: 'edit', child: AppText('Edit')),
|
||||||
PopupMenuItem(value: 'delete', child: Text('删除')),
|
PopupMenuItem(value: 'delete', child: AppText('Delete')),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -159,6 +186,7 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
_password = '';
|
_password = '';
|
||||||
_formError = widget.app.lastError;
|
_formError = widget.app.lastError;
|
||||||
});
|
});
|
||||||
|
_focusPasswordIfNeeded(_formError);
|
||||||
widget.app.clearLastError();
|
widget.app.clearLastError();
|
||||||
} else if (mounted) {
|
} else if (mounted) {
|
||||||
setState(() => _connecting = false);
|
setState(() => _connecting = false);
|
||||||
@@ -194,56 +222,71 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
setState(() => _editing = false);
|
setState(() => _editing = false);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'),
|
title: AppText(_editNew ? 'Add server' : trArgs('Connect to {0}', [_edit!.label])),
|
||||||
),
|
),
|
||||||
body: ListView(
|
body: ListView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
children: [
|
children: [
|
||||||
_labelText('名称'),
|
_labelText('Name'),
|
||||||
TextField(
|
TextField(
|
||||||
controller: TextEditingController(text: _label),
|
controller: TextEditingController(text: _label),
|
||||||
onChanged: (v) => _label = v,
|
onChanged: (v) => _label = v,
|
||||||
decoration: const InputDecoration(hintText: '如 我的电脑', border: OutlineInputBorder()),
|
decoration: InputDecoration(
|
||||||
|
hintText: tr('e.g. My computer'), border: const OutlineInputBorder()),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
_labelText('服务器地址'),
|
if (_edit?.isRelay == true) ...[
|
||||||
TextField(
|
const ListTile(
|
||||||
controller: TextEditingController(text: _url),
|
contentPadding: EdgeInsets.zero,
|
||||||
onChanged: (v) => _url = v,
|
leading: Icon(Icons.lock_outline, size: 20),
|
||||||
keyboardType: TextInputType.url,
|
title: AppText('Connect through Relay'),
|
||||||
decoration: const InputDecoration(
|
subtitle: AppText('End-to-end encrypted; the server and device token stay the same'),
|
||||||
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
|
),
|
||||||
),
|
] else ...[
|
||||||
const SizedBox(height: 12),
|
_labelText('Server address'),
|
||||||
_labelText('代理(可选)'),
|
TextField(
|
||||||
TextField(
|
controller: TextEditingController(text: _url),
|
||||||
controller: TextEditingController(text: _proxy),
|
onChanged: (v) => _url = v,
|
||||||
onChanged: (v) => _proxy = v,
|
keyboardType: TextInputType.url,
|
||||||
keyboardType: TextInputType.url,
|
decoration: const InputDecoration(
|
||||||
decoration: const InputDecoration(
|
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
|
||||||
hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()),
|
),
|
||||||
),
|
const SizedBox(height: 12),
|
||||||
const SizedBox(height: 12),
|
_labelText('Proxy (optional)'),
|
||||||
_labelText('自签证书指纹(可选)'),
|
TextField(
|
||||||
TextField(
|
controller: TextEditingController(text: _proxy),
|
||||||
controller: TextEditingController(text: _fingerprint),
|
onChanged: (v) => _proxy = v,
|
||||||
onChanged: (v) => _fingerprint = v,
|
keyboardType: TextInputType.url,
|
||||||
decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()),
|
decoration: InputDecoration(
|
||||||
),
|
hintText: tr('http://… or socks5://…'),
|
||||||
SwitchListTile(
|
border: const OutlineInputBorder()),
|
||||||
contentPadding: EdgeInsets.zero,
|
),
|
||||||
title: const Text('信任自签名证书'),
|
const SizedBox(height: 12),
|
||||||
value: _insecure,
|
_labelText('Self-signed certificate fingerprint (optional)'),
|
||||||
onChanged: (v) => setState(() => _insecure = v),
|
TextField(
|
||||||
),
|
controller: TextEditingController(text: _fingerprint),
|
||||||
if (!_editNew) ...[
|
onChanged: (v) => _fingerprint = v,
|
||||||
_labelText('密码'),
|
decoration: InputDecoration(
|
||||||
|
hintText: tr('SHA-256 hex'),
|
||||||
|
border: const OutlineInputBorder()),
|
||||||
|
),
|
||||||
|
SwitchListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const AppText('Trust self-signed certificates'),
|
||||||
|
value: _insecure,
|
||||||
|
onChanged: (v) => setState(() => _insecure = v),
|
||||||
|
),
|
||||||
|
// Shown for new servers too: a password-protected instance rejects
|
||||||
|
// the first attempt, and this is where the password goes.
|
||||||
|
_labelText('Password (if required)'),
|
||||||
TextField(
|
TextField(
|
||||||
controller: TextEditingController(text: _password),
|
controller: TextEditingController(text: _password),
|
||||||
|
focusNode: _passwordFocus,
|
||||||
onChanged: (v) => _password = v,
|
onChanged: (v) => _password = v,
|
||||||
obscureText: true,
|
obscureText: true,
|
||||||
decoration: const InputDecoration(
|
decoration: InputDecoration(
|
||||||
hintText: '服务器密码', border: OutlineInputBorder()),
|
hintText: tr('Server password; leave empty if the server has none'),
|
||||||
|
border: const OutlineInputBorder()),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
if (_formError != null)
|
if (_formError != null)
|
||||||
@@ -258,7 +301,7 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
child: _connecting
|
child: _connecting
|
||||||
? const SizedBox(
|
? const SizedBox(
|
||||||
height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
||||||
: const Text('连接'),
|
: const AppText('Connect'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -267,7 +310,7 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
|
|
||||||
Widget _labelText(String s) => Padding(
|
Widget _labelText(String s) => Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 4),
|
padding: const EdgeInsets.only(bottom: 4),
|
||||||
child: Text(s, style: Theme.of(context).textTheme.bodySmall),
|
child: AppText(s, style: Theme.of(context).textTheme.bodySmall),
|
||||||
);
|
);
|
||||||
|
|
||||||
Future<void> _submit() async {
|
Future<void> _submit() async {
|
||||||
@@ -275,14 +318,20 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
_connecting = true;
|
_connecting = true;
|
||||||
_formError = null;
|
_formError = null;
|
||||||
});
|
});
|
||||||
final c = Connection(
|
final relay = _edit?.isRelay == true ? _edit : null;
|
||||||
id: _edit?.id ?? _newId(),
|
final c = relay != null
|
||||||
label: _label.isEmpty ? _hostOf(_url) : _label,
|
? relay.copyWith(
|
||||||
url: _url,
|
label: _label.isEmpty ? relay.label : _label,
|
||||||
proxy: _proxy,
|
lastUsedAt: DateTime.now().millisecondsSinceEpoch,
|
||||||
insecure: _insecure,
|
)
|
||||||
fingerprint: _fingerprint,
|
: Connection(
|
||||||
);
|
id: _edit?.id ?? Storage.newId(),
|
||||||
|
label: _label.isEmpty ? _hostOf(_url) : _label,
|
||||||
|
url: _url,
|
||||||
|
proxy: _proxy,
|
||||||
|
insecure: _insecure,
|
||||||
|
fingerprint: _fingerprint,
|
||||||
|
);
|
||||||
// Only a connection that works is saved (AppState saves it on success),
|
// Only a connection that works is saved (AppState saves it on success),
|
||||||
// so failed attempts do not pile up in the server list.
|
// so failed attempts do not pile up in the server list.
|
||||||
await widget.app.connect(c, password: _password);
|
await widget.app.connect(c, password: _password);
|
||||||
@@ -296,34 +345,47 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
_connecting = false;
|
_connecting = false;
|
||||||
_formError = widget.app.lastError;
|
_formError = widget.app.lastError;
|
||||||
});
|
});
|
||||||
|
_focusPasswordIfNeeded(_formError);
|
||||||
widget.app.clearLastError();
|
widget.app.clearLastError();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The server asked for a password: put the caret where it is typed.
|
||||||
|
void _focusPasswordIfNeeded(String? message) {
|
||||||
|
// The message is already in the UI's language; look for the same word.
|
||||||
|
if (message == null || !message.contains(tr('Password'))) return;
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (mounted) _passwordFocus.requestFocus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _pair() {
|
||||||
|
widget.app.error = null;
|
||||||
|
widget.app.clearLastError();
|
||||||
|
showPairingDialog(context, widget.app);
|
||||||
|
}
|
||||||
|
|
||||||
void _confirmDelete(Connection c) {
|
void _confirmDelete(Connection c) {
|
||||||
showDialog(
|
showDialog(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => AlertDialog(
|
builder: (context) => AlertDialog(
|
||||||
title: const Text('删除服务器?'),
|
title: const AppText('Delete server?'),
|
||||||
content: Text('“${c.label}”将从列表移除,设备令牌也会删除。'),
|
content: AppText(trArgs('“{0}” will be removed from the list, and its device token will be deleted.', [c.label])),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
TextButton(onPressed: () => Navigator.pop(context), child: const AppText('Cancel')),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
onPressed: () {
|
onPressed: () {
|
||||||
Navigator.pop(context);
|
Navigator.pop(context);
|
||||||
widget.app.removeConnection(c);
|
widget.app.removeConnection(c);
|
||||||
},
|
},
|
||||||
child: const Text('删除'),
|
child: const AppText('Delete'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
static String _newId() =>
|
|
||||||
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}';
|
|
||||||
|
|
||||||
static String _hostOf(String raw) {
|
static String _hostOf(String raw) {
|
||||||
try {
|
try {
|
||||||
return Uri.parse(raw).host;
|
return Uri.parse(raw).host;
|
||||||
@@ -332,3 +394,140 @@ class _ServersScreenState extends State<ServersScreen> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Opens the paste-a-pairing-link dialog (also reachable from the connected
|
||||||
|
/// sidebar's server sheet).
|
||||||
|
Future<void> showPairingDialog(BuildContext context, AppState app) {
|
||||||
|
app.error = null;
|
||||||
|
app.clearLastError();
|
||||||
|
return showDialog<void>(
|
||||||
|
context: context,
|
||||||
|
builder: (_) => _PairingDialog(app: app),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paste an `openchamber://connect` link and pair. The relay candidate in the
|
||||||
|
/// link is used when no direct address answers.
|
||||||
|
class _PairingDialog extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
const _PairingDialog({required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_PairingDialog> createState() => _PairingDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PairingDialogState extends State<_PairingDialog> {
|
||||||
|
final TextEditingController _text = TextEditingController();
|
||||||
|
bool _busy = false;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_text.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _scan() async {
|
||||||
|
final text = await scanPairingQr(context);
|
||||||
|
if (!mounted || text == null) return;
|
||||||
|
setState(() => _text.text = text);
|
||||||
|
// A scan is an explicit "connect these": do not make the person press
|
||||||
|
// another button after pointing the camera at the code.
|
||||||
|
await _connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _paste() async {
|
||||||
|
final data = await Clipboard.getData(Clipboard.kTextPlain);
|
||||||
|
final text = data?.text?.trim() ?? '';
|
||||||
|
if (text.isEmpty || !mounted) return;
|
||||||
|
setState(() => _text.text = text);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _connect() async {
|
||||||
|
final link = _text.text.trim();
|
||||||
|
if (link.isEmpty || _busy) return;
|
||||||
|
setState(() {
|
||||||
|
_busy = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
final paired = await widget.app.connectWithPairing(link);
|
||||||
|
if (!mounted) return;
|
||||||
|
if (paired && widget.app.client != null) {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_busy = false;
|
||||||
|
_error = widget.app.lastError ?? tr('Pairing failed');
|
||||||
|
});
|
||||||
|
widget.app.clearLastError();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return AlertDialog(
|
||||||
|
title: const AppText('Pairing link'),
|
||||||
|
content: SizedBox(
|
||||||
|
width: 420,
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
AppText(
|
||||||
|
'In the OpenChamber web app, open “Connect a device”, then paste the link or scan the QR code. The link carries a one-time key and either a direct address or a private Relay.',
|
||||||
|
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _text,
|
||||||
|
autofocus: true,
|
||||||
|
minLines: 2,
|
||||||
|
maxLines: 4,
|
||||||
|
keyboardType: TextInputType.multiline,
|
||||||
|
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
hintText: 'openchamber://connect?v=2&p=…',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_error != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 8),
|
||||||
|
child: Text(_error!,
|
||||||
|
style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)),
|
||||||
|
),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: _busy ? null : _scan,
|
||||||
|
icon: const Icon(Icons.qr_code_scanner, size: 18),
|
||||||
|
label: const AppText('Scan QR code'),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: _busy ? null : _paste,
|
||||||
|
icon: const Icon(Icons.content_paste, size: 18),
|
||||||
|
label: const AppText('Paste'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: _busy ? null : () => Navigator.of(context).pop(),
|
||||||
|
child: const AppText('Cancel'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: _busy ? null : _connect,
|
||||||
|
child: _busy
|
||||||
|
? const SizedBox(
|
||||||
|
width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
|
||||||
|
: const AppText('Pair and connect'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+700
-167
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,939 @@
|
|||||||
|
// 统计: the OpenCode session statistics, as the OpenChamber web client shows
|
||||||
|
// them — prompts, steps, tokens, cost, activity, models and tool calls — sized
|
||||||
|
// for a phone. The numbers come from `/api/experimental/session/stats`.
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/client.dart';
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../api/usage_stats.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import '../time_zone.dart';
|
||||||
|
import '../widgets/project_icon.dart';
|
||||||
|
import '../widgets/project_picker.dart';
|
||||||
|
|
||||||
|
const _tokenColors = [
|
||||||
|
Color(0xFF7C6CF6),
|
||||||
|
Color(0xFF3FB6A8),
|
||||||
|
Color(0xFFE0A03A),
|
||||||
|
Color(0xFFB06AD6),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Tools mode used for the model filter of the models section.
|
||||||
|
enum _ModelDimension { tokens, cost, steps }
|
||||||
|
|
||||||
|
class StatsScreen extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
const StatsScreen({super.key, required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<StatsScreen> createState() => _StatsScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StatsScreenState extends State<StatsScreen> {
|
||||||
|
UsageRange _range = UsageRange.month;
|
||||||
|
ProjectInfo? _project;
|
||||||
|
UsageStats? _stats;
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
int _fetchedAt = 0;
|
||||||
|
int _generation = 0;
|
||||||
|
|
||||||
|
UsageTools? _tools;
|
||||||
|
bool _toolsLoading = false;
|
||||||
|
String? _toolsError;
|
||||||
|
_ModelDimension _dimension = _ModelDimension.tokens;
|
||||||
|
int? _activeBar;
|
||||||
|
|
||||||
|
AppState get app => widget.app;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
String? get _directory => (_project?.canonical.isNotEmpty ?? false)
|
||||||
|
? _project!.canonical
|
||||||
|
: app.directory;
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
final client = app.client;
|
||||||
|
if (client == null) {
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_error = tr('Not connected to a server');
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final generation = ++_generation;
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
_activeBar = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final zone = await deviceTimeZone();
|
||||||
|
final stats = await client.sessionStats(
|
||||||
|
from: _range.startFrom(DateTime.now()),
|
||||||
|
project: _project?.id,
|
||||||
|
timezone: zone,
|
||||||
|
directory: _directory,
|
||||||
|
);
|
||||||
|
if (!mounted || generation != _generation) return;
|
||||||
|
setState(() {
|
||||||
|
_stats = stats;
|
||||||
|
_loading = false;
|
||||||
|
_fetchedAt = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
_tools = null;
|
||||||
|
_toolsError = null;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted || generation != _generation) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_error = e is ApiError ? e.message : '$e';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tool counts make the server read every message in the window, so they are
|
||||||
|
/// only requested when the person asks for them (as in the web client).
|
||||||
|
Future<void> _loadTools() async {
|
||||||
|
final client = app.client;
|
||||||
|
final stats = _stats;
|
||||||
|
if (client == null || stats == null) return;
|
||||||
|
setState(() {
|
||||||
|
_toolsLoading = true;
|
||||||
|
_toolsError = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final zone = await deviceTimeZone();
|
||||||
|
final withTools = await client.sessionStats(
|
||||||
|
from: stats.from,
|
||||||
|
to: stats.to,
|
||||||
|
project: _project?.id,
|
||||||
|
timezone: zone,
|
||||||
|
tools: true,
|
||||||
|
directory: _directory,
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_tools = withTools.tools;
|
||||||
|
_toolsLoading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_toolsLoading = false;
|
||||||
|
_toolsError = e is ApiError ? e.message : '$e';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickProject() async {
|
||||||
|
final choice = await showProjectPicker(
|
||||||
|
context,
|
||||||
|
app: app,
|
||||||
|
selected: _project?.canonical ?? allProjectsTarget,
|
||||||
|
includeAll: true,
|
||||||
|
includeChat: false,
|
||||||
|
);
|
||||||
|
if (choice == null || !mounted) return;
|
||||||
|
setState(() => _project = choice.isAll ? null : choice.project);
|
||||||
|
await _load();
|
||||||
|
}
|
||||||
|
|
||||||
|
String _rangeLabel(UsageRange range) => switch (range) {
|
||||||
|
UsageRange.day => tr('Today'),
|
||||||
|
UsageRange.week => tr('7 days'),
|
||||||
|
UsageRange.month => tr('30 days'),
|
||||||
|
UsageRange.quarter => tr('90 days'),
|
||||||
|
UsageRange.all => tr('All time'),
|
||||||
|
};
|
||||||
|
|
||||||
|
String _updatedLabel() {
|
||||||
|
final at = DateTime.fromMillisecondsSinceEpoch(_fetchedAt);
|
||||||
|
final now = DateTime.now();
|
||||||
|
final time = '${at.hour.toString().padLeft(2, '0')}:'
|
||||||
|
'${at.minute.toString().padLeft(2, '0')}';
|
||||||
|
final sameDay = at.year == now.year && at.month == now.month && at.day == now.day;
|
||||||
|
final text = sameDay
|
||||||
|
? time
|
||||||
|
: '${at.month.toString().padLeft(2, '0')}-'
|
||||||
|
'${at.day.toString().padLeft(2, '0')} $time';
|
||||||
|
return trArgs('Updated {0}', [text]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const AppText('Stats'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.refresh),
|
||||||
|
tooltip: tr('Refresh'),
|
||||||
|
onPressed: _loading ? null : _load,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
body: RefreshIndicator(
|
||||||
|
onRefresh: _load,
|
||||||
|
child: ListView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 6, 16, 40),
|
||||||
|
children: [
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 4,
|
||||||
|
children: [
|
||||||
|
for (final range in UsageRange.values)
|
||||||
|
ChoiceChip(
|
||||||
|
label: Text(_rangeLabel(range)),
|
||||||
|
selected: _range == range,
|
||||||
|
onSelected: (_) {
|
||||||
|
if (_range == range) return;
|
||||||
|
setState(() => _range = range);
|
||||||
|
_load();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
_scopeRow(theme),
|
||||||
|
if (_loading && _stats != null)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.only(top: 2),
|
||||||
|
child: LinearProgressIndicator(minHeight: 2),
|
||||||
|
),
|
||||||
|
if (!_loading && _error == null && _fetchedAt > 0)
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 2, right: 6),
|
||||||
|
child: Text(_updatedLabel(),
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
..._body(theme),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _scopeRow(ThemeData theme) {
|
||||||
|
return InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
onTap: _pickProject,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
if (_project == null)
|
||||||
|
Icon(Icons.folder_copy_outlined,
|
||||||
|
size: 18, color: theme.hintColor)
|
||||||
|
else
|
||||||
|
ProjectIcon(app: app, project: _project, size: 18),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_project?.label ?? tr('All projects'),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(fontSize: 14),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _body(ThemeData theme) {
|
||||||
|
final stats = _stats;
|
||||||
|
if (stats == null) {
|
||||||
|
if (_loading) {
|
||||||
|
return const [
|
||||||
|
Padding(
|
||||||
|
padding: EdgeInsets.only(top: 48),
|
||||||
|
child: Center(child: CircularProgressIndicator()),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 40),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
const AppText('Couldn\'t load stats',
|
||||||
|
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
|
||||||
|
if (_error != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
|
||||||
|
child: Text(_error!,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
OutlinedButton(onPressed: _load, child: const AppText('Try again')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (stats.isEmpty) {
|
||||||
|
return [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 48),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
AppText('No activity in this period',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 15,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: theme.colorScheme.onSurface)),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
AppText('Sessions you run will show up here.',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
final today = _range == UsageRange.day;
|
||||||
|
final cache = stats.tokens.cacheRead + stats.tokens.cacheWrite;
|
||||||
|
final activity = buildUsageActivity(stats);
|
||||||
|
return [
|
||||||
|
_tiles(theme, [
|
||||||
|
(
|
||||||
|
label: tr('Sessions'),
|
||||||
|
value: usageCompactNumber(stats.sessions),
|
||||||
|
hint: trArgs('Subagents: {0}', [usageCompactNumber(stats.subagents)]),
|
||||||
|
),
|
||||||
|
(label: tr('Prompts'), value: usageCompactNumber(stats.prompts), hint: null),
|
||||||
|
(
|
||||||
|
label: tr('Tokens'),
|
||||||
|
value: usageCompactNumber(stats.tokens.total),
|
||||||
|
hint: trArgs('In {0} · Out {1} · Cache {2}', [
|
||||||
|
usageCompactNumber(stats.tokens.input),
|
||||||
|
usageCompactNumber(stats.tokens.produced),
|
||||||
|
usageCompactNumber(cache),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
(label: tr('Cost'), value: usageCost(stats.cost), hint: null),
|
||||||
|
if (!today)
|
||||||
|
(
|
||||||
|
label: tr('Active days'),
|
||||||
|
value: usageCompactNumber(stats.activeDays),
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
if (!today)
|
||||||
|
(
|
||||||
|
label: tr('Longest streak (days)'),
|
||||||
|
value: usageCompactNumber(stats.streak),
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
if (!today) ...[
|
||||||
|
const SizedBox(height: 18),
|
||||||
|
_sectionTitle(
|
||||||
|
theme,
|
||||||
|
activity.weekly ? tr('Weekly activity') : tr('Daily activity'),
|
||||||
|
activity.weekly ? tr('Model steps per week') : tr('Model steps per day'),
|
||||||
|
),
|
||||||
|
_activity(theme, activity),
|
||||||
|
],
|
||||||
|
if (stats.tokens.total > 0) ...[
|
||||||
|
const SizedBox(height: 18),
|
||||||
|
_sectionTitle(theme, tr('Token composition'), null),
|
||||||
|
_tokenComposition(theme, stats),
|
||||||
|
],
|
||||||
|
const SizedBox(height: 18),
|
||||||
|
_sectionTitle(theme, tr('Efficiency'), null),
|
||||||
|
_tiles(theme, _efficiencyTiles(stats)),
|
||||||
|
const SizedBox(height: 18),
|
||||||
|
_models(theme, stats),
|
||||||
|
const SizedBox(height: 18),
|
||||||
|
_toolsSection(theme),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
List<({String label, String value, String? hint})> _efficiencyTiles(
|
||||||
|
UsageStats stats) {
|
||||||
|
String? percent(double? value) =>
|
||||||
|
value == null ? null : usagePercent(value);
|
||||||
|
return [
|
||||||
|
(
|
||||||
|
label: tr('Cache hit rate'),
|
||||||
|
value: percent(usageCacheHitRate(stats.tokens)) ?? '—',
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Cost / session'),
|
||||||
|
value: usageCostPerSession(stats) == null
|
||||||
|
? '—'
|
||||||
|
: usageCost(usageCostPerSession(stats)!),
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Cost per 1M tokens'),
|
||||||
|
value: usageCostPerMillionTokens(stats) == null
|
||||||
|
? '—'
|
||||||
|
: usageCost(usageCostPerMillionTokens(stats)!),
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Tokens / session'),
|
||||||
|
value: usageTokensPerSession(stats) == null
|
||||||
|
? '—'
|
||||||
|
: usageCompactNumber(usageTokensPerSession(stats)!),
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Steps / session'),
|
||||||
|
value: usageStepsPerSession(stats) == null
|
||||||
|
? '—'
|
||||||
|
: usageStepsPerSession(stats)!.toStringAsFixed(1),
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Reasoning share'),
|
||||||
|
value: percent(usageReasoningShare(stats.tokens)) ?? '—',
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sectionTitle(ThemeData theme, String title, String? caption) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||||||
|
textBaseline: TextBaseline.alphabetic,
|
||||||
|
children: [
|
||||||
|
Text(title,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13.5,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
color: theme.colorScheme.onSurface)),
|
||||||
|
if (caption != null) ...[
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(caption,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _tiles(
|
||||||
|
ThemeData theme, List<({String label, String value, String? hint})> tiles) {
|
||||||
|
return LayoutBuilder(builder: (context, constraints) {
|
||||||
|
final width = (constraints.maxWidth - 8) / 2;
|
||||||
|
return Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final tile in tiles)
|
||||||
|
SizedBox(
|
||||||
|
width: width,
|
||||||
|
child: _StatTile(
|
||||||
|
label: tile.label,
|
||||||
|
value: tile.value,
|
||||||
|
hint: tile.hint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _activity(ThemeData theme, UsageActivitySeries series) {
|
||||||
|
if (series.bars.isEmpty) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
final active = _activeBar != null && _activeBar! < series.bars.length
|
||||||
|
? series.bars[_activeBar!]
|
||||||
|
: null;
|
||||||
|
String describe(UsageBar bar) {
|
||||||
|
final range = bar.start == bar.end
|
||||||
|
? usageDayLabel(bar.start)
|
||||||
|
: '${usageDayLabel(bar.start)} – ${usageDayLabel(bar.end)}';
|
||||||
|
return trArgs('{0} · steps: {1}', [range, usageCompactNumber(bar.steps)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.5)),
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
height: 18,
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Text(
|
||||||
|
active != null
|
||||||
|
? describe(active)
|
||||||
|
: trArgs('{0} steps', [usageCompactNumber(series.max)]),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
SizedBox(
|
||||||
|
height: 96,
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
for (var i = 0; i < series.bars.length; i++)
|
||||||
|
Expanded(
|
||||||
|
child: GestureDetector(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onTap: () => setState(
|
||||||
|
() => _activeBar = _activeBar == i ? null : i),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(right: 1),
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.bottomCenter,
|
||||||
|
child: Container(
|
||||||
|
height: series.max > 0
|
||||||
|
? series.bars[i].steps > 0
|
||||||
|
? math.max(
|
||||||
|
3,
|
||||||
|
series.bars[i].steps /
|
||||||
|
series.max *
|
||||||
|
90)
|
||||||
|
: 1.5
|
||||||
|
: 1.5,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: series.bars[i].steps > 0
|
||||||
|
? (active == null || _activeBar == i
|
||||||
|
? theme.colorScheme.primary
|
||||||
|
: theme.colorScheme.primary
|
||||||
|
.withValues(alpha: 0.35))
|
||||||
|
: theme.dividerColor,
|
||||||
|
borderRadius: const BorderRadius.vertical(
|
||||||
|
top: Radius.circular(1)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Text(usageDayLabel(series.bars.first.start),
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor)),
|
||||||
|
const Spacer(),
|
||||||
|
Text(usageDayLabel(series.bars.last.end),
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _tokenComposition(ThemeData theme, UsageStats stats) {
|
||||||
|
final total = stats.tokens.total;
|
||||||
|
final segments = <({String label, int value, Color color})>[
|
||||||
|
(
|
||||||
|
label: tr('Input'),
|
||||||
|
value: stats.tokens.input,
|
||||||
|
color: _tokenColors[0]
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Output + reasoning'),
|
||||||
|
value: stats.tokens.produced,
|
||||||
|
color: _tokenColors[1]
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Cache reads'),
|
||||||
|
value: stats.tokens.cacheRead,
|
||||||
|
color: _tokenColors[2]
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Cache writes'),
|
||||||
|
value: stats.tokens.cacheWrite,
|
||||||
|
color: _tokenColors[3]
|
||||||
|
),
|
||||||
|
];
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.5)),
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.all(10),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(5),
|
||||||
|
child: SizedBox(
|
||||||
|
height: 10,
|
||||||
|
// A Row lays a childless ColoredBox out at zero height unless
|
||||||
|
// the cross axis is stretched; without this the bar is invisible.
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
for (final segment in segments)
|
||||||
|
if (segment.value > 0)
|
||||||
|
Expanded(
|
||||||
|
flex: segment.value,
|
||||||
|
child: ColoredBox(color: segment.color),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
LayoutBuilder(builder: (context, constraints) {
|
||||||
|
final width = (constraints.maxWidth - 12) / 2;
|
||||||
|
return Wrap(
|
||||||
|
spacing: 12,
|
||||||
|
runSpacing: 6,
|
||||||
|
children: [
|
||||||
|
for (final segment in segments)
|
||||||
|
SizedBox(
|
||||||
|
width: width,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
width: 8,
|
||||||
|
height: 8,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: segment.color, shape: BoxShape.circle),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Expanded(
|
||||||
|
child: Text(segment.label,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text(
|
||||||
|
'${usageCompactNumber(segment.value)} · '
|
||||||
|
'${usagePercent(segment.value / total)}',
|
||||||
|
style: const TextStyle(fontSize: 11),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _models(ThemeData theme, UsageStats stats) {
|
||||||
|
double valueOf(UsageModelStat model) => switch (_dimension) {
|
||||||
|
_ModelDimension.tokens => model.tokens.total.toDouble(),
|
||||||
|
_ModelDimension.cost => model.cost,
|
||||||
|
_ModelDimension.steps => model.steps.toDouble(),
|
||||||
|
};
|
||||||
|
final ranked = [...stats.models]
|
||||||
|
..sort((a, b) => valueOf(b).compareTo(valueOf(a)));
|
||||||
|
final max = ranked.fold<double>(0, (peak, model) => math.max(peak, valueOf(model)));
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
_sectionTitle(theme, tr('Models'), null),
|
||||||
|
if (stats.models.isNotEmpty)
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final dimension in _ModelDimension.values)
|
||||||
|
ChoiceChip(
|
||||||
|
label: Text(switch (dimension) {
|
||||||
|
_ModelDimension.tokens => tr('Tokens'),
|
||||||
|
_ModelDimension.cost => tr('Cost'),
|
||||||
|
_ModelDimension.steps => tr('Steps'),
|
||||||
|
}),
|
||||||
|
selected: _dimension == dimension,
|
||||||
|
onSelected: (_) => setState(() => _dimension = dimension),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
if (stats.models.isEmpty)
|
||||||
|
AppText('No model usage in this period.',
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor))
|
||||||
|
else
|
||||||
|
for (final model in ranked) _modelRow(theme, model, valueOf, max),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _modelRow(ThemeData theme, UsageModelStat model,
|
||||||
|
double Function(UsageModelStat) valueOf, double max) {
|
||||||
|
final value = valueOf(model);
|
||||||
|
final share =
|
||||||
|
max > 0 ? (value / max).clamp(0.0, 1.0).toDouble() : 0.0;
|
||||||
|
final name = app.modelName(ModelRef(model.modelId, model.providerId,
|
||||||
|
model.variant));
|
||||||
|
final secondary = [
|
||||||
|
if (model.variant != null && model.variant != 'default') model.variant!,
|
||||||
|
model.providerId,
|
||||||
|
].join(' · ');
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 10),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(fontSize: 13.5)),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
_dimension == _ModelDimension.steps
|
||||||
|
? '${usageCompactNumber(model.steps)} · ${usageCost(model.cost)}'
|
||||||
|
: '${usageCompactNumber(model.tokens.total)} · ${usageCost(model.cost)}',
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (secondary.isNotEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 1),
|
||||||
|
child: Text(secondary,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
LayoutBuilder(builder: (context, constraints) {
|
||||||
|
// A nonzero share always paints at least a few pixels, so a small
|
||||||
|
// model reads as a sliver on the track, never as an empty bar.
|
||||||
|
final visible = share <= 0
|
||||||
|
? 0.0
|
||||||
|
: math.max(share, 8 / constraints.maxWidth);
|
||||||
|
return SizedBox(
|
||||||
|
height: 8,
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(3),
|
||||||
|
child: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: [
|
||||||
|
// A full-width track: a small share still reads as a sliver
|
||||||
|
// of colour on it, not as an empty bar.
|
||||||
|
ColoredBox(color: theme.dividerColor.withValues(alpha: 0.35)),
|
||||||
|
if (visible > 0)
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: FractionallySizedBox(
|
||||||
|
widthFactor: visible,
|
||||||
|
heightFactor: 1,
|
||||||
|
child: _dimension == _ModelDimension.tokens
|
||||||
|
? Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
for (final (i, value) in [
|
||||||
|
model.tokens.input,
|
||||||
|
model.tokens.produced,
|
||||||
|
model.tokens.cacheRead,
|
||||||
|
model.tokens.cacheWrite,
|
||||||
|
].indexed)
|
||||||
|
if (value > 0)
|
||||||
|
Expanded(
|
||||||
|
flex: value,
|
||||||
|
child: ColoredBox(color: _tokenColors[i]),
|
||||||
|
),
|
||||||
|
])
|
||||||
|
: ColoredBox(color: theme.colorScheme.primary),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _toolsSection(ThemeData theme) {
|
||||||
|
final tools = _tools != null && _tools!.hasTotals ? _tools : null;
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
_sectionTitle(theme, tr('Tool calls'), tr('Counting them reads every message in the period.')),
|
||||||
|
if (tools == null) ...[
|
||||||
|
if (_toolsError != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: Text(_toolsError!,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12, color: theme.colorScheme.error)),
|
||||||
|
),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: OutlinedButton.icon(
|
||||||
|
onPressed: _toolsLoading ? null : _loadTools,
|
||||||
|
icon: _toolsLoading
|
||||||
|
? const SizedBox(
|
||||||
|
width: 14,
|
||||||
|
height: 14,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2))
|
||||||
|
: const Icon(Icons.build_outlined, size: 18),
|
||||||
|
label: AppText(_toolsLoading ? 'Loading…' : 'Show tool calls'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
] else ...[
|
||||||
|
_tiles(theme, [
|
||||||
|
(label: tr('Calls'), value: usageCompactNumber(tools.calls), hint: null),
|
||||||
|
(
|
||||||
|
label: tr('Success rate'),
|
||||||
|
value: tools.calls > 0
|
||||||
|
? usagePercent(tools.succeeded / tools.calls)
|
||||||
|
: '—',
|
||||||
|
hint: null,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Failed'),
|
||||||
|
value: usageCompactNumber(tools.failed),
|
||||||
|
hint: null
|
||||||
|
),
|
||||||
|
(
|
||||||
|
label: tr('Unfinished'),
|
||||||
|
value: usageCompactNumber(tools.unfinished),
|
||||||
|
hint: null
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
for (final row in tools.rows.where((row) => row.calls > 0).take(8))
|
||||||
|
_toolRow(theme, row),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _toolRow(ThemeData theme, UsageToolStat tool) {
|
||||||
|
final stats = tool.durationP50 != null
|
||||||
|
? trArgs('calls: {0} · median: {1}', [
|
||||||
|
usageCompactNumber(tool.calls),
|
||||||
|
usageDuration(tool.durationP50!),
|
||||||
|
])
|
||||||
|
: trArgs('calls: {0}', [usageCompactNumber(tool.calls)]);
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(tool.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12.5, fontFamily: 'monospace')),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(stats,
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 3),
|
||||||
|
ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(3),
|
||||||
|
child: SizedBox(
|
||||||
|
height: 5,
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (tool.succeeded > 0)
|
||||||
|
Expanded(
|
||||||
|
flex: tool.succeeded,
|
||||||
|
child: ColoredBox(color: theme.colorScheme.primary),
|
||||||
|
),
|
||||||
|
if (tool.failed > 0)
|
||||||
|
Expanded(
|
||||||
|
flex: tool.failed,
|
||||||
|
child: ColoredBox(color: theme.colorScheme.error),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StatTile extends StatelessWidget {
|
||||||
|
final String label;
|
||||||
|
final String value;
|
||||||
|
final String? hint;
|
||||||
|
|
||||||
|
const _StatTile({required this.label, required this.value, this.hint});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.45),
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(label,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(value,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 19,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
fontFeatures: [FontFeature.tabularFigures()])),
|
||||||
|
if (hint != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 1),
|
||||||
|
child: Text(hint!,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 10.5, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
// The terminal tab: xterm renders the PTY, a status bar offers the tab
|
||||||
|
// dropdown (switch / new), restart and close, and the key bar below sends what
|
||||||
|
// a phone keyboard cannot (Esc, Tab, Ctrl, arrows, punctuation), the way
|
||||||
|
// Termux does.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:xterm/xterm.dart';
|
||||||
|
|
||||||
|
import '../api/terminal.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import '../terminal_state.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// A light palette, so the terminal does not turn into a black hole in the
|
||||||
|
/// light theme. (xterm ships only dark ones.)
|
||||||
|
const _lightTheme = TerminalTheme(
|
||||||
|
cursor: Color(0xFF3A3A3A),
|
||||||
|
selection: Color(0x553A6EA5),
|
||||||
|
foreground: Color(0xFF1F1F1F),
|
||||||
|
background: Color(0xFFFFFFFF),
|
||||||
|
black: Color(0xFF000000),
|
||||||
|
red: Color(0xFFCD3131),
|
||||||
|
green: Color(0xFF0D7A44),
|
||||||
|
yellow: Color(0xFF7A6200),
|
||||||
|
blue: Color(0xFF1B5FA6),
|
||||||
|
magenta: Color(0xFFA626A4),
|
||||||
|
cyan: Color(0xFF0E7490),
|
||||||
|
white: Color(0xFFBDBDBD),
|
||||||
|
brightBlack: Color(0xFF666666),
|
||||||
|
brightRed: Color(0xFFD73A49),
|
||||||
|
brightGreen: Color(0xFF1A8A4E),
|
||||||
|
brightYellow: Color(0xFF8A6D00),
|
||||||
|
brightBlue: Color(0xFF2E6FBF),
|
||||||
|
brightMagenta: Color(0xFFB23BB0),
|
||||||
|
brightCyan: Color(0xFF12859B),
|
||||||
|
brightWhite: Color(0xFFEEEEEE),
|
||||||
|
searchHitBackground: Color(0xFFFFF176),
|
||||||
|
searchHitBackgroundCurrent: Color(0xFFAED581),
|
||||||
|
searchHitForeground: Color(0xFF000000),
|
||||||
|
);
|
||||||
|
|
||||||
|
class TerminalPanel extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
final String directory;
|
||||||
|
const TerminalPanel({super.key, required this.app, this.directory = ''});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<TerminalPanel> createState() => _TerminalPanelState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _TerminalPanelState extends State<TerminalPanel> {
|
||||||
|
late final TerminalWorkspace _workspace;
|
||||||
|
final FocusNode _focus = FocusNode();
|
||||||
|
|
||||||
|
/// The dropdown's value for "new terminal"; tab values are their index.
|
||||||
|
static const _newTab = -1;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_workspace = widget.app.terminalFor(widget.directory);
|
||||||
|
_workspace.ensureOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_focus.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: _workspace,
|
||||||
|
builder: (context, _) {
|
||||||
|
final tab = _workspace.activeTab;
|
||||||
|
if (tab == null) return const SizedBox.shrink();
|
||||||
|
final state = tab.state;
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: state,
|
||||||
|
builder: (context, _) {
|
||||||
|
return Column(
|
||||||
|
children: [
|
||||||
|
_statusBar(theme, tab, state),
|
||||||
|
Expanded(
|
||||||
|
child: ColoredBox(
|
||||||
|
color: theme.brightness == Brightness.dark
|
||||||
|
? const Color(0xFF1E1E1E)
|
||||||
|
: Colors.white,
|
||||||
|
child: TerminalView(
|
||||||
|
// A fresh view per tab, so scroll position and selection
|
||||||
|
// do not leak from the one before it.
|
||||||
|
key: ObjectKey(state),
|
||||||
|
state.model,
|
||||||
|
focusNode: _focus,
|
||||||
|
theme: theme.brightness == Brightness.dark
|
||||||
|
? TerminalThemes.defaultTheme
|
||||||
|
: _lightTheme,
|
||||||
|
textStyle: const TerminalStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.25,
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
|
||||||
|
keyboardType: TextInputType.text,
|
||||||
|
deleteDetection: true,
|
||||||
|
backgroundOpacity: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_keyBar(theme, state),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _statusBar(
|
||||||
|
ThemeData theme, TerminalTab tab, TerminalSessionState state) {
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
final (label, color) = switch (state.link) {
|
||||||
|
TerminalLinkState.idle => (tr('Not started'), theme.hintColor),
|
||||||
|
TerminalLinkState.creating => (tr('Creating…'), theme.hintColor),
|
||||||
|
TerminalLinkState.connecting => (tr('Connecting…'), theme.hintColor),
|
||||||
|
TerminalLinkState.reconnecting =>
|
||||||
|
(tr('Connection lost, reconnecting…'), scheme.error),
|
||||||
|
TerminalLinkState.open => (tr('Running'), scheme.primary),
|
||||||
|
TerminalLinkState.exited => (state.detail ?? tr('Exited'), theme.hintColor),
|
||||||
|
TerminalLinkState.error => (state.detail ?? tr('Connection failed'), scheme.error),
|
||||||
|
};
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: PopupMenuButton<int>(
|
||||||
|
tooltip: tr('Switch terminal'),
|
||||||
|
position: PopupMenuPosition.under,
|
||||||
|
onSelected: _onTabMenu,
|
||||||
|
itemBuilder: (_) => [
|
||||||
|
for (var i = 0; i < _workspace.tabs.length; i++)
|
||||||
|
PopupMenuItem<int>(
|
||||||
|
value: i,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
i == _workspace.activeIndex
|
||||||
|
? Icons.check
|
||||||
|
: Icons.terminal_outlined,
|
||||||
|
size: 18,
|
||||||
|
color: i == _workspace.activeIndex
|
||||||
|
? scheme.primary
|
||||||
|
: theme.hintColor,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_workspace.tabs[i].label,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const PopupMenuDivider(),
|
||||||
|
const PopupMenuItem<int>(
|
||||||
|
value: _newTab,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.add, size: 18),
|
||||||
|
SizedBox(width: 10),
|
||||||
|
AppText('New terminal'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
child: Container(
|
||||||
|
height: 40,
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 2, 4, 2),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.circle, size: 8, color: color),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
tab.label,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12.5, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
'· $label',
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 12, color: color),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(Icons.arrow_drop_down, size: 20, color: theme.hintColor),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: tr('Keyboard'),
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
icon: const Icon(Icons.keyboard_outlined, size: 18),
|
||||||
|
onPressed: () => _focus.requestFocus(),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: tr('Restart'),
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
icon: const Icon(Icons.restart_alt, size: 18),
|
||||||
|
onPressed: state.link == TerminalLinkState.exited ||
|
||||||
|
state.link == TerminalLinkState.error ||
|
||||||
|
state.isRunning
|
||||||
|
? _restart
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
PopupMenuButton<String>(
|
||||||
|
tooltip: tr('More'),
|
||||||
|
icon: const Icon(Icons.more_vert, size: 18),
|
||||||
|
onSelected: (value) {
|
||||||
|
switch (value) {
|
||||||
|
case 'clear':
|
||||||
|
state.model.write('\x1b[2J\x1b[H');
|
||||||
|
break;
|
||||||
|
case 'close':
|
||||||
|
_workspace.closeActive();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
itemBuilder: (_) => const [
|
||||||
|
PopupMenuItem(value: 'clear', child: AppText('Clear screen')),
|
||||||
|
PopupMenuItem(value: 'close', child: AppText('Close this terminal')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onTabMenu(int value) {
|
||||||
|
if (value == _newTab) {
|
||||||
|
_workspace.addTab();
|
||||||
|
} else {
|
||||||
|
_workspace.select(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _restart() async {
|
||||||
|
final state = _workspace.activeTab?.state;
|
||||||
|
if (state == null) return;
|
||||||
|
if (state.link == TerminalLinkState.error) {
|
||||||
|
// A dead session cannot restart in place; a fresh shell replaces it
|
||||||
|
// inside the same tab.
|
||||||
|
await state.closeSession();
|
||||||
|
await state.ensureOpen();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await state.restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- key bar
|
||||||
|
|
||||||
|
/// Two rows of seven, the way Termux lays them out: the keys a phone
|
||||||
|
/// keyboard cannot produce, all reachable with a thumb.
|
||||||
|
Widget _keyBar(ThemeData theme, TerminalSessionState state) {
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerHigh,
|
||||||
|
border: Border(top: BorderSide(color: theme.dividerColor, width: 0.5)),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.fromLTRB(3, 3, 3, 3),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
_keyRow([
|
||||||
|
_key('ESC', onTap: () => _sendKey(state, TerminalKey.escape)),
|
||||||
|
_key('/', onTap: () => _sendText(state, '/')),
|
||||||
|
_key('—', onTap: () => _sendText(state, '-')),
|
||||||
|
_key('HOME', onTap: () => _sendKey(state, TerminalKey.home)),
|
||||||
|
_key('↑',
|
||||||
|
big: true, onTap: () => _sendKey(state, TerminalKey.arrowUp)),
|
||||||
|
_key('END', onTap: () => _sendKey(state, TerminalKey.end)),
|
||||||
|
_key('PGUP', onTap: () => _sendKey(state, TerminalKey.pageUp)),
|
||||||
|
]),
|
||||||
|
_keyRow([
|
||||||
|
_key('TAB', onTap: () => _sendKey(state, TerminalKey.tab)),
|
||||||
|
_key('CTRL', active: state.ctrl, onTap: state.toggleCtrl),
|
||||||
|
_key('ALT', active: state.alt, onTap: state.toggleAlt),
|
||||||
|
_key('←',
|
||||||
|
big: true,
|
||||||
|
onTap: () => _sendKey(state, TerminalKey.arrowLeft)),
|
||||||
|
_key('↓',
|
||||||
|
big: true,
|
||||||
|
onTap: () => _sendKey(state, TerminalKey.arrowDown)),
|
||||||
|
_key('→',
|
||||||
|
big: true,
|
||||||
|
onTap: () => _sendKey(state, TerminalKey.arrowRight)),
|
||||||
|
_key('PGDN', onTap: () => _sendKey(state, TerminalKey.pageDown)),
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _keyRow(List<Widget> keys) => Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 1.5),
|
||||||
|
child: Row(
|
||||||
|
children: [for (final key in keys) Expanded(child: key)],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// [big] draws a single glyph (an arrow) larger than a word.
|
||||||
|
Widget _key(String label,
|
||||||
|
{bool active = false, bool big = false, required VoidCallback onTap}) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
return GestureDetector(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onTap: onTap,
|
||||||
|
child: Container(
|
||||||
|
height: 30,
|
||||||
|
margin: const EdgeInsets.symmetric(horizontal: 1.5),
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: active
|
||||||
|
? scheme.primary.withValues(alpha: 0.22)
|
||||||
|
: scheme.surfaceContainerHighest,
|
||||||
|
borderRadius: BorderRadius.circular(6),
|
||||||
|
border: Border.all(
|
||||||
|
color: active ? scheme.primary : Colors.transparent, width: 1),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
maxLines: 1,
|
||||||
|
style: TextStyle(
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
fontSize: big ? 16 : 11,
|
||||||
|
fontWeight: active ? FontWeight.w700 : FontWeight.w500,
|
||||||
|
color: active ? scheme.primary : scheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _sendKey(TerminalSessionState state, TerminalKey key) => state.model
|
||||||
|
.keyInput(key, ctrl: state.ctrl, alt: state.alt, shift: state.shift);
|
||||||
|
|
||||||
|
void _sendText(TerminalSessionState state, String text) =>
|
||||||
|
state.model.textInput(text);
|
||||||
|
}
|
||||||
+1398
-88
File diff suppressed because it is too large.
Load diff
+126
-2
@@ -7,6 +7,8 @@ import 'dart:convert';
|
|||||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import 'l10n.dart';
|
||||||
|
|
||||||
class Connection {
|
class Connection {
|
||||||
final String id;
|
final String id;
|
||||||
final String label;
|
final String label;
|
||||||
@@ -15,6 +17,14 @@ class Connection {
|
|||||||
final bool insecure;
|
final bool insecure;
|
||||||
final String fingerprint;
|
final String fingerprint;
|
||||||
final int lastUsedAt;
|
final int lastUsedAt;
|
||||||
|
|
||||||
|
/// Set for a server reached through the private relay. The host's public
|
||||||
|
/// key (JSON JWK) is the E2EE trust anchor from the pairing link.
|
||||||
|
final String relayUrl;
|
||||||
|
final String serverId;
|
||||||
|
final String hostKey;
|
||||||
|
final String grant;
|
||||||
|
|
||||||
Connection({
|
Connection({
|
||||||
required this.id,
|
required this.id,
|
||||||
required this.label,
|
required this.label,
|
||||||
@@ -23,8 +33,15 @@ class Connection {
|
|||||||
this.insecure = false,
|
this.insecure = false,
|
||||||
this.fingerprint = '',
|
this.fingerprint = '',
|
||||||
this.lastUsedAt = 0,
|
this.lastUsedAt = 0,
|
||||||
|
this.relayUrl = '',
|
||||||
|
this.serverId = '',
|
||||||
|
this.hostKey = '',
|
||||||
|
this.grant = '',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
bool get isRelay =>
|
||||||
|
relayUrl.isNotEmpty && serverId.isNotEmpty && hostKey.isNotEmpty;
|
||||||
|
|
||||||
factory Connection.fromJson(Map<String, dynamic> j) => Connection(
|
factory Connection.fromJson(Map<String, dynamic> j) => Connection(
|
||||||
id: j['id'] as String? ?? '',
|
id: j['id'] as String? ?? '',
|
||||||
label: j['label'] as String? ?? '',
|
label: j['label'] as String? ?? '',
|
||||||
@@ -33,6 +50,10 @@ class Connection {
|
|||||||
insecure: j['insecure'] as bool? ?? false,
|
insecure: j['insecure'] as bool? ?? false,
|
||||||
fingerprint: j['fingerprint'] as String? ?? '',
|
fingerprint: j['fingerprint'] as String? ?? '',
|
||||||
lastUsedAt: (j['lastUsedAt'] as num?)?.toInt() ?? 0,
|
lastUsedAt: (j['lastUsedAt'] as num?)?.toInt() ?? 0,
|
||||||
|
relayUrl: j['relayUrl'] as String? ?? '',
|
||||||
|
serverId: j['serverId'] as String? ?? '',
|
||||||
|
hostKey: j['hostKey'] as String? ?? '',
|
||||||
|
grant: j['grant'] as String? ?? '',
|
||||||
);
|
);
|
||||||
|
|
||||||
Map<String, dynamic> toJson() => {
|
Map<String, dynamic> toJson() => {
|
||||||
@@ -43,6 +64,10 @@ class Connection {
|
|||||||
'insecure': insecure,
|
'insecure': insecure,
|
||||||
'fingerprint': fingerprint,
|
'fingerprint': fingerprint,
|
||||||
'lastUsedAt': lastUsedAt,
|
'lastUsedAt': lastUsedAt,
|
||||||
|
if (relayUrl.isNotEmpty) 'relayUrl': relayUrl,
|
||||||
|
if (serverId.isNotEmpty) 'serverId': serverId,
|
||||||
|
if (hostKey.isNotEmpty) 'hostKey': hostKey,
|
||||||
|
if (grant.isNotEmpty) 'grant': grant,
|
||||||
};
|
};
|
||||||
|
|
||||||
Connection copyWith({
|
Connection copyWith({
|
||||||
@@ -52,6 +77,10 @@ class Connection {
|
|||||||
bool? insecure,
|
bool? insecure,
|
||||||
String? fingerprint,
|
String? fingerprint,
|
||||||
int? lastUsedAt,
|
int? lastUsedAt,
|
||||||
|
String? relayUrl,
|
||||||
|
String? serverId,
|
||||||
|
String? hostKey,
|
||||||
|
String? grant,
|
||||||
}) =>
|
}) =>
|
||||||
Connection(
|
Connection(
|
||||||
id: id,
|
id: id,
|
||||||
@@ -61,12 +90,32 @@ class Connection {
|
|||||||
insecure: insecure ?? this.insecure,
|
insecure: insecure ?? this.insecure,
|
||||||
fingerprint: fingerprint ?? this.fingerprint,
|
fingerprint: fingerprint ?? this.fingerprint,
|
||||||
lastUsedAt: lastUsedAt ?? this.lastUsedAt,
|
lastUsedAt: lastUsedAt ?? this.lastUsedAt,
|
||||||
|
relayUrl: relayUrl ?? this.relayUrl,
|
||||||
|
serverId: serverId ?? this.serverId,
|
||||||
|
hostKey: hostKey ?? this.hostKey,
|
||||||
|
grant: grant ?? this.grant,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One remembered terminal tab: the server's session id and the local label.
|
||||||
|
class SavedTerminalTab {
|
||||||
|
final String id;
|
||||||
|
final String label;
|
||||||
|
const SavedTerminalTab(this.id, this.label);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The terminal tabs remembered for one directory, with the tab that was
|
||||||
|
/// showing.
|
||||||
|
class SavedTerminalTabs {
|
||||||
|
final List<SavedTerminalTab> tabs;
|
||||||
|
final String? activeId;
|
||||||
|
const SavedTerminalTabs(this.tabs, this.activeId);
|
||||||
|
}
|
||||||
|
|
||||||
class Storage {
|
class Storage {
|
||||||
static const _connsKey = 'openchamber.connections';
|
static const _connsKey = 'openchamber.connections';
|
||||||
static const _installKey = 'openchamber.installId';
|
static const _installKey = 'openchamber.installId';
|
||||||
|
static const _terminalPrefix = 'openchamber.terminalSessions.';
|
||||||
// v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default.
|
// v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default.
|
||||||
final _secure = const FlutterSecureStorage();
|
final _secure = const FlutterSecureStorage();
|
||||||
|
|
||||||
@@ -92,11 +141,86 @@ class Storage {
|
|||||||
await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList()));
|
await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- terminals
|
||||||
|
|
||||||
|
// The terminal tabs per directory, so reopening the terminal after an app
|
||||||
|
// restart can reattach to the shells the server still holds instead of
|
||||||
|
// starting new ones. Ids are meaningless across servers, hence one map per
|
||||||
|
// connection.
|
||||||
|
|
||||||
|
static String _terminalKey(String connectionId) =>
|
||||||
|
'$_terminalPrefix$connectionId';
|
||||||
|
|
||||||
|
Future<Map<String, dynamic>> _terminalMap(String connectionId) async {
|
||||||
|
if (connectionId.isEmpty) return {};
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final raw = prefs.getString(_terminalKey(connectionId));
|
||||||
|
if (raw == null || raw.isEmpty) return {};
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is Map) return Map<String, dynamic>.from(decoded);
|
||||||
|
} catch (_) {}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tabs saved for [directory], or null when there are none. A value
|
||||||
|
/// written by 0.4.2 (a bare session id) is read as a single tab.
|
||||||
|
Future<SavedTerminalTabs?> terminalTabs(
|
||||||
|
String connectionId, String directory) async {
|
||||||
|
final entry = (await _terminalMap(connectionId))[directory];
|
||||||
|
if (entry is String && entry.isNotEmpty) {
|
||||||
|
return SavedTerminalTabs(
|
||||||
|
[SavedTerminalTab(entry, tr('Terminal 1'))], entry);
|
||||||
|
}
|
||||||
|
if (entry is! Map) return null;
|
||||||
|
final rawTabs = entry['tabs'];
|
||||||
|
if (rawTabs is! List) return null;
|
||||||
|
final tabs = <SavedTerminalTab>[];
|
||||||
|
for (final raw in rawTabs) {
|
||||||
|
if (raw is! Map) continue;
|
||||||
|
final id = raw['id'];
|
||||||
|
final label = raw['label'];
|
||||||
|
if (id is! String || id.isEmpty) continue;
|
||||||
|
tabs.add(SavedTerminalTab(
|
||||||
|
id, label is String && label.trim().isNotEmpty ? label : tr('Terminal')));
|
||||||
|
}
|
||||||
|
if (tabs.isEmpty) return null;
|
||||||
|
final active = entry['active'];
|
||||||
|
return SavedTerminalTabs(tabs, active is String ? active : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveTerminalTabs(
|
||||||
|
String connectionId, String directory, SavedTerminalTabs value) async {
|
||||||
|
if (connectionId.isEmpty || directory.isEmpty) return;
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final map = await _terminalMap(connectionId);
|
||||||
|
map[directory] = {
|
||||||
|
'tabs': [
|
||||||
|
for (final tab in value.tabs) {'id': tab.id, 'label': tab.label},
|
||||||
|
],
|
||||||
|
if (value.activeId != null) 'active': value.activeId,
|
||||||
|
};
|
||||||
|
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> clearTerminalTabs(
|
||||||
|
String connectionId, String directory) async {
|
||||||
|
if (connectionId.isEmpty) return;
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final map = await _terminalMap(connectionId);
|
||||||
|
if (map.remove(directory) == null) return;
|
||||||
|
if (map.isEmpty) {
|
||||||
|
await prefs.remove(_terminalKey(connectionId));
|
||||||
|
} else {
|
||||||
|
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<String> installId() async {
|
Future<String> installId() async {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
var id = prefs.getString(_installKey);
|
var id = prefs.getString(_installKey);
|
||||||
if (id == null || id.isEmpty) {
|
if (id == null || id.isEmpty) {
|
||||||
id = _newId();
|
id = newId();
|
||||||
await prefs.setString(_installKey, id);
|
await prefs.setString(_installKey, id);
|
||||||
}
|
}
|
||||||
return id;
|
return id;
|
||||||
@@ -119,7 +243,7 @@ class Storage {
|
|||||||
return 'openchamber.token.$digest';
|
return 'openchamber.token.$digest';
|
||||||
}
|
}
|
||||||
|
|
||||||
static String _newId() =>
|
static String newId() =>
|
||||||
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}${(_rand() & 0xffffff).toRadixString(36).padLeft(6, '0')}';
|
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}${(_rand() & 0xffffff).toRadixString(36).padLeft(6, '0')}';
|
||||||
|
|
||||||
static int _rand() => DateTime.now().microsecondsSinceEpoch % 0xffffffff;
|
static int _rand() => DateTime.now().microsecondsSinceEpoch % 0xffffffff;
|
||||||
|
|||||||
@@ -0,0 +1,572 @@
|
|||||||
|
// The live terminal: the xterm model the view renders, and the socket that
|
||||||
|
// carries its bytes. A directory can hold several tabs; the workspace keeps
|
||||||
|
// them and owns which one is attached, so closing the panel (or switching
|
||||||
|
// tabs) does not end the shells — reattaching replays the server's snapshot.
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:xterm/xterm.dart';
|
||||||
|
|
||||||
|
import 'api/terminal.dart';
|
||||||
|
import 'l10n.dart';
|
||||||
|
import 'state.dart';
|
||||||
|
import 'storage.dart';
|
||||||
|
|
||||||
|
/// One terminal tab. [state] holds the model and the socket; the label is the
|
||||||
|
/// local name ("终端 1") the dropdown shows.
|
||||||
|
class TerminalTab {
|
||||||
|
final TerminalSessionState state;
|
||||||
|
String label;
|
||||||
|
TerminalTab(this.state, this.label);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tab before its state exists: [id] is the server session when the tab is
|
||||||
|
/// restored, null when it is about to be created.
|
||||||
|
class TerminalTabPlan {
|
||||||
|
final String? id;
|
||||||
|
final String label;
|
||||||
|
const TerminalTabPlan({this.id, required this.label});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every terminal tab of one working directory, and which one is showing.
|
||||||
|
class TerminalWorkspace extends ChangeNotifier {
|
||||||
|
final AppState app;
|
||||||
|
final String directory;
|
||||||
|
|
||||||
|
final List<TerminalTab> tabs = [];
|
||||||
|
int activeIndex = 0;
|
||||||
|
bool _loaded = false;
|
||||||
|
bool _disposed = false;
|
||||||
|
|
||||||
|
TerminalWorkspace(this.app, this.directory);
|
||||||
|
|
||||||
|
TerminalTab? get activeTab => tabs.isEmpty
|
||||||
|
? null
|
||||||
|
: tabs[activeIndex.clamp(0, tabs.length - 1)];
|
||||||
|
|
||||||
|
String get _connectionId => app.conn?.id ?? '';
|
||||||
|
|
||||||
|
/// Opens the workspace on first use: the saved tabs and the server's sessions
|
||||||
|
/// for this directory are reconciled, then the active tab attaches. Later
|
||||||
|
/// calls just make sure its socket is alive.
|
||||||
|
Future<void> ensureOpen() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
if (_loaded) {
|
||||||
|
await activeTab?.state.ensureOpen();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_loaded = true;
|
||||||
|
await _load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
final saved = await _savedTabs();
|
||||||
|
final server = await _serverTabs();
|
||||||
|
final plans = planTabs(saved: saved?.tabs ?? const [], server: server);
|
||||||
|
await _applyPlans(plans, activeId: saved?.activeId);
|
||||||
|
await activeTab?.state.ensureOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tabs to show, given what was saved locally and what the server holds for
|
||||||
|
/// the directory. A saved tab whose session is gone is dropped; sessions
|
||||||
|
/// from elsewhere (the web UI, another phone) become tabs of their own.
|
||||||
|
static List<TerminalTabPlan> planTabs({
|
||||||
|
required List<SavedTerminalTab> saved,
|
||||||
|
required List<ServerTerminal>? server,
|
||||||
|
}) {
|
||||||
|
final plans = <TerminalTabPlan>[];
|
||||||
|
String label() => freeLabel(plans.map((p) => p.label));
|
||||||
|
if (server == null) {
|
||||||
|
// The listing failed: trust what was saved, and let the attach path
|
||||||
|
// report a dead id.
|
||||||
|
for (final tab in saved) {
|
||||||
|
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
|
||||||
|
}
|
||||||
|
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
|
||||||
|
return plans;
|
||||||
|
}
|
||||||
|
// Project-action command runners are PTYs too, but they are not the
|
||||||
|
// person's terminal tabs.
|
||||||
|
final sessions = [
|
||||||
|
for (final s in server)
|
||||||
|
if (s.interactive) s,
|
||||||
|
];
|
||||||
|
final byId = {for (final s in sessions) s.sessionId: s};
|
||||||
|
final seen = <String>{};
|
||||||
|
for (final tab in saved) {
|
||||||
|
if (!byId.containsKey(tab.id) || !seen.add(tab.id)) continue;
|
||||||
|
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
|
||||||
|
}
|
||||||
|
final rest = [
|
||||||
|
for (final s in sessions)
|
||||||
|
if (s.sessionId.isNotEmpty && !seen.contains(s.sessionId)) s,
|
||||||
|
]..sort((a, b) => (a.createdAt ?? 0).compareTo(b.createdAt ?? 0));
|
||||||
|
for (final session in rest) {
|
||||||
|
if (!seen.add(session.sessionId)) continue;
|
||||||
|
plans.add(TerminalTabPlan(id: session.sessionId, label: label()));
|
||||||
|
}
|
||||||
|
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
|
||||||
|
return plans;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first free "终端 N" among [labels], so closing a tab makes its number
|
||||||
|
/// available again.
|
||||||
|
static String freeLabel(Iterable<String> labels) {
|
||||||
|
final used = <int>{};
|
||||||
|
for (final label in labels) {
|
||||||
|
final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim()) ??
|
||||||
|
RegExp(r'^Terminal (\d+)$').firstMatch(label.trim());
|
||||||
|
if (match != null) used.add(int.parse(match.group(1)!));
|
||||||
|
}
|
||||||
|
var n = 1;
|
||||||
|
while (used.contains(n)) {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return trArgs('Terminal {0}', [n]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<SavedTerminalTabs?> _savedTabs() async {
|
||||||
|
final connection = _connectionId;
|
||||||
|
if (connection.isEmpty) return null;
|
||||||
|
return app.storage.terminalTabs(connection, directory);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The interactive terminals the server holds for this directory, or null
|
||||||
|
/// when the listing failed (then the saved tabs are kept as they are).
|
||||||
|
Future<List<ServerTerminal>?> _serverTabs() async {
|
||||||
|
final client = app.client;
|
||||||
|
if (client == null) return null;
|
||||||
|
try {
|
||||||
|
final all = await client.listTerminals(cwd: directory);
|
||||||
|
return [
|
||||||
|
for (final session in all)
|
||||||
|
if (session.interactive) session,
|
||||||
|
];
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _applyPlans(List<TerminalTabPlan> plans,
|
||||||
|
{String? activeId}) async {
|
||||||
|
final reuse = <String, TerminalTab>{};
|
||||||
|
for (final tab in tabs) {
|
||||||
|
final id = tab.state.sessionId;
|
||||||
|
if (id != null) reuse[id] = tab;
|
||||||
|
}
|
||||||
|
final next = <TerminalTab>[];
|
||||||
|
for (final plan in plans) {
|
||||||
|
final existing = plan.id == null ? null : reuse[plan.id];
|
||||||
|
final state = existing?.state ??
|
||||||
|
TerminalSessionState(app, directory,
|
||||||
|
onSessionIdChanged: _persistLater);
|
||||||
|
if (plan.id != null) state.sessionId = plan.id;
|
||||||
|
next.add(TerminalTab(state, plan.label));
|
||||||
|
}
|
||||||
|
for (final tab in tabs) {
|
||||||
|
if (!next.any((entry) => entry.state == tab.state)) tab.state.dispose();
|
||||||
|
}
|
||||||
|
tabs
|
||||||
|
..clear()
|
||||||
|
..addAll(next);
|
||||||
|
final match = activeId == null
|
||||||
|
? -1
|
||||||
|
: tabs.indexWhere((tab) => tab.state.sessionId == activeId);
|
||||||
|
activeIndex = match >= 0 ? match : tabs.length - 1;
|
||||||
|
notifyListeners();
|
||||||
|
await _persist();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _persistLater() {
|
||||||
|
unawaited(_persist());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _persist() async {
|
||||||
|
final connection = _connectionId;
|
||||||
|
if (connection.isEmpty || _disposed) return;
|
||||||
|
final saved = [
|
||||||
|
for (final tab in tabs)
|
||||||
|
if (tab.state.sessionId case final id?)
|
||||||
|
SavedTerminalTab(id, tab.label),
|
||||||
|
];
|
||||||
|
if (saved.isEmpty) {
|
||||||
|
await app.storage.clearTerminalTabs(connection, directory);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await app.storage.saveTerminalTabs(connection, directory,
|
||||||
|
SavedTerminalTabs(saved, activeTab?.state.sessionId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switches tabs: the old one detaches (its shell stays on the server) and
|
||||||
|
/// the new one attaches or is created.
|
||||||
|
Future<void> select(int index) async {
|
||||||
|
if (_disposed || tabs.isEmpty) return;
|
||||||
|
index = index.clamp(0, tabs.length - 1);
|
||||||
|
if (index == activeIndex) return;
|
||||||
|
final previous = activeTab;
|
||||||
|
activeIndex = index;
|
||||||
|
notifyListeners();
|
||||||
|
await previous?.state.detach();
|
||||||
|
await activeTab?.state.ensureOpen();
|
||||||
|
await _persist();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds an empty tab and shows it; its shell is created on open.
|
||||||
|
Future<void> addTab() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
final previous = activeTab;
|
||||||
|
final state = TerminalSessionState(app, directory,
|
||||||
|
onSessionIdChanged: _persistLater);
|
||||||
|
tabs.add(TerminalTab(state, freeLabel(tabs.map((tab) => tab.label))));
|
||||||
|
activeIndex = tabs.length - 1;
|
||||||
|
notifyListeners();
|
||||||
|
await previous?.state.detach();
|
||||||
|
await state.ensureOpen();
|
||||||
|
await _persist();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes the active tab on the server and in the list; when it was the last
|
||||||
|
/// one, a fresh tab takes its place so the panel stays usable.
|
||||||
|
Future<void> closeActive() async {
|
||||||
|
if (_disposed || tabs.isEmpty) return;
|
||||||
|
final closing = tabs.removeAt(activeIndex.clamp(0, tabs.length - 1));
|
||||||
|
if (tabs.isEmpty) {
|
||||||
|
final state = TerminalSessionState(app, directory,
|
||||||
|
onSessionIdChanged: _persistLater);
|
||||||
|
tabs.add(TerminalTab(state, freeLabel(const [])));
|
||||||
|
activeIndex = 0;
|
||||||
|
} else {
|
||||||
|
activeIndex = activeIndex.clamp(0, tabs.length - 1);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
await closing.state.closeSession();
|
||||||
|
closing.state.dispose();
|
||||||
|
await activeTab?.state.ensureOpen();
|
||||||
|
await _persist();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends every shell and forgets the directory's tabs (an explicit
|
||||||
|
/// disconnect, not the panel closing).
|
||||||
|
Future<void> closeAll() async {
|
||||||
|
final connection = _connectionId;
|
||||||
|
for (final tab in List.of(tabs)) {
|
||||||
|
await tab.state.closeSession();
|
||||||
|
tab.state.dispose();
|
||||||
|
}
|
||||||
|
tabs.clear();
|
||||||
|
_loaded = false;
|
||||||
|
if (connection.isNotEmpty) {
|
||||||
|
await app.storage.clearTerminalTabs(connection, directory);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After the app returns from the background: the socket may be dead
|
||||||
|
/// without having reported it.
|
||||||
|
Future<void> reconnectIfNeeded() async {
|
||||||
|
await activeTab?.state.reconnectIfNeeded();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
|
for (final tab in tabs) {
|
||||||
|
tab.state.dispose();
|
||||||
|
}
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TerminalSessionState extends ChangeNotifier {
|
||||||
|
final AppState app;
|
||||||
|
final String directory;
|
||||||
|
|
||||||
|
/// Called when [sessionId] changes (created, replaced, cleared), so the
|
||||||
|
/// workspace can save its tab list.
|
||||||
|
final VoidCallback? onSessionIdChanged;
|
||||||
|
|
||||||
|
final Terminal model = Terminal(maxLines: 5000);
|
||||||
|
|
||||||
|
TerminalSocket? _socket;
|
||||||
|
TerminalLinkState link = TerminalLinkState.idle;
|
||||||
|
String? detail;
|
||||||
|
String? sessionId;
|
||||||
|
|
||||||
|
/// Key-bar modifiers. They apply to the next character, whichever keyboard
|
||||||
|
/// produced it: the on-screen bar or the phone's IME (which never sends
|
||||||
|
/// Ctrl itself).
|
||||||
|
bool ctrl = false;
|
||||||
|
bool alt = false;
|
||||||
|
bool shift = false;
|
||||||
|
|
||||||
|
int _cols = 80;
|
||||||
|
int _rows = 24;
|
||||||
|
Timer? _resizeTimer;
|
||||||
|
bool _opened = false;
|
||||||
|
bool _disposed = false;
|
||||||
|
bool _recovering = false;
|
||||||
|
|
||||||
|
TerminalSessionState(this.app, this.directory, {this.onSessionIdChanged}) {
|
||||||
|
model.onOutput = _onOutput;
|
||||||
|
model.onResize = (cols, rows, _, __) {
|
||||||
|
_cols = cols;
|
||||||
|
_rows = rows;
|
||||||
|
_scheduleResize();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isOpen => link == TerminalLinkState.open;
|
||||||
|
bool get isRunning =>
|
||||||
|
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
|
||||||
|
|
||||||
|
/// Attaches to the tab's session, or creates one when the tab has none yet.
|
||||||
|
Future<void> ensureOpen() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
if (!_opened) {
|
||||||
|
_opened = true;
|
||||||
|
if (sessionId == null) {
|
||||||
|
await _create();
|
||||||
|
} else {
|
||||||
|
await _attach();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_socket == null && link != TerminalLinkState.exited) await _attach();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the socket without ending the shell; [ensureOpen] attaches again.
|
||||||
|
Future<void> detach() async {
|
||||||
|
await _socket?.dispose();
|
||||||
|
_socket = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void toggleCtrl() {
|
||||||
|
ctrl = !ctrl;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void toggleAlt() {
|
||||||
|
alt = !alt;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void toggleShift() {
|
||||||
|
shift = !shift;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends one typed character, with whatever modifiers are pending, then
|
||||||
|
/// drops them. Escape sequences (arrows, Home, …) arrive already complete
|
||||||
|
/// and pass through untouched.
|
||||||
|
void _onOutput(String data) {
|
||||||
|
var out = data;
|
||||||
|
if (out.isNotEmpty) {
|
||||||
|
final code = out.codeUnitAt(0);
|
||||||
|
final printable = out.length == 1 && code >= 0x20 && code != 0x7f;
|
||||||
|
if (printable && ctrl) {
|
||||||
|
if (code >= 0x61 && code <= 0x7a) {
|
||||||
|
out = String.fromCharCode(code - 0x60);
|
||||||
|
} else if (code >= 0x41 && code <= 0x5a) {
|
||||||
|
out = String.fromCharCode(code - 0x40);
|
||||||
|
} else if (code >= 0x5b && code <= 0x5f) {
|
||||||
|
out = String.fromCharCode(code - 0x40);
|
||||||
|
} else if (code == 0x20) {
|
||||||
|
out = '\x00';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Alt is an ESC prefix on the character.
|
||||||
|
if (printable && alt) out = '\x1b$out';
|
||||||
|
}
|
||||||
|
_socket?.write(out);
|
||||||
|
if ((ctrl || alt || shift) && out.isNotEmpty) {
|
||||||
|
ctrl = false;
|
||||||
|
alt = false;
|
||||||
|
shift = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _create() async {
|
||||||
|
final client = app.client;
|
||||||
|
if (client == null) return;
|
||||||
|
_set(TerminalLinkState.creating);
|
||||||
|
try {
|
||||||
|
final info = await client.createTerminal(
|
||||||
|
cwd: directory, cols: _cols, rows: _rows);
|
||||||
|
if (_disposed) return;
|
||||||
|
sessionId = info.sessionId;
|
||||||
|
_cols = info.cols;
|
||||||
|
_rows = info.rows;
|
||||||
|
onSessionIdChanged?.call();
|
||||||
|
await _attach();
|
||||||
|
} catch (error) {
|
||||||
|
_set(TerminalLinkState.error, detail: _message(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _attach() async {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
if (client == null || id == null || _disposed) return;
|
||||||
|
await _socket?.dispose();
|
||||||
|
final socket = TerminalSocket(
|
||||||
|
transport: client.transport,
|
||||||
|
headers: client.eventHeaders,
|
||||||
|
sessionId: id,
|
||||||
|
onEvent: _onEvent,
|
||||||
|
onState: (state, {detail}) => _set(state, detail: detail),
|
||||||
|
);
|
||||||
|
_socket = socket;
|
||||||
|
await socket.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onEvent(TerminalEvent event) {
|
||||||
|
if (_disposed) return;
|
||||||
|
switch (event.type) {
|
||||||
|
case 'snapshot':
|
||||||
|
// Replay at the size the server drew the history for, then clear what
|
||||||
|
// this view already had: a reattach must not duplicate the screen.
|
||||||
|
if (event.cols != null && event.rows != null) {
|
||||||
|
model.resize(event.cols!, event.rows!);
|
||||||
|
}
|
||||||
|
_clear();
|
||||||
|
if (event.data.isNotEmpty) model.write(event.data);
|
||||||
|
if (event.status == 'exited') {
|
||||||
|
_set(TerminalLinkState.exited,
|
||||||
|
detail: event.exitCode == null
|
||||||
|
? tr('Exited')
|
||||||
|
: trArgs('Exit code {0}', [event.exitCode]));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'restarted':
|
||||||
|
_clear();
|
||||||
|
if (event.data.isNotEmpty) model.write(event.data);
|
||||||
|
_set(TerminalLinkState.open);
|
||||||
|
break;
|
||||||
|
case 'output':
|
||||||
|
model.write(event.data);
|
||||||
|
break;
|
||||||
|
case 'exit':
|
||||||
|
_set(TerminalLinkState.exited,
|
||||||
|
detail: event.exitCode == null
|
||||||
|
? tr('Exited')
|
||||||
|
: trArgs('Exit code {0}', [event.exitCode]));
|
||||||
|
break;
|
||||||
|
case 'error':
|
||||||
|
if (event.fatal) {
|
||||||
|
if (event.code == 'SESSION_NOT_FOUND') {
|
||||||
|
// The remembered id outlived the server's session (a server
|
||||||
|
// restart, or the idle reaper won a race with the attach): open a
|
||||||
|
// new shell instead of leaving a dead panel.
|
||||||
|
_recoverMissing();
|
||||||
|
} else {
|
||||||
|
_set(TerminalLinkState.error,
|
||||||
|
detail: event.message ?? event.code ?? tr('Terminal connection failed'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears the screen and the scrollback, then homes the cursor.
|
||||||
|
void _clear() => model.write('\x1b[2J\x1b[3J\x1b[H');
|
||||||
|
|
||||||
|
void _set(TerminalLinkState state, {String? detail}) {
|
||||||
|
link = state;
|
||||||
|
if (detail != null) this.detail = detail;
|
||||||
|
if (state == TerminalLinkState.open) this.detail = null;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleResize() {
|
||||||
|
_resizeTimer?.cancel();
|
||||||
|
_resizeTimer = Timer(const Duration(milliseconds: 250), () {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
if (client == null || id == null || _disposed) return;
|
||||||
|
client
|
||||||
|
.resizeTerminal(id, _cols, _rows, directory: directory)
|
||||||
|
.catchError((_) {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restarts the shell in place (the server keeps the session id).
|
||||||
|
Future<void> restart() async {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
if (client == null || id == null) return;
|
||||||
|
_set(TerminalLinkState.connecting);
|
||||||
|
try {
|
||||||
|
await client.restartTerminal(id,
|
||||||
|
cwd: directory, cols: _cols, rows: _rows);
|
||||||
|
if (_disposed) return;
|
||||||
|
_clear();
|
||||||
|
_set(TerminalLinkState.open);
|
||||||
|
} catch (error) {
|
||||||
|
_set(TerminalLinkState.error, detail: _message(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After the app returns from the background: the socket may be dead
|
||||||
|
/// without having reported it.
|
||||||
|
Future<void> reconnectIfNeeded() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
if (link == TerminalLinkState.exited || link == TerminalLinkState.error) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_socket == null) await _attach();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends the shell on the server and drops the socket.
|
||||||
|
Future<void> closeSession() async {
|
||||||
|
final client = app.client;
|
||||||
|
final id = sessionId;
|
||||||
|
sessionId = null;
|
||||||
|
_opened = false;
|
||||||
|
link = TerminalLinkState.idle;
|
||||||
|
detail = null;
|
||||||
|
onSessionIdChanged?.call();
|
||||||
|
await _socket?.dispose();
|
||||||
|
_socket = null;
|
||||||
|
if (!_disposed) notifyListeners();
|
||||||
|
if (client != null && id != null) {
|
||||||
|
try {
|
||||||
|
await client.closeTerminal(id, directory: directory);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops a session the server no longer has and opens another one in its
|
||||||
|
/// place, so a stale id does not leave the tab unusable.
|
||||||
|
Future<void> _recoverMissing() async {
|
||||||
|
if (_recovering || _disposed) return;
|
||||||
|
_recovering = true;
|
||||||
|
try {
|
||||||
|
sessionId = null;
|
||||||
|
onSessionIdChanged?.call();
|
||||||
|
await _socket?.dispose();
|
||||||
|
_socket = null;
|
||||||
|
if (_disposed) return;
|
||||||
|
_opened = true;
|
||||||
|
await _create();
|
||||||
|
} finally {
|
||||||
|
_recovering = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_disposed = true;
|
||||||
|
_resizeTimer?.cancel();
|
||||||
|
_socket?.dispose();
|
||||||
|
_socket = null;
|
||||||
|
// The session is left for the server's idle reaper when the app goes
|
||||||
|
// away; [closeSession] handles an explicit disconnect.
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
String _message(Object error) {
|
||||||
|
final text = '$error';
|
||||||
|
return text.startsWith('ApiError') ? text : text;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// The device's IANA time zone, which the statistics API wants for bucketing
|
||||||
|
// days. Dart only exposes the abbreviation ("CST"), and Guava/ICU's zone id
|
||||||
|
// lives on the Android side; the desktop build has no zone plugin, so it
|
||||||
|
// falls back to UTC (the UI still works, only the day boundaries shift).
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
const _channel = MethodChannel('openchamber/device');
|
||||||
|
|
||||||
|
String? _cached;
|
||||||
|
|
||||||
|
Future<String> deviceTimeZone() async {
|
||||||
|
final cached = _cached;
|
||||||
|
if (cached != null) return cached;
|
||||||
|
try {
|
||||||
|
final name = await _channel.invokeMethod<String>('ianaTimeZone');
|
||||||
|
if (name != null && name.isNotEmpty) return _cached = name;
|
||||||
|
} catch (_) {
|
||||||
|
// No handler (desktop) or a platform failure: UTC keeps the request valid.
|
||||||
|
}
|
||||||
|
return _cached = 'UTC';
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// The build's version: shown in 设置 → 关于 and sent to the server in pairing
|
||||||
|
// and relay handshakes. Read from the platform at startup, so pubspec.yaml
|
||||||
|
// stays the only place the number is written.
|
||||||
|
import 'package:package_info_plus/package_info_plus.dart';
|
||||||
|
|
||||||
|
/// The version this build was made from, empty until [loadAppVersion] has
|
||||||
|
/// read it. The Android build number is left out on purpose: an ABI split
|
||||||
|
/// prefixes it with its own digit, so it would differ between the APKs of one
|
||||||
|
/// release.
|
||||||
|
String appVersion = '';
|
||||||
|
|
||||||
|
/// Reads the version this build was made from. Failure leaves [appVersion]
|
||||||
|
/// empty: the handshake still works and 关于 says the version is unknown.
|
||||||
|
Future<void> loadAppVersion() async {
|
||||||
|
try {
|
||||||
|
final info =
|
||||||
|
await PackageInfo.fromPlatform().timeout(const Duration(seconds: 3));
|
||||||
|
appVersion = info.version.trim();
|
||||||
|
} catch (_) {
|
||||||
|
// Keep the empty fallback.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// Attachments shared by the chat composer and the new-session draft: what a
|
||||||
|
// picked file becomes (a data URL the server stores) and the chips that show
|
||||||
|
// it above the input.
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:file_picker/file_picker.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
class ComposerAttachment {
|
||||||
|
final String name;
|
||||||
|
final String mime;
|
||||||
|
final String dataUrl;
|
||||||
|
final String? path;
|
||||||
|
|
||||||
|
const ComposerAttachment({
|
||||||
|
required this.name,
|
||||||
|
required this.mime,
|
||||||
|
required this.dataUrl,
|
||||||
|
this.path,
|
||||||
|
});
|
||||||
|
|
||||||
|
bool get isImage => mime.startsWith('image/');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the system picker and turns each choice into an attachment. Files
|
||||||
|
/// over 10 MB are refused with a message instead of being dropped silently.
|
||||||
|
Future<List<ComposerAttachment>> pickComposerAttachments(
|
||||||
|
BuildContext context) async {
|
||||||
|
final picked = await FilePicker.pickFiles();
|
||||||
|
if (picked.isEmpty) return const [];
|
||||||
|
final out = <ComposerAttachment>[];
|
||||||
|
for (final file in picked) {
|
||||||
|
final bytes = await file.readAsBytes();
|
||||||
|
if (bytes.length > 10 * 1024 * 1024) {
|
||||||
|
if (context.mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(content: AppText('Attachments cannot be larger than 10 MB')));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final mime = _mimeOf(file.name);
|
||||||
|
String? keptPath;
|
||||||
|
if (mime.startsWith('image/') && file.path != null) {
|
||||||
|
keptPath = await _keepImage(file.path!, file.name);
|
||||||
|
}
|
||||||
|
out.add(ComposerAttachment(
|
||||||
|
name: file.name,
|
||||||
|
mime: mime,
|
||||||
|
dataUrl: 'data:$mime;base64,${base64Encode(bytes)}',
|
||||||
|
path: keptPath,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chips with a thumbnail, unfolded above the input bar.
|
||||||
|
class AttachmentTray extends StatelessWidget {
|
||||||
|
final List<ComposerAttachment> items;
|
||||||
|
final ValueChanged<int> onRemove;
|
||||||
|
|
||||||
|
const AttachmentTray({
|
||||||
|
super.key,
|
||||||
|
required this.items,
|
||||||
|
required this.onRemove,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return SizedBox(
|
||||||
|
height: 46,
|
||||||
|
child: ListView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
children: [
|
||||||
|
for (var i = 0; i < items.length; i++)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(right: 6),
|
||||||
|
child: InputChip(
|
||||||
|
avatar: items[i].path != null
|
||||||
|
? CircleAvatar(
|
||||||
|
backgroundImage: FileImage(File(items[i].path!)),
|
||||||
|
)
|
||||||
|
: const Icon(Icons.insert_drive_file, size: 16),
|
||||||
|
label: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 160),
|
||||||
|
child: Text(items[i].name,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
),
|
||||||
|
onDeleted: () => onRemove(i),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _mimeOf(String name) {
|
||||||
|
final ext = name.split('.').last.toLowerCase();
|
||||||
|
return switch (ext) {
|
||||||
|
'png' => 'image/png',
|
||||||
|
'jpg' || 'jpeg' => 'image/jpeg',
|
||||||
|
'gif' => 'image/gif',
|
||||||
|
'webp' => 'image/webp',
|
||||||
|
'bmp' => 'image/bmp',
|
||||||
|
'avif' => 'image/avif',
|
||||||
|
'ico' => 'image/x-icon',
|
||||||
|
'pdf' => 'application/pdf',
|
||||||
|
'json' => 'application/json',
|
||||||
|
'md' || 'markdown' => 'text/markdown',
|
||||||
|
'txt' => 'text/plain',
|
||||||
|
'csv' => 'text/csv',
|
||||||
|
'html' => 'text/html',
|
||||||
|
'xml' => 'text/xml',
|
||||||
|
'zip' => 'application/zip',
|
||||||
|
_ => 'application/octet-stream',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _keepImage(String src, String name) async {
|
||||||
|
try {
|
||||||
|
// No plugin needed: a cache copy is enough for the message being sent.
|
||||||
|
final dir = Directory(
|
||||||
|
'${Directory.systemTemp.path}/openchamber-attachments');
|
||||||
|
await dir.create(recursive: true);
|
||||||
|
final safe =
|
||||||
|
name.replaceAll(RegExp(r'[/\\:*?"<>|]'), '_');
|
||||||
|
final dst =
|
||||||
|
'${dir.path}/${DateTime.now().microsecondsSinceEpoch}-$safe';
|
||||||
|
await File(src).copy(dst);
|
||||||
|
return dst;
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
// The input capsule. Focus opens it into two rows — the text above, the
|
||||||
|
// model / mode / keys below — and losing focus folds it back to one line, the
|
||||||
|
// way dsh-Go's composer behaves. The field keeps its state across the two
|
||||||
|
// layouts through a GlobalKey.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class ComposerBox extends StatefulWidget {
|
||||||
|
final TextEditingController controller;
|
||||||
|
final FocusNode focusNode;
|
||||||
|
final String hint;
|
||||||
|
final int maxLines;
|
||||||
|
|
||||||
|
/// The soft keyboard's height, from the page (a Scaffold removes the bottom
|
||||||
|
/// view inset from its body, so the composer cannot read it itself).
|
||||||
|
final double keyboardInset;
|
||||||
|
final ValueChanged<String>? onChanged;
|
||||||
|
final ValueChanged<String>? onSubmitted;
|
||||||
|
final TextInputAction textInputAction;
|
||||||
|
|
||||||
|
/// The attach key; shown on the text's line when folded and on the second
|
||||||
|
/// row when open.
|
||||||
|
final Widget leading;
|
||||||
|
|
||||||
|
/// Model (and thinking level) pill, second row.
|
||||||
|
final Widget? model;
|
||||||
|
|
||||||
|
/// The mode (Build / Plan), second row and separate from [model].
|
||||||
|
final Widget? mode;
|
||||||
|
|
||||||
|
/// The context ring, right of the keys.
|
||||||
|
final Widget? accessory;
|
||||||
|
|
||||||
|
/// Send or stop.
|
||||||
|
final Widget trailing;
|
||||||
|
|
||||||
|
const ComposerBox({
|
||||||
|
super.key,
|
||||||
|
required this.controller,
|
||||||
|
required this.focusNode,
|
||||||
|
required this.hint,
|
||||||
|
required this.leading,
|
||||||
|
required this.trailing,
|
||||||
|
this.model,
|
||||||
|
this.mode,
|
||||||
|
this.accessory,
|
||||||
|
this.maxLines = 5,
|
||||||
|
this.keyboardInset = 0,
|
||||||
|
this.onChanged,
|
||||||
|
this.onSubmitted,
|
||||||
|
this.textInputAction = TextInputAction.newline,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ComposerBox> createState() => _ComposerBoxState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ComposerBoxState extends State<ComposerBox> {
|
||||||
|
// The editor moves between the one-line row and the two-line column; a
|
||||||
|
// GlobalKey carries its state (and its input connection) across the swap.
|
||||||
|
final GlobalKey _fieldKey = GlobalKey();
|
||||||
|
bool _open = false;
|
||||||
|
|
||||||
|
// The keyboard went down with the field still focused (the phone's back
|
||||||
|
// gesture closes the IME without unfocusing). dsh-Go folds the composer in
|
||||||
|
// that case too, so the same rule is kept here.
|
||||||
|
bool _keyboardDown = false;
|
||||||
|
double _keyboardPeak = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.focusNode.addListener(_onFocus);
|
||||||
|
_open = widget.focusNode.hasFocus;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
widget.focusNode.removeListener(_onFocus);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(ComposerBox oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (oldWidget.focusNode != widget.focusNode) {
|
||||||
|
oldWidget.focusNode.removeListener(_onFocus);
|
||||||
|
widget.focusNode.addListener(_onFocus);
|
||||||
|
}
|
||||||
|
if (oldWidget.keyboardInset != widget.keyboardInset) {
|
||||||
|
_keyboardMoved(oldWidget.keyboardInset, widget.keyboardInset);
|
||||||
|
// The build that follows reads this; no second one is needed.
|
||||||
|
_open = widget.focusNode.hasFocus && !_keyboardDown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeDependencies() {
|
||||||
|
super.didChangeDependencies();
|
||||||
|
// A sheet over the page takes the keyboard for a moment; when the page is
|
||||||
|
// current again, settle on where the composer should be.
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) => _syncOpen());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A keyboard rising clears "down"; falling to well under its peak means it
|
||||||
|
/// was dismissed (a height change alone stays open).
|
||||||
|
void _keyboardMoved(double before, double inset) {
|
||||||
|
if (!(ModalRoute.of(context)?.isCurrent ?? true)) return;
|
||||||
|
if (inset > before) {
|
||||||
|
_keyboardDown = false;
|
||||||
|
if (inset > _keyboardPeak) _keyboardPeak = inset;
|
||||||
|
} else if (inset < _keyboardPeak * 0.5) {
|
||||||
|
_keyboardDown = true;
|
||||||
|
_keyboardPeak = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onFocus() {
|
||||||
|
if (widget.focusNode.hasFocus) _keyboardDown = false;
|
||||||
|
_syncOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _syncOpen() {
|
||||||
|
if (!mounted) return;
|
||||||
|
// The model sheet (or any page over this one) takes focus for a moment:
|
||||||
|
// leave the composer as it is until it is current again.
|
||||||
|
if (!(ModalRoute.of(context)?.isCurrent ?? true)) return;
|
||||||
|
final open = widget.focusNode.hasFocus && !_keyboardDown;
|
||||||
|
if (open == _open) return;
|
||||||
|
setState(() => _open = open);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _field() {
|
||||||
|
return TextField(
|
||||||
|
key: _fieldKey,
|
||||||
|
controller: widget.controller,
|
||||||
|
focusNode: widget.focusNode,
|
||||||
|
minLines: 1,
|
||||||
|
maxLines: widget.maxLines,
|
||||||
|
keyboardType: TextInputType.multiline,
|
||||||
|
textInputAction: widget.textInputAction,
|
||||||
|
onChanged: widget.onChanged,
|
||||||
|
onSubmitted: widget.onSubmitted,
|
||||||
|
style: const TextStyle(fontSize: 15, height: 1.45),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: widget.hint,
|
||||||
|
hintMaxLines: 1,
|
||||||
|
isDense: true,
|
||||||
|
border: InputBorder.none,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(vertical: 6),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final accessory = widget.accessory;
|
||||||
|
return AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 200),
|
||||||
|
curve: Curves.easeOutCubic,
|
||||||
|
padding: const EdgeInsets.all(6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: scheme.surfaceContainerHighest,
|
||||||
|
borderRadius: BorderRadius.circular(_open ? 20 : 26),
|
||||||
|
),
|
||||||
|
child: AnimatedSize(
|
||||||
|
duration: const Duration(milliseconds: 200),
|
||||||
|
curve: Curves.easeOutCubic,
|
||||||
|
alignment: Alignment.bottomCenter,
|
||||||
|
child: _open
|
||||||
|
? Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(6, 0, 6, 2),
|
||||||
|
child: _field(),
|
||||||
|
),
|
||||||
|
_secondRow(),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
widget.leading,
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Expanded(child: _field()),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
if (accessory != null) ...[
|
||||||
|
// The keys are 36 high and the row aligns to its bottom:
|
||||||
|
// lift the smaller accessory by half the difference so it
|
||||||
|
// sits on the keys' centre line, not below it.
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 10),
|
||||||
|
child: accessory,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 2),
|
||||||
|
],
|
||||||
|
widget.trailing,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _secondRow() {
|
||||||
|
final accessory = widget.accessory;
|
||||||
|
// The row fades and rises a little as the composer opens.
|
||||||
|
return TweenAnimationBuilder<double>(
|
||||||
|
tween: Tween(begin: 0, end: 1),
|
||||||
|
duration: const Duration(milliseconds: 220),
|
||||||
|
curve: Curves.easeOutCubic,
|
||||||
|
builder: (context, t, child) => Opacity(
|
||||||
|
opacity: t,
|
||||||
|
child: Transform.translate(
|
||||||
|
offset: Offset(0, (1 - t) * 4),
|
||||||
|
child: child,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(0, 2, 0, 0),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
widget.leading,
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
if (widget.model != null)
|
||||||
|
Flexible(
|
||||||
|
fit: FlexFit.loose,
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: widget.model!,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
if (widget.mode != null) widget.mode!,
|
||||||
|
const Spacer(),
|
||||||
|
if (accessory != null) ...[
|
||||||
|
accessory,
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
],
|
||||||
|
widget.trailing,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
// Line-level diffs for edit/write/patch tool calls, as the first-party and
|
||||||
|
// dsh-Go clients show them: added and removed lines tinted, hunk headers
|
||||||
|
// marked, and the before/after text never dumped as one blob.
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
enum DiffLineKind { context, add, del, hunk, meta }
|
||||||
|
|
||||||
|
class DiffLine {
|
||||||
|
final DiffLineKind kind;
|
||||||
|
final String text;
|
||||||
|
|
||||||
|
const DiffLine(this.kind, this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
class DiffFile {
|
||||||
|
/// The path the server put in the tool metadata, when it named one.
|
||||||
|
final String? path;
|
||||||
|
final List<DiffLine> lines;
|
||||||
|
|
||||||
|
const DiffFile({this.path, required this.lines});
|
||||||
|
|
||||||
|
int get added =>
|
||||||
|
lines.where((line) => line.kind == DiffLineKind.add).length;
|
||||||
|
|
||||||
|
int get removed =>
|
||||||
|
lines.where((line) => line.kind == DiffLineKind.del).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
const _diffTools = {
|
||||||
|
'edit',
|
||||||
|
'write',
|
||||||
|
'create',
|
||||||
|
'file_write',
|
||||||
|
'patch',
|
||||||
|
'apply_patch',
|
||||||
|
'str_replace',
|
||||||
|
'str_replace_based_edit_tool',
|
||||||
|
};
|
||||||
|
|
||||||
|
bool isDiffTool(String? name) => _diffTools.contains(name ?? '');
|
||||||
|
|
||||||
|
String? _text(Object? value) => value is String ? value : null;
|
||||||
|
|
||||||
|
String? _nonEmptyText(Object? value) {
|
||||||
|
final text = _text(value);
|
||||||
|
return text == null || text.trim().isEmpty ? null : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _patchText(Object? value) {
|
||||||
|
if (value is Map) {
|
||||||
|
return _nonEmptyText(value['patch']) ?? _nonEmptyText(value['diff']);
|
||||||
|
}
|
||||||
|
return _nonEmptyText(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _filePath(Map<dynamic, dynamic> file) =>
|
||||||
|
_nonEmptyText(file['file']) ??
|
||||||
|
_nonEmptyText(file['filePath']) ??
|
||||||
|
_nonEmptyText(file['relativePath']) ??
|
||||||
|
_nonEmptyText(file['movePath']);
|
||||||
|
|
||||||
|
/// The diff a tool call carries, from the server's `metadata.files[].patch`
|
||||||
|
/// (falling back to a top-level patch), or computed from the edit's old/new
|
||||||
|
/// text when an older server sends no patch.
|
||||||
|
List<DiffFile> toolDiffFiles(ContentPart part) {
|
||||||
|
if (part.type != 'tool' || !isDiffTool(part.name)) return const [];
|
||||||
|
final state = part.state;
|
||||||
|
if (state == null) return const [];
|
||||||
|
if (_nonEmptyText(state.error) != null) return const [];
|
||||||
|
|
||||||
|
final files = <DiffFile>[];
|
||||||
|
final metadata = state.metadata;
|
||||||
|
final rawFiles = metadata?['files'];
|
||||||
|
if (rawFiles is List) {
|
||||||
|
for (final raw in rawFiles) {
|
||||||
|
if (raw is! Map) continue;
|
||||||
|
final patch =
|
||||||
|
_patchText(raw['patch']) ?? _patchText(raw['diff']);
|
||||||
|
if (patch == null) continue;
|
||||||
|
final lines = parseUnifiedDiff(patch);
|
||||||
|
if (lines.isEmpty) continue;
|
||||||
|
files.add(DiffFile(path: _filePath(raw), lines: lines));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (files.isEmpty) {
|
||||||
|
final patch =
|
||||||
|
_patchText(metadata?['patch']) ?? _patchText(metadata?['diff']);
|
||||||
|
if (patch != null) {
|
||||||
|
final lines = parseUnifiedDiff(patch);
|
||||||
|
if (lines.isNotEmpty) files.add(DiffFile(lines: lines));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (files.isEmpty) {
|
||||||
|
final input = state.input;
|
||||||
|
final path = _nonEmptyText(input['path']) ??
|
||||||
|
_nonEmptyText(input['filePath']) ??
|
||||||
|
_nonEmptyText(input['file_path']);
|
||||||
|
final oldText = _text(input['oldString']) ??
|
||||||
|
_text(input['old_string']) ??
|
||||||
|
_text(input['old_str']);
|
||||||
|
final newText = _text(input['newString']) ??
|
||||||
|
_text(input['new_string']) ??
|
||||||
|
_text(input['new_str']);
|
||||||
|
if (newText != null) {
|
||||||
|
final lines = computeLineDiff(oldText ?? '', newText);
|
||||||
|
if (lines.isNotEmpty) files.add(DiffFile(path: path, lines: lines));
|
||||||
|
} else if (part.name == 'write' ||
|
||||||
|
part.name == 'create' ||
|
||||||
|
part.name == 'file_write') {
|
||||||
|
final content = _text(input['content']) ?? _text(input['file_text']);
|
||||||
|
if (content != null && content.isNotEmpty) {
|
||||||
|
files.add(DiffFile(
|
||||||
|
path: path,
|
||||||
|
lines: [
|
||||||
|
for (final line in content.replaceAll('\r\n', '\n').split('\n'))
|
||||||
|
DiffLine(DiffLineKind.add, '+$line'),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A unified diff: `@@` hunks, `+++`/`---`/`diff`/`index` metadata, `+` and
|
||||||
|
/// `-` changes, everything else context. Trailing blank context is dropped so
|
||||||
|
/// a file's diff ends on its last real line.
|
||||||
|
List<DiffLine> parseUnifiedDiff(String text) {
|
||||||
|
final lines = <DiffLine>[];
|
||||||
|
for (final raw in text.replaceAll('\r\n', '\n').split('\n')) {
|
||||||
|
final kind = raw.startsWith('@@')
|
||||||
|
? DiffLineKind.hunk
|
||||||
|
: raw.startsWith('+++') ||
|
||||||
|
raw.startsWith('---') ||
|
||||||
|
raw.startsWith('diff ') ||
|
||||||
|
raw.startsWith('index ') ||
|
||||||
|
raw.startsWith('Index: ') ||
|
||||||
|
raw.startsWith('===')
|
||||||
|
? DiffLineKind.meta
|
||||||
|
: raw.startsWith('+')
|
||||||
|
? DiffLineKind.add
|
||||||
|
: raw.startsWith('-')
|
||||||
|
? DiffLineKind.del
|
||||||
|
: DiffLineKind.context;
|
||||||
|
lines.add(DiffLine(kind, raw));
|
||||||
|
}
|
||||||
|
while (lines.isNotEmpty &&
|
||||||
|
lines.last.kind == DiffLineKind.context &&
|
||||||
|
lines.last.text.isEmpty) {
|
||||||
|
lines.removeLast();
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Line-level LCS diff for an edit that came without server patches. Very
|
||||||
|
/// large pairs fall back to one removed and one added block.
|
||||||
|
List<DiffLine> computeLineDiff(String oldText, String newText) {
|
||||||
|
final a = oldText.isEmpty ? <String>[] : oldText.split('\n');
|
||||||
|
final b = newText.isEmpty ? <String>[] : newText.split('\n');
|
||||||
|
if (a.length * b.length > 400 * 400) {
|
||||||
|
return [
|
||||||
|
for (final line in a) DiffLine(DiffLineKind.del, '-$line'),
|
||||||
|
for (final line in b) DiffLine(DiffLineKind.add, '+$line'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
final dp = List.generate(
|
||||||
|
a.length + 1, (_) => List<int>.filled(b.length + 1, 0));
|
||||||
|
for (var i = a.length - 1; i >= 0; i--) {
|
||||||
|
for (var j = b.length - 1; j >= 0; j--) {
|
||||||
|
dp[i][j] = a[i] == b[j]
|
||||||
|
? dp[i + 1][j + 1] + 1
|
||||||
|
: math.max(dp[i + 1][j], dp[i][j + 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final lines = <DiffLine>[];
|
||||||
|
var i = 0;
|
||||||
|
var j = 0;
|
||||||
|
while (i < a.length && j < b.length) {
|
||||||
|
if (a[i] == b[j]) {
|
||||||
|
lines.add(DiffLine(DiffLineKind.context, ' ${a[i]}'));
|
||||||
|
i++;
|
||||||
|
j++;
|
||||||
|
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
||||||
|
lines.add(DiffLine(DiffLineKind.del, '-${a[i]}'));
|
||||||
|
i++;
|
||||||
|
} else {
|
||||||
|
lines.add(DiffLine(DiffLineKind.add, '+${b[j]}'));
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (i < a.length) {
|
||||||
|
lines.add(DiffLine(DiffLineKind.del, '-${a[i]}'));
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
while (j < b.length) {
|
||||||
|
lines.add(DiffLine(DiffLineKind.add, '+${b[j]}'));
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tinted, horizontally wrapped diff lines. Selection spans the whole block,
|
||||||
|
/// so the diff can be copied line by line as it reads.
|
||||||
|
class DiffView extends StatelessWidget {
|
||||||
|
final List<DiffFile> files;
|
||||||
|
|
||||||
|
/// Phone-sized preview: a huge generated diff does not build thousands of
|
||||||
|
/// rows in the message list; the rest is counted, not drawn.
|
||||||
|
final int maxLines;
|
||||||
|
|
||||||
|
const DiffView({super.key, required this.files, this.maxLines = 600});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
final dark = theme.brightness == Brightness.dark;
|
||||||
|
final addBg = const Color(0xFF22C55E).withValues(alpha: dark ? 0.18 : 0.12);
|
||||||
|
final addFg =
|
||||||
|
dark ? const Color(0xFF86E7A6) : const Color(0xFF116329);
|
||||||
|
final delBg = const Color(0xFFEF4444).withValues(alpha: dark ? 0.18 : 0.12);
|
||||||
|
final delFg =
|
||||||
|
dark ? const Color(0xFFFF9B9B) : const Color(0xFFA40E26);
|
||||||
|
final hunkBg = scheme.primary.withValues(alpha: dark ? 0.10 : 0.07);
|
||||||
|
const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace');
|
||||||
|
|
||||||
|
var remaining = maxLines;
|
||||||
|
var total = 0;
|
||||||
|
for (final file in files) {
|
||||||
|
total += file.lines.length;
|
||||||
|
}
|
||||||
|
final rows = <Widget>[];
|
||||||
|
for (var fileIndex = 0; fileIndex < files.length; fileIndex++) {
|
||||||
|
final file = files[fileIndex];
|
||||||
|
if (files.length > 1) {
|
||||||
|
rows.add(Container(
|
||||||
|
color: scheme.surfaceContainer,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
file.path ?? trArgs('File {0}', [fileIndex + 1]),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: scheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
DiffStats(added: file.added, removed: file.removed),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for (final line in file.lines) {
|
||||||
|
// The step row already names the file; `Index:`/`---`/`+++` headers
|
||||||
|
// are noise above the hunks (the first-party viewer hides them too).
|
||||||
|
if (line.kind == DiffLineKind.meta) continue;
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
remaining--;
|
||||||
|
final (background, foreground) = switch (line.kind) {
|
||||||
|
DiffLineKind.add => (addBg, addFg),
|
||||||
|
DiffLineKind.del => (delBg, delFg),
|
||||||
|
DiffLineKind.hunk => (hunkBg, scheme.primary),
|
||||||
|
DiffLineKind.meta => (null, theme.hintColor),
|
||||||
|
DiffLineKind.context => (null, scheme.onSurfaceVariant),
|
||||||
|
};
|
||||||
|
rows.add(Container(
|
||||||
|
color: background,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
|
||||||
|
child: Text(
|
||||||
|
line.text.isEmpty ? ' ' : line.text,
|
||||||
|
style: mono.copyWith(color: foreground),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (total > maxLines) {
|
||||||
|
rows.add(Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
|
||||||
|
child: AppText(
|
||||||
|
trArgs('Showing the first {0} of {1} lines', [maxLines, total]),
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: scheme.surfaceContainerHighest,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: SelectionArea(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: rows,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `+3 −1`, as the row and a multi-file header show it.
|
||||||
|
class DiffStats extends StatelessWidget {
|
||||||
|
final int added;
|
||||||
|
final int removed;
|
||||||
|
|
||||||
|
const DiffStats({super.key, required this.added, required this.removed});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final dark = Theme.of(context).brightness == Brightness.dark;
|
||||||
|
final addFg =
|
||||||
|
dark ? const Color(0xFF86E7A6) : const Color(0xFF116329);
|
||||||
|
final delFg =
|
||||||
|
dark ? const Color(0xFFFF9B9B) : const Color(0xFFA40E26);
|
||||||
|
const style = TextStyle(fontSize: 11, fontFamily: 'monospace');
|
||||||
|
return Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (added > 0) AppText('+$added', style: style.copyWith(color: addFg)),
|
||||||
|
if (added > 0 && removed > 0) const SizedBox(width: 4),
|
||||||
|
if (removed > 0)
|
||||||
|
AppText('−$removed', style: style.copyWith(color: delFg)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
// The add-project browser: walks the server's directories from the user's
|
||||||
|
// home and adds the chosen folder to OpenChamber's project list. A project
|
||||||
|
// stored only in the settings document (no session yet) is still a valid
|
||||||
|
// target; the first session in it makes OpenCode list it too.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
|
||||||
|
/// Opens the folder browser and returns the canonical path that was added, or
|
||||||
|
/// null when the sheet was dismissed.
|
||||||
|
Future<String?> showDirectoryPicker(BuildContext context,
|
||||||
|
{required AppState app}) {
|
||||||
|
return showModalBottomSheet<String>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
useSafeArea: true,
|
||||||
|
builder: (context) => Padding(
|
||||||
|
// Keep the sheet above the keyboard; the folder list gets the rest.
|
||||||
|
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
|
||||||
|
child: FractionallySizedBox(
|
||||||
|
heightFactor: 0.9,
|
||||||
|
child: _DirectoryPickerSheet(app: app),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DirectoryPickerSheet extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
|
||||||
|
const _DirectoryPickerSheet({required this.app});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_DirectoryPickerSheet> createState() => _DirectoryPickerSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DirectoryPickerSheetState extends State<_DirectoryPickerSheet> {
|
||||||
|
final TextEditingController _pathCtrl = TextEditingController();
|
||||||
|
String _path = '';
|
||||||
|
List<FsEntry> _dirs = const [];
|
||||||
|
bool _loading = true;
|
||||||
|
bool _adding = false;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
AppState get _app => widget.app;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_pathCtrl.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _start() async {
|
||||||
|
var home = _app.homeDirectory.trim();
|
||||||
|
if (home.isEmpty) {
|
||||||
|
try {
|
||||||
|
home = (await _app.client?.fsHome())?.home.trim() ?? '';
|
||||||
|
} catch (_) {
|
||||||
|
// Fall back to the filesystem root; the path field still works.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await _open(home.isEmpty ? '/' : home);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// trims a typed path, keeps the root and drops trailing separators.
|
||||||
|
String _normalize(String path) {
|
||||||
|
var p = path.trim();
|
||||||
|
if (p.isEmpty) return '/';
|
||||||
|
while (p.length > 1 && (p.endsWith('/') || p.endsWith('\\'))) {
|
||||||
|
p = p.substring(0, p.length - 1);
|
||||||
|
}
|
||||||
|
return p.isEmpty ? '/' : p;
|
||||||
|
}
|
||||||
|
|
||||||
|
String _parent(String path) {
|
||||||
|
final p = _normalize(path);
|
||||||
|
if (p == '/') return '/';
|
||||||
|
final index = p.lastIndexOf(RegExp(r'[/\\]'));
|
||||||
|
if (index <= 0) return '/';
|
||||||
|
return p.substring(0, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _join(String folder) => _path == '/' ? '/$folder' : '$_path/$folder';
|
||||||
|
|
||||||
|
Future<void> _open(String path) async {
|
||||||
|
final target = _normalize(path);
|
||||||
|
setState(() {
|
||||||
|
_path = target;
|
||||||
|
_pathCtrl.text = target;
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
final client = _app.client;
|
||||||
|
if (client == null) {
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_error = tr('Not connected to a server');
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final entries =
|
||||||
|
await client.fsList(target, respectGitignore: false);
|
||||||
|
final dirs = [
|
||||||
|
for (final entry in entries)
|
||||||
|
if (entry.isDirectory) entry,
|
||||||
|
]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_dirs = dirs;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_dirs = const [];
|
||||||
|
_loading = false;
|
||||||
|
_error = trArgs('Could not load this folder: {0}', [e]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _createFolder() async {
|
||||||
|
final name = await _askFolderName();
|
||||||
|
if (name == null || !mounted) return;
|
||||||
|
final client = _app.client;
|
||||||
|
if (client == null) return;
|
||||||
|
final target = _join(name);
|
||||||
|
try {
|
||||||
|
await client.fsMkdir(target);
|
||||||
|
if (!mounted) return;
|
||||||
|
await _open(target);
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _error = trArgs('Could not create the folder: {0}', [e]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _askFolderName() async {
|
||||||
|
final controller = TextEditingController();
|
||||||
|
final name = await showDialog<String>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
title: const AppText('New folder'),
|
||||||
|
content: TextField(
|
||||||
|
controller: controller,
|
||||||
|
autofocus: true,
|
||||||
|
decoration: InputDecoration(hintText: tr('Folder name')),
|
||||||
|
onSubmitted: (value) => Navigator.pop(context, value.trim()),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
child: const AppText('Cancel')),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.pop(context, controller.text.trim()),
|
||||||
|
child: const AppText('Create')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
controller.dispose();
|
||||||
|
if (name == null || name.isEmpty) return null;
|
||||||
|
if (name == '.' || name == '..' || name.contains('/') || name.contains('\\')) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: AppText(tr('Enter a valid folder name'))));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _add() async {
|
||||||
|
if (_adding || _loading) return;
|
||||||
|
setState(() {
|
||||||
|
_adding = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final project = await _app.addProjectDirectory(_path);
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.pop(context, project?.canonical ?? _path);
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_adding = false;
|
||||||
|
_error = trArgs('Could not add the project: {0}', [e]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Column(
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(4, 6, 12, 0),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close),
|
||||||
|
tooltip: tr('Close'),
|
||||||
|
onPressed: () => Navigator.pop(context)),
|
||||||
|
const Expanded(
|
||||||
|
child: AppText('Add project',
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 4, 12, 6),
|
||||||
|
child: TextField(
|
||||||
|
controller: _pathCtrl,
|
||||||
|
textInputAction: TextInputAction.go,
|
||||||
|
onSubmitted: _open,
|
||||||
|
style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
isDense: true,
|
||||||
|
prefixIcon: const Icon(Icons.folder_outlined, size: 18),
|
||||||
|
hintText: tr('Folder path'),
|
||||||
|
border:
|
||||||
|
OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
|
||||||
|
suffixIcon: TextButton(
|
||||||
|
onPressed: () => _open(_pathCtrl.text),
|
||||||
|
child: const AppText('Go')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_upward, size: 18),
|
||||||
|
tooltip: tr('Up'),
|
||||||
|
onPressed: _path == '/' ? null : () => _open(_parent(_path)),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
_path,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: _createFolder,
|
||||||
|
icon: const Icon(Icons.create_new_folder_outlined, size: 18),
|
||||||
|
label: const AppText('New folder'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_error != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),
|
||||||
|
child: Text(_error!,
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.colorScheme.error)),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: _loading
|
||||||
|
? const Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2)))
|
||||||
|
: ListView(
|
||||||
|
children: [
|
||||||
|
for (final entry in _dirs)
|
||||||
|
ListTile(
|
||||||
|
dense: true,
|
||||||
|
leading:
|
||||||
|
const Icon(Icons.folder_outlined, size: 20),
|
||||||
|
title: Text(entry.name,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
trailing:
|
||||||
|
const Icon(Icons.chevron_right, size: 18),
|
||||||
|
onTap: () => _open(entry.path),
|
||||||
|
),
|
||||||
|
if (_dirs.isEmpty && _error == null)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.all(24),
|
||||||
|
child: AppText('No folders here',
|
||||||
|
textAlign: TextAlign.center),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SafeArea(
|
||||||
|
top: false,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
|
||||||
|
child: SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: FilledButton.icon(
|
||||||
|
onPressed: _adding || _loading ? null : _add,
|
||||||
|
icon: _adding
|
||||||
|
? const SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2))
|
||||||
|
: const Icon(Icons.add, size: 18),
|
||||||
|
label: const AppText('Add this folder'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,460 @@
|
|||||||
|
// Full-screen picture viewer, modelled on dsh-Go's image gallery: black
|
||||||
|
// background, one picture per page, pinch to 8x, double-tap to 2.5x around the
|
||||||
|
// touched point, drag to pan. Paging is disabled while a picture is zoomed so
|
||||||
|
// a drag pans the picture instead of swiping to the next one. A single tap
|
||||||
|
// hides the title/keys so nothing covers the picture; another tap brings them
|
||||||
|
// back.
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io' show Platform;
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../api/client.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// One picture in the viewer. [source] is a `data:` URL or a file path the
|
||||||
|
/// client can read with the session's directory.
|
||||||
|
class ImageSlide {
|
||||||
|
final String title;
|
||||||
|
final String source;
|
||||||
|
const ImageSlide(this.title, this.source);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens [images] at [initial] as a full-screen gallery.
|
||||||
|
Future<void> showImageViewer(
|
||||||
|
BuildContext context, {
|
||||||
|
required List<ImageSlide> images,
|
||||||
|
int initial = 0,
|
||||||
|
required String directory,
|
||||||
|
required Client client,
|
||||||
|
}) {
|
||||||
|
if (images.isEmpty) return Future.value();
|
||||||
|
return Navigator.of(context).push(PageRouteBuilder<void>(
|
||||||
|
opaque: true,
|
||||||
|
transitionDuration: const Duration(milliseconds: 180),
|
||||||
|
reverseTransitionDuration: const Duration(milliseconds: 140),
|
||||||
|
pageBuilder: (_, __, ___) => ImageViewerPage(
|
||||||
|
images: images,
|
||||||
|
initial: initial.clamp(0, images.length - 1),
|
||||||
|
directory: directory,
|
||||||
|
client: client,
|
||||||
|
),
|
||||||
|
transitionsBuilder: (_, animation, __, child) =>
|
||||||
|
FadeTransition(opacity: animation, child: child),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
class ImageViewerPage extends StatefulWidget {
|
||||||
|
final List<ImageSlide> images;
|
||||||
|
final int initial;
|
||||||
|
final String directory;
|
||||||
|
final Client client;
|
||||||
|
|
||||||
|
/// Whether to offer save/share; null follows the platform (Android only).
|
||||||
|
/// Tests set it to true on the desktop host.
|
||||||
|
final bool? mediaActions;
|
||||||
|
|
||||||
|
const ImageViewerPage({
|
||||||
|
super.key,
|
||||||
|
required this.images,
|
||||||
|
this.initial = 0,
|
||||||
|
required this.directory,
|
||||||
|
required this.client,
|
||||||
|
this.mediaActions,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ImageViewerPage> createState() => _ImageViewerPageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ImageViewerPageState extends State<ImageViewerPage> {
|
||||||
|
static const MethodChannel _media = MethodChannel('openchamber/media');
|
||||||
|
|
||||||
|
late int _index = widget.initial;
|
||||||
|
late final PageController _pages = PageController(initialPage: _index);
|
||||||
|
final Map<int, Uint8List> _loaded = {};
|
||||||
|
bool _zoomed = false;
|
||||||
|
bool _chrome = true;
|
||||||
|
bool _saving = false;
|
||||||
|
|
||||||
|
ImageSlide get _current => widget.images[_index];
|
||||||
|
Uint8List? get _currentBytes => _loaded[_index];
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_pages.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _toggleChrome() => setState(() => _chrome = !_chrome);
|
||||||
|
|
||||||
|
void _loadedAt(int index, Uint8List bytes) {
|
||||||
|
if (_loaded[index] == bytes) return;
|
||||||
|
// A data URL decodes synchronously, so this can arrive while the page is
|
||||||
|
// still building; update after the frame.
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _loaded[index] = bytes);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _snack(String text) {
|
||||||
|
ScaffoldMessenger.of(context)
|
||||||
|
..hideCurrentSnackBar()
|
||||||
|
..showSnackBar(SnackBar(content: Text(text)));
|
||||||
|
}
|
||||||
|
|
||||||
|
String _mimeOf(ImageSlide slide) {
|
||||||
|
final source = slide.source;
|
||||||
|
if (source.startsWith('data:')) {
|
||||||
|
final colon = source.indexOf(':');
|
||||||
|
final semi = source.indexOf(';');
|
||||||
|
if (colon >= 0 && semi > colon) {
|
||||||
|
return source.substring(colon + 1, semi);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final name = slide.title.isNotEmpty ? slide.title : source;
|
||||||
|
final dot = name.lastIndexOf('.');
|
||||||
|
final ext = dot >= 0 ? name.substring(dot + 1).toLowerCase() : '';
|
||||||
|
return switch (ext) {
|
||||||
|
'jpg' || 'jpeg' => 'image/jpeg',
|
||||||
|
'gif' => 'image/gif',
|
||||||
|
'webp' => 'image/webp',
|
||||||
|
'bmp' => 'image/bmp',
|
||||||
|
'avif' => 'image/avif',
|
||||||
|
_ => 'image/png',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
String _extensionFor(String mime) => switch (mime) {
|
||||||
|
'image/jpeg' => 'jpg',
|
||||||
|
'image/gif' => 'gif',
|
||||||
|
'image/webp' => 'webp',
|
||||||
|
'image/bmp' => 'bmp',
|
||||||
|
'image/avif' => 'avif',
|
||||||
|
_ => 'png',
|
||||||
|
};
|
||||||
|
|
||||||
|
String _fileName(ImageSlide slide) {
|
||||||
|
var name = slide.title.trim().replaceAll(RegExp(r'[/\\]'), '_');
|
||||||
|
if (name.isEmpty) name = 'image';
|
||||||
|
final dot = name.lastIndexOf('.');
|
||||||
|
if (dot <= 0 || dot == name.length - 1) {
|
||||||
|
name = '$name.${_extensionFor(_mimeOf(slide))}';
|
||||||
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _save() async {
|
||||||
|
final bytes = _currentBytes;
|
||||||
|
if (bytes == null || _saving) return;
|
||||||
|
setState(() => _saving = true);
|
||||||
|
try {
|
||||||
|
await _media.invokeMethod<bool>('saveImage', {
|
||||||
|
'bytes': bytes,
|
||||||
|
'name': _fileName(_current),
|
||||||
|
'mime': _mimeOf(_current),
|
||||||
|
});
|
||||||
|
if (mounted) _snack(tr('Saved to Photos'));
|
||||||
|
} on PlatformException catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
_snack(e.code == 'permission'
|
||||||
|
? tr('Storage permission is required to save the picture')
|
||||||
|
: (e.message ?? tr("Couldn't save the picture")));
|
||||||
|
} catch (_) {
|
||||||
|
if (mounted) _snack(tr("Couldn't save the picture"));
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _saving = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _share() async {
|
||||||
|
final bytes = _currentBytes;
|
||||||
|
if (bytes == null) return;
|
||||||
|
try {
|
||||||
|
await _media.invokeMethod<bool>('shareImage', {
|
||||||
|
'bytes': bytes,
|
||||||
|
'name': _fileName(_current),
|
||||||
|
'mime': _mimeOf(_current),
|
||||||
|
});
|
||||||
|
} on PlatformException catch (e) {
|
||||||
|
if (mounted) _snack(e.message ?? tr('Share failed'));
|
||||||
|
} catch (_) {
|
||||||
|
if (mounted) _snack(tr('Share failed'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final padding = MediaQuery.paddingOf(context);
|
||||||
|
final image = widget.images[_index];
|
||||||
|
final canSave = _currentBytes != null;
|
||||||
|
final showMedia = widget.mediaActions ?? Platform.isAndroid;
|
||||||
|
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||||
|
value: SystemUiOverlayStyle.light,
|
||||||
|
child: Scaffold(
|
||||||
|
backgroundColor: Colors.black,
|
||||||
|
body: Stack(
|
||||||
|
children: [
|
||||||
|
Positioned.fill(
|
||||||
|
child: PageView.builder(
|
||||||
|
controller: _pages,
|
||||||
|
physics: _zoomed
|
||||||
|
? const NeverScrollableScrollPhysics()
|
||||||
|
: const PageScrollPhysics(),
|
||||||
|
itemCount: widget.images.length,
|
||||||
|
onPageChanged: (index) => setState(() {
|
||||||
|
_index = index;
|
||||||
|
_zoomed = false;
|
||||||
|
}),
|
||||||
|
itemBuilder: (context, index) => _ZoomableImage(
|
||||||
|
// A page that leaves the viewport forgets its zoom.
|
||||||
|
key: ValueKey((index, index == _index)),
|
||||||
|
slide: widget.images[index],
|
||||||
|
directory: widget.directory,
|
||||||
|
client: widget.client,
|
||||||
|
onTap: _toggleChrome,
|
||||||
|
onLoaded: (bytes) => _loadedAt(index, bytes),
|
||||||
|
onZoomChanged: (zoomed) {
|
||||||
|
if (index == _index && zoomed != _zoomed) {
|
||||||
|
setState(() => _zoomed = zoomed);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// The title and keys cover part of a picture, so a tap hides them
|
||||||
|
// until the next tap. The gradient keeps them readable.
|
||||||
|
Positioned(
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
child: AnimatedOpacity(
|
||||||
|
key: const ValueKey('viewer-chrome'),
|
||||||
|
opacity: _chrome ? 1 : 0,
|
||||||
|
duration: const Duration(milliseconds: 160),
|
||||||
|
child: IgnorePointer(
|
||||||
|
ignoring: !_chrome,
|
||||||
|
child: Container(
|
||||||
|
padding: EdgeInsets.only(top: padding.top + 4),
|
||||||
|
decoration: const BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: [Colors.black54, Colors.transparent],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_back),
|
||||||
|
color: Colors.white,
|
||||||
|
tooltip: tr('Back'),
|
||||||
|
onPressed: () => Navigator.of(context).maybePop(),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
image.title,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: FontWeight.w500),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (showMedia) ...[
|
||||||
|
IconButton(
|
||||||
|
icon: _saving
|
||||||
|
? const SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: Colors.white))
|
||||||
|
: const Icon(Icons.download_outlined),
|
||||||
|
color: Colors.white,
|
||||||
|
tooltip: tr('Save to Photos'),
|
||||||
|
onPressed: canSave && !_saving ? _save : null,
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.ios_share),
|
||||||
|
color: Colors.white,
|
||||||
|
tooltip: tr('Share'),
|
||||||
|
onPressed: canSave ? _share : null,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (widget.images.length > 1)
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: padding.bottom + 16,
|
||||||
|
child: AnimatedOpacity(
|
||||||
|
key: const ValueKey('viewer-page-indicator'),
|
||||||
|
opacity: _chrome ? 1 : 0,
|
||||||
|
duration: const Duration(milliseconds: 160),
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: Text(
|
||||||
|
'${_index + 1} / ${widget.images.length}',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white70, fontSize: 13),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ZoomableImage extends StatefulWidget {
|
||||||
|
final ImageSlide slide;
|
||||||
|
final String directory;
|
||||||
|
final Client client;
|
||||||
|
final VoidCallback? onTap;
|
||||||
|
final ValueChanged<Uint8List>? onLoaded;
|
||||||
|
final ValueChanged<bool>? onZoomChanged;
|
||||||
|
|
||||||
|
const _ZoomableImage({
|
||||||
|
super.key,
|
||||||
|
required this.slide,
|
||||||
|
required this.directory,
|
||||||
|
required this.client,
|
||||||
|
this.onTap,
|
||||||
|
this.onLoaded,
|
||||||
|
this.onZoomChanged,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_ZoomableImage> createState() => _ZoomableImageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ZoomableImageState extends State<_ZoomableImage> {
|
||||||
|
static const double _maxScale = 8;
|
||||||
|
static const double _doubleTapScale = 2.5;
|
||||||
|
|
||||||
|
final TransformationController _transform = TransformationController();
|
||||||
|
Uint8List? _bytes;
|
||||||
|
Object? _error;
|
||||||
|
bool _loading = true;
|
||||||
|
bool _zoomed = false;
|
||||||
|
Offset _doubleTap = Offset.zero;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_transform.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
try {
|
||||||
|
final source = widget.slide.source;
|
||||||
|
final bytes = source.startsWith('data:')
|
||||||
|
? _dataUrlBytes(source)
|
||||||
|
: Uint8List.fromList(
|
||||||
|
await widget.client.rawFile(source, directory: widget.directory));
|
||||||
|
if (!mounted) return;
|
||||||
|
widget.onLoaded?.call(bytes);
|
||||||
|
setState(() {
|
||||||
|
_bytes = bytes;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = e;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Uint8List _dataUrlBytes(String source) {
|
||||||
|
final comma = source.indexOf(',');
|
||||||
|
if (comma < 0) throw Exception(tr('Invalid data URL'));
|
||||||
|
if (!source.substring(5, comma).contains('base64')) {
|
||||||
|
throw Exception(tr('Unsupported data URL'));
|
||||||
|
}
|
||||||
|
return base64Decode(source.substring(comma + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void _notifyZoom() {
|
||||||
|
final zoomed = _transform.value.getMaxScaleOnAxis() > 1.01;
|
||||||
|
if (zoomed == _zoomed) return;
|
||||||
|
setState(() => _zoomed = zoomed);
|
||||||
|
widget.onZoomChanged?.call(zoomed);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _toggleZoom() {
|
||||||
|
final scale = _transform.value.getMaxScaleOnAxis();
|
||||||
|
if (scale > 1.01) {
|
||||||
|
_transform.value = Matrix4.identity();
|
||||||
|
} else {
|
||||||
|
final p = _doubleTap;
|
||||||
|
_transform.value = Matrix4.identity()
|
||||||
|
..translate(p.dx, p.dy)
|
||||||
|
..scale(_doubleTapScale)
|
||||||
|
..translate(-p.dx, -p.dy);
|
||||||
|
}
|
||||||
|
_notifyZoom();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (_loading) {
|
||||||
|
return const Center(
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white));
|
||||||
|
}
|
||||||
|
if (_bytes == null) {
|
||||||
|
return Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(32),
|
||||||
|
child: Text(
|
||||||
|
trArgs('Cannot preview: {0}', ['$_error']),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: const TextStyle(color: Colors.white70),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return GestureDetector(
|
||||||
|
onTap: widget.onTap,
|
||||||
|
onDoubleTapDown: (details) => _doubleTap = details.localPosition,
|
||||||
|
onDoubleTap: _toggleZoom,
|
||||||
|
child: InteractiveViewer(
|
||||||
|
transformationController: _transform,
|
||||||
|
minScale: 1,
|
||||||
|
maxScale: _maxScale,
|
||||||
|
// One finger swipes to the next picture until a pinch zooms in; from
|
||||||
|
// then on it pans the zoomed picture instead.
|
||||||
|
panEnabled: _zoomed,
|
||||||
|
scaleEnabled: true,
|
||||||
|
onInteractionEnd: (_) => _notifyZoom(),
|
||||||
|
child: SizedBox.expand(
|
||||||
|
child: Image.memory(
|
||||||
|
_bytes!,
|
||||||
|
fit: BoxFit.contain,
|
||||||
|
gaplessPlayback: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,11 +40,24 @@ class MarkdownView extends StatelessWidget {
|
|||||||
return mui.Theme(
|
return mui.Theme(
|
||||||
data: markdownThemeData(Theme.of(context)),
|
data: markdownThemeData(Theme.of(context)),
|
||||||
child: GptMarkdown(
|
child: GptMarkdown(
|
||||||
text,
|
_taskMarkers(text),
|
||||||
// The server already streams deltas; show them as they arrive.
|
// The server already streams deltas; show them as they arrive.
|
||||||
isStreaming: false,
|
isStreaming: false,
|
||||||
style: TextStyle(fontSize: fontSize, height: height, color: color),
|
style: TextStyle(fontSize: fontSize, height: height, color: color),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// gpt_markdown draws task lists with `material_ui`'s Checkbox, which wants
|
||||||
|
/// a `material_ui` Material ancestor the app never provides (its Scaffold is
|
||||||
|
/// Flutter's). Boxed emoji read the same and cost no widget tree.
|
||||||
|
static String _taskMarkers(String source) {
|
||||||
|
var out = source.replaceAllMapped(
|
||||||
|
RegExp(r'^(\s*)[-*+]\s+\[[xX]\]\s+', multiLine: true),
|
||||||
|
(match) => '${match[1]}- ✅ ');
|
||||||
|
out = out.replaceAllMapped(
|
||||||
|
RegExp(r'^(\s*)[-*+]\s+\[\s?\]\s+', multiLine: true),
|
||||||
|
(match) => '${match[1]}- ⬜ ');
|
||||||
|
return out;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
// The composer's two controls: the model pill (model and thinking level in
|
||||||
|
// one group) and, separately, the mode (Build / Plan).
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../model_prefs.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import 'model_picker.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// `deepseek-flash · 高` — model and effort together, as dsh-Go shows them.
|
||||||
|
class ModelPill extends StatelessWidget {
|
||||||
|
final AppState app;
|
||||||
|
final ModelRef? model;
|
||||||
|
final ValueChanged<ModelRef> onModel;
|
||||||
|
|
||||||
|
const ModelPill({
|
||||||
|
super.key,
|
||||||
|
required this.app,
|
||||||
|
required this.model,
|
||||||
|
required this.onModel,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final info = app.modelInfo(model);
|
||||||
|
// The server may name the default level "default"; only a level the
|
||||||
|
// catalog lists counts as a choice.
|
||||||
|
final effort = model?.variant != null &&
|
||||||
|
info != null &&
|
||||||
|
info.variants.contains(model!.variant)
|
||||||
|
? model!.variant
|
||||||
|
: null;
|
||||||
|
final name = model == null ? 'Model' : app.modelName(model!);
|
||||||
|
final label = effort == null ? name : '$name · ${effortLabel(effort)}';
|
||||||
|
return _Pill(
|
||||||
|
icon: Icons.smart_toy_outlined,
|
||||||
|
label: label,
|
||||||
|
onTap: () => showModelPickerSheet(
|
||||||
|
context,
|
||||||
|
app: app,
|
||||||
|
model: model,
|
||||||
|
onModel: onModel,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mode is its own control: Build or Plan, not part of the model.
|
||||||
|
class ModeChip extends StatelessWidget {
|
||||||
|
final AppState app;
|
||||||
|
final String agent;
|
||||||
|
final ValueChanged<String> onAgent;
|
||||||
|
|
||||||
|
const ModeChip({
|
||||||
|
super.key,
|
||||||
|
required this.app,
|
||||||
|
required this.agent,
|
||||||
|
required this.onAgent,
|
||||||
|
});
|
||||||
|
|
||||||
|
static const _modes = ['build', 'plan'];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final current = agent.isEmpty ? _modes.first : agent;
|
||||||
|
return _Pill(
|
||||||
|
icon: Icons.tune,
|
||||||
|
label: _label(current),
|
||||||
|
onTap: () => _open(context, current),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _open(BuildContext context, String current) async {
|
||||||
|
final known = [
|
||||||
|
for (final a in app.agentList)
|
||||||
|
if (a.mode == 'primary' && !a.hidden) a,
|
||||||
|
];
|
||||||
|
final ids = <String>{..._modes, for (final a in known) a.id};
|
||||||
|
final names = {for (final a in known) a.id: a.name};
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final picked = await showModalBottomSheet<String>(
|
||||||
|
context: context,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (sheet) => SafeArea(
|
||||||
|
top: false,
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
|
||||||
|
child: AppText('Mode',
|
||||||
|
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
|
||||||
|
),
|
||||||
|
for (final id in ids)
|
||||||
|
ListTile(
|
||||||
|
leading: Icon(
|
||||||
|
id == 'plan' ? Icons.map_outlined : Icons.construction_outlined,
|
||||||
|
color: id == current ? scheme.primary : null,
|
||||||
|
),
|
||||||
|
title: AppText(
|
||||||
|
names[id]?.isNotEmpty == true ? names[id]! : _label(id),
|
||||||
|
style: TextStyle(
|
||||||
|
fontWeight: id == current ? FontWeight.w700 : FontWeight.w400,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
subtitle: AppText(id == 'plan' ? 'Plan first without changing files' : 'Build directly',
|
||||||
|
style: const TextStyle(fontSize: 12)),
|
||||||
|
trailing: id == current
|
||||||
|
? Icon(Icons.check, size: 20, color: scheme.primary)
|
||||||
|
: null,
|
||||||
|
onTap: () => Navigator.pop(sheet, id),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (picked != null && picked != current) onAgent(picked);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _label(String id) =>
|
||||||
|
id.isEmpty ? 'Build' : id[0].toUpperCase() + id.substring(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Pill extends StatelessWidget {
|
||||||
|
final IconData icon;
|
||||||
|
final String label;
|
||||||
|
final VoidCallback? onTap;
|
||||||
|
|
||||||
|
const _Pill({required this.icon, required this.label, this.onTap});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
return InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
onTap: onTap,
|
||||||
|
child: Container(
|
||||||
|
constraints: const BoxConstraints(minHeight: 30),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
|
||||||
|
decoration: ShapeDecoration(
|
||||||
|
color: scheme.onSurface.withValues(alpha: 0.07),
|
||||||
|
shape: const StadiumBorder(),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(icon, size: 14, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
color: scheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
// The model picker: favourites, recents, models grouped by provider with their
|
||||||
|
// context size, and — when a model has them — its thinking levels, chosen in
|
||||||
|
// the same sheet because model and effort are one selection.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../model_prefs.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
Future<void> showModelPickerSheet(
|
||||||
|
BuildContext context, {
|
||||||
|
required AppState app,
|
||||||
|
required ModelRef? model,
|
||||||
|
required ValueChanged<ModelRef> onModel,
|
||||||
|
}) async {
|
||||||
|
app.refreshModels();
|
||||||
|
await ModelPrefs.instance.ensureLoaded();
|
||||||
|
if (!context.mounted) return;
|
||||||
|
return showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
builder: (context) => DraggableScrollableSheet(
|
||||||
|
expand: false,
|
||||||
|
initialChildSize: 0.85,
|
||||||
|
maxChildSize: 0.95,
|
||||||
|
builder: (context, controller) => _PickerSheet(
|
||||||
|
app: app,
|
||||||
|
model: model,
|
||||||
|
scrollController: controller,
|
||||||
|
onModel: onModel,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PickerSheet extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
final ModelRef? model;
|
||||||
|
final ScrollController scrollController;
|
||||||
|
final ValueChanged<ModelRef> onModel;
|
||||||
|
|
||||||
|
const _PickerSheet({
|
||||||
|
required this.app,
|
||||||
|
required this.model,
|
||||||
|
required this.scrollController,
|
||||||
|
required this.onModel,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_PickerSheet> createState() => _PickerSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PickerSheetState extends State<_PickerSheet> {
|
||||||
|
String _filter = '';
|
||||||
|
final Set<String> _collapsed = {};
|
||||||
|
|
||||||
|
/// The model whose thinking level the bottom panel is offering; null hides
|
||||||
|
/// the panel.
|
||||||
|
ModelInfo? _effortModel;
|
||||||
|
String? _effortVariant;
|
||||||
|
|
||||||
|
ModelPrefs get _prefs => ModelPrefs.instance;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: widget.app,
|
||||||
|
builder: (context, _) => Column(
|
||||||
|
children: [
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(12, 12, 12, 4),
|
||||||
|
child: AppText('Select model',
|
||||||
|
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: TextField(
|
||||||
|
onChanged: (v) => setState(() => _filter = v),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: tr('Search'),
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
isDense: true),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(child: _models()),
|
||||||
|
if (_effortModel != null) _effortPanel(_effortModel!),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _models() {
|
||||||
|
final all = widget.app.modelList;
|
||||||
|
if (all.isEmpty) {
|
||||||
|
return const Center(child: AppText('Loading models…'));
|
||||||
|
}
|
||||||
|
final filter = _filter.trim().toLowerCase();
|
||||||
|
final matching = filter.isEmpty
|
||||||
|
? all
|
||||||
|
: [
|
||||||
|
for (final m in all)
|
||||||
|
if (m.name.toLowerCase().contains(filter) ||
|
||||||
|
m.id.toLowerCase().contains(filter))
|
||||||
|
m,
|
||||||
|
];
|
||||||
|
if (matching.isEmpty) return const Center(child: AppText('No results'));
|
||||||
|
|
||||||
|
final byKey = {
|
||||||
|
for (final m in all) ModelPrefs.keyFor(m.providerId, m.id): m,
|
||||||
|
};
|
||||||
|
final favorites = [
|
||||||
|
for (final key in _prefs.favorites)
|
||||||
|
if (byKey[key] != null) byKey[key]!,
|
||||||
|
]..sort((a, b) => a.name.compareTo(b.name));
|
||||||
|
final recents = [
|
||||||
|
for (final key in _prefs.recents)
|
||||||
|
if (byKey[key] != null && !_prefs.favorites.contains(key)) byKey[key]!,
|
||||||
|
];
|
||||||
|
|
||||||
|
final providers = <String, List<ModelInfo>>{};
|
||||||
|
for (final model in matching) {
|
||||||
|
providers.putIfAbsent(model.providerId, () => []).add(model);
|
||||||
|
}
|
||||||
|
|
||||||
|
final children = <Widget>[];
|
||||||
|
if (filter.isEmpty) {
|
||||||
|
if (favorites.isNotEmpty) {
|
||||||
|
children.add(_sectionHeader(tr('Favorites'), 'favorites', count: favorites.length));
|
||||||
|
if (!_collapsed.contains('favorites')) {
|
||||||
|
for (final model in favorites) {
|
||||||
|
children.add(_modelRow(model));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (recents.isNotEmpty) {
|
||||||
|
children.add(_sectionHeader(tr('Recent'), 'recents', count: recents.length));
|
||||||
|
if (!_collapsed.contains('recents')) {
|
||||||
|
for (final model in recents) {
|
||||||
|
children.add(_modelRow(model));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final entry in providers.entries) {
|
||||||
|
final label = entry.key.isEmpty ? tr('Other') : entry.key;
|
||||||
|
children.add(_sectionHeader(label, 'provider:${entry.key}',
|
||||||
|
count: entry.value.length));
|
||||||
|
if (!_collapsed.contains('provider:${entry.key}')) {
|
||||||
|
for (final model in entry.value) {
|
||||||
|
children.add(_modelRow(model));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ListView(controller: widget.scrollController, children: children);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sectionHeader(String label, String key, {int? count}) {
|
||||||
|
final collapsed = _collapsed.contains(key);
|
||||||
|
return InkWell(
|
||||||
|
onTap: () => setState(() {
|
||||||
|
if (collapsed) {
|
||||||
|
_collapsed.remove(key);
|
||||||
|
} else {
|
||||||
|
_collapsed.add(key);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 10, 16, 4),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(collapsed ? Icons.chevron_right : Icons.expand_more,
|
||||||
|
size: 16, color: Theme.of(context).hintColor),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Expanded(
|
||||||
|
child: AppText(
|
||||||
|
count == null ? label : trArgs('{0} ({1})', [label, count]),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
color: Theme.of(context).hintColor),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _modelRow(ModelInfo model) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final key = ModelPrefs.keyFor(model.providerId, model.id);
|
||||||
|
final selected = widget.model != null &&
|
||||||
|
widget.model!.id == model.id &&
|
||||||
|
widget.model!.providerId == model.providerId;
|
||||||
|
final favorite = _prefs.isFavorite(key);
|
||||||
|
return ListTile(
|
||||||
|
dense: true,
|
||||||
|
contentPadding: const EdgeInsets.only(left: 20, right: 4),
|
||||||
|
title: Row(
|
||||||
|
children: [
|
||||||
|
Flexible(
|
||||||
|
child: Text(model.name,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
),
|
||||||
|
if (model.reasoning)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(left: 4),
|
||||||
|
child: Icon(Icons.psychology_outlined,
|
||||||
|
size: 14, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
subtitle: model.context > 0
|
||||||
|
? AppText(
|
||||||
|
trArgs('{0} context', [formatTokenCount(model.context)]),
|
||||||
|
style: TextStyle(fontSize: 11, color: theme.hintColor))
|
||||||
|
: null,
|
||||||
|
trailing: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (selected)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(right: 4),
|
||||||
|
child: Icon(Icons.check,
|
||||||
|
size: 18, color: theme.colorScheme.primary),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
icon: Icon(
|
||||||
|
favorite ? Icons.star : Icons.star_border,
|
||||||
|
size: 18,
|
||||||
|
color: favorite ? theme.colorScheme.primary : theme.hintColor,
|
||||||
|
),
|
||||||
|
tooltip: favorite ? tr('Remove from favorites') : tr('Favorites'),
|
||||||
|
onPressed: () async {
|
||||||
|
await _prefs.toggleFavorite(key);
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
onTap: () => _select(model),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _select(ModelInfo model) async {
|
||||||
|
final key = ModelPrefs.keyFor(model.providerId, model.id);
|
||||||
|
final remembered = _prefs.effortFor(key);
|
||||||
|
final variant = remembered != null && model.variants.contains(remembered)
|
||||||
|
? remembered
|
||||||
|
: null;
|
||||||
|
await _prefs.rememberModel(key);
|
||||||
|
if (!mounted) return;
|
||||||
|
// Model and effort are one choice: apply the model with its remembered
|
||||||
|
// level, then let the level be changed without leaving the sheet.
|
||||||
|
widget.onModel(ModelRef(model.id, model.providerId, variant));
|
||||||
|
if (model.hasEffort) {
|
||||||
|
setState(() {
|
||||||
|
_effortModel = model;
|
||||||
|
_effortVariant = variant;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
Navigator.pop(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickEffort(ModelInfo model, String? variant) async {
|
||||||
|
final key = ModelPrefs.keyFor(model.providerId, model.id);
|
||||||
|
await _prefs.rememberEffort(key, variant);
|
||||||
|
widget.onModel(ModelRef(model.id, model.providerId, variant));
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.pop(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _effortPanel(ModelInfo model) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final options = <String?>[null, ...model.variants];
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
border: Border(
|
||||||
|
top: BorderSide(
|
||||||
|
color: theme.dividerColor.withValues(alpha: 0.6))),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
const AppText('Thinking effort',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13, fontWeight: FontWeight.w700)),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Expanded(
|
||||||
|
child: Text(model.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
child: const AppText('Done'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Wrap(
|
||||||
|
spacing: 6,
|
||||||
|
runSpacing: 6,
|
||||||
|
children: [
|
||||||
|
for (final option in options)
|
||||||
|
ChoiceChip(
|
||||||
|
label: AppText(effortLabel(option),
|
||||||
|
style: const TextStyle(fontSize: 12.5)),
|
||||||
|
selected: (_effortVariant ?? '') == (option ?? ''),
|
||||||
|
onSelected: (_) => _pickEffort(model, option),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
// The input-box pet. A PetSprite plays the pack's sheet frames; PetLayer is
|
||||||
|
// the floating layer it lives in, placed over the chat's message area so the
|
||||||
|
// messages keep their full height and show through around the pet. Nothing
|
||||||
|
// renders until a pack is imported and enabled.
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:ui' as ui;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../pets/pet_library.dart';
|
||||||
|
import '../pets/pet_pack.dart';
|
||||||
|
|
||||||
|
/// The pet over the chat. It reserves no layout space: the message list runs
|
||||||
|
/// underneath, and only the sprite's body takes touches. The feet rest on the
|
||||||
|
/// bottom edge of the layer, which is the composer's top (or the activity
|
||||||
|
/// cap's while a turn runs). Dragging it sideways moves it along that edge.
|
||||||
|
class PetLayer extends StatefulWidget {
|
||||||
|
final String state;
|
||||||
|
|
||||||
|
/// How far below the layer's bottom edge the feet stand: the composer's
|
||||||
|
/// top padding, or the status capsule's edge when one sits above it.
|
||||||
|
final double footOffset;
|
||||||
|
|
||||||
|
const PetLayer({super.key, required this.state, this.footOffset = 6});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<PetLayer> createState() => _PetLayerState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PetLayerState extends State<PetLayer> {
|
||||||
|
/// Where the feet are, as a fraction of the layer's width. Null: use the
|
||||||
|
/// saved spot.
|
||||||
|
double? _fraction;
|
||||||
|
bool _dragging = false;
|
||||||
|
double _lift = 0;
|
||||||
|
|
||||||
|
/// How far from either end the body keeps, logical px.
|
||||||
|
static const _edge = 8.0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: PetLibrary.instance,
|
||||||
|
builder: (context, _) {
|
||||||
|
final library = PetLibrary.instance;
|
||||||
|
final pack = library.pack;
|
||||||
|
if (!library.enabled || pack == null) return const SizedBox.shrink();
|
||||||
|
return LayoutBuilder(builder: (context, constraints) {
|
||||||
|
final width = constraints.maxWidth;
|
||||||
|
final size = library.size;
|
||||||
|
final scale = size / pack.canvas.width;
|
||||||
|
final height = size * pack.canvas.height / pack.canvas.width;
|
||||||
|
|
||||||
|
// Body extents left and right of the feet, so dragging keeps the
|
||||||
|
// whole pet on screen.
|
||||||
|
final leftExtent = (pack.anchor.dx - pack.contentBox.left) * scale;
|
||||||
|
final rightExtent = (pack.contentBox.right - pack.anchor.dx) * scale;
|
||||||
|
final lo = leftExtent + _edge;
|
||||||
|
final hi = width - rightExtent - _edge;
|
||||||
|
final minFoot = hi <= lo ? width / 2 : lo;
|
||||||
|
final maxFoot = hi <= lo ? width / 2 : hi;
|
||||||
|
|
||||||
|
final fraction = (_fraction ?? library.position).clamp(0.0, 1.0);
|
||||||
|
final foot = (fraction * width).clamp(minFoot, maxFoot);
|
||||||
|
|
||||||
|
// Stand on the composer's top edge. The sprite's own canvas goes a
|
||||||
|
// little below the anchor, and the composer keeps a few px of top
|
||||||
|
// padding above its capsule, so step past both; that overflow is
|
||||||
|
// fine, the layer does not clip.
|
||||||
|
final bottom = -((pack.canvas.height - pack.anchor.dy) * scale +
|
||||||
|
widget.footOffset) +
|
||||||
|
_lift;
|
||||||
|
|
||||||
|
return Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
Positioned(
|
||||||
|
left: foot - pack.anchor.dx * scale,
|
||||||
|
bottom: bottom,
|
||||||
|
width: size,
|
||||||
|
height: height,
|
||||||
|
child: PetSprite(
|
||||||
|
pack: pack,
|
||||||
|
state: widget.state,
|
||||||
|
width: size,
|
||||||
|
dragging: _dragging,
|
||||||
|
onDragStart: () => setState(() {
|
||||||
|
_dragging = true;
|
||||||
|
_lift = -6;
|
||||||
|
}),
|
||||||
|
onDragUpdate: (dx) {
|
||||||
|
final next = ((_fraction ?? library.position) * width + dx)
|
||||||
|
.clamp(minFoot, maxFoot);
|
||||||
|
setState(() => _fraction = next / width);
|
||||||
|
},
|
||||||
|
onDragEnd: () {
|
||||||
|
final spot = _fraction;
|
||||||
|
setState(() {
|
||||||
|
_dragging = false;
|
||||||
|
_lift = 0;
|
||||||
|
});
|
||||||
|
if (spot != null) library.setPosition(spot);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PetSprite extends StatefulWidget {
|
||||||
|
final PetPack pack;
|
||||||
|
final String state;
|
||||||
|
|
||||||
|
/// The pack canvas's on-screen width; the height follows the canvas ratio.
|
||||||
|
final double width;
|
||||||
|
|
||||||
|
/// A drag is in progress: play the pack's drag reaction while held.
|
||||||
|
final bool dragging;
|
||||||
|
|
||||||
|
/// Called when the body is dragged; the layer moves the pet.
|
||||||
|
final VoidCallback? onDragStart;
|
||||||
|
final ValueChanged<double>? onDragUpdate;
|
||||||
|
final VoidCallback? onDragEnd;
|
||||||
|
|
||||||
|
const PetSprite({
|
||||||
|
super.key,
|
||||||
|
required this.pack,
|
||||||
|
required this.state,
|
||||||
|
required this.width,
|
||||||
|
this.dragging = false,
|
||||||
|
this.onDragStart,
|
||||||
|
this.onDragUpdate,
|
||||||
|
this.onDragEnd,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<PetSprite> createState() => _PetSpriteState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PetSpriteState extends State<PetSprite> {
|
||||||
|
PetAnimation? _animation;
|
||||||
|
ui.Image? _image;
|
||||||
|
String? _sheet;
|
||||||
|
int _frame = 0;
|
||||||
|
Timer? _timer;
|
||||||
|
int _loadToken = 0;
|
||||||
|
|
||||||
|
/// A reaction being played; the state resumes when it ends.
|
||||||
|
String? _oneShot;
|
||||||
|
String? _pendingState;
|
||||||
|
|
||||||
|
/// The drag reaction's name while a drag holds it.
|
||||||
|
String? _dragAnimation;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_begin(widget.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(PetSprite oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (oldWidget.pack != widget.pack) {
|
||||||
|
_oneShot = null;
|
||||||
|
_pendingState = null;
|
||||||
|
_dragAnimation = null;
|
||||||
|
_begin(widget.state);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (oldWidget.dragging != widget.dragging) {
|
||||||
|
_oneShot = null;
|
||||||
|
if (widget.dragging) {
|
||||||
|
final drag = widget.pack.reactions['drag'];
|
||||||
|
_dragAnimation =
|
||||||
|
drag != null && widget.pack.animations.containsKey(drag) ? drag : null;
|
||||||
|
final name = _dragAnimation ?? widget.pack.animationForState(widget.state);
|
||||||
|
if (name != null) _beginNamed(name);
|
||||||
|
} else {
|
||||||
|
final next = _pendingState ?? widget.state;
|
||||||
|
_pendingState = null;
|
||||||
|
_dragAnimation = null;
|
||||||
|
_begin(next);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (oldWidget.state != widget.state) {
|
||||||
|
if (_oneShot != null || widget.dragging) {
|
||||||
|
_pendingState = widget.state;
|
||||||
|
} else {
|
||||||
|
_begin(widget.state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_timer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _begin(String state) => _beginNamed(widget.pack.animationForState(state));
|
||||||
|
|
||||||
|
void _beginNamed(String? name) {
|
||||||
|
final animation = widget.pack.animation(name);
|
||||||
|
if (animation == null) {
|
||||||
|
_timer?.cancel();
|
||||||
|
_animation = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_animation = animation;
|
||||||
|
_frame = 0;
|
||||||
|
_showSheet(animation);
|
||||||
|
_schedule();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads a new sheet; a frame from the old one must not be cropped with the
|
||||||
|
/// new animation's box, so the image clears while it loads.
|
||||||
|
void _showSheet(PetAnimation animation) {
|
||||||
|
if (animation.sheet == _sheet) return;
|
||||||
|
_sheet = animation.sheet;
|
||||||
|
_image = null;
|
||||||
|
final token = ++_loadToken;
|
||||||
|
PetLibrary.instance.imageFor(animation).then((image) {
|
||||||
|
if (!mounted || token != _loadToken) return;
|
||||||
|
setState(() => _image = image);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _schedule() {
|
||||||
|
_timer?.cancel();
|
||||||
|
final animation = _animation;
|
||||||
|
if (animation == null || animation.frames.isEmpty) return;
|
||||||
|
final frame = animation.frames[_frame.clamp(0, animation.frames.length - 1)];
|
||||||
|
_timer = Timer(Duration(milliseconds: frame.ms), _tick);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _tick() {
|
||||||
|
final animation = _animation;
|
||||||
|
if (!mounted || animation == null) return;
|
||||||
|
if (_frame + 1 < animation.frames.length) {
|
||||||
|
setState(() => _frame++);
|
||||||
|
_schedule();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final oneShot = _oneShot;
|
||||||
|
if (oneShot != null) {
|
||||||
|
_oneShot = null;
|
||||||
|
final next = _pendingState ?? widget.state;
|
||||||
|
_pendingState = null;
|
||||||
|
_begin(next);
|
||||||
|
setState(() {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Held by a drag: keep the pose until it is let go, even when the pack's
|
||||||
|
// drag sheet plays once.
|
||||||
|
if (widget.dragging &&
|
||||||
|
_dragAnimation != null &&
|
||||||
|
animation.name == _dragAnimation &&
|
||||||
|
!animation.loop) {
|
||||||
|
setState(() => _frame = 0);
|
||||||
|
_schedule();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (animation.loop) {
|
||||||
|
setState(() => _frame = 0);
|
||||||
|
_schedule();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_begin(widget.state);
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _react(TapUpDetails details) {
|
||||||
|
final left = details.localPosition.dx < widget.width / 2;
|
||||||
|
final name = widget.pack.reactions[left ? 'tapLeft' : 'tapRight'];
|
||||||
|
final animation = widget.pack.animation(name);
|
||||||
|
if (animation == null) return;
|
||||||
|
_oneShot = name;
|
||||||
|
_pendingState = widget.state;
|
||||||
|
_animation = animation;
|
||||||
|
_frame = 0;
|
||||||
|
_showSheet(animation);
|
||||||
|
_schedule();
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final width = widget.width;
|
||||||
|
final height = width * widget.pack.canvas.height / widget.pack.canvas.width;
|
||||||
|
return GestureDetector(
|
||||||
|
// Only the body takes touches; the rest of the layer lets the message
|
||||||
|
// list scroll.
|
||||||
|
behavior: HitTestBehavior.deferToChild,
|
||||||
|
onTapUp: _react,
|
||||||
|
onHorizontalDragStart: (_) => widget.onDragStart?.call(),
|
||||||
|
onHorizontalDragUpdate: (details) =>
|
||||||
|
widget.onDragUpdate?.call(details.delta.dx),
|
||||||
|
onHorizontalDragEnd: (_) => widget.onDragEnd?.call(),
|
||||||
|
onHorizontalDragCancel: () => widget.onDragEnd?.call(),
|
||||||
|
child: CustomPaint(
|
||||||
|
size: Size(width, height),
|
||||||
|
painter: _PetPainter(
|
||||||
|
pack: widget.pack,
|
||||||
|
animation: _animation,
|
||||||
|
image: _image,
|
||||||
|
frame: _frame,
|
||||||
|
spriteSize: Size(width, height),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PetPainter extends CustomPainter {
|
||||||
|
final PetPack pack;
|
||||||
|
final PetAnimation? animation;
|
||||||
|
final ui.Image? image;
|
||||||
|
final int frame;
|
||||||
|
|
||||||
|
/// The on-screen size, for hit testing.
|
||||||
|
final Size spriteSize;
|
||||||
|
|
||||||
|
const _PetPainter({
|
||||||
|
required this.pack,
|
||||||
|
required this.animation,
|
||||||
|
required this.image,
|
||||||
|
required this.frame,
|
||||||
|
required this.spriteSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The body only: taps and drags on the transparent canvas around it go to
|
||||||
|
/// whatever is underneath.
|
||||||
|
@override
|
||||||
|
bool? hitTest(Offset position) {
|
||||||
|
if (spriteSize.width <= 0) return false;
|
||||||
|
final scale = spriteSize.width / pack.canvas.width;
|
||||||
|
final body = Rect.fromLTRB(
|
||||||
|
pack.contentBox.left * scale,
|
||||||
|
pack.contentBox.top * scale,
|
||||||
|
pack.contentBox.right * scale,
|
||||||
|
pack.contentBox.bottom * scale,
|
||||||
|
).inflate(4);
|
||||||
|
return body.contains(position);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void paint(Canvas canvas, Size size) {
|
||||||
|
final animation = this.animation;
|
||||||
|
final image = this.image;
|
||||||
|
if (image == null || animation == null || animation.frames.isEmpty) return;
|
||||||
|
final cols = animation.cols;
|
||||||
|
final maxCols = image.width ~/ animation.frameW;
|
||||||
|
final maxRows = image.height ~/ animation.frameH;
|
||||||
|
if (maxCols <= 0 || maxRows <= 0) return;
|
||||||
|
|
||||||
|
final entry =
|
||||||
|
animation.frames[frame.clamp(0, animation.frames.length - 1)];
|
||||||
|
final col = (entry.index % cols).clamp(0, maxCols - 1);
|
||||||
|
final row = (entry.index ~/ cols).clamp(0, maxRows - 1);
|
||||||
|
final src = Rect.fromLTWH(
|
||||||
|
col * animation.frameW.toDouble(),
|
||||||
|
row * animation.frameH.toDouble(),
|
||||||
|
animation.frameW.toDouble(),
|
||||||
|
animation.frameH.toDouble(),
|
||||||
|
);
|
||||||
|
|
||||||
|
final scale = size.width / pack.canvas.width;
|
||||||
|
final dst = Rect.fromLTWH(
|
||||||
|
animation.box.left * scale,
|
||||||
|
animation.box.top * scale,
|
||||||
|
animation.box.width * scale,
|
||||||
|
animation.box.height * scale,
|
||||||
|
);
|
||||||
|
canvas.drawImageRect(
|
||||||
|
image,
|
||||||
|
src,
|
||||||
|
dst,
|
||||||
|
Paint()
|
||||||
|
..filterQuality =
|
||||||
|
pack.pixelArt ? FilterQuality.none : FilterQuality.medium,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(_PetPainter oldDelegate) =>
|
||||||
|
oldDelegate.image != image ||
|
||||||
|
oldDelegate.animation != animation ||
|
||||||
|
oldDelegate.frame != frame ||
|
||||||
|
oldDelegate.pack != pack ||
|
||||||
|
oldDelegate.spriteSize != spriteSize;
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// A project's sidebar icon: the operator's chosen icon in its colour, a custom
|
||||||
|
// icon image from the project, or a folder. OpenChamber's managed chats have
|
||||||
|
// no project and get a chat bubble instead.
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_svg/flutter_svg.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
|
||||||
|
/// The Flutter equivalent of OpenChamber's `PROJECT_ICON_MAP` keys.
|
||||||
|
IconData? projectIconData(String key) => switch (key) {
|
||||||
|
'code' => Icons.code,
|
||||||
|
'terminal' => Icons.terminal,
|
||||||
|
'rocket' => Icons.rocket_launch_outlined,
|
||||||
|
'flask' => Icons.science_outlined,
|
||||||
|
'gamepad' => Icons.sports_esports_outlined,
|
||||||
|
'briefcase' => Icons.work_outline,
|
||||||
|
'home' => Icons.home_outlined,
|
||||||
|
'globe' => Icons.public,
|
||||||
|
'leaf' => Icons.eco_outlined,
|
||||||
|
'shield' => Icons.shield_outlined,
|
||||||
|
'palette' => Icons.palette_outlined,
|
||||||
|
'server' => Icons.dns_outlined,
|
||||||
|
'phone' => Icons.smartphone,
|
||||||
|
'database' => Icons.storage,
|
||||||
|
'lightbulb' => Icons.lightbulb_outline,
|
||||||
|
'music' => Icons.music_note_outlined,
|
||||||
|
'camera' => Icons.photo_camera_outlined,
|
||||||
|
'book' => Icons.menu_book_outlined,
|
||||||
|
'heart' => Icons.favorite_outline,
|
||||||
|
'cpu' => Icons.memory,
|
||||||
|
'cloud' => Icons.cloud_outlined,
|
||||||
|
'store' => Icons.storefront_outlined,
|
||||||
|
'school' => Icons.school_outlined,
|
||||||
|
'chat' => Icons.chat_bubble_outline,
|
||||||
|
'mail' => Icons.mail_outline,
|
||||||
|
'map' => Icons.place_outlined,
|
||||||
|
'robot' => Icons.smart_toy_outlined,
|
||||||
|
'ai' => Icons.psychology_outlined,
|
||||||
|
'plugin' => Icons.extension_outlined,
|
||||||
|
'tools' => Icons.build_outlined,
|
||||||
|
'chart' => Icons.bar_chart,
|
||||||
|
'writing' => Icons.edit_outlined,
|
||||||
|
'image' => Icons.image_outlined,
|
||||||
|
'film' => Icons.movie_outlined,
|
||||||
|
'trophy' => Icons.emoji_events_outlined,
|
||||||
|
'travel' => Icons.flight,
|
||||||
|
'coffee' => Icons.coffee_outlined,
|
||||||
|
'bug' => Icons.bug_report_outlined,
|
||||||
|
'apple' => Icons.apple,
|
||||||
|
'android' => Icons.android,
|
||||||
|
'windows' => Icons.window,
|
||||||
|
'github' => Icons.code,
|
||||||
|
'stack' => Icons.layers_outlined,
|
||||||
|
'finance' => Icons.account_balance_outlined,
|
||||||
|
'team' => Icons.groups_outlined,
|
||||||
|
'fire' => Icons.local_fire_department_outlined,
|
||||||
|
'planet' => Icons.public,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A stored project colour as a Flutter colour. Newer projects store hex;
|
||||||
|
/// older ones a theme/syntax key, resolved against the app's scheme.
|
||||||
|
Color? projectColor(String value, ColorScheme scheme) {
|
||||||
|
final hex = projectHexColor(value);
|
||||||
|
if (hex != null) return hex;
|
||||||
|
return switch (value.trim()) {
|
||||||
|
'primary' => scheme.primary,
|
||||||
|
'error' => scheme.error,
|
||||||
|
'success' => Colors.green,
|
||||||
|
'keyword' => scheme.primary,
|
||||||
|
'string' => Colors.green,
|
||||||
|
'number' => Colors.orange,
|
||||||
|
'type' => Colors.teal,
|
||||||
|
'constant' => Colors.blue,
|
||||||
|
'comment' => scheme.onSurfaceVariant,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Color? projectHexColor(String value) {
|
||||||
|
final text = value.trim();
|
||||||
|
if (!text.startsWith('#')) return null;
|
||||||
|
var hex = text.substring(1);
|
||||||
|
if (hex.length == 3) {
|
||||||
|
hex = hex.split('').map((c) => '$c$c').join();
|
||||||
|
}
|
||||||
|
if (hex.length != 6 && hex.length != 8) return null;
|
||||||
|
final parsed = int.tryParse(hex, radix: 16);
|
||||||
|
if (parsed == null) return null;
|
||||||
|
return Color(hex.length == 6 ? 0xff000000 | parsed : parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _hexOf(Color color) =>
|
||||||
|
'#${(color.toARGB32() & 0xffffff).toRadixString(16).padLeft(6, '0')}';
|
||||||
|
|
||||||
|
class ProjectIcon extends StatelessWidget {
|
||||||
|
final AppState app;
|
||||||
|
final ProjectInfo? project;
|
||||||
|
final bool chat;
|
||||||
|
final double size;
|
||||||
|
|
||||||
|
const ProjectIcon({
|
||||||
|
super.key,
|
||||||
|
required this.app,
|
||||||
|
this.project,
|
||||||
|
this.chat = false,
|
||||||
|
this.size = 16,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
if (chat) {
|
||||||
|
return Icon(Icons.chat_bubble_outline, size: size, color: scheme.primary);
|
||||||
|
}
|
||||||
|
final project = this.project;
|
||||||
|
if (project == null) {
|
||||||
|
return Icon(Icons.folder_outlined, size: size, color: theme.hintColor);
|
||||||
|
}
|
||||||
|
final color = projectColor(project.color, scheme) ?? theme.hintColor;
|
||||||
|
final glyph = Icon(projectIconData(project.icon) ?? Icons.folder_outlined,
|
||||||
|
size: size, color: color);
|
||||||
|
if (!project.hasIconImage) return glyph;
|
||||||
|
|
||||||
|
final future = app.projectIcon(
|
||||||
|
project,
|
||||||
|
dark: theme.brightness == Brightness.dark,
|
||||||
|
iconColor: _hexOf(scheme.onSurface),
|
||||||
|
);
|
||||||
|
return FutureBuilder<Uint8List?>(
|
||||||
|
future: future,
|
||||||
|
builder: (context, snapshot) {
|
||||||
|
final bytes = snapshot.data;
|
||||||
|
if (bytes == null || bytes.isEmpty) {
|
||||||
|
// Loading or unavailable: keep the glyph so the row does not jump.
|
||||||
|
return glyph;
|
||||||
|
}
|
||||||
|
final Widget image = project.iconImageMime.contains('svg')
|
||||||
|
? SvgPicture.memory(bytes,
|
||||||
|
width: size, height: size, fit: BoxFit.contain)
|
||||||
|
: Image.memory(bytes,
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
fit: BoxFit.contain,
|
||||||
|
gaplessPlayback: true);
|
||||||
|
final background = projectHexColor(project.iconBackground);
|
||||||
|
if (background == null) return image;
|
||||||
|
return Container(
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: background,
|
||||||
|
borderRadius: BorderRadius.circular(3),
|
||||||
|
),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: image,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
// Choosing a project, shared by the new-session draft and scheduled tasks.
|
||||||
|
// The sheet opens at once and refreshes the project list behind it: a tap on
|
||||||
|
// the project chip should never wait for the server before anything appears.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import 'directory_picker.dart';
|
||||||
|
import 'project_icon.dart';
|
||||||
|
|
||||||
|
/// The "All projects" row of the stats scope picker, where a report is not
|
||||||
|
/// narrowed to one checkout.
|
||||||
|
const allProjectsTarget = '\u0000all-projects';
|
||||||
|
|
||||||
|
/// What the picker returns: the Chat row, the All projects row, or a checkout.
|
||||||
|
class ProjectChoice {
|
||||||
|
/// Null for the Chat and All projects rows.
|
||||||
|
final ProjectInfo? project;
|
||||||
|
final bool all;
|
||||||
|
|
||||||
|
const ProjectChoice.chat()
|
||||||
|
: project = null,
|
||||||
|
all = false;
|
||||||
|
const ProjectChoice.allProjects()
|
||||||
|
: project = null,
|
||||||
|
all = true;
|
||||||
|
const ProjectChoice.project(this.project) : all = false;
|
||||||
|
|
||||||
|
bool get isChat => project == null && !all;
|
||||||
|
bool get isAll => all;
|
||||||
|
String get canonical =>
|
||||||
|
all ? allProjectsTarget : (project?.canonical ?? AppState.chatTarget);
|
||||||
|
String get label => all ? tr('All projects') : (project?.label ?? tr('Chat'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the project sheet and returns the chosen target, or null when the
|
||||||
|
/// person dismissed it. [selected] is a checkout path, or [AppState.chatTarget]
|
||||||
|
/// for the Chat row. [onlyProjects] limits the list to exactly those projects
|
||||||
|
/// (the archive page offers only projects that hold archived sessions, since
|
||||||
|
/// it never archives anything itself); null lists every selectable checkout.
|
||||||
|
Future<ProjectChoice?> showProjectPicker(
|
||||||
|
BuildContext context, {
|
||||||
|
required AppState app,
|
||||||
|
required String selected,
|
||||||
|
bool includeAll = false,
|
||||||
|
bool includeChat = true,
|
||||||
|
List<ProjectInfo>? onlyProjects,
|
||||||
|
}) {
|
||||||
|
return showModalBottomSheet<ProjectChoice>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
builder: (context) => DraggableScrollableSheet(
|
||||||
|
expand: false,
|
||||||
|
initialChildSize: 0.6,
|
||||||
|
maxChildSize: 0.9,
|
||||||
|
builder: (context, controller) => _ProjectPickerSheet(
|
||||||
|
app: app,
|
||||||
|
selected: selected,
|
||||||
|
includeAll: includeAll,
|
||||||
|
includeChat: includeChat,
|
||||||
|
projects: onlyProjects,
|
||||||
|
controller: controller,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The projects a picker offers: checkouts, not the server's chat folders.
|
||||||
|
/// The server can list the same path twice (a project record and a sandbox),
|
||||||
|
/// so one path is one row, preferring the one that knows its VCS.
|
||||||
|
List<ProjectInfo> selectableProjects(AppState app) {
|
||||||
|
final byPath = <String, ProjectInfo>{};
|
||||||
|
for (final project in app.projects) {
|
||||||
|
if (project.canonical.isEmpty) continue;
|
||||||
|
if (app.isChatDirectory(project.canonical)) continue;
|
||||||
|
final existing = byPath[project.canonical];
|
||||||
|
if (existing == null ||
|
||||||
|
(existing.vcs.isEmpty && project.vcs.isNotEmpty)) {
|
||||||
|
byPath[project.canonical] = project;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return byPath.values.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ProjectPickerSheet extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
final String selected;
|
||||||
|
final bool includeAll;
|
||||||
|
final bool includeChat;
|
||||||
|
|
||||||
|
/// Null offers every selectable checkout; a list limits the picker to it
|
||||||
|
/// (the archive page) and hides the add-project action.
|
||||||
|
final List<ProjectInfo>? projects;
|
||||||
|
final ScrollController controller;
|
||||||
|
|
||||||
|
const _ProjectPickerSheet({
|
||||||
|
required this.app,
|
||||||
|
required this.selected,
|
||||||
|
required this.includeAll,
|
||||||
|
required this.includeChat,
|
||||||
|
required this.projects,
|
||||||
|
required this.controller,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_ProjectPickerSheet> createState() => _ProjectPickerSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ProjectPickerSheetState extends State<_ProjectPickerSheet> {
|
||||||
|
/// True until the list behind the sheet has been refreshed. The sheet is
|
||||||
|
/// already up by then; only its body shows the spinner.
|
||||||
|
bool _refreshing = true;
|
||||||
|
|
||||||
|
final TextEditingController _searchCtrl = TextEditingController();
|
||||||
|
String _filter = '';
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_searchCtrl.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _refresh() async {
|
||||||
|
await Future.wait([
|
||||||
|
widget.app.refreshProjects(),
|
||||||
|
widget.app.refreshFsHome(),
|
||||||
|
]);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _refreshing = false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Browses the server's folders and returns with the new project selected.
|
||||||
|
Future<void> _addProject() async {
|
||||||
|
final path = await showDirectoryPicker(context, app: widget.app);
|
||||||
|
if (path == null || !mounted) return;
|
||||||
|
final project = widget.app.projectFor(path) ??
|
||||||
|
ProjectInfo(id: '', canonical: path, name: pathLeaf(path));
|
||||||
|
Navigator.pop(context, ProjectChoice.project(project));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final chat = widget.selected == AppState.chatTarget;
|
||||||
|
// A cached list is shown at once; the refresh updates it in place.
|
||||||
|
final projects = widget.projects ?? selectableProjects(widget.app);
|
||||||
|
final query = _filter.trim().toLowerCase();
|
||||||
|
final visible = query.isEmpty
|
||||||
|
? projects
|
||||||
|
: [
|
||||||
|
for (final project in projects)
|
||||||
|
if (project.label.toLowerCase().contains(query) ||
|
||||||
|
project.canonical.toLowerCase().contains(query))
|
||||||
|
project,
|
||||||
|
];
|
||||||
|
final loading = _refreshing && projects.isEmpty;
|
||||||
|
return Column(
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 6, 8, 0),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
const Expanded(
|
||||||
|
child: AppText('Choose project',
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 17, fontWeight: FontWeight.w600)),
|
||||||
|
),
|
||||||
|
if (widget.projects == null)
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: _addProject,
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8)),
|
||||||
|
icon: const Icon(Icons.create_new_folder_outlined, size: 18),
|
||||||
|
label: const AppText('Add project'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 2, 12, 6),
|
||||||
|
child: TextField(
|
||||||
|
controller: _searchCtrl,
|
||||||
|
onChanged: (value) => setState(() => _filter = value),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: tr('Search projects'),
|
||||||
|
prefixIcon: const Icon(Icons.search, size: 18),
|
||||||
|
isDense: true,
|
||||||
|
border: OutlineInputBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: loading
|
||||||
|
? const Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.all(24),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2)),
|
||||||
|
SizedBox(height: 12),
|
||||||
|
AppText('Loading projects…'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: ListView(
|
||||||
|
controller: widget.controller,
|
||||||
|
children: [
|
||||||
|
if (widget.includeAll)
|
||||||
|
ListTile(
|
||||||
|
dense: true,
|
||||||
|
leading: Icon(Icons.folder_copy_outlined,
|
||||||
|
size: 20,
|
||||||
|
color: Theme.of(context).colorScheme.onSurfaceVariant),
|
||||||
|
title: const AppText('All projects'),
|
||||||
|
trailing: widget.selected == allProjectsTarget
|
||||||
|
? Icon(Icons.check,
|
||||||
|
size: 18,
|
||||||
|
color: Theme.of(context).colorScheme.primary)
|
||||||
|
: null,
|
||||||
|
onTap: () => Navigator.pop(
|
||||||
|
context, const ProjectChoice.allProjects()),
|
||||||
|
),
|
||||||
|
if (widget.includeChat)
|
||||||
|
ListTile(
|
||||||
|
dense: true,
|
||||||
|
leading:
|
||||||
|
ProjectIcon(app: widget.app, chat: true, size: 20),
|
||||||
|
title: const AppText('Chat'),
|
||||||
|
subtitle: const AppText(
|
||||||
|
'Not tied to a project, saved in OpenChamber\'s chat directory'),
|
||||||
|
trailing: chat
|
||||||
|
? Icon(Icons.check,
|
||||||
|
size: 18,
|
||||||
|
color: Theme.of(context).colorScheme.primary)
|
||||||
|
: null,
|
||||||
|
onTap: () =>
|
||||||
|
Navigator.pop(context, const ProjectChoice.chat()),
|
||||||
|
),
|
||||||
|
for (final project in visible)
|
||||||
|
ListTile(
|
||||||
|
dense: true,
|
||||||
|
leading: ProjectIcon(
|
||||||
|
app: widget.app, project: project, size: 20),
|
||||||
|
title: Text(project.label,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
subtitle: Text(project.canonical,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
trailing: samePath(project.canonical, widget.selected)
|
||||||
|
? Icon(Icons.check,
|
||||||
|
size: 18,
|
||||||
|
color: Theme.of(context).colorScheme.primary)
|
||||||
|
: null,
|
||||||
|
onTap: () => Navigator.pop(
|
||||||
|
context, ProjectChoice.project(project)),
|
||||||
|
),
|
||||||
|
if (!_refreshing && visible.isEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: AppText(
|
||||||
|
query.isEmpty
|
||||||
|
? 'No projects available'
|
||||||
|
: 'No matching projects',
|
||||||
|
textAlign: TextAlign.center),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,495 @@
|
|||||||
|
// The scheduled-task editor: name, prompt, schedule and the run's model. The
|
||||||
|
// server validates the same limits again; saving hands the draft back so the
|
||||||
|
// page can keep the list it answers with.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api/models.dart';
|
||||||
|
import '../api/scheduled_tasks.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
import 'model_picker.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
class ScheduledTaskEditor extends StatefulWidget {
|
||||||
|
final AppState app;
|
||||||
|
|
||||||
|
/// What the task runs in, as the page names it.
|
||||||
|
final String scopeLabel;
|
||||||
|
|
||||||
|
/// Null creates a task.
|
||||||
|
final ScheduledTask? initial;
|
||||||
|
|
||||||
|
/// Saves the draft; false keeps the sheet open (the page has said why).
|
||||||
|
final Future<bool> Function(ScheduledTask draft) onSave;
|
||||||
|
|
||||||
|
const ScheduledTaskEditor({
|
||||||
|
super.key,
|
||||||
|
required this.app,
|
||||||
|
required this.scopeLabel,
|
||||||
|
required this.onSave,
|
||||||
|
this.initial,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ScheduledTaskEditor> createState() => _ScheduledTaskEditorState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ScheduledTaskEditorState extends State<ScheduledTaskEditor> {
|
||||||
|
late final TextEditingController _name;
|
||||||
|
late final TextEditingController _prompt;
|
||||||
|
late final TextEditingController _cron;
|
||||||
|
|
||||||
|
late String _kind;
|
||||||
|
late List<String> _times;
|
||||||
|
late Set<int> _weekdays;
|
||||||
|
late DateTime _date;
|
||||||
|
late String _time;
|
||||||
|
late bool _useDefaults;
|
||||||
|
late String _providerId;
|
||||||
|
late String _modelId;
|
||||||
|
late String _variant;
|
||||||
|
late String _agent;
|
||||||
|
late bool _enabled;
|
||||||
|
|
||||||
|
bool _saving = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
final task = widget.initial;
|
||||||
|
_name = TextEditingController(text: task?.name ?? '');
|
||||||
|
_prompt = TextEditingController(text: task?.prompt ?? '');
|
||||||
|
_cron = TextEditingController(
|
||||||
|
text: task?.kind == 'cron' && task!.cron.isNotEmpty
|
||||||
|
? task.cron
|
||||||
|
: '0 9 * * *');
|
||||||
|
_kind = task != null && task.kind.isNotEmpty ? task.kind : 'daily';
|
||||||
|
_times = task != null && task.times.isNotEmpty
|
||||||
|
? [...task.times]
|
||||||
|
: [task?.time.isNotEmpty == true ? task!.time : '09:00'];
|
||||||
|
_weekdays = task != null && task.weekdays.isNotEmpty
|
||||||
|
? {...task.weekdays}
|
||||||
|
: {1};
|
||||||
|
_date = _parseDate(task?.date ?? '') ?? _tomorrow();
|
||||||
|
_time = task != null && task.time.isNotEmpty ? task.time : '09:00';
|
||||||
|
_useDefaults = task?.useDefaults ?? true;
|
||||||
|
_providerId = task?.providerId ?? '';
|
||||||
|
_modelId = task?.modelId ?? '';
|
||||||
|
_variant = task?.variant ?? '';
|
||||||
|
_agent = task?.agent ?? '';
|
||||||
|
_enabled = task?.enabled ?? true;
|
||||||
|
if (widget.app.modelList.isEmpty) widget.app.refreshModels();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_name.dispose();
|
||||||
|
_prompt.dispose();
|
||||||
|
_cron.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
static DateTime _tomorrow() {
|
||||||
|
final now = DateTime.now();
|
||||||
|
return DateTime(now.year, now.month, now.day + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DateTime? _parseDate(String value) {
|
||||||
|
final parts = value.split('-');
|
||||||
|
if (parts.length != 3) return null;
|
||||||
|
final year = int.tryParse(parts[0]);
|
||||||
|
final month = int.tryParse(parts[1]);
|
||||||
|
final day = int.tryParse(parts[2]);
|
||||||
|
if (year == null || month == null || day == null) return null;
|
||||||
|
return DateTime(year, month, day);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _two(int value) => value.toString().padLeft(2, '0');
|
||||||
|
|
||||||
|
static String _dateText(DateTime date) =>
|
||||||
|
'${date.year}-${_two(date.month)}-${_two(date.day)}';
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return FractionallySizedBox(
|
||||||
|
heightFactor: 0.92,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 0, 12, 4),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: AppText(
|
||||||
|
widget.initial == null ? 'New scheduled task' : 'Edit scheduled task',
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 18, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: _saving ? null : _save,
|
||||||
|
child: AppText(_saving ? 'Saving…' : 'Save'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: ListView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 32),
|
||||||
|
children: [
|
||||||
|
AppText(trArgs('Runs in: {0}', [widget.scopeLabel]),
|
||||||
|
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _name,
|
||||||
|
maxLength: 80,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: tr('Task name'),
|
||||||
|
hintText: tr('Daily sync'),
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextField(
|
||||||
|
controller: _prompt,
|
||||||
|
minLines: 4,
|
||||||
|
maxLines: 10,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: tr('Prompt'),
|
||||||
|
hintText: tr('Summarize unfinished tasks and suggest next steps'),
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
alignLabelWithHint: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
const _FieldLabel('Schedule type'),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final entry in scheduledTaskKindLabels.entries)
|
||||||
|
ChoiceChip(
|
||||||
|
label: AppText(entry.value),
|
||||||
|
selected: _kind == entry.key,
|
||||||
|
onSelected: (_) => setState(() => _kind = entry.key),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
..._scheduleFields(theme),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SwitchListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const AppText('Use default model and agent'),
|
||||||
|
subtitle: const AppText('Turn off to pin the model and agent this run uses.'),
|
||||||
|
value: _useDefaults,
|
||||||
|
onChanged: (v) => setState(() => _useDefaults = v),
|
||||||
|
),
|
||||||
|
if (!_useDefaults) ..._executionFields(theme),
|
||||||
|
SwitchListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const AppText('Enabled'),
|
||||||
|
subtitle: const AppText('Paused tasks don\'t run on schedule but can still be run manually.'),
|
||||||
|
value: _enabled,
|
||||||
|
onChanged: (v) => setState(() => _enabled = v),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: _saving ? null : _save,
|
||||||
|
child: AppText(_saving ? 'Saving…' : 'Save'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _scheduleFields(ThemeData theme) {
|
||||||
|
switch (_kind) {
|
||||||
|
case 'daily':
|
||||||
|
return [_timesField(theme)];
|
||||||
|
case 'weekly':
|
||||||
|
return [
|
||||||
|
const _FieldLabel('Weekdays'),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (var day = 0; day < scheduledWeekdays.length; day++)
|
||||||
|
FilterChip(
|
||||||
|
label: AppText(scheduledWeekdays[day]),
|
||||||
|
selected: _weekdays.contains(day),
|
||||||
|
onSelected: (selected) => setState(() {
|
||||||
|
if (selected) {
|
||||||
|
_weekdays.add(day);
|
||||||
|
} else if (_weekdays.length > 1) {
|
||||||
|
_weekdays.remove(day);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
_timesField(theme),
|
||||||
|
];
|
||||||
|
case 'once':
|
||||||
|
return [
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const AppText('Date'),
|
||||||
|
trailing: Text(_dateText(_date)),
|
||||||
|
onTap: _pickDate,
|
||||||
|
),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const AppText('Time'),
|
||||||
|
trailing: Text(_time),
|
||||||
|
onTap: () async {
|
||||||
|
final picked = await _pickTime(_time);
|
||||||
|
if (picked != null) setState(() => _time = picked);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
case 'cron':
|
||||||
|
return [
|
||||||
|
TextField(
|
||||||
|
controller: _cron,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: tr('Cron expression'),
|
||||||
|
hintText: '*/5 * * * *',
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final example in const [
|
||||||
|
('Every 5 minutes', '*/5 * * * *'),
|
||||||
|
('Every hour', '0 * * * *'),
|
||||||
|
('Daily at 9', '0 9 * * *'),
|
||||||
|
('Mondays at 9', '0 9 * * 1'),
|
||||||
|
('1st of each month', '0 9 1 * *'),
|
||||||
|
])
|
||||||
|
ActionChip(
|
||||||
|
label: AppText(example.$1),
|
||||||
|
onPressed: () =>
|
||||||
|
setState(() => _cron.text = example.$2),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _timesField(ThemeData theme) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
const _FieldLabel('Times'),
|
||||||
|
for (var i = 0; i < _times.length; i++)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 4),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: OutlinedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
final picked = await _pickTime(_times[i]);
|
||||||
|
if (picked != null) setState(() => _times[i] = picked);
|
||||||
|
},
|
||||||
|
child: Text(_times[i]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.remove_circle_outline, size: 20),
|
||||||
|
tooltip: tr('Remove time'),
|
||||||
|
onPressed: _times.length <= 1
|
||||||
|
? null
|
||||||
|
: () => setState(() => _times.removeAt(i)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: () async {
|
||||||
|
final picked = await _pickTime(_times.isEmpty ? '09:00' : _times.last);
|
||||||
|
if (picked != null) setState(() => _times.add(picked));
|
||||||
|
},
|
||||||
|
icon: const Icon(Icons.add, size: 18),
|
||||||
|
label: const AppText('Add time'),
|
||||||
|
),
|
||||||
|
AppText('Times follow the server\'s time zone.', style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _executionFields(ThemeData theme) {
|
||||||
|
final model = _modelId.isEmpty
|
||||||
|
? 'Select model'
|
||||||
|
: (widget.app.modelNames['$_providerId/$_modelId'] ?? '$_providerId/$_modelId');
|
||||||
|
final agent = _agent.isEmpty ? 'Default agent' : _agent;
|
||||||
|
return [
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: const Icon(Icons.memory, size: 20),
|
||||||
|
title: const AppText('Model'),
|
||||||
|
trailing: Text(model, overflow: TextOverflow.ellipsis),
|
||||||
|
onTap: _pickModel,
|
||||||
|
),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: const Icon(Icons.smart_toy_outlined, size: 20),
|
||||||
|
title: const AppText('Agent'),
|
||||||
|
trailing: AppText(agent, overflow: TextOverflow.ellipsis),
|
||||||
|
onTap: _pickAgent,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickDate() async {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final picked = await showDatePicker(
|
||||||
|
context: context,
|
||||||
|
initialDate: _date,
|
||||||
|
firstDate: now.subtract(const Duration(days: 1)),
|
||||||
|
lastDate: now.add(const Duration(days: 365 * 5)),
|
||||||
|
);
|
||||||
|
if (picked != null) setState(() => _date = picked);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _pickTime(String current) async {
|
||||||
|
final parts = current.split(':');
|
||||||
|
final picked = await showTimePicker(
|
||||||
|
context: context,
|
||||||
|
initialTime: TimeOfDay(
|
||||||
|
hour: int.tryParse(parts.first) ?? 9,
|
||||||
|
minute: parts.length > 1 ? int.tryParse(parts[1]) ?? 0 : 0,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (picked == null) return null;
|
||||||
|
return '${_two(picked.hour)}:${_two(picked.minute)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickModel() async {
|
||||||
|
final current = _modelId.isEmpty
|
||||||
|
? null
|
||||||
|
: ModelRef(_modelId, _providerId, _variant.isEmpty ? null : _variant);
|
||||||
|
await showModelPickerSheet(
|
||||||
|
context,
|
||||||
|
app: widget.app,
|
||||||
|
model: current,
|
||||||
|
onModel: (model) {
|
||||||
|
setState(() {
|
||||||
|
_modelId = model.id;
|
||||||
|
_providerId = model.providerId;
|
||||||
|
_variant = model.variant ?? '';
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickAgent() async {
|
||||||
|
if (widget.app.agentList.isEmpty) await widget.app.refreshModels();
|
||||||
|
if (!mounted) return;
|
||||||
|
final chosen = await showModalBottomSheet<String>(
|
||||||
|
context: context,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (sheet) => ListView(
|
||||||
|
shrinkWrap: true,
|
||||||
|
children: [
|
||||||
|
ListTile(
|
||||||
|
title: const AppText('Default agent'),
|
||||||
|
trailing: _agent.isEmpty ? const Icon(Icons.check, size: 20) : null,
|
||||||
|
onTap: () => Navigator.pop(sheet, ''),
|
||||||
|
),
|
||||||
|
for (final agent in widget.app.agentList)
|
||||||
|
ListTile(
|
||||||
|
title: Text(agent.name.isEmpty ? agent.id : agent.name),
|
||||||
|
trailing: _agent == agent.id
|
||||||
|
? const Icon(Icons.check, size: 20)
|
||||||
|
: null,
|
||||||
|
onTap: () => Navigator.pop(sheet, agent.id),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (chosen == null) return;
|
||||||
|
setState(() => _agent = chosen);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _save() async {
|
||||||
|
final name = _name.text.trim();
|
||||||
|
final prompt = _prompt.text.trim();
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
String? problem;
|
||||||
|
if (name.isEmpty) {
|
||||||
|
problem = 'Task name is required';
|
||||||
|
} else if (name.length > 80) {
|
||||||
|
problem = 'Task name can\'t exceed 80 characters';
|
||||||
|
} else if (prompt.isEmpty) {
|
||||||
|
problem = 'Prompt is required';
|
||||||
|
} else if (prompt.length > 20000) {
|
||||||
|
problem = 'Prompt can\'t exceed 20,000 characters';
|
||||||
|
} else if ((_kind == 'daily' || _kind == 'weekly') &&
|
||||||
|
_times.any((t) => !RegExp(r'^([01]\d|2[0-3]):[0-5]\d$').hasMatch(t))) {
|
||||||
|
problem = 'Time must be in HH:mm format';
|
||||||
|
} else if (_kind == 'weekly' && _weekdays.isEmpty) {
|
||||||
|
problem = 'Select at least one weekday';
|
||||||
|
} else if (_kind == 'cron' && _cron.text.trim().isEmpty) {
|
||||||
|
problem = 'Cron expression is required';
|
||||||
|
} else if (!_useDefaults && _modelId.isEmpty) {
|
||||||
|
problem = 'Select a model, or switch back to the default model';
|
||||||
|
}
|
||||||
|
if (problem != null) {
|
||||||
|
messenger.showSnackBar(SnackBar(content: AppText(problem)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() => _saving = true);
|
||||||
|
final initial = widget.initial;
|
||||||
|
final draft = ScheduledTask(
|
||||||
|
id: initial?.id ?? '',
|
||||||
|
name: name,
|
||||||
|
enabled: _enabled,
|
||||||
|
kind: _kind,
|
||||||
|
times: _kind == 'daily' || _kind == 'weekly'
|
||||||
|
? ([..._times]..sort())
|
||||||
|
: const [],
|
||||||
|
weekdays: _kind == 'weekly' ? ([..._weekdays]..sort()) : const [],
|
||||||
|
date: _kind == 'once' ? _dateText(_date) : '',
|
||||||
|
time: _kind == 'once' ? _time : '',
|
||||||
|
cron: _kind == 'cron' ? _cron.text.trim() : '',
|
||||||
|
timezone: initial?.timezone ?? '',
|
||||||
|
prompt: prompt,
|
||||||
|
useDefaults: _useDefaults,
|
||||||
|
providerId: _useDefaults ? '' : _providerId,
|
||||||
|
modelId: _useDefaults ? '' : _modelId,
|
||||||
|
variant: _useDefaults ? '' : _variant,
|
||||||
|
agent: _useDefaults ? '' : _agent,
|
||||||
|
targetSessionId: initial?.targetSessionId ?? '',
|
||||||
|
);
|
||||||
|
final ok = await widget.onSave(draft);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _saving = false);
|
||||||
|
if (ok) Navigator.of(context).pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FieldLabel extends StatelessWidget {
|
||||||
|
final String text;
|
||||||
|
const _FieldLabel(this.text);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
|
child: AppText(text,
|
||||||
|
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,750 @@
|
|||||||
|
// The background-command surfaces: a strip above the composer that names what
|
||||||
|
// is running, a sheet with its live output, and the output preview inside the
|
||||||
|
// tool row that detached the command.
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../api/client.dart';
|
||||||
|
import '../api/shells.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
/// One line of "正在执行 N 条命令", folding when there are many.
|
||||||
|
class ShellTaskBar extends StatefulWidget {
|
||||||
|
final List<ShellTask> tasks;
|
||||||
|
|
||||||
|
/// The chat's own session: a task from a child session is marked.
|
||||||
|
final String sessionId;
|
||||||
|
|
||||||
|
/// Tapping a row opens its output; the stop lives in that sheet.
|
||||||
|
final void Function(ShellTask task) onOpen;
|
||||||
|
|
||||||
|
const ShellTaskBar({
|
||||||
|
super.key,
|
||||||
|
required this.tasks,
|
||||||
|
required this.sessionId,
|
||||||
|
required this.onOpen,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ShellTaskBar> createState() => _ShellTaskBarState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShellTaskBarState extends State<ShellTaskBar> {
|
||||||
|
/// Null until the person folds or unfolds: by default a short list shows.
|
||||||
|
bool? _expanded;
|
||||||
|
|
||||||
|
bool get _open => _expanded ?? widget.tasks.length <= 3;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final tasks = widget.tasks;
|
||||||
|
if (tasks.isEmpty) return const SizedBox.shrink();
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final single = tasks.length == 1;
|
||||||
|
// The same capsule as the activity strip above it: one row of text in the
|
||||||
|
// same stadium, with the same margins, so the two read as one stack.
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
|
||||||
|
child: Material(
|
||||||
|
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.7),
|
||||||
|
shape: const StadiumBorder(),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(minHeight: 36),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (!single) _header(theme, tasks.length),
|
||||||
|
if (single || _open)
|
||||||
|
for (final task in tasks)
|
||||||
|
_ShellTaskRow(
|
||||||
|
key: ValueKey(task.id),
|
||||||
|
task: task,
|
||||||
|
subagent: task.sessionId.isNotEmpty &&
|
||||||
|
task.sessionId != widget.sessionId,
|
||||||
|
onTap: () => widget.onOpen(task),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _header(ThemeData theme, int count) {
|
||||||
|
return InkWell(
|
||||||
|
onTap: () => setState(() => _expanded = !_open),
|
||||||
|
child: SizedBox(
|
||||||
|
height: 24,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.terminal, size: 15, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
trArgs('Running {0} commands', [count]),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: theme.colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Icon(_open ? Icons.expand_less : Icons.expand_more,
|
||||||
|
size: 18, color: theme.hintColor),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShellTaskRow extends StatelessWidget {
|
||||||
|
final ShellTask task;
|
||||||
|
final bool subagent;
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
const _ShellTaskRow({
|
||||||
|
super.key,
|
||||||
|
required this.task,
|
||||||
|
required this.subagent,
|
||||||
|
required this.onTap,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
child: SizedBox(
|
||||||
|
height: 24,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.terminal, size: 15, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
task.command.replaceAll(RegExp(r'\s+'), ' ').trim(),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12.5, fontFamily: 'monospace', height: 1.3),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (subagent) ...[
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
AppText('Subagent',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
)),
|
||||||
|
],
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
// The clock ends on the capsule's inner edge, the same line the
|
||||||
|
// activity strip's clock ends on above it; stopping is a tap away
|
||||||
|
// in the sheet, so no button here to break that line.
|
||||||
|
ShellElapsed(startedAt: task.startedAt),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `3分05秒`, ticking while the command runs.
|
||||||
|
class ShellElapsed extends StatefulWidget {
|
||||||
|
final int startedAt;
|
||||||
|
final bool running;
|
||||||
|
|
||||||
|
const ShellElapsed(
|
||||||
|
{super.key, required this.startedAt, this.running = true});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ShellElapsed> createState() => _ShellElapsedState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShellElapsedState extends State<ShellElapsed> {
|
||||||
|
Timer? _timer;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
if (widget.running) {
|
||||||
|
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_timer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (widget.startedAt <= 0 || !widget.running) return const SizedBox.shrink();
|
||||||
|
final label =
|
||||||
|
formatElapsed(DateTime.now().millisecondsSinceEpoch - widget.startedAt);
|
||||||
|
return Text(
|
||||||
|
label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: Theme.of(context).hintColor,
|
||||||
|
fontFeatures: const [FontFeature.tabularFigures()],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the live output of [task] in a sheet. A command that already ended
|
||||||
|
/// hands in its completion text instead, since the shell (and its output
|
||||||
|
/// file) may be gone.
|
||||||
|
Future<void> showShellOutput(
|
||||||
|
BuildContext context, {
|
||||||
|
required Client client,
|
||||||
|
required ShellTask task,
|
||||||
|
required String directory,
|
||||||
|
required Future<void> Function() onStop,
|
||||||
|
String? finalOutput,
|
||||||
|
bool done = false,
|
||||||
|
}) {
|
||||||
|
return showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
useSafeArea: true,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (_) => FractionallySizedBox(
|
||||||
|
heightFactor: 0.8,
|
||||||
|
child: ShellOutputSheet(
|
||||||
|
client: client,
|
||||||
|
task: task,
|
||||||
|
directory: directory,
|
||||||
|
onStop: onStop,
|
||||||
|
finalOutput: finalOutput,
|
||||||
|
done: done,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The command, its status, and the output so far, following the tail.
|
||||||
|
class ShellOutputSheet extends StatefulWidget {
|
||||||
|
final Client client;
|
||||||
|
final ShellTask task;
|
||||||
|
final String directory;
|
||||||
|
final Future<void> Function() onStop;
|
||||||
|
|
||||||
|
/// The completion text when the command has already ended; the sheet then
|
||||||
|
/// does not poll a shell that may no longer exist.
|
||||||
|
final String? finalOutput;
|
||||||
|
final bool done;
|
||||||
|
|
||||||
|
const ShellOutputSheet({
|
||||||
|
super.key,
|
||||||
|
required this.client,
|
||||||
|
required this.task,
|
||||||
|
required this.directory,
|
||||||
|
required this.onStop,
|
||||||
|
this.finalOutput,
|
||||||
|
this.done = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ShellOutputSheet> createState() => _ShellOutputSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShellOutputSheetState extends State<ShellOutputSheet> {
|
||||||
|
late final ShellOutputFeed _feed = ShellOutputFeed(
|
||||||
|
client: widget.client,
|
||||||
|
task: widget.task,
|
||||||
|
directory: widget.directory,
|
||||||
|
);
|
||||||
|
final ScrollController _scroll = ScrollController();
|
||||||
|
bool _stick = true;
|
||||||
|
bool _stopping = false;
|
||||||
|
|
||||||
|
String get _text => widget.done ? (widget.finalOutput ?? '') : _feed.text;
|
||||||
|
bool get _running => !widget.done && !_feed.ended;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_scroll.addListener(() {
|
||||||
|
if (!_scroll.hasClients) return;
|
||||||
|
final atBottom =
|
||||||
|
_scroll.position.maxScrollExtent - _scroll.position.pixels <= 40;
|
||||||
|
if (atBottom != _stick) setState(() => _stick = atBottom);
|
||||||
|
});
|
||||||
|
if (!widget.done) _feed.start(_onFeed);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onFeed() {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {});
|
||||||
|
if (_stick) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (_scroll.hasClients) {
|
||||||
|
_scroll.jumpTo(_scroll.position.maxScrollExtent);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_feed.dispose();
|
||||||
|
_scroll.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _stop() async {
|
||||||
|
final ok = await confirmStopShell(context, widget.task.command);
|
||||||
|
if (ok != true || !mounted) return;
|
||||||
|
setState(() => _stopping = true);
|
||||||
|
try {
|
||||||
|
await widget.onStop();
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _stopping = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final running = _running;
|
||||||
|
return Padding(
|
||||||
|
padding: EdgeInsets.only(
|
||||||
|
bottom: MediaQuery.of(context).viewInsets.bottom),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
// The drag handle above and a tap on the scrim close the sheet;
|
||||||
|
// a close button would only repeat them.
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Icon(Icons.terminal, size: 18, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
widget.task.command,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 13, fontFamily: 'monospace', height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
// No "运行中" label: a live sheet is running by definition,
|
||||||
|
// and the clock says since when. Only the end is worth saying.
|
||||||
|
if (running)
|
||||||
|
ShellElapsed(
|
||||||
|
startedAt: widget.task.startedAt, running: true)
|
||||||
|
else ...[
|
||||||
|
Icon(Icons.check_circle_outline,
|
||||||
|
size: 15, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
AppText('Ended',
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
|
],
|
||||||
|
const Spacer(),
|
||||||
|
if (running)
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: _stopping ? null : _stop,
|
||||||
|
icon: const Icon(Icons.stop_rounded, size: 17),
|
||||||
|
label: AppText(_stopping ? 'Stopping…' : 'Stop'),
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
foregroundColor: theme.colorScheme.error,
|
||||||
|
minimumSize: const Size(0, 32),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: _text.isEmpty ? null : _copy,
|
||||||
|
icon: const Icon(Icons.copy, size: 15),
|
||||||
|
label: const AppText('Copy'),
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
minimumSize: const Size(0, 32),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 1),
|
||||||
|
Expanded(
|
||||||
|
child: Stack(
|
||||||
|
children: [
|
||||||
|
Positioned.fill(
|
||||||
|
child: _text.isEmpty
|
||||||
|
? Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (_feed.error == null && !_feed.loaded) ...[
|
||||||
|
const SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child:
|
||||||
|
CircularProgressIndicator(strokeWidth: 1.8),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
],
|
||||||
|
AppText(
|
||||||
|
_feed.error ??
|
||||||
|
(!_feed.loaded
|
||||||
|
? 'Reading output…'
|
||||||
|
: running
|
||||||
|
? 'Waiting for output…'
|
||||||
|
: 'No output'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13, color: theme.hintColor),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: Scrollbar(
|
||||||
|
controller: _scroll,
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
controller: _scroll,
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
child: SelectableText(
|
||||||
|
_text,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
height: 1.45),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (!_stick && _text.isNotEmpty)
|
||||||
|
Positioned(
|
||||||
|
right: 12,
|
||||||
|
bottom: 12,
|
||||||
|
child: FilledButton.tonalIcon(
|
||||||
|
onPressed: () {
|
||||||
|
setState(() => _stick = true);
|
||||||
|
_onFeed();
|
||||||
|
},
|
||||||
|
icon: const Icon(Icons.arrow_downward, size: 15),
|
||||||
|
label: const AppText('Jump to latest'),
|
||||||
|
style: FilledButton.styleFrom(
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _copy() async {
|
||||||
|
await Clipboard.setData(ClipboardData(text: _text));
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context)
|
||||||
|
.showSnackBar(const SnackBar(content: AppText('Output copied')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The live output inside the tool row that detached the command: the last
|
||||||
|
/// lines, with the way to the full sheet.
|
||||||
|
class ShellOutputInline extends StatefulWidget {
|
||||||
|
final Client client;
|
||||||
|
final ShellTask task;
|
||||||
|
final String directory;
|
||||||
|
final VoidCallback onOpen;
|
||||||
|
final Future<void> Function() onStop;
|
||||||
|
|
||||||
|
/// The report of a command that already ended (the shell may be gone, so
|
||||||
|
/// there is nothing left to poll).
|
||||||
|
final String? finalOutput;
|
||||||
|
final bool done;
|
||||||
|
|
||||||
|
const ShellOutputInline({
|
||||||
|
super.key,
|
||||||
|
required this.client,
|
||||||
|
required this.task,
|
||||||
|
required this.directory,
|
||||||
|
required this.onOpen,
|
||||||
|
required this.onStop,
|
||||||
|
this.finalOutput,
|
||||||
|
this.done = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ShellOutputInline> createState() => _ShellOutputInlineState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShellOutputInlineState extends State<ShellOutputInline> {
|
||||||
|
late final ShellOutputFeed _feed = ShellOutputFeed(
|
||||||
|
client: widget.client,
|
||||||
|
task: widget.task,
|
||||||
|
directory: widget.directory,
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
if (!widget.done) {
|
||||||
|
_feed.start(() {
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_feed.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final ended = widget.done || _feed.ended;
|
||||||
|
final text = widget.done ? (widget.finalOutput ?? '') : _feed.text;
|
||||||
|
final tail = _tail(text, 8);
|
||||||
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.fromLTRB(10, 8, 10, 4),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerHighest,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.terminal, size: 15, color: theme.hintColor),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
AppText('Background output',
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
if (!ended)
|
||||||
|
AppText('Running',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12, color: theme.colorScheme.primary)),
|
||||||
|
if (ended && text.isEmpty)
|
||||||
|
AppText('Ended',
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
|
const Spacer(),
|
||||||
|
if (!ended)
|
||||||
|
TextButton(
|
||||||
|
onPressed: _stop,
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
foregroundColor: theme.colorScheme.error,
|
||||||
|
minimumSize: const Size(0, 32),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
textStyle: const TextStyle(fontSize: 12.5),
|
||||||
|
),
|
||||||
|
child: const AppText('Stop'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: widget.onOpen,
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
minimumSize: const Size(0, 32),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
textStyle: const TextStyle(fontSize: 12.5),
|
||||||
|
),
|
||||||
|
child: const AppText('View all'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (tail.isEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
|
child: AppText(
|
||||||
|
_feed.error ?? (ended ? 'No output' : 'Waiting for output…'),
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 2, bottom: 6),
|
||||||
|
child: SelectableText(
|
||||||
|
tail,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 12, fontFamily: 'monospace', height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _stop() async {
|
||||||
|
final ok = await confirmStopShell(context, widget.task.command);
|
||||||
|
if (ok == true) await widget.onStop();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _tail(String text, int lines) {
|
||||||
|
if (text.isEmpty) return '';
|
||||||
|
final all = text.split('\n');
|
||||||
|
if (all.length <= lines) return text;
|
||||||
|
return '…\n${all.sublist(all.length - lines).join('\n')}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "停止这个任务?" with the command, as the first-party client asks.
|
||||||
|
Future<bool?> confirmStopShell(BuildContext context, String command) {
|
||||||
|
return showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (dialog) => AlertDialog(
|
||||||
|
title: const AppText('Stop this task?'),
|
||||||
|
content: Text(
|
||||||
|
command,
|
||||||
|
maxLines: 4,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(dialog, false),
|
||||||
|
child: const AppText('Cancel')),
|
||||||
|
FilledButton(
|
||||||
|
style: FilledButton.styleFrom(
|
||||||
|
backgroundColor: Theme.of(dialog).colorScheme.error,
|
||||||
|
foregroundColor: Theme.of(dialog).colorScheme.onError,
|
||||||
|
),
|
||||||
|
onPressed: () => Navigator.pop(dialog, true),
|
||||||
|
child: const AppText('Stop'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a shell's output a page at a time (one poll a second) and says when
|
||||||
|
/// the command ended. Shared by the sheet and the tool row preview.
|
||||||
|
class ShellOutputFeed {
|
||||||
|
ShellOutputFeed({
|
||||||
|
required this.client,
|
||||||
|
required this.task,
|
||||||
|
required this.directory,
|
||||||
|
});
|
||||||
|
|
||||||
|
final Client client;
|
||||||
|
final ShellTask task;
|
||||||
|
final String directory;
|
||||||
|
|
||||||
|
String text = '';
|
||||||
|
|
||||||
|
/// The first page has been read: before that, an empty [text] means the
|
||||||
|
/// read is still under way, not that the command has printed nothing.
|
||||||
|
bool loaded = false;
|
||||||
|
bool ended = false;
|
||||||
|
String? error;
|
||||||
|
|
||||||
|
int _cursor = 0;
|
||||||
|
bool _first = true;
|
||||||
|
bool _busy = false;
|
||||||
|
int _ticks = 0;
|
||||||
|
Timer? _timer;
|
||||||
|
VoidCallback? _onUpdate;
|
||||||
|
|
||||||
|
void start(VoidCallback onUpdate) {
|
||||||
|
if (_timer != null) return;
|
||||||
|
_onUpdate = onUpdate;
|
||||||
|
unawaited(_poll());
|
||||||
|
_timer = Timer.periodic(const Duration(seconds: 1), (_) => _poll());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _poll() async {
|
||||||
|
if (_busy) return;
|
||||||
|
_busy = true;
|
||||||
|
try {
|
||||||
|
if (_first) {
|
||||||
|
final page = await client.shellOutput(task.id, directory: directory);
|
||||||
|
_first = false;
|
||||||
|
if (page.size > shellOutputTailBytes) {
|
||||||
|
// Long command: start near the end instead of reading it all.
|
||||||
|
final tail = await client.shellOutput(
|
||||||
|
task.id,
|
||||||
|
cursor: page.size - shellOutputTailBytes,
|
||||||
|
limit: shellOutputTailBytes,
|
||||||
|
directory: directory,
|
||||||
|
);
|
||||||
|
text = tail.output;
|
||||||
|
_cursor = tail.cursor;
|
||||||
|
} else {
|
||||||
|
text = page.output;
|
||||||
|
_cursor = page.cursor;
|
||||||
|
}
|
||||||
|
error = null;
|
||||||
|
loaded = true;
|
||||||
|
} else if (!ended) {
|
||||||
|
final page = await client.shellOutput(task.id,
|
||||||
|
cursor: _cursor, directory: directory);
|
||||||
|
if (page.output.isNotEmpty) text = _keepTail(text + page.output);
|
||||||
|
_cursor = page.cursor;
|
||||||
|
error = null;
|
||||||
|
}
|
||||||
|
if (!ended && ++_ticks % 3 == 0) {
|
||||||
|
final shell = await client.shell(task.id, directory: directory);
|
||||||
|
if (shell == null || !shell.running) {
|
||||||
|
if (!ended) {
|
||||||
|
final last = await client
|
||||||
|
.shellOutput(task.id, cursor: _cursor, directory: directory)
|
||||||
|
.catchError((_) => const ShellOutputPage());
|
||||||
|
if (last.output.isNotEmpty) text = _keepTail(text + last.output);
|
||||||
|
_cursor = last.cursor;
|
||||||
|
}
|
||||||
|
ended = true;
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_onUpdate?.call();
|
||||||
|
} on ApiError catch (e) {
|
||||||
|
if (e.status == 404) {
|
||||||
|
ended = true;
|
||||||
|
loaded = true;
|
||||||
|
error = null;
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = null;
|
||||||
|
} else {
|
||||||
|
error = trArgs('Could not read output: {0}', [e.message]);
|
||||||
|
}
|
||||||
|
_onUpdate?.call();
|
||||||
|
} catch (e) {
|
||||||
|
error = trArgs('Could not read output: {0}', ['$e']);
|
||||||
|
_onUpdate?.call();
|
||||||
|
} finally {
|
||||||
|
_busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _keepTail(String text) => text.length <= shellOutputTailBytes
|
||||||
|
? text
|
||||||
|
: text.substring(text.length - shellOutputTailBytes);
|
||||||
|
|
||||||
|
void dispose() {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
// The `/` palette above a composer, shared by the chat and the new-session
|
||||||
|
// draft: commands and skills of one directory, filtered as the name is typed.
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../state.dart';
|
||||||
|
import '../l10n.dart';
|
||||||
|
|
||||||
|
const _slashLabels = {
|
||||||
|
'compact': 'Compact',
|
||||||
|
'init': 'Init',
|
||||||
|
'review': 'Review',
|
||||||
|
'goal': 'Goal',
|
||||||
|
'new-extension': 'New extension',
|
||||||
|
'permission': 'Permission',
|
||||||
|
'plan': 'Plans',
|
||||||
|
'feedback': 'Feedback',
|
||||||
|
};
|
||||||
|
|
||||||
|
String? slashLabel(SlashItem item) =>
|
||||||
|
item.skill ? null : _slashLabels[item.name];
|
||||||
|
|
||||||
|
/// Rows for a draft, or null when the palette should stay closed. It stays
|
||||||
|
/// up while only the command name is typed and closes once an argument
|
||||||
|
/// starts, unless the same text was dismissed with Esc.
|
||||||
|
List<SlashItem>? matchSlashItems({
|
||||||
|
required List<SlashItem> items,
|
||||||
|
required String text,
|
||||||
|
String? dismissed,
|
||||||
|
}) {
|
||||||
|
if (dismissed == text) return null;
|
||||||
|
final trimmed = text.trimLeft();
|
||||||
|
if (!trimmed.startsWith('/')) return null;
|
||||||
|
if (trimmed.length > 1 && RegExp(r'\s').hasMatch(trimmed.substring(1))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final query = trimmed.substring(1).toLowerCase().trim();
|
||||||
|
if (query.isEmpty) return items;
|
||||||
|
bool hit(SlashItem item) {
|
||||||
|
final label = slashLabel(item) ?? '';
|
||||||
|
return item.name.toLowerCase().contains(query) ||
|
||||||
|
label.toLowerCase().contains(query) ||
|
||||||
|
item.description.toLowerCase().contains(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return items.where(hit).toList()
|
||||||
|
..sort((a, b) {
|
||||||
|
final aPrefix = a.name.toLowerCase().startsWith(query) ? 0 : 1;
|
||||||
|
final bPrefix = b.name.toLowerCase().startsWith(query) ? 0 : 1;
|
||||||
|
if (aPrefix != bPrefix) return aPrefix - bPrefix;
|
||||||
|
if (a.skill != b.skill) return a.skill ? 1 : -1;
|
||||||
|
return a.name.compareTo(b.name);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The panel itself: rows with an icon, the command and its description.
|
||||||
|
class SlashPalette extends StatelessWidget {
|
||||||
|
final List<SlashItem> items;
|
||||||
|
final int index;
|
||||||
|
final bool loading;
|
||||||
|
final ValueChanged<SlashItem> onPick;
|
||||||
|
|
||||||
|
const SlashPalette({
|
||||||
|
super.key,
|
||||||
|
required this.items,
|
||||||
|
required this.index,
|
||||||
|
required this.loading,
|
||||||
|
required this.onPick,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final selected = items.isEmpty ? 0 : index.clamp(0, items.length - 1);
|
||||||
|
Widget row(IconData icon, String title, String subtitle) => Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(14, 14, 14, 14),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 32,
|
||||||
|
child: Icon(icon, size: 20, color: scheme.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(title,
|
||||||
|
style:
|
||||||
|
TextStyle(fontSize: 14, color: scheme.onSurface)),
|
||||||
|
if (subtitle.isNotEmpty)
|
||||||
|
Text(subtitle,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: scheme.onSurfaceVariant)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return Container(
|
||||||
|
constraints: const BoxConstraints(maxHeight: 56 * 5.5),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: scheme.surfaceContainerHigh,
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
border: Border.all(color: scheme.outlineVariant.withValues(alpha: 0.6)),
|
||||||
|
),
|
||||||
|
child: items.isEmpty
|
||||||
|
? (loading
|
||||||
|
? const Padding(
|
||||||
|
padding: EdgeInsets.all(18),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: row(Icons.search_off, 'No commands available', 'This directory has no commands or skills yet'))
|
||||||
|
: ListView.builder(
|
||||||
|
shrinkWrap: true,
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
|
||||||
|
itemCount: items.length,
|
||||||
|
itemBuilder: (context, i) {
|
||||||
|
final item = items[i];
|
||||||
|
final label = slashLabel(item);
|
||||||
|
final isSelected = i == selected;
|
||||||
|
return InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(14),
|
||||||
|
onTap: () => onPick(item),
|
||||||
|
child: Container(
|
||||||
|
height: 56,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: isSelected
|
||||||
|
? scheme.primary.withValues(alpha: 0.10)
|
||||||
|
: null,
|
||||||
|
borderRadius: BorderRadius.circular(14),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 32,
|
||||||
|
child: Icon(
|
||||||
|
item.skill
|
||||||
|
? Icons.extension_outlined
|
||||||
|
: Icons.terminal,
|
||||||
|
size: 20,
|
||||||
|
color: scheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
AppText('/${item.name}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: scheme.onSurface)),
|
||||||
|
if (label != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(left: 6),
|
||||||
|
child: AppText(label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: scheme.onSurfaceVariant)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (item.description.isNotEmpty)
|
||||||
|
Text(item.description,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: scheme.onSurfaceVariant)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,7 +33,7 @@ static void my_application_activate(GApplication* application) {
|
|||||||
// gtk_header_bar_set_show_close_button(header_bar, TRUE);
|
// gtk_header_bar_set_show_close_button(header_bar, TRUE);
|
||||||
// gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
|
// gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
|
||||||
|
|
||||||
gtk_window_set_title(window, "openchamber");
|
gtk_window_set_title(window, "Chamber Go");
|
||||||
|
|
||||||
g_autoptr(FlDartProject) project = fl_dart_project_new();
|
g_autoptr(FlDartProject) project = fl_dart_project_new();
|
||||||
fl_dart_project_set_dart_entrypoint_arguments(
|
fl_dart_project_set_dart_entrypoint_arguments(
|
||||||
|
|||||||
+322
-122
File diff suppressed because it is too large.
Load diff
+13
-1
@@ -2,7 +2,7 @@ name: openchamber
|
|||||||
description: "A lightweight OpenChamber client for phones."
|
description: "A lightweight OpenChamber client for phones."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 0.3.9+309
|
version: 0.7.4+704
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.14.0
|
sdk: ^3.14.0
|
||||||
@@ -16,10 +16,22 @@ dependencies:
|
|||||||
file_picker: ^13.0.0
|
file_picker: ^13.0.0
|
||||||
gpt_markdown: ^1.4.0
|
gpt_markdown: ^1.4.0
|
||||||
socks5_proxy: ^2.1.2
|
socks5_proxy: ^2.1.2
|
||||||
|
xterm: ^4.0.0
|
||||||
|
flutter_slidable: ^5.2.0
|
||||||
|
archive: ^3.6.1
|
||||||
|
pointycastle: ^4.0.0
|
||||||
|
camera: ^0.12.2
|
||||||
|
zxing2: ^0.2.4
|
||||||
|
flutter_svg: ^2.5.0
|
||||||
|
package_info_plus: ^10.2.2
|
||||||
|
flutter_localizations:
|
||||||
|
sdk: flutter
|
||||||
|
webview_flutter: ^4.14.1
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
flutter_lints: ^6.0.0
|
flutter_lints: ^6.0.0
|
||||||
|
qr: ^4.0.1
|
||||||
|
|
||||||
flutter:
|
flutter:
|
||||||
uses-material-design: true
|
uses-material-design: true
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/screens/archived_sessions_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
class _FakeTransport implements Transport {
|
||||||
|
final List<Map<String, dynamic>> archived;
|
||||||
|
|
||||||
|
_FakeTransport(this.archived);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
Object? body;
|
||||||
|
if (r.path == '/api/session') {
|
||||||
|
body = {'data': archived};
|
||||||
|
} else if (r.path == '/api/project') {
|
||||||
|
body = [
|
||||||
|
{'id': 'p1', 'canonical': '/home/me/alpha', 'vcs': 'git'},
|
||||||
|
{'id': 'p2', 'canonical': '/home/me/beta', 'vcs': 'git'},
|
||||||
|
// A project with no archived sessions must not be offered.
|
||||||
|
{'id': 'p3', 'canonical': '/home/me/gamma', 'vcs': 'git'},
|
||||||
|
];
|
||||||
|
} else if (r.path == '/api/config/settings') {
|
||||||
|
body = {'projects': <dynamic>[]};
|
||||||
|
} else if (r.path == '/api/fs/home') {
|
||||||
|
body = {'home': '/home/me'};
|
||||||
|
} else if (r.method == 'PATCH') {
|
||||||
|
archived.removeWhere((s) => s['id'] == r.path.split('/').last);
|
||||||
|
body = {'data': <String, dynamic>{}};
|
||||||
|
} else if (r.method == 'DELETE') {
|
||||||
|
archived.removeWhere((s) => s['id'] == r.path.split('/').last);
|
||||||
|
body = <String, dynamic>{};
|
||||||
|
} else {
|
||||||
|
body = <String, dynamic>{};
|
||||||
|
}
|
||||||
|
return TransportResponse(
|
||||||
|
200,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _session(
|
||||||
|
String id, String title, String directory, int archived) =>
|
||||||
|
{
|
||||||
|
'id': id,
|
||||||
|
'title': title,
|
||||||
|
'time': {'created': archived - 1000, 'updated': archived - 500, 'archived': archived},
|
||||||
|
'location': {'directory': directory},
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => L10n.instance.apply(AppLanguage.en));
|
||||||
|
tearDown(() => L10n.instance.apply(AppLanguage.zh));
|
||||||
|
|
||||||
|
testWidgets('archived sessions are listed, filtered and restored',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport([
|
||||||
|
_session('a1', 'Old alpha', '/home/me/alpha', 1000),
|
||||||
|
_session('b1', 'Old beta', '/home/me/beta', 2000),
|
||||||
|
]);
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(home: ArchivedSessionsScreen(app: app)));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Archive'), findsOneWidget);
|
||||||
|
expect(find.text('2 archived sessions'), findsOneWidget);
|
||||||
|
expect(find.text('Old alpha'), findsOneWidget);
|
||||||
|
expect(find.text('Old beta'), findsOneWidget);
|
||||||
|
expect(find.text('All projects'), findsOneWidget);
|
||||||
|
|
||||||
|
// The shared project sheet narrows the archive; "All projects" brings both
|
||||||
|
// back.
|
||||||
|
await tester.tap(find.text('All projects'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
// Only projects with archived sessions are offered; no add-project here.
|
||||||
|
expect(find.text('Add project'), findsNothing);
|
||||||
|
expect(find.text('/home/me/gamma'), findsNothing);
|
||||||
|
await tester.tap(find.text('/home/me/alpha'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Old alpha'), findsOneWidget);
|
||||||
|
expect(find.text('Old beta'), findsNothing);
|
||||||
|
expect(find.text('1 archived session'), findsOneWidget);
|
||||||
|
await tester.tap(find.text('alpha'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('All projects'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Old beta'), findsOneWidget);
|
||||||
|
|
||||||
|
// Search across projects.
|
||||||
|
await tester.enterText(find.byType(TextField), 'beta');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Old alpha'), findsNothing);
|
||||||
|
expect(find.text('Old beta'), findsOneWidget);
|
||||||
|
expect(find.text('1 archived session'), findsOneWidget);
|
||||||
|
|
||||||
|
// Restoring removes the row from the archive and from the list.
|
||||||
|
await tester.tap(find.byIcon(Icons.unarchive_outlined));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Old beta'), findsNothing);
|
||||||
|
expect(find.text('Session restored'), findsOneWidget);
|
||||||
|
expect(app.archivedSessions.map((s) => s.id), ['a1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the project sheet filters the archive', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport([
|
||||||
|
_session('a1', 'Old alpha', '/home/me/alpha', 1000),
|
||||||
|
_session('b1', 'Old beta', '/home/me/beta', 2000),
|
||||||
|
]);
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(home: ArchivedSessionsScreen(app: app)));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('All projects'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('/home/me/gamma'), findsNothing);
|
||||||
|
await tester.tap(find.text('/home/me/beta'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Old beta'), findsOneWidget);
|
||||||
|
expect(find.text('Old alpha'), findsNothing);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/screens/browser_panel.dart';
|
||||||
|
import 'package:openchamber/screens/files_panel.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
class _FakeTransport implements Transport {
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
final body = switch (r.path) {
|
||||||
|
'/api/fs/list' => {'entries': <dynamic>[]},
|
||||||
|
_ => <String, dynamic>{},
|
||||||
|
};
|
||||||
|
return TransportResponse(
|
||||||
|
200,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => L10n.instance.apply(AppLanguage.en));
|
||||||
|
tearDown(() => L10n.instance.apply(AppLanguage.zh));
|
||||||
|
|
||||||
|
testWidgets('the browser tab shows the mobile-only hint on desktop',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: BrowserPanel(app: app, directory: '/home/me')),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.byIcon(Icons.public_off), findsOneWidget);
|
||||||
|
expect(find.text('Browser is only available on Android and iOS'),
|
||||||
|
findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the panel tabs are icons with tooltips and open the browser',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.client =
|
||||||
|
Client(Uri.parse('http://test'), transport: _FakeTransport());
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: FilesPanel(app: app, directory: '/home/me')),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
for (final label in [
|
||||||
|
'Files',
|
||||||
|
'Project knowledge',
|
||||||
|
'Terminal',
|
||||||
|
'Browser',
|
||||||
|
]) {
|
||||||
|
expect(find.byTooltip(label), findsOneWidget, reason: label);
|
||||||
|
}
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Browser'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Browser is only available on Android and iOS'),
|
||||||
|
findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/widgets/composer_box.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('the composer opens on focus and folds when the IME closes',
|
||||||
|
(tester) async {
|
||||||
|
final controller = TextEditingController();
|
||||||
|
final focus = FocusNode();
|
||||||
|
final keyboard = ValueNotifier<double>(0);
|
||||||
|
addTearDown(controller.dispose);
|
||||||
|
addTearDown(focus.dispose);
|
||||||
|
addTearDown(keyboard.dispose);
|
||||||
|
|
||||||
|
// A stand-in for the second row's contents: it only exists while open.
|
||||||
|
const model = Text('MODEL');
|
||||||
|
|
||||||
|
// The page owns the keyboard inset (a Scaffold removes it from the body),
|
||||||
|
// so the test feeds it in as the screens do.
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: ValueListenableBuilder<double>(
|
||||||
|
valueListenable: keyboard,
|
||||||
|
builder: (context, inset, _) => Scaffold(
|
||||||
|
body: ComposerBox(
|
||||||
|
controller: controller,
|
||||||
|
focusNode: focus,
|
||||||
|
hint: 'hi',
|
||||||
|
keyboardInset: inset,
|
||||||
|
leading: const Icon(Icons.attach_file),
|
||||||
|
model: model,
|
||||||
|
trailing: const Icon(Icons.send),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
// Unfocused: one line, no model pill.
|
||||||
|
expect(find.text('MODEL'), findsNothing);
|
||||||
|
|
||||||
|
// Focus: the composer opens into two rows.
|
||||||
|
focus.requestFocus();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('MODEL'), findsOneWidget);
|
||||||
|
|
||||||
|
// The soft keyboard rises, then the back gesture closes it while the
|
||||||
|
// field keeps focus: the composer folds back to one line.
|
||||||
|
keyboard.value = 300;
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('MODEL'), findsOneWidget);
|
||||||
|
|
||||||
|
keyboard.value = 0;
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('MODEL'), findsNothing);
|
||||||
|
expect(focus.hasFocus, isTrue);
|
||||||
|
|
||||||
|
// Typing again brings the keyboard back: the composer opens.
|
||||||
|
keyboard.value = 300;
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('MODEL'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/dev_tunnel.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('loopback hosts and ports are recognised', () {
|
||||||
|
for (final host in [
|
||||||
|
'localhost',
|
||||||
|
'127.0.0.1',
|
||||||
|
'::1',
|
||||||
|
'[::1]',
|
||||||
|
'0.0.0.0',
|
||||||
|
'::',
|
||||||
|
]) {
|
||||||
|
expect(isLoopbackDevHost(host), isTrue, reason: host);
|
||||||
|
}
|
||||||
|
expect(isLoopbackDevHost('192.168.1.10'), isFalse);
|
||||||
|
expect(devServerPort(Uri.parse('http://localhost:5173/')), 5173);
|
||||||
|
expect(devServerPort(Uri.parse('http://127.0.0.1')), 80);
|
||||||
|
expect(devServerPort(Uri.parse('https://localhost')), 443);
|
||||||
|
expect(devServerPort(Uri.parse('https://example.com:8443')), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the tunnel keeps path, query and fragment', () {
|
||||||
|
final local = localTunnelUri(
|
||||||
|
Uri.parse('http://localhost:5173/a/b?x=1#top'), 4000);
|
||||||
|
expect(local.toString(), 'http://127.0.0.1:4000/a/b?x=1#top');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the address bar is mapped back to the dev server', () {
|
||||||
|
expect(
|
||||||
|
displayUrlFor('http://127.0.0.1:4000/a', 4000, 'http://localhost:5173'),
|
||||||
|
'http://localhost:5173/a',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
displayUrlFor('http://127.0.0.1:4000', 4000, 'http://localhost:5173'),
|
||||||
|
'http://localhost:5173',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
displayUrlFor('https://example.com/x', 4000, 'http://localhost:5173'),
|
||||||
|
'https://example.com/x',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/widgets/diff_view.dart';
|
||||||
|
|
||||||
|
ContentPart editPart({
|
||||||
|
String name = 'edit',
|
||||||
|
Map<String, dynamic> input = const {},
|
||||||
|
Map<String, dynamic>? metadata,
|
||||||
|
String status = 'completed',
|
||||||
|
String? error,
|
||||||
|
}) {
|
||||||
|
return ContentPart(
|
||||||
|
type: 'tool',
|
||||||
|
name: name,
|
||||||
|
state: ToolState(
|
||||||
|
status: status,
|
||||||
|
input: input,
|
||||||
|
metadata: metadata,
|
||||||
|
error: error,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('an edit uses the server patch from metadata.files', () {
|
||||||
|
final part = editPart(
|
||||||
|
input: {'path': 'PLAN.md'},
|
||||||
|
metadata: {
|
||||||
|
'files': [
|
||||||
|
{
|
||||||
|
'file': 'PLAN.md',
|
||||||
|
'patch': '--- PLAN.md\n'
|
||||||
|
'+++ PLAN.md\n'
|
||||||
|
'@@ -1,3 +1,4 @@\n'
|
||||||
|
' same\n'
|
||||||
|
'-old line\n'
|
||||||
|
'+new line\n'
|
||||||
|
'+added line\n'
|
||||||
|
' tail\n',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final files = toolDiffFiles(part);
|
||||||
|
expect(files, hasLength(1));
|
||||||
|
expect(files.single.path, 'PLAN.md');
|
||||||
|
expect(files.single.added, 2);
|
||||||
|
expect(files.single.removed, 1);
|
||||||
|
expect(files.single.lines.first.kind, DiffLineKind.meta);
|
||||||
|
expect(
|
||||||
|
files.single.lines.where((line) => line.kind == DiffLineKind.hunk),
|
||||||
|
hasLength(1),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
files.single.lines.map((line) => line.text),
|
||||||
|
containsAll(['-old line', '+new line', '+added line']),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an edit without a patch is diffed from its old and new text', () {
|
||||||
|
final part = editPart(input: {
|
||||||
|
'path': '/tmp/a.txt',
|
||||||
|
'oldString': 'one\ntwo',
|
||||||
|
'newString': 'one\ntwo\nthree',
|
||||||
|
});
|
||||||
|
|
||||||
|
final files = toolDiffFiles(part);
|
||||||
|
expect(files, hasLength(1));
|
||||||
|
expect(files.single.added, 1);
|
||||||
|
expect(files.single.removed, 0);
|
||||||
|
expect(files.single.lines.last.text, '+three');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a new write without a patch shows its content as added lines', () {
|
||||||
|
final part = editPart(
|
||||||
|
name: 'write',
|
||||||
|
input: {'path': 'hello.txt', 'content': 'hello\nworld'},
|
||||||
|
);
|
||||||
|
|
||||||
|
final files = toolDiffFiles(part);
|
||||||
|
expect(files, hasLength(1));
|
||||||
|
expect(files.single.added, 2);
|
||||||
|
expect(files.single.removed, 0);
|
||||||
|
expect(files.single.lines.map((line) => line.text),
|
||||||
|
['+hello', '+world']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed tool and a non-diff tool have no diff', () {
|
||||||
|
expect(
|
||||||
|
toolDiffFiles(editPart(
|
||||||
|
metadata: {
|
||||||
|
'files': [
|
||||||
|
{'file': 'a', 'patch': '@@ -1 +1 @@\n-a\n+b\n'},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
error: 'file not found',
|
||||||
|
)),
|
||||||
|
isEmpty,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
toolDiffFiles(editPart(name: 'bash', input: {'command': 'ls'})),
|
||||||
|
isEmpty,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the diff view tints added and removed lines', (tester) async {
|
||||||
|
final files = toolDiffFiles(editPart(
|
||||||
|
metadata: {
|
||||||
|
'files': [
|
||||||
|
{
|
||||||
|
'file': 'a.txt',
|
||||||
|
'patch': '@@ -1,2 +1,2 @@\n old\n-removed\n+added\n',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
));
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: DiffView(files: files)),
|
||||||
|
));
|
||||||
|
|
||||||
|
expect(find.text('@@ -1,2 +1,2 @@'), findsOneWidget);
|
||||||
|
expect(find.text(' old'), findsOneWidget);
|
||||||
|
expect(find.text('-removed'), findsOneWidget);
|
||||||
|
expect(find.text('+added'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
import 'package:openchamber/widgets/project_picker.dart';
|
||||||
|
|
||||||
|
/// A server with one project folder, and an add-project endpoint that records
|
||||||
|
/// the folder in both its project list and its settings document.
|
||||||
|
class _FakeTransport implements Transport {
|
||||||
|
final List<Map<String, dynamic>> projects = [];
|
||||||
|
Map<String, dynamic> settings = {'projects': <dynamic>[]};
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
Object? body;
|
||||||
|
switch (r.path) {
|
||||||
|
case '/api/fs/home':
|
||||||
|
body = {'home': '/home/me'};
|
||||||
|
break;
|
||||||
|
case '/api/fs/list':
|
||||||
|
final path = r.query['path'] ?? '/';
|
||||||
|
body = {
|
||||||
|
'entries': [
|
||||||
|
{'name': 'project', 'path': '$path/project', 'isDirectory': true},
|
||||||
|
{'name': 'notes.txt', 'path': '$path/notes.txt', 'isDirectory': false},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case '/api/project':
|
||||||
|
body = projects;
|
||||||
|
break;
|
||||||
|
case '/api/config/settings':
|
||||||
|
body = settings;
|
||||||
|
break;
|
||||||
|
case '/api/openchamber/directory':
|
||||||
|
final payload = jsonDecode(utf8.decode(r.body!)) as Map<String, dynamic>;
|
||||||
|
final path = payload['path'] as String;
|
||||||
|
projects.add({'id': 'oc1', 'canonical': path, 'vcs': 'git'});
|
||||||
|
settings = {
|
||||||
|
'projects': [
|
||||||
|
{
|
||||||
|
'id': 'settings1',
|
||||||
|
'path': path,
|
||||||
|
'label': 'Project',
|
||||||
|
'addedAt': 1,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
body = {'success': true, 'path': path};
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
body = <String, dynamic>{};
|
||||||
|
}
|
||||||
|
return TransportResponse(
|
||||||
|
200,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => L10n.instance.apply(AppLanguage.en));
|
||||||
|
tearDown(() => L10n.instance.apply(AppLanguage.zh));
|
||||||
|
|
||||||
|
testWidgets('a folder can be browsed and added as a project',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport();
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
ProjectChoice? choice;
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: Builder(
|
||||||
|
builder: (context) => TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
choice = await showProjectPicker(context,
|
||||||
|
app: app, selected: AppState.chatTarget);
|
||||||
|
},
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Add project'), findsOneWidget);
|
||||||
|
await tester.tap(find.text('Add project'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// The browser starts at home and lists folders, not files.
|
||||||
|
expect(find.text('project'), findsOneWidget);
|
||||||
|
expect(find.text('notes.txt'), findsNothing);
|
||||||
|
await tester.tap(find.text('project'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('/home/me/project'), findsWidgets);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Add this folder'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(choice, isNotNull);
|
||||||
|
expect(choice!.canonical, '/home/me/project');
|
||||||
|
expect(app.projects.any((p) => p.canonical == '/home/me/project'), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a project added before it has a session is still listed',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: _SettingsOnly());
|
||||||
|
|
||||||
|
await app.refreshProjects();
|
||||||
|
|
||||||
|
expect(app.projects.map((p) => p.canonical),
|
||||||
|
contains('/home/me/fresh-project'));
|
||||||
|
expect(app.projectLabelFor('/home/me/fresh-project'), 'Fresh');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `/api/project` is empty, but the settings document already has the folder:
|
||||||
|
/// the state must keep it so the picker can offer a first session there.
|
||||||
|
class _SettingsOnly implements Transport {
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
final body = switch (r.path) {
|
||||||
|
'/api/project' => <dynamic>[],
|
||||||
|
'/api/config/settings' => {
|
||||||
|
'projects': [
|
||||||
|
{
|
||||||
|
'id': 'settings1',
|
||||||
|
'path': '/home/me/fresh-project',
|
||||||
|
'label': 'Fresh',
|
||||||
|
'addedAt': 1,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
_ => <String, dynamic>{},
|
||||||
|
};
|
||||||
|
return TransportResponse(
|
||||||
|
200,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
Vendored
+274
@@ -0,0 +1,274 @@
|
|||||||
|
{
|
||||||
|
"schema": 1,
|
||||||
|
"id": "deepy-whale",
|
||||||
|
"name": "Deepy 小鲸鱼",
|
||||||
|
"author": "DSH-TUI",
|
||||||
|
"license": "DSH-TUI 吉祥物,作者授权 dsh-go 使用",
|
||||||
|
"source": "DSH-TUI(Clawd on Desk 主题包 v1.0.0)",
|
||||||
|
"pixelArt": true,
|
||||||
|
"scale": 5,
|
||||||
|
"canvas": {"w": 52, "h": 52},
|
||||||
|
"anchor": {"x": 28, "baseline": 48},
|
||||||
|
"contentBox": {"x": 12, "y": 26, "w": 36, "h": 22},
|
||||||
|
"hitBoxes": {
|
||||||
|
"default": {"x": 12, "y": 26, "w": 33, "h": 22},
|
||||||
|
"wide": {"x": 8, "y": 18, "w": 44, "h": 31},
|
||||||
|
"sleeping": {"x": 7, "y": 23, "w": 39, "h": 25},
|
||||||
|
"byAnim": {
|
||||||
|
"typing": {"x": 0, "y": 26, "w": 52, "h": 23},
|
||||||
|
"conducting": {"x": 3, "y": 27, "w": 39, "h": 22},
|
||||||
|
"react-drag": {"x": 12, "y": 6, "w": 37, "h": 26}
|
||||||
|
},
|
||||||
|
"wideAnims": ["idle-spout", "building", "music", "error", "happy", "notification", "carrying", "waking", "roam-hop", "react-double"],
|
||||||
|
"sleepingAnims": ["sleeping"]
|
||||||
|
},
|
||||||
|
"animations": {
|
||||||
|
"idle": {
|
||||||
|
"sheet": "idle.png",
|
||||||
|
"frameW": 180,
|
||||||
|
"frameH": 120,
|
||||||
|
"cols": 21,
|
||||||
|
"box": {"x": 12, "y": 26, "w": 36, "h": 24},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 35, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 30, "ms": 50}, {"i": 29, "ms": 50}, {"i": 28, "ms": 50}, {"i": 27, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}]
|
||||||
|
},
|
||||||
|
"idle-look": {
|
||||||
|
"sheet": "idle-look.png",
|
||||||
|
"frameW": 185,
|
||||||
|
"frameH": 195,
|
||||||
|
"cols": 22,
|
||||||
|
"box": {"x": 11, "y": 11, "w": 37, "h": 39},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 3400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}, {"i": 56, "ms": 50}, {"i": 57, "ms": 50}, {"i": 58, "ms": 50}, {"i": 59, "ms": 50}, {"i": 60, "ms": 50}, {"i": 61, "ms": 50}, {"i": 62, "ms": 50}, {"i": 63, "ms": 50}, {"i": 64, "ms": 50}, {"i": 65, "ms": 50}, {"i": 65, "ms": 50}]
|
||||||
|
},
|
||||||
|
"idle-spout": {
|
||||||
|
"sheet": "idle-spout.png",
|
||||||
|
"frameW": 195,
|
||||||
|
"frameH": 165,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 8, "y": 17, "w": 39, "h": 33},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 3200,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}, {"i": 56, "ms": 50}, {"i": 57, "ms": 50}, {"i": 58, "ms": 50}, {"i": 59, "ms": 50}, {"i": 60, "ms": 50}, {"i": 61, "ms": 50}, {"i": 62, "ms": 50}, {"i": 63, "ms": 50}]
|
||||||
|
},
|
||||||
|
"thinking": {
|
||||||
|
"sheet": "thinking.png",
|
||||||
|
"frameW": 235,
|
||||||
|
"frameH": 220,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 0, "y": 6, "w": 47, "h": 44},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
|
||||||
|
},
|
||||||
|
"typing": {
|
||||||
|
"sheet": "typing.png",
|
||||||
|
"frameW": 260,
|
||||||
|
"frameH": 165,
|
||||||
|
"cols": 12,
|
||||||
|
"box": {"x": 0, "y": 17, "w": 52, "h": 33},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
|
||||||
|
},
|
||||||
|
"building": {
|
||||||
|
"sheet": "building.png",
|
||||||
|
"frameW": 250,
|
||||||
|
"frameH": 250,
|
||||||
|
"cols": 15,
|
||||||
|
"box": {"x": 2, "y": 0, "w": 50, "h": 50},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 0, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}]
|
||||||
|
},
|
||||||
|
"music": {
|
||||||
|
"sheet": "music.png",
|
||||||
|
"frameW": 240,
|
||||||
|
"frameH": 200,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 2, "y": 10, "w": 48, "h": 40},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 1600,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}]
|
||||||
|
},
|
||||||
|
"conducting": {
|
||||||
|
"sheet": "conducting.png",
|
||||||
|
"frameW": 255,
|
||||||
|
"frameH": 250,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 1, "y": 0, "w": 51, "h": 50},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"sheet": "error.png",
|
||||||
|
"frameW": 225,
|
||||||
|
"frameH": 165,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 4, "y": 17, "w": 45, "h": 33},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
|
||||||
|
},
|
||||||
|
"happy": {
|
||||||
|
"sheet": "happy.png",
|
||||||
|
"frameW": 260,
|
||||||
|
"frameH": 225,
|
||||||
|
"cols": 13,
|
||||||
|
"box": {"x": 0, "y": 5, "w": 52, "h": 45},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2600,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}]
|
||||||
|
},
|
||||||
|
"notification": {
|
||||||
|
"sheet": "notification.png",
|
||||||
|
"frameW": 235,
|
||||||
|
"frameH": 215,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 3, "y": 7, "w": 47, "h": 43},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 1600,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}]
|
||||||
|
},
|
||||||
|
"compacting": {
|
||||||
|
"sheet": "compacting.png",
|
||||||
|
"frameW": 230,
|
||||||
|
"frameH": 180,
|
||||||
|
"cols": 14,
|
||||||
|
"box": {"x": 2, "y": 14, "w": 46, "h": 36},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 2800,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}]
|
||||||
|
},
|
||||||
|
"carrying": {
|
||||||
|
"sheet": "carrying.png",
|
||||||
|
"frameW": 200,
|
||||||
|
"frameH": 160,
|
||||||
|
"cols": 18,
|
||||||
|
"box": {"x": 9, "y": 18, "w": 40, "h": 32},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 1600,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 16, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 17, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}]
|
||||||
|
},
|
||||||
|
"sleeping": {
|
||||||
|
"sheet": "sleeping.png",
|
||||||
|
"frameW": 220,
|
||||||
|
"frameH": 240,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 2, "y": 2, "w": 44, "h": 48},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 3200,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}, {"i": 48, "ms": 50}, {"i": 49, "ms": 50}, {"i": 50, "ms": 50}, {"i": 51, "ms": 50}, {"i": 52, "ms": 50}, {"i": 53, "ms": 50}, {"i": 54, "ms": 50}, {"i": 55, "ms": 50}, {"i": 56, "ms": 50}, {"i": 57, "ms": 50}, {"i": 58, "ms": 50}, {"i": 59, "ms": 50}, {"i": 60, "ms": 50}, {"i": 61, "ms": 50}, {"i": 62, "ms": 50}, {"i": 63, "ms": 50}]
|
||||||
|
},
|
||||||
|
"waking": {
|
||||||
|
"sheet": "waking.png",
|
||||||
|
"frameW": 220,
|
||||||
|
"frameH": 230,
|
||||||
|
"cols": 15,
|
||||||
|
"box": {"x": 8, "y": 4, "w": 44, "h": 46},
|
||||||
|
"loop": false,
|
||||||
|
"ms": 1500,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}]
|
||||||
|
},
|
||||||
|
"roam-hop": {
|
||||||
|
"sheet": "roam-hop.png",
|
||||||
|
"frameW": 185,
|
||||||
|
"frameH": 150,
|
||||||
|
"cols": 13,
|
||||||
|
"box": {"x": 10, "y": 20, "w": 37, "h": 30},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 1200,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 12, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}]
|
||||||
|
},
|
||||||
|
"react-left": {
|
||||||
|
"sheet": "react-left.png",
|
||||||
|
"frameW": 250,
|
||||||
|
"frameH": 170,
|
||||||
|
"cols": 14,
|
||||||
|
"box": {"x": 1, "y": 16, "w": 50, "h": 34},
|
||||||
|
"loop": false,
|
||||||
|
"ms": 2000,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}]
|
||||||
|
},
|
||||||
|
"react-right": {
|
||||||
|
"sheet": "react-right.png",
|
||||||
|
"frameW": 220,
|
||||||
|
"frameH": 170,
|
||||||
|
"cols": 14,
|
||||||
|
"box": {"x": 8, "y": 16, "w": 44, "h": 34},
|
||||||
|
"loop": false,
|
||||||
|
"ms": 2000,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}]
|
||||||
|
},
|
||||||
|
"react-double": {
|
||||||
|
"sheet": "react-double.png",
|
||||||
|
"frameW": 215,
|
||||||
|
"frameH": 165,
|
||||||
|
"cols": 16,
|
||||||
|
"box": {"x": 9, "y": 17, "w": 43, "h": 33},
|
||||||
|
"loop": false,
|
||||||
|
"ms": 2400,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}, {"i": 24, "ms": 50}, {"i": 25, "ms": 50}, {"i": 26, "ms": 50}, {"i": 27, "ms": 50}, {"i": 28, "ms": 50}, {"i": 29, "ms": 50}, {"i": 30, "ms": 50}, {"i": 31, "ms": 50}, {"i": 32, "ms": 50}, {"i": 33, "ms": 50}, {"i": 34, "ms": 50}, {"i": 35, "ms": 50}, {"i": 36, "ms": 50}, {"i": 37, "ms": 50}, {"i": 38, "ms": 50}, {"i": 39, "ms": 50}, {"i": 40, "ms": 50}, {"i": 41, "ms": 50}, {"i": 42, "ms": 50}, {"i": 43, "ms": 50}, {"i": 44, "ms": 50}, {"i": 45, "ms": 50}, {"i": 46, "ms": 50}, {"i": 47, "ms": 50}]
|
||||||
|
},
|
||||||
|
"react-drag": {
|
||||||
|
"sheet": "react-drag.png",
|
||||||
|
"frameW": 205,
|
||||||
|
"frameH": 230,
|
||||||
|
"cols": 12,
|
||||||
|
"box": {"x": 10, "y": 4, "w": 41, "h": 46},
|
||||||
|
"loop": true,
|
||||||
|
"ms": 1200,
|
||||||
|
"frames": [{"i": 0, "ms": 50}, {"i": 1, "ms": 50}, {"i": 2, "ms": 50}, {"i": 3, "ms": 50}, {"i": 4, "ms": 50}, {"i": 5, "ms": 50}, {"i": 6, "ms": 50}, {"i": 7, "ms": 50}, {"i": 8, "ms": 50}, {"i": 9, "ms": 50}, {"i": 10, "ms": 50}, {"i": 11, "ms": 50}, {"i": 12, "ms": 50}, {"i": 13, "ms": 50}, {"i": 14, "ms": 50}, {"i": 15, "ms": 50}, {"i": 16, "ms": 50}, {"i": 17, "ms": 50}, {"i": 18, "ms": 50}, {"i": 19, "ms": 50}, {"i": 20, "ms": 50}, {"i": 21, "ms": 50}, {"i": 22, "ms": 50}, {"i": 23, "ms": 50}]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"idlePool": {
|
||||||
|
"everyMs": {"mean": 120000, "min": 45000, "max": 300000},
|
||||||
|
"anims": [
|
||||||
|
{"anim": "idle-look", "ms": 6800, "weight": 1},
|
||||||
|
{"anim": "idle-spout", "ms": 6400, "weight": 1}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"states": {
|
||||||
|
"idle": ["idle"],
|
||||||
|
"thinking": ["thinking"],
|
||||||
|
"working": ["typing"],
|
||||||
|
"juggling": ["music"],
|
||||||
|
"error": ["error"],
|
||||||
|
"attention": ["happy"],
|
||||||
|
"notification": ["notification"],
|
||||||
|
"sweeping": ["compacting"],
|
||||||
|
"carrying": ["carrying"],
|
||||||
|
"sleeping": ["sleeping"],
|
||||||
|
"waking": ["waking"],
|
||||||
|
"roam": ["roam-hop"]
|
||||||
|
},
|
||||||
|
"bonus": {},
|
||||||
|
"tiers": {
|
||||||
|
"working": [{"min": 3, "anim": "building"}, {"min": 2, "anim": "music"}, {"min": 1, "anim": "typing"}],
|
||||||
|
"juggling": [{"min": 2, "anim": "conducting"}, {"min": 1, "anim": "music"}]
|
||||||
|
},
|
||||||
|
"timings": {
|
||||||
|
"minDisplay": {
|
||||||
|
"attention": 5200,
|
||||||
|
"error": 4800,
|
||||||
|
"sweeping": 5600,
|
||||||
|
"notification": 3200,
|
||||||
|
"carrying": 3200,
|
||||||
|
"working": 1000,
|
||||||
|
"thinking": 1000
|
||||||
|
},
|
||||||
|
"autoReturn": {"attention": 5200, "error": 4800, "sweeping": 300000, "carrying": 3200},
|
||||||
|
"wakeMs": 1500
|
||||||
|
},
|
||||||
|
"reactions": {
|
||||||
|
"tapLeft": "react-left",
|
||||||
|
"tapRight": "react-right",
|
||||||
|
"tickle": "react-double",
|
||||||
|
"drag": "react-drag"
|
||||||
|
},
|
||||||
|
"roam": {"anim": "roam-hop", "faces": "left"},
|
||||||
|
"sleep": {"afterMs": 60000}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('follow-up behavior reads as the first-party default when unknown', () {
|
||||||
|
expect(AppState.normalizeFollowUp('steer'), 'steer');
|
||||||
|
// The removed "immediate" mode was wire-identical to steer.
|
||||||
|
expect(AppState.normalizeFollowUp('immediate'), 'steer');
|
||||||
|
expect(AppState.normalizeFollowUp('queue'), 'queue');
|
||||||
|
expect(AppState.normalizeFollowUp(null), 'queue');
|
||||||
|
expect(AppState.normalizeFollowUp('bogus'), 'queue');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
|
||||||
|
ContentPart imageTool({
|
||||||
|
String name = 'openchamber_image',
|
||||||
|
String status = 'completed',
|
||||||
|
String text = '',
|
||||||
|
String? error,
|
||||||
|
}) {
|
||||||
|
return ContentPart(
|
||||||
|
type: 'tool',
|
||||||
|
name: name,
|
||||||
|
state: ToolState(
|
||||||
|
status: status,
|
||||||
|
content: [ContentPart(type: 'text', text: text)],
|
||||||
|
error: error,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const envelope =
|
||||||
|
'{"schemaVersion":1,"ok":true,"action":"image.generate","data":'
|
||||||
|
'{"model":"axonhub-image/sensenova-u1.5-lite","images":['
|
||||||
|
'{"path":"/tmp/opencode/generated-images/a.png","mime":"image/png"},'
|
||||||
|
'{"path":"/tmp/opencode/generated-images/b.png","mime":"image/png"}]}}';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('generatedImagePaths', () {
|
||||||
|
test('reads every path from a finished image call', () {
|
||||||
|
final part = imageTool(text: envelope);
|
||||||
|
expect(generatedImagePaths(part), [
|
||||||
|
'/tmp/opencode/generated-images/a.png',
|
||||||
|
'/tmp/opencode/generated-images/b.png',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows nothing while the call still runs', () {
|
||||||
|
expect(generatedImagePaths(imageTool(status: 'running', text: envelope)),
|
||||||
|
isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows nothing for a failed call', () {
|
||||||
|
expect(
|
||||||
|
generatedImagePaths(
|
||||||
|
imageTool(status: 'error', text: envelope, error: 'no model')),
|
||||||
|
isEmpty,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('only the openchamber_image tool is lifted out', () {
|
||||||
|
expect(generatedImagePaths(imageTool(name: 'bash', text: envelope)),
|
||||||
|
isEmpty);
|
||||||
|
expect(
|
||||||
|
generatedImagePaths(ContentPart(type: 'text', text: envelope)),
|
||||||
|
isEmpty,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a plain text result is not a picture', () {
|
||||||
|
expect(generatedImagePaths(imageTool(text: '图片已生成')), isEmpty);
|
||||||
|
expect(
|
||||||
|
generatedImagePaths(imageTool(text: '{"ok":false,"action":"x"}')),
|
||||||
|
isEmpty,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('relativePath', () {
|
||||||
|
test('drops the session directory', () {
|
||||||
|
expect(
|
||||||
|
relativePath('/home/blumia/src/app/lib/main.dart',
|
||||||
|
'/home/blumia/src/app'),
|
||||||
|
'lib/main.dart',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keeps paths outside it whole', () {
|
||||||
|
expect(
|
||||||
|
relativePath('/tmp/opencode/generated-images/a.png',
|
||||||
|
'/home/blumia/src/app'),
|
||||||
|
'/tmp/opencode/generated-images/a.png',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tolerates a trailing slash and a file elsewhere', () {
|
||||||
|
expect(relativePath('/a/b/c.txt', '/a/b/'), 'c.txt');
|
||||||
|
expect(relativePath('/a/bc/c.txt', '/a/b'), '/a/bc/c.txt');
|
||||||
|
expect(relativePath('x.txt', ''), 'x.txt');
|
||||||
|
expect(relativePath('/a/b', '/a/b'), '.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
/// A server that keeps `/api/config/settings` in memory, like OpenChamber's
|
||||||
|
/// settings document. [failWrites] makes the PUT answer 500 so the rollback
|
||||||
|
/// can be checked.
|
||||||
|
class _FakeTransport implements Transport {
|
||||||
|
Map<String, dynamic> settings;
|
||||||
|
bool failWrites;
|
||||||
|
|
||||||
|
_FakeTransport(this.settings, {this.failWrites = false});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
final isSettings = r.path == '/api/config/settings';
|
||||||
|
if (isSettings && r.method == 'PUT' && failWrites) {
|
||||||
|
return TransportResponse(
|
||||||
|
500,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(
|
||||||
|
utf8.encode(jsonEncode({'error': 'save failed'})))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (isSettings && r.method == 'PUT' && r.body != null) {
|
||||||
|
final patch = jsonDecode(utf8.decode(r.body!)) as Map<String, dynamic>;
|
||||||
|
settings = {...settings, ...patch};
|
||||||
|
}
|
||||||
|
final body = isSettings ? settings : <String, dynamic>{};
|
||||||
|
return TransportResponse(
|
||||||
|
200,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('the server gitignore setting is read and written', () async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport({'filesViewShowGitignored': true});
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
await app.refreshChatSettings();
|
||||||
|
expect(app.showGitignored, isTrue);
|
||||||
|
|
||||||
|
expect(await app.setShowGitignored(false), isTrue);
|
||||||
|
expect(app.showGitignored, isFalse);
|
||||||
|
expect(transport.settings['filesViewShowGitignored'], isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an absent setting starts off', () async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.client =
|
||||||
|
Client(Uri.parse('http://test'), transport: _FakeTransport({}));
|
||||||
|
|
||||||
|
await app.refreshChatSettings();
|
||||||
|
expect(app.showGitignored, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed save restores the previous value', () async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.client = Client(Uri.parse('http://test'),
|
||||||
|
transport: _FakeTransport({'filesViewShowGitignored': true},
|
||||||
|
failWrites: true));
|
||||||
|
|
||||||
|
await app.refreshChatSettings();
|
||||||
|
expect(await app.setShowGitignored(false), isFalse);
|
||||||
|
expect(app.showGitignored, isTrue);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/widgets/image_viewer.dart';
|
||||||
|
|
||||||
|
class _NoopTransport implements Transport {
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A 1x1 transparent PNG.
|
||||||
|
const _png =
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => L10n.instance.apply(AppLanguage.en));
|
||||||
|
tearDown(() => L10n.instance.apply(AppLanguage.zh));
|
||||||
|
|
||||||
|
final client = Client(Uri.parse('http://test'), transport: _NoopTransport());
|
||||||
|
|
||||||
|
Future<void> pumpViewer(WidgetTester tester, {bool mediaActions = false}) async {
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: ImageViewerPage(
|
||||||
|
images: const [
|
||||||
|
ImageSlide('One', 'data:image/png;base64,$_png'),
|
||||||
|
ImageSlide('Two', 'data:image/png;base64,$_png'),
|
||||||
|
],
|
||||||
|
directory: '/home/me',
|
||||||
|
client: client,
|
||||||
|
mediaActions: mediaActions,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.pump(const Duration(milliseconds: 200));
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('a picture opens full screen and can be zoomed and panned',
|
||||||
|
(tester) async {
|
||||||
|
await pumpViewer(tester);
|
||||||
|
|
||||||
|
expect(find.text('One'), findsOneWidget);
|
||||||
|
expect(find.text('1 / 2'), findsOneWidget);
|
||||||
|
final viewer = find.byType(InteractiveViewer);
|
||||||
|
expect(viewer, findsOneWidget);
|
||||||
|
|
||||||
|
final center = tester.getCenter(viewer);
|
||||||
|
final left = await tester.startGesture(center - const Offset(20, 0));
|
||||||
|
final right = await tester.startGesture(center + const Offset(20, 0));
|
||||||
|
await left.moveTo(center - const Offset(80, 0));
|
||||||
|
await right.moveTo(center + const Offset(80, 0));
|
||||||
|
await tester.pump();
|
||||||
|
await left.up();
|
||||||
|
await right.up();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
final zoomed = tester.widget<InteractiveViewer>(viewer);
|
||||||
|
final controller = zoomed.transformationController!;
|
||||||
|
expect(controller.value.getMaxScaleOnAxis(), greaterThan(1.0));
|
||||||
|
|
||||||
|
// Once zoomed, a one-finger drag pans the picture instead of paging.
|
||||||
|
final before = controller.value.getTranslation();
|
||||||
|
await tester.drag(viewer, const Offset(30, 12));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
final after = controller.value.getTranslation();
|
||||||
|
expect(after.x, isNot(before.x));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a swipe moves to the next picture while not zoomed',
|
||||||
|
(tester) async {
|
||||||
|
await pumpViewer(tester);
|
||||||
|
|
||||||
|
await tester.drag(find.byType(InteractiveViewer), const Offset(-600, 0));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Two'), findsOneWidget);
|
||||||
|
expect(find.text('2 / 2'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('save and share send the current picture to the platform',
|
||||||
|
(tester) async {
|
||||||
|
final calls = <MethodCall>[];
|
||||||
|
const channel = MethodChannel('openchamber/media');
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(channel, (call) async {
|
||||||
|
calls.add(call);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
addTearDown(() => TestDefaultBinaryMessengerBinding.instance
|
||||||
|
.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(channel, null));
|
||||||
|
|
||||||
|
await pumpViewer(tester, mediaActions: true);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('Save to Photos'));
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(find.byTooltip('Share'));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(calls.map((call) => call.method),
|
||||||
|
containsAll(['saveImage', 'shareImage']));
|
||||||
|
final save = calls.firstWhere((call) => call.method == 'saveImage');
|
||||||
|
final args = save.arguments as Map;
|
||||||
|
expect(args['name'], 'One.png');
|
||||||
|
expect(args['mime'], 'image/png');
|
||||||
|
expect(args['bytes'], isA<Uint8List>());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a tap hides the title and keys until the next tap',
|
||||||
|
(tester) async {
|
||||||
|
await pumpViewer(tester);
|
||||||
|
|
||||||
|
double chromeOpacity() => tester
|
||||||
|
.widget<AnimatedOpacity>(find.byKey(const ValueKey('viewer-chrome')))
|
||||||
|
.opacity;
|
||||||
|
|
||||||
|
expect(chromeOpacity(), 1);
|
||||||
|
await tester.tap(find.byType(InteractiveViewer));
|
||||||
|
await tester.pump(const Duration(milliseconds: 400));
|
||||||
|
expect(chromeOpacity(), 0);
|
||||||
|
await tester.tap(find.byType(InteractiveViewer));
|
||||||
|
await tester.pump(const Duration(milliseconds: 400));
|
||||||
|
expect(chromeOpacity(), 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('an inbox list item parses its text, delivery and files', () {
|
||||||
|
final item = InboxItem.fromJson({
|
||||||
|
'id': 'msg_1',
|
||||||
|
'sessionID': 'ses_1',
|
||||||
|
'time': {'created': 123},
|
||||||
|
'type': 'user',
|
||||||
|
'delivery': 'queue',
|
||||||
|
'payload': {
|
||||||
|
'text': 'hello',
|
||||||
|
'files': [
|
||||||
|
{'name': 'a.png', 'mime': 'image/png', 'data': 'AAAA'},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(item.id, 'msg_1');
|
||||||
|
expect(item.text, 'hello');
|
||||||
|
expect(item.delivery, 'queue');
|
||||||
|
expect(item.created, 123);
|
||||||
|
expect(item.files.single.name, 'a.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an enqueued event carries the id beside the item', () {
|
||||||
|
final item = InboxItem.fromEvent(
|
||||||
|
'msg_2',
|
||||||
|
{
|
||||||
|
'type': 'user',
|
||||||
|
'delivery': 'steer',
|
||||||
|
'payload': {'text': 'steer me'},
|
||||||
|
},
|
||||||
|
456,
|
||||||
|
);
|
||||||
|
expect(item.id, 'msg_2');
|
||||||
|
expect(item.text, 'steer me');
|
||||||
|
expect(item.delivery, 'steer');
|
||||||
|
expect(item.created, 456);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('withDelivery keeps the rest', () {
|
||||||
|
final item = const InboxItem(id: 'm', text: 't', delivery: 'queue');
|
||||||
|
expect(item.withDelivery('steer').delivery, 'steer');
|
||||||
|
expect(item.withDelivery('steer').text, 't');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/l10n/zh.dart';
|
||||||
|
|
||||||
|
/// Strings that are deliberately the same in both languages, or not UI text
|
||||||
|
/// at all (a screen reader label, a path pattern built at runtime).
|
||||||
|
const _notTranslated = <String>{
|
||||||
|
'English',
|
||||||
|
'中文',
|
||||||
|
'Chamber Go',
|
||||||
|
// Product names, separators and glyphs read the same everywhere.
|
||||||
|
'OpenChamber',
|
||||||
|
'OpenCode',
|
||||||
|
' / ',
|
||||||
|
'·',
|
||||||
|
'🖼',
|
||||||
|
' *',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The literal arguments of AppText, tr and trArgs in [source]: the strings
|
||||||
|
/// our own code writes and therefore the ones a translation exists for.
|
||||||
|
Iterable<String> _uiLiterals(String source) sync* {
|
||||||
|
const quote = r'''(?:'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")''';
|
||||||
|
final patterns = <RegExp>[
|
||||||
|
RegExp('AppText\\(\\s*(?:$quote)(?:\\s*(?:$quote))*'),
|
||||||
|
RegExp(r'\btr\(\s*(?:' + quote + ')'),
|
||||||
|
RegExp(r'\btrArgs\(\s*(?:' + quote + r')(?:\s*(?:' + quote + '))*'),
|
||||||
|
];
|
||||||
|
final single = RegExp(quote);
|
||||||
|
for (final pattern in patterns) {
|
||||||
|
for (final match in pattern.allMatches(source)) {
|
||||||
|
final call = match.group(0)!;
|
||||||
|
final joined = single
|
||||||
|
.allMatches(call)
|
||||||
|
.map((m) => m.group(0)!.substring(1, m.group(0)!.length - 1))
|
||||||
|
.map((s) => s.replaceAll(r'\n', '\n').replaceAll(r"\'", "'"))
|
||||||
|
.join();
|
||||||
|
// Interpolated text is built at runtime, not a translation key.
|
||||||
|
if (joined.contains(r'$')) continue;
|
||||||
|
yield joined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
tearDown(() {
|
||||||
|
L10n.instance.apply(AppLanguage.en);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Chinese lookup falls back on the English it was given', () {
|
||||||
|
L10n.instance.apply(AppLanguage.zh);
|
||||||
|
expect(tr('Save'), '保存');
|
||||||
|
expect(tr('A text with no translation'), 'A text with no translation');
|
||||||
|
expect(trArgs('{0} subagents', [3]), '3 个子代理');
|
||||||
|
expect(trArgs('{0} notes', [1]), isNot(contains('notes')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('English is the source, so it needs no table', () {
|
||||||
|
L10n.instance.apply(AppLanguage.en);
|
||||||
|
expect(tr('Save'), 'Save');
|
||||||
|
expect(trArgs('{0} subagents', [3]), '3 subagents');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a language without a table reads English', () {
|
||||||
|
L10n.instance.apply(AppLanguage.zh);
|
||||||
|
// Spanish follows the system language branch; the app has no Spanish
|
||||||
|
// table, so everything is the English source.
|
||||||
|
final dispatcher = TestWidgetsFlutterBinding.instance.platformDispatcher;
|
||||||
|
dispatcher.localeTestValue = const Locale('es', 'ES');
|
||||||
|
addTearDown(dispatcher.clearLocaleTestValue);
|
||||||
|
L10n.instance.apply(AppLanguage.system);
|
||||||
|
expect(L10n.instance.locale.languageCode, 'en');
|
||||||
|
expect(tr('Save'), 'Save');
|
||||||
|
expect(trArgs('{0} subagents', [3]), '3 subagents');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('AppText follows the chosen language', (tester) async {
|
||||||
|
L10n.instance.apply(AppLanguage.en);
|
||||||
|
await tester
|
||||||
|
.pumpWidget(const MaterialApp(home: Scaffold(body: AppText('Save'))));
|
||||||
|
expect(find.text('Save'), findsOneWidget);
|
||||||
|
|
||||||
|
L10n.instance.apply(AppLanguage.zh);
|
||||||
|
await tester
|
||||||
|
.pumpWidget(const MaterialApp(home: Scaffold(body: AppText('Save'))));
|
||||||
|
expect(find.text('保存'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every UI string the code writes has a Chinese entry', () {
|
||||||
|
final missing = <String>{};
|
||||||
|
for (final entity in Directory('lib').listSync(recursive: true)) {
|
||||||
|
if (entity is! File || !entity.path.endsWith('.dart')) continue;
|
||||||
|
if (entity.path.startsWith('lib/l10n')) continue;
|
||||||
|
final source = entity.readAsStringSync();
|
||||||
|
for (final text in _uiLiterals(source)) {
|
||||||
|
if (text.trim().isEmpty) continue;
|
||||||
|
if (chineseStrings.containsKey(text)) continue;
|
||||||
|
if (_notTranslated.contains(text)) continue;
|
||||||
|
missing.add(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(missing, isEmpty,
|
||||||
|
reason: 'Add these to lib/l10n/zh.dart (or to _notTranslated if they '
|
||||||
|
'are not UI text):\n${missing.join('\n')}');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/pairing.dart';
|
||||||
|
|
||||||
|
String _link(Map<String, dynamic> payload) =>
|
||||||
|
'openchamber://connect?v=2&p=${base64Url.encode(utf8.encode(jsonEncode(payload))).replaceAll('=', '')}';
|
||||||
|
|
||||||
|
Map<String, dynamic> _payload({
|
||||||
|
String? expiresAt,
|
||||||
|
List<Map<String, dynamic>>? candidates,
|
||||||
|
}) =>
|
||||||
|
{
|
||||||
|
'v': 2,
|
||||||
|
'pairingId': 'pair_123',
|
||||||
|
'secret': 'secret-abc',
|
||||||
|
'label': '我的电脑',
|
||||||
|
if (expiresAt != null) 'expiresAt': expiresAt,
|
||||||
|
'candidates': candidates ??
|
||||||
|
[
|
||||||
|
{'type': 'lan', 'url': 'http://192.168.1.10:3000', 'priority': 10},
|
||||||
|
{
|
||||||
|
'type': 'relay',
|
||||||
|
'relayUrl': 'wss://relay.openchamber.dev/ws',
|
||||||
|
'serverId': 'server-1',
|
||||||
|
'hostEncPubJwk': {
|
||||||
|
'kty': 'EC',
|
||||||
|
'crv': 'P-256',
|
||||||
|
'x': 'abc',
|
||||||
|
'y': 'def',
|
||||||
|
},
|
||||||
|
'priority': 30,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('parses a link with direct and relay candidates, direct first', () {
|
||||||
|
final payload = parsePairingLink(_link(_payload()));
|
||||||
|
expect(payload, isNotNull);
|
||||||
|
expect(payload!.pairingId, 'pair_123');
|
||||||
|
expect(payload.secret, 'secret-abc');
|
||||||
|
expect(payload.label, '我的电脑');
|
||||||
|
expect(payload.candidates, hasLength(2));
|
||||||
|
expect(payload.candidates.first.isRelay, isFalse);
|
||||||
|
expect(payload.candidates.first.url, 'http://192.168.1.10:3000');
|
||||||
|
|
||||||
|
final relay = payload.candidates.last;
|
||||||
|
expect(relay.isRelay, isTrue);
|
||||||
|
expect(relay.relayUrl, 'wss://relay.openchamber.dev/ws');
|
||||||
|
expect(relay.serverId, 'server-1');
|
||||||
|
expect(relay.hostKey?['x'], 'abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a relay-only link works and keeps the grant', () {
|
||||||
|
final payload = parsePairingLink(_link(_payload(candidates: [
|
||||||
|
{
|
||||||
|
'type': 'relay',
|
||||||
|
'relayUrl': 'wss://relay.example/ws',
|
||||||
|
'serverId': 'srv',
|
||||||
|
'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-256', 'x': 'x', 'y': 'y'},
|
||||||
|
'grant': 'g-1',
|
||||||
|
},
|
||||||
|
])));
|
||||||
|
expect(payload, isNotNull);
|
||||||
|
expect(payload!.candidates.single.isRelay, isTrue);
|
||||||
|
expect(payload.candidates.single.grant, 'g-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a bare base64url payload is accepted too', () {
|
||||||
|
final encoded =
|
||||||
|
base64Url.encode(utf8.encode(jsonEncode(_payload()))).replaceAll('=', '');
|
||||||
|
expect(parsePairingLink(encoded), isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('expired and malformed links are refused', () {
|
||||||
|
final past = DateTime.now()
|
||||||
|
.subtract(const Duration(minutes: 1))
|
||||||
|
.toUtc()
|
||||||
|
.toIso8601String();
|
||||||
|
expect(parsePairingLink(_link(_payload(expiresAt: past))), isNull);
|
||||||
|
expect(parsePairingLink('openchamber://connect?v=2&p=not-json'), isNull);
|
||||||
|
expect(parsePairingLink('https://example.com'), isNull);
|
||||||
|
|
||||||
|
// A candidate with a missing key or a bad scheme invalidates the list.
|
||||||
|
expect(
|
||||||
|
parsePairingLink(_link(_payload(candidates: [
|
||||||
|
{
|
||||||
|
'type': 'relay',
|
||||||
|
'relayUrl': 'https://relay.example/ws',
|
||||||
|
'serverId': 'srv',
|
||||||
|
'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-256', 'x': 'x', 'y': 'y'},
|
||||||
|
},
|
||||||
|
]))),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
parsePairingLink(_link(_payload(candidates: [
|
||||||
|
{
|
||||||
|
'type': 'relay',
|
||||||
|
'relayUrl': 'wss://relay.example/ws',
|
||||||
|
'serverId': 'srv',
|
||||||
|
'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-384', 'x': 'x', 'y': 'y'},
|
||||||
|
},
|
||||||
|
]))),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a Windows project path reads as its folder name', () {
|
||||||
|
expect(pathLeaf(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
|
||||||
|
'pineapple-notepad');
|
||||||
|
expect(pathLeaf('/home/blumia/Sources/telegram/'), 'telegram');
|
||||||
|
expect(pathLeaf('relative'), 'relative');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
ProjectInfo(id: 'p', canonical: r'C:\work\pineapple-notepad').label,
|
||||||
|
'pineapple-notepad',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
ProjectInfo(id: 'p', canonical: '/w/x', name: '显式名称').label,
|
||||||
|
'显式名称',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the same place compares across separators and Windows case', () {
|
||||||
|
expect(samePath(r'C:\x\y', 'C:/x/y'), isTrue);
|
||||||
|
expect(samePath(r'C:\X\y', r'c:\x\Y'), isTrue);
|
||||||
|
expect(samePath('/a/b/', '/a/b'), isTrue);
|
||||||
|
expect(samePath('/a/b', '/a/c'), isFalse);
|
||||||
|
// A POSIX path stays case-sensitive.
|
||||||
|
expect(samePath('/a/B', '/a/b'), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('slashPath only unifies separators', () {
|
||||||
|
expect(slashPath(r'C:\a\b\'), 'C:/a/b');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a directory is recognised under a chats root', () {
|
||||||
|
expect(isUnderDirectory('/home/me/.config/openchamber/chats/2026-11-23/x',
|
||||||
|
'/home/me/.config/openchamber/chats'), isTrue);
|
||||||
|
expect(isUnderDirectory(r'C:\Users\me\.config\openchamber\chats\a\b',
|
||||||
|
r'c:\users\me\.config\openchamber\chats'), isTrue);
|
||||||
|
expect(isUnderDirectory('/home/me/.config/openchamber/chats-other/x',
|
||||||
|
'/home/me/.config/openchamber/chats'), isFalse);
|
||||||
|
expect(isUnderDirectory('/home/me/project', '/home/me/.config/openchamber/chats'),
|
||||||
|
isFalse);
|
||||||
|
expect(isUnderDirectory('', '/x'), isFalse);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:archive/archive.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/pets/pet_library.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
test('a zip with a nested pack is unpacked and activated', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final root = await Directory.systemTemp.createTemp('pet-import-');
|
||||||
|
addTearDown(() async {
|
||||||
|
await PetLibrary.instance.remove();
|
||||||
|
if (await root.exists()) await root.delete(recursive: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
final manifest = jsonEncode({
|
||||||
|
'id': 'test-pet',
|
||||||
|
'name': '测试宠物',
|
||||||
|
'canvas': {'w': 8, 'h': 8},
|
||||||
|
'anchor': {'x': 4, 'baseline': 7},
|
||||||
|
'animations': {
|
||||||
|
'idle': {
|
||||||
|
'sheet': 'idle.png',
|
||||||
|
'frameW': 40,
|
||||||
|
'frameH': 40,
|
||||||
|
'cols': 1,
|
||||||
|
'loop': true,
|
||||||
|
'ms': 100,
|
||||||
|
'box': {'x': 0, 'y': 0, 'w': 8, 'h': 8},
|
||||||
|
'frames': [
|
||||||
|
{'i': 0, 'ms': 100},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'states': {
|
||||||
|
'idle': ['idle'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
final archive = Archive();
|
||||||
|
void add(String name, List<int> bytes) =>
|
||||||
|
archive.addFile(ArchiveFile(name, bytes.length, bytes));
|
||||||
|
add('pet/pack.json', utf8.encode(manifest));
|
||||||
|
add('pet/idle.png', [1, 2, 3, 4]);
|
||||||
|
add('pet/README.md', utf8.encode('ignored? no, kept'));
|
||||||
|
|
||||||
|
final bytes = ZipEncoder().encode(archive);
|
||||||
|
expect(bytes, isNotNull);
|
||||||
|
|
||||||
|
final pack = await PetLibrary.instance.importZip(bytes!, root: root);
|
||||||
|
expect(pack.id, 'test-pet');
|
||||||
|
expect(pack.name, '测试宠物');
|
||||||
|
expect(PetLibrary.instance.hasPet, isTrue);
|
||||||
|
expect(PetLibrary.instance.enabled, isTrue);
|
||||||
|
|
||||||
|
final unpacked = Directory('${root.path}/test-pet');
|
||||||
|
expect(await File('${unpacked.path}/pack.json').exists(), isTrue);
|
||||||
|
expect(await File('${unpacked.path}/idle.png').exists(), isTrue);
|
||||||
|
// The nested folder is stripped, not kept as an extra level.
|
||||||
|
expect(await Directory('${unpacked.path}/pet').exists(), isFalse);
|
||||||
|
|
||||||
|
await PetLibrary.instance.remove();
|
||||||
|
expect(PetLibrary.instance.pack, isNull);
|
||||||
|
expect(PetLibrary.instance.enabled, isFalse);
|
||||||
|
expect(await unpacked.exists(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a zip without pack.json is refused', () async {
|
||||||
|
final root = await Directory.systemTemp.createTemp('pet-import-bad-');
|
||||||
|
addTearDown(() async {
|
||||||
|
if (await root.exists()) await root.delete(recursive: true);
|
||||||
|
});
|
||||||
|
final archive = Archive();
|
||||||
|
final bytes = ZipEncoder().encode(archive)!;
|
||||||
|
expect(
|
||||||
|
() => PetLibrary.instance.importZip(bytes, root: root),
|
||||||
|
throwsA(isA<PetImportException>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/pets/pet_library.dart';
|
||||||
|
import 'package:openchamber/pets/pet_pack.dart';
|
||||||
|
import 'package:openchamber/widgets/pet_sprite.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
final library = PetLibrary.instance;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
library.pack = PetPack.fromJson(
|
||||||
|
jsonDecode(File('test/fixtures/deepy-pack.json').readAsStringSync())
|
||||||
|
as Map<String, dynamic>,
|
||||||
|
);
|
||||||
|
library.enabled = true;
|
||||||
|
library.size = 52;
|
||||||
|
library.position = 0.5;
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() {
|
||||||
|
library.pack = null;
|
||||||
|
library.enabled = false;
|
||||||
|
library.position = 0.5;
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The chat's shape: a message area with the pet floating over it and the
|
||||||
|
/// composer below.
|
||||||
|
Future<int Function()> pumpChat(WidgetTester tester) async {
|
||||||
|
var taps = 0;
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: Column(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Stack(
|
||||||
|
children: [
|
||||||
|
Positioned.fill(
|
||||||
|
child: GestureDetector(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onTap: () => taps++,
|
||||||
|
child: const ColoredBox(color: Color(0xFF101014)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Positioned.fill(child: PetLayer(state: 'idle')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 80),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
return () => taps;
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('the pet floats over the messages and only its body takes taps',
|
||||||
|
(tester) async {
|
||||||
|
final taps = await pumpChat(tester);
|
||||||
|
expect(find.byType(PetSprite), findsOneWidget);
|
||||||
|
|
||||||
|
final pet = tester.getCenter(find.byType(PetSprite));
|
||||||
|
// The transparent part of the layer is not a hit target: the message
|
||||||
|
// area still receives the tap.
|
||||||
|
await tester.tapAt(Offset(pet.dx - 160, pet.dy));
|
||||||
|
await tester.pump();
|
||||||
|
expect(taps(), 1);
|
||||||
|
|
||||||
|
// The body is: tapping it reacts instead of reaching the page.
|
||||||
|
await tester.tapAt(pet);
|
||||||
|
await tester.pump();
|
||||||
|
expect(taps(), 1);
|
||||||
|
|
||||||
|
// Nothing reserved in the layout: the message area runs under the pet, so
|
||||||
|
// the pet's box reaches the composer's top edge.
|
||||||
|
final layer = tester.getRect(find.byType(PetLayer));
|
||||||
|
final sprite = tester.getRect(find.byType(PetSprite));
|
||||||
|
expect(layer.bottom, closeTo(sprite.bottom - 10, 0.5));
|
||||||
|
expect(sprite.bottom, greaterThanOrEqualTo(layer.bottom));
|
||||||
|
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('dragging the pet moves it and keeps the spot', (tester) async {
|
||||||
|
await pumpChat(tester);
|
||||||
|
|
||||||
|
final before = tester.getTopLeft(find.byType(PetSprite)).dx;
|
||||||
|
await tester.drag(find.byType(PetSprite), const Offset(80, 0));
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
final after = tester.getTopLeft(find.byType(PetSprite)).dx;
|
||||||
|
expect(after, greaterThan(before + 50));
|
||||||
|
expect(library.position, greaterThan(0.5));
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
expect(prefs.getDouble('pet.x.v1'), library.position);
|
||||||
|
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('nothing is drawn without an imported, enabled pet',
|
||||||
|
(tester) async {
|
||||||
|
library.enabled = false;
|
||||||
|
final taps = await pumpChat(tester);
|
||||||
|
expect(find.byType(PetSprite), findsNothing);
|
||||||
|
|
||||||
|
await tester.tapAt(const Offset(100, 100));
|
||||||
|
await tester.pump();
|
||||||
|
expect(taps(), 1);
|
||||||
|
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/pets/pet_pack.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('the deepy pack parses into canvas, states and animations', () {
|
||||||
|
final json = jsonDecode(File('test/fixtures/deepy-pack.json').readAsStringSync())
|
||||||
|
as Map<String, dynamic>;
|
||||||
|
final pack = PetPack.fromJson(json);
|
||||||
|
|
||||||
|
expect(pack.isValid, isTrue);
|
||||||
|
expect(pack.id, 'deepy-whale');
|
||||||
|
expect(pack.name, 'Deepy 小鲸鱼');
|
||||||
|
expect(pack.canvas.width, closeTo(52, 0.001));
|
||||||
|
expect(pack.canvas.height, closeTo(52, 0.001));
|
||||||
|
expect(pack.anchor.dy, closeTo(48, 0.001));
|
||||||
|
|
||||||
|
expect(pack.animationForState('idle'), 'idle');
|
||||||
|
expect(pack.animationForState('thinking'), 'thinking');
|
||||||
|
expect(pack.animationForState('working'), 'typing');
|
||||||
|
expect(pack.animationForState('attention'), 'happy');
|
||||||
|
expect(pack.animationForState('missing'), 'idle');
|
||||||
|
|
||||||
|
final idle = pack.animation('idle')!;
|
||||||
|
expect(idle.frames, isNotEmpty);
|
||||||
|
expect(idle.frames.first.index, 0);
|
||||||
|
expect(idle.loop, isTrue);
|
||||||
|
// The frame is the box at the pack's 5x export.
|
||||||
|
expect(idle.frameW, (idle.box.width * 5).round());
|
||||||
|
expect(idle.frameH, (idle.box.height * 5).round());
|
||||||
|
// 52 frames in a 21-column sheet, so the sheet has several rows.
|
||||||
|
expect(idle.frames.map((f) => f.index).reduce((a, b) => a > b ? a : b),
|
||||||
|
greaterThan(idle.cols));
|
||||||
|
|
||||||
|
expect(pack.reactions['tapLeft'], 'react-left');
|
||||||
|
expect(pack.reactions['tapRight'], 'react-right');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('frames default to one column when the pack omits the list', () {
|
||||||
|
final pack = PetPack.fromJson({
|
||||||
|
'id': 'p',
|
||||||
|
'canvas': {'w': 8, 'h': 8},
|
||||||
|
'animations': {
|
||||||
|
'idle': {
|
||||||
|
'sheet': 'idle.png',
|
||||||
|
'frameW': 40,
|
||||||
|
'frameH': 40,
|
||||||
|
'cols': 4,
|
||||||
|
'ms': 400,
|
||||||
|
'box': {'x': 0, 'y': 0, 'w': 8, 'h': 8},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'states': {
|
||||||
|
'idle': ['idle'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(pack.isValid, isTrue);
|
||||||
|
final idle = pack.animation('idle')!;
|
||||||
|
expect(idle.frames.length, 4);
|
||||||
|
expect(idle.frames.first.ms, 100);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/widgets/project_icon.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('OpenChamber icon keys map to Flutter icons', () {
|
||||||
|
expect(projectIconData('code'), Icons.code);
|
||||||
|
expect(projectIconData('terminal'), Icons.terminal);
|
||||||
|
expect(projectIconData('ai'), Icons.psychology_outlined);
|
||||||
|
expect(projectIconData('unknown'), isNull);
|
||||||
|
expect(projectIconData(''), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hex and legacy project colours resolve', () {
|
||||||
|
final scheme = ColorScheme.fromSeed(seedColor: Colors.indigo);
|
||||||
|
expect(projectHexColor('#30a46c'), const Color(0xff30a46c));
|
||||||
|
expect(projectHexColor('#abc'), const Color(0xffaabbcc));
|
||||||
|
expect(projectHexColor('30a46c'), isNull);
|
||||||
|
expect(projectColor('error', scheme), scheme.error);
|
||||||
|
expect(projectColor('primary', scheme), scheme.primary);
|
||||||
|
expect(projectColor('comment', scheme), scheme.onSurfaceVariant);
|
||||||
|
expect(projectColor('#30a46c', scheme), const Color(0xff30a46c));
|
||||||
|
expect(projectColor('', scheme), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a settings row decorates the project with label and icon metadata', () {
|
||||||
|
const project = ProjectInfo(id: 'p1', canonical: '/w/app');
|
||||||
|
final merged = project.withMeta({
|
||||||
|
'id': 'path_L3cL2FwcA',
|
||||||
|
'path': '/w/app',
|
||||||
|
'label': 'My App',
|
||||||
|
'icon': 'rocket',
|
||||||
|
'color': '#30a46c',
|
||||||
|
'iconBackground': '#101010',
|
||||||
|
'iconImage': {'mime': 'image/svg+xml', 'updatedAt': 42},
|
||||||
|
});
|
||||||
|
expect(merged.label, 'My App');
|
||||||
|
expect(merged.icon, 'rocket');
|
||||||
|
expect(merged.color, '#30a46c');
|
||||||
|
expect(merged.metaId, 'path_L3cL2FwcA');
|
||||||
|
expect(merged.hasIconImage, isTrue);
|
||||||
|
expect(merged.iconImageMime, 'image/svg+xml');
|
||||||
|
expect(merged.iconImageUpdatedAt, 42);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/screens/scheduled_tasks_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
import 'package:openchamber/widgets/project_picker.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => L10n.instance.apply(AppLanguage.en));
|
||||||
|
tearDown(() => L10n.instance.apply(AppLanguage.zh));
|
||||||
|
|
||||||
|
test('a filesystem root keeps its own name', () {
|
||||||
|
expect(pathLeaf('/'), '/');
|
||||||
|
expect(pathLeaf('/home/me/project/'), 'project');
|
||||||
|
expect(pathLeaf(r'C:\Users\me'), 'me');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the picker lists checkouts and the Chat row', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.projects = const [
|
||||||
|
ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'),
|
||||||
|
// The server also knows the root; it must not read as a blank row.
|
||||||
|
ProjectInfo(id: 'root', canonical: '/'),
|
||||||
|
// The same checkout listed twice (a project record and a sandbox).
|
||||||
|
ProjectInfo(
|
||||||
|
id: 'p2', canonical: '/home/me/project', name: 'My project', vcs: 'git'),
|
||||||
|
];
|
||||||
|
|
||||||
|
ProjectChoice? choice;
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: Builder(
|
||||||
|
builder: (context) => TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
choice = await showProjectPicker(context,
|
||||||
|
app: app, selected: AppState.chatTarget);
|
||||||
|
},
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Choose project'), findsOneWidget);
|
||||||
|
expect(find.text('Chat'), findsWidgets);
|
||||||
|
expect(find.text('My project'), findsOneWidget);
|
||||||
|
// The root's label and its path are the same text.
|
||||||
|
expect(find.text('/'), findsWidgets);
|
||||||
|
|
||||||
|
await tester.tap(find.text('My project'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(choice, isNotNull);
|
||||||
|
expect(choice!.canonical, '/home/me/project');
|
||||||
|
expect(choice!.isChat, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the stats picker adds All projects and drops the Chat row',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.projects = const [
|
||||||
|
ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'),
|
||||||
|
];
|
||||||
|
|
||||||
|
ProjectChoice? choice;
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: Builder(
|
||||||
|
builder: (context) => TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
choice = await showProjectPicker(context,
|
||||||
|
app: app,
|
||||||
|
selected: allProjectsTarget,
|
||||||
|
includeAll: true,
|
||||||
|
includeChat: false);
|
||||||
|
},
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('All projects'), findsOneWidget);
|
||||||
|
expect(find.text('Chat'), findsNothing);
|
||||||
|
expect(find.text('My project'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('All projects'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(choice, isNotNull);
|
||||||
|
expect(choice!.isAll, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('scheduled tasks open the same project sheet', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
app.projects = const [
|
||||||
|
ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'),
|
||||||
|
];
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(home: ScheduledTasksScreen(app: app)));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('My project'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Choose project'), findsOneWidget);
|
||||||
|
expect(find.text('My project'), findsWidgets);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/qr_scan.dart';
|
||||||
|
import 'package:qr/qr.dart';
|
||||||
|
|
||||||
|
/// Renders [data] as a black-on-white luminance image, like a camera frame's
|
||||||
|
/// Y plane, with a quiet zone and the requested scale.
|
||||||
|
Uint8List _qrImage(String data, {int scale = 6, int quiet = 4, int pad = 0}) {
|
||||||
|
final code = QrCode(
|
||||||
|
payload: QrPayload.fromString(data),
|
||||||
|
errorCorrectLevel: QrErrorCorrectLevel.medium,
|
||||||
|
);
|
||||||
|
final image = QrImage(code);
|
||||||
|
final size = (image.moduleCount + quiet * 2) * scale;
|
||||||
|
final stride = size + pad;
|
||||||
|
final out = Uint8List(stride * size)..fillRange(0, stride * size, 255);
|
||||||
|
for (var r = 0; r < image.moduleCount; r++) {
|
||||||
|
for (var c = 0; c < image.moduleCount; c++) {
|
||||||
|
if (!image.isDark(r, c)) continue;
|
||||||
|
final y0 = (r + quiet) * scale;
|
||||||
|
final x0 = (c + quiet) * scale;
|
||||||
|
for (var dy = 0; dy < scale; dy++) {
|
||||||
|
final row = (y0 + dy) * stride;
|
||||||
|
out.fillRange(row + x0, row + x0 + scale, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
const link =
|
||||||
|
'openchamber://connect?v=2&p=eyJ2IjoyLCJwYWlyaW5nSWQiOiJwYWlyX2FiYyJ9';
|
||||||
|
|
||||||
|
test('decodes a QR rendered as a camera Y plane', () {
|
||||||
|
const scale = 6;
|
||||||
|
const quiet = 4;
|
||||||
|
final code = QrCode(
|
||||||
|
payload: QrPayload.fromString(link),
|
||||||
|
errorCorrectLevel: QrErrorCorrectLevel.medium,
|
||||||
|
);
|
||||||
|
final size = (code.moduleCount + quiet * 2) * scale;
|
||||||
|
final image = _qrImage(link, scale: scale, quiet: quiet);
|
||||||
|
expect(decodeQrLuminance(image, size, size, size), link);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a frame can be decoded in a background isolate', () async {
|
||||||
|
const scale = 6;
|
||||||
|
const quiet = 4;
|
||||||
|
final code = QrCode(
|
||||||
|
payload: QrPayload.fromString(link),
|
||||||
|
errorCorrectLevel: QrErrorCorrectLevel.medium,
|
||||||
|
);
|
||||||
|
final size = (code.moduleCount + quiet * 2) * scale;
|
||||||
|
final image = _qrImage(link, scale: scale, quiet: quiet);
|
||||||
|
final text = await compute(
|
||||||
|
decodeQrFrame,
|
||||||
|
QrFrame(
|
||||||
|
luminance: image,
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
rowStride: size,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(text, link);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('respects a padded row stride', () {
|
||||||
|
const scale = 6;
|
||||||
|
const quiet = 4;
|
||||||
|
const pad = 12;
|
||||||
|
final code = QrCode(
|
||||||
|
payload: QrPayload.fromString(link),
|
||||||
|
errorCorrectLevel: QrErrorCorrectLevel.medium,
|
||||||
|
);
|
||||||
|
final size = (code.moduleCount + quiet * 2) * scale;
|
||||||
|
final image = _qrImage(link, scale: scale, quiet: quiet, pad: pad);
|
||||||
|
expect(decodeQrLuminance(image, size, size, size + pad), link);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a last row without its padding still decodes', () {
|
||||||
|
const scale = 6;
|
||||||
|
const quiet = 4;
|
||||||
|
const pad = 12;
|
||||||
|
final code = QrCode(
|
||||||
|
payload: QrPayload.fromString(link),
|
||||||
|
errorCorrectLevel: QrErrorCorrectLevel.medium,
|
||||||
|
);
|
||||||
|
final size = (code.moduleCount + quiet * 2) * scale;
|
||||||
|
final stride = size + pad;
|
||||||
|
final full = _qrImage(link, scale: scale, quiet: quiet, pad: pad);
|
||||||
|
// Some cameras return rowStride * (height - 1) + width bytes: the padding
|
||||||
|
// after the final row is simply not there.
|
||||||
|
final short = Uint8List(stride * (size - 1) + size)
|
||||||
|
..setRange(0, stride * (size - 1) + size, full);
|
||||||
|
expect(decodeQrLuminance(short, size, size, stride), link);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a light-on-dark QR decodes through the inverted fallback', () {
|
||||||
|
const scale = 6;
|
||||||
|
const quiet = 4;
|
||||||
|
final code = QrCode(
|
||||||
|
payload: QrPayload.fromString(link),
|
||||||
|
errorCorrectLevel: QrErrorCorrectLevel.medium,
|
||||||
|
);
|
||||||
|
final size = (code.moduleCount + quiet * 2) * scale;
|
||||||
|
final normal = _qrImage(link, scale: scale, quiet: quiet);
|
||||||
|
final inverted = Uint8List.fromList(
|
||||||
|
[for (final value in normal) 255 - value]);
|
||||||
|
expect(decodeQrLuminance(inverted, size, size, size), link);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a frame without a QR code yields null', () {
|
||||||
|
final blank = Uint8List(320 * 240)..fillRange(0, 320 * 240, 255);
|
||||||
|
expect(decodeQrLuminance(blank, 320, 240, 320), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('short buffers and impossible sizes are refused', () {
|
||||||
|
expect(decodeQrLuminance(Uint8List(10), 100, 100, 100), isNull);
|
||||||
|
expect(decodeQrLuminance(Uint8List(100), 0, 10, 10), isNull);
|
||||||
|
expect(decodeQrLuminance(Uint8List(100), 20, 10, 10), isNull);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/relay_crypto.dart';
|
||||||
|
|
||||||
|
Uint8List _bytes(String text) => Uint8List.fromList(utf8.encode(text));
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('P-256 JWK round-trips and fingerprints stably', () {
|
||||||
|
final pair = newRelayKeyPair();
|
||||||
|
final jwk = publicJwk(pair.publicKey);
|
||||||
|
expect(jwk['kty'], 'EC');
|
||||||
|
expect(jwk['crv'], 'P-256');
|
||||||
|
|
||||||
|
final imported = importPublicJwk(jwk);
|
||||||
|
expect(publicJwk(imported), jwk);
|
||||||
|
expect(jwkFingerprint(jwk), jwkFingerprint(Map<String, dynamic>.from(jwk)));
|
||||||
|
expect(jwkFingerprint(jwk), isNot(contains('"d"')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('both sides derive the same directional keys and can talk', () {
|
||||||
|
final client = newRelayKeyPair();
|
||||||
|
final host = newRelayKeyPair();
|
||||||
|
final nonce = randomBytes(16);
|
||||||
|
|
||||||
|
final clientKeys = deriveSessionKeys(client.privateKey, host.publicKey, nonce);
|
||||||
|
final hostKeys = deriveSessionKeys(host.privateKey, client.publicKey, nonce);
|
||||||
|
expect(clientKeys.clientToHost, hostKeys.clientToHost);
|
||||||
|
expect(clientKeys.hostToClient, hostKeys.hostToClient);
|
||||||
|
expect(clientKeys.clientToHost, isNot(clientKeys.hostToClient));
|
||||||
|
|
||||||
|
final encryptor = RelayEncryptor(clientKeys.clientToHost);
|
||||||
|
final decryptor = RelayDecryptor(hostKeys.clientToHost);
|
||||||
|
final frame = encryptor.encrypt(_bytes('hello over the relay'));
|
||||||
|
expect(frame.first, encryptedFrameVersion);
|
||||||
|
expect(utf8.decode(decryptor.decrypt(frame)), 'hello over the relay');
|
||||||
|
|
||||||
|
// A second frame works; a replayed counter does not.
|
||||||
|
final second = encryptor.encrypt(_bytes('hello over the relay'));
|
||||||
|
expect(utf8.decode(decryptor.decrypt(second)), 'hello over the relay');
|
||||||
|
expect(() => decryptor.decrypt(second), throwsA(isA<RelayCryptoError>()));
|
||||||
|
|
||||||
|
// A different nonce gives different keys.
|
||||||
|
final otherKeys =
|
||||||
|
deriveSessionKeys(client.privateKey, host.publicKey, randomBytes(16));
|
||||||
|
expect(otherKeys.clientToHost, isNot(clientKeys.clientToHost));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tampered frames fail closed', () {
|
||||||
|
final a = newRelayKeyPair();
|
||||||
|
final b = newRelayKeyPair();
|
||||||
|
final nonce = randomBytes(16);
|
||||||
|
final keys = deriveSessionKeys(a.privateKey, b.publicKey, nonce);
|
||||||
|
final frame = RelayEncryptor(keys.clientToHost).encrypt(_bytes('tamper me'));
|
||||||
|
final bad = Uint8List.fromList(frame)..[frame.length - 1] ^= 0xff;
|
||||||
|
expect(() => RelayDecryptor(keys.clientToHost).decrypt(bad),
|
||||||
|
throwsA(isA<RelayCryptoError>()));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('base64url helpers follow the protocol (no padding)', () {
|
||||||
|
final bytes = Uint8List.fromList([0, 1, 2, 250, 255]);
|
||||||
|
final encoded = base64UrlEncodeBytes(bytes);
|
||||||
|
expect(encoded, isNot(contains('=')));
|
||||||
|
expect(base64UrlDecodeBytes(encoded), bytes);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('context reading', () {
|
||||||
|
late AppState app;
|
||||||
|
late ChatState chat;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
app = AppState();
|
||||||
|
chat = ChatState(app, Session(id: 'ses_a', title: '会话'));
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() {
|
||||||
|
chat.dispose();
|
||||||
|
app.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
Message assistant() => Message(
|
||||||
|
id: 'a1',
|
||||||
|
type: 'assistant',
|
||||||
|
model: ModelRef('getdeepin/deepseek-flash', 'axonhub'),
|
||||||
|
tokens: TokenUsage(input: 33800, output: 810, cacheRead: 1792),
|
||||||
|
);
|
||||||
|
|
||||||
|
test('a known model reports its limit and no estimate', () {
|
||||||
|
app.modelLimits = {
|
||||||
|
'axonhub/getdeepin/deepseek-flash': (1000000, 100000),
|
||||||
|
};
|
||||||
|
chat.msgs = [assistant()];
|
||||||
|
|
||||||
|
final reading = chat.usageReading();
|
||||||
|
expect(reading.$1, 36402);
|
||||||
|
expect(reading.$2, 1000000);
|
||||||
|
expect(reading.$5, isTrue);
|
||||||
|
expect(reading.$6, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an unknown model keeps the ring and marks the window estimated', () {
|
||||||
|
app.modelLimits = {};
|
||||||
|
chat.msgs = [assistant()];
|
||||||
|
|
||||||
|
final reading = chat.usageReading();
|
||||||
|
expect(reading.$5, isTrue);
|
||||||
|
expect(reading.$6, isTrue);
|
||||||
|
expect(reading.$2, ChatState.estimatedContextWindow);
|
||||||
|
expect(reading.$4, greaterThan(0));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no assistant tokens means no ring', () {
|
||||||
|
chat.msgs = [Message(id: 'u1', type: 'user')];
|
||||||
|
expect(chat.usageReading().$5, isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The app can be in the background while a turn starts or ends; the events
|
||||||
|
// that said so never arrive, so the chat's running flag has to be taken
|
||||||
|
// from the server again when the app comes back.
|
||||||
|
group('reconciling a turn on return', () {
|
||||||
|
late AppState app;
|
||||||
|
late ChatState chat;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
app = AppState();
|
||||||
|
chat = ChatState(app, Session(id: 'ses_a', title: '会话'));
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() {
|
||||||
|
chat.dispose();
|
||||||
|
app.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the server saying idle ends a turn that was left running', () {
|
||||||
|
chat.running = true;
|
||||||
|
chat.reconcileRunning({'ses_other'}, known: true);
|
||||||
|
expect(chat.running, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the server saying running keeps the strip, even without events', () {
|
||||||
|
chat.running = false;
|
||||||
|
chat.reconcileRunning({'ses_a'}, known: true);
|
||||||
|
expect(chat.running, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the server not answering falls back on the transcript tail', () {
|
||||||
|
chat.running = false;
|
||||||
|
chat.msgs = [
|
||||||
|
Message(id: 'u1', type: 'user'),
|
||||||
|
Message(id: 'a1', type: 'assistant', completed: 100),
|
||||||
|
Message(id: 'u2', type: 'user'),
|
||||||
|
Message(id: 'a2', type: 'assistant'),
|
||||||
|
];
|
||||||
|
chat.reconcileRunning(const {}, known: false);
|
||||||
|
expect(chat.running, isTrue);
|
||||||
|
|
||||||
|
chat.running = true;
|
||||||
|
chat.msgs = [
|
||||||
|
Message(id: 'u1', type: 'user'),
|
||||||
|
Message(id: 'a1', type: 'assistant', completed: 100),
|
||||||
|
];
|
||||||
|
chat.reconcileRunning(const {}, known: false);
|
||||||
|
expect(chat.running, isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/scheduled_tasks.dart';
|
||||||
|
import 'package:openchamber/screens/features_screen.dart';
|
||||||
|
import 'package:openchamber/screens/scheduled_tasks_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
import 'package:openchamber/widgets/scheduled_task_editor.dart';
|
||||||
|
|
||||||
|
Map<String, dynamic> dailyJson() => {
|
||||||
|
'id': 'task_1',
|
||||||
|
'name': '每日同步',
|
||||||
|
'enabled': true,
|
||||||
|
'schedule': {
|
||||||
|
'kind': 'daily',
|
||||||
|
'times': ['09:00', '18:30'],
|
||||||
|
'timezone': 'Asia/Shanghai',
|
||||||
|
},
|
||||||
|
'execution': {
|
||||||
|
'prompt': '总结未完成任务',
|
||||||
|
'providerID': 'axonhub',
|
||||||
|
'modelID': 'deepseek-flash',
|
||||||
|
'agent': 'build',
|
||||||
|
},
|
||||||
|
'state': {
|
||||||
|
'lastStatus': 'success',
|
||||||
|
'lastRunAt': 1000,
|
||||||
|
'nextRunAt': 2000,
|
||||||
|
'lastDurationMs': 4000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('scheduled task wire shape', () {
|
||||||
|
test('a daily task reads its schedule, execution and state', () {
|
||||||
|
final task = ScheduledTask.fromJson(dailyJson());
|
||||||
|
expect(task.id, 'task_1');
|
||||||
|
expect(task.name, '每日同步');
|
||||||
|
expect(task.enabled, isTrue);
|
||||||
|
expect(task.kind, 'daily');
|
||||||
|
expect(task.times, ['09:00', '18:30']);
|
||||||
|
expect(task.timezone, 'Asia/Shanghai');
|
||||||
|
expect(task.prompt, '总结未完成任务');
|
||||||
|
expect(task.useDefaults, isFalse);
|
||||||
|
expect(task.providerId, 'axonhub');
|
||||||
|
expect(task.modelId, 'deepseek-flash');
|
||||||
|
expect(task.agent, 'build');
|
||||||
|
expect(task.lastStatus, 'success');
|
||||||
|
expect(task.nextRunAt, 2000);
|
||||||
|
expect(scheduledScheduleText(task), '每天 09:00、18:30');
|
||||||
|
expect(task.modelLabel, 'axonhub/deepseek-flash · build');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing useDefaults means the session defaults', () {
|
||||||
|
final json = dailyJson();
|
||||||
|
(json['execution'] as Map<String, dynamic>)
|
||||||
|
..remove('providerID')
|
||||||
|
..remove('modelID')
|
||||||
|
..remove('agent');
|
||||||
|
final task = ScheduledTask.fromJson(json);
|
||||||
|
expect(task.useDefaults, isTrue);
|
||||||
|
expect(task.modelLabel, '使用默认模型与智能体');
|
||||||
|
expect(scheduledScheduleText(task), '每天 09:00、18:30');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('weekly, once and cron schedules read as the web client says', () {
|
||||||
|
final weekly = ScheduledTask.fromJson({
|
||||||
|
'schedule': {
|
||||||
|
'kind': 'weekly',
|
||||||
|
'times': ['09:00'],
|
||||||
|
'weekdays': [1, 3],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(scheduledScheduleText(weekly), '每周 周一、周三 09:00');
|
||||||
|
|
||||||
|
final once = ScheduledTask.fromJson({
|
||||||
|
'schedule': {
|
||||||
|
'kind': 'once',
|
||||||
|
'date': '2026-12-01',
|
||||||
|
'time': '08:05',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(scheduledScheduleText(once), '一次性 2026-12-01 08:05');
|
||||||
|
|
||||||
|
final cron = ScheduledTask.fromJson({
|
||||||
|
'schedule': {'kind': 'cron', 'cron': '*/5 * * * *'},
|
||||||
|
});
|
||||||
|
expect(scheduledScheduleText(cron), 'Cron:*/5 * * * *');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saving sends only the schedule fields the kind uses', () {
|
||||||
|
const daily = ScheduledTask(
|
||||||
|
id: 'task_9',
|
||||||
|
name: '每日同步',
|
||||||
|
kind: 'daily',
|
||||||
|
times: ['09:00'],
|
||||||
|
prompt: '总结',
|
||||||
|
useDefaults: true,
|
||||||
|
);
|
||||||
|
final json = daily.toJson();
|
||||||
|
expect(json['id'], 'task_9');
|
||||||
|
expect(json['schedule'], {'kind': 'daily', 'times': ['09:00']});
|
||||||
|
expect(json['execution'], {'prompt': '总结', 'useDefaults': true});
|
||||||
|
expect(json.containsKey('targetSessionId'), isFalse);
|
||||||
|
|
||||||
|
const once = ScheduledTask(
|
||||||
|
name: '一次性',
|
||||||
|
kind: 'once',
|
||||||
|
date: '2026-12-01',
|
||||||
|
time: '08:05',
|
||||||
|
prompt: '提醒',
|
||||||
|
useDefaults: false,
|
||||||
|
providerId: 'axonhub',
|
||||||
|
modelId: 'deepseek-flash',
|
||||||
|
agent: 'plan',
|
||||||
|
);
|
||||||
|
final onceJson = once.toJson();
|
||||||
|
expect(onceJson.containsKey('id'), isFalse);
|
||||||
|
expect(onceJson['schedule'],
|
||||||
|
{'kind': 'once', 'date': '2026-12-01', 'time': '08:05'});
|
||||||
|
expect(onceJson['execution'], {
|
||||||
|
'prompt': '提醒',
|
||||||
|
'useDefaults': false,
|
||||||
|
'providerID': 'axonhub',
|
||||||
|
'modelID': 'deepseek-flash',
|
||||||
|
'agent': 'plan',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status labels and relative times', () {
|
||||||
|
expect(scheduledStatusLabel('success'), '成功');
|
||||||
|
expect(scheduledStatusLabel('running'), '运行中');
|
||||||
|
expect(scheduledStatusLabel('failed'), '错误');
|
||||||
|
expect(scheduledStatusLabel(''), '空闲');
|
||||||
|
|
||||||
|
final soon = scheduledRelativeTime(
|
||||||
|
DateTime.now().add(const Duration(minutes: 5)).millisecondsSinceEpoch);
|
||||||
|
expect(soon, contains('分钟后'));
|
||||||
|
final past = scheduledRelativeTime(
|
||||||
|
DateTime.now().subtract(const Duration(hours: 2)).millisecondsSinceEpoch);
|
||||||
|
expect(past, contains('小时前'));
|
||||||
|
expect(scheduledRelativeTime(0), '');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('screens', () {
|
||||||
|
testWidgets('全部功能 lists the scheduled tasks entry', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
await tester.pumpWidget(MaterialApp(home: FeaturesScreen(app: app)));
|
||||||
|
|
||||||
|
expect(find.text('全部功能'), findsOneWidget);
|
||||||
|
expect(find.text('计划任务'), findsOneWidget);
|
||||||
|
expect(find.text('按时间向会话发送提示词'), findsOneWidget);
|
||||||
|
expect(find.text('统计'), findsOneWidget);
|
||||||
|
expect(find.text('提示词、词元、费用与模型活动'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('计划任务'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
// No client in the test: the page says so instead of listing tasks.
|
||||||
|
expect(find.byType(ScheduledTasksScreen), findsOneWidget);
|
||||||
|
expect(find.text('未连接服务器'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the editor validates and hands back the draft', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
ScheduledTask? saved;
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: SizedBox(
|
||||||
|
height: 900,
|
||||||
|
child: ScheduledTaskEditor(
|
||||||
|
app: app,
|
||||||
|
scopeLabel: 'openchamber-android-native',
|
||||||
|
onSave: (draft) async {
|
||||||
|
saved = draft;
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
|
||||||
|
expect(find.text('新建计划任务'), findsOneWidget);
|
||||||
|
expect(find.text('运行位置:openchamber-android-native'), findsOneWidget);
|
||||||
|
|
||||||
|
// An empty name is refused with a message, not saved.
|
||||||
|
await tester.tap(find.widgetWithText(TextButton, '保存'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('任务名称为必填项'), findsOneWidget);
|
||||||
|
expect(saved, isNull);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), '每日同步');
|
||||||
|
await tester.enterText(find.byType(TextField).at(1), '总结未完成任务');
|
||||||
|
await tester.tap(find.widgetWithText(TextButton, '保存'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(saved, isNotNull);
|
||||||
|
expect(saved!.name, '每日同步');
|
||||||
|
expect(saved!.prompt, '总结未完成任务');
|
||||||
|
expect(saved!.kind, 'daily');
|
||||||
|
expect(saved!.times, ['09:00']);
|
||||||
|
expect(saved!.enabled, isTrue);
|
||||||
|
expect(saved!.useDefaults, isTrue);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/screens/servers_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('a new server form offers the password field', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: ServersScreen(app: app, startEditing: true),
|
||||||
|
));
|
||||||
|
|
||||||
|
expect(find.text('添加服务器'), findsOneWidget);
|
||||||
|
// New servers need it too: a password-protected instance rejects the
|
||||||
|
// first attempt, and there must be somewhere to type the password.
|
||||||
|
expect(find.text('密码(如果需要)'), findsOneWidget);
|
||||||
|
expect(find.text('服务器密码;服务器未设置可留空'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/screens/settings_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
Future<AppState> pumpSettings(WidgetTester tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
await tester.pumpWidget(MaterialApp(home: SettingsScreen(app: app)));
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('settings is an index of categories, not one long page',
|
||||||
|
(tester) async {
|
||||||
|
await pumpSettings(tester);
|
||||||
|
|
||||||
|
expect(find.text('常规'), findsOneWidget);
|
||||||
|
expect(find.text('通用'), findsOneWidget);
|
||||||
|
expect(find.text('外观'), findsOneWidget);
|
||||||
|
expect(find.text('帮助与关于'), findsOneWidget);
|
||||||
|
expect(find.text('聊天'), findsOneWidget);
|
||||||
|
expect(find.text('主题'), findsOneWidget);
|
||||||
|
expect(find.text('宠物'), findsOneWidget);
|
||||||
|
expect(find.text('关于'), findsOneWidget);
|
||||||
|
|
||||||
|
// The category pages keep their controls off the index.
|
||||||
|
expect(find.text('主题模式'), findsNothing);
|
||||||
|
expect(find.byType(Switch), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('通用 opens the agent-tool page with the web defaults',
|
||||||
|
(tester) async {
|
||||||
|
final app = await pumpSettings(tester);
|
||||||
|
app.memoryToolsAvailable = true;
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
await tester.tap(find.text('通用'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('在聊天中'), findsOneWidget);
|
||||||
|
expect(find.text('图表和原型'), findsOneWidget);
|
||||||
|
expect(find.text('密钥'), findsOneWidget);
|
||||||
|
expect(find.text('项目知识'), findsOneWidget);
|
||||||
|
expect(find.text('用量限额'), findsOneWidget);
|
||||||
|
|
||||||
|
SwitchListTile tile(String title) => tester
|
||||||
|
.widget<SwitchListTile>(find.widgetWithText(SwitchListTile, title));
|
||||||
|
// The same defaults the web client starts from.
|
||||||
|
expect(tile('图表和原型').value, isTrue);
|
||||||
|
expect(tile('图像').value, isFalse);
|
||||||
|
expect(tile('密钥').value, isTrue);
|
||||||
|
expect(tile('通知').value, isFalse);
|
||||||
|
expect(tile('记忆').value, isFalse);
|
||||||
|
expect(tile('项目知识').value, isTrue);
|
||||||
|
expect(tile('用量限额').value, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('聊天 opens the follow-up behavior page', (tester) async {
|
||||||
|
final app = await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('聊天'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('追问处理行为'), findsOneWidget);
|
||||||
|
ChoiceChip chip(String label) =>
|
||||||
|
tester.widget<ChoiceChip>(find.widgetWithText(ChoiceChip, label));
|
||||||
|
expect(chip('排队').selected, isTrue);
|
||||||
|
|
||||||
|
await tester.tap(find.text('转向'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.followUpBehavior, 'steer');
|
||||||
|
expect(chip('转向').selected, isTrue);
|
||||||
|
expect(chip('排队').selected, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('主题 opens the theme page', (tester) async {
|
||||||
|
await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('主题'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('主题模式'), findsOneWidget);
|
||||||
|
expect(find.text('主题色'), findsOneWidget);
|
||||||
|
expect(find.text('跟随系统'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('宠物 opens the pet page', (tester) async {
|
||||||
|
await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('宠物'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('尚未导入宠物'), findsOneWidget);
|
||||||
|
expect(find.text('导入宠物包'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('关于 shows the app version, the server versions and licenses',
|
||||||
|
(tester) async {
|
||||||
|
await pumpSettings(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.text('关于'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('版本'), findsOneWidget);
|
||||||
|
expect(find.text('未知'), findsOneWidget); // no platform version in a test
|
||||||
|
expect(find.text('开源许可'), findsOneWidget);
|
||||||
|
expect(find.widgetWithText(ListTile, 'OpenCode'), findsOneWidget);
|
||||||
|
// The header carries the name too, so look for the server row itself.
|
||||||
|
expect(find.widgetWithText(ListTile, 'OpenChamber'), findsOneWidget);
|
||||||
|
// No client: both server rows say so instead of showing a dash.
|
||||||
|
expect(find.text('未连接'), findsNWidgets(2));
|
||||||
|
|
||||||
|
await tester.tap(find.text('开源许可'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('第三方组件'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/api/shells.dart';
|
||||||
|
import 'package:openchamber/background_jobs.dart';
|
||||||
|
import 'package:openchamber/widgets/shell_jobs.dart';
|
||||||
|
|
||||||
|
ContentPart shellCall({
|
||||||
|
String name = 'bash',
|
||||||
|
String status = 'completed',
|
||||||
|
String command = 'pnpm dev',
|
||||||
|
Map<String, dynamic>? metadata,
|
||||||
|
}) {
|
||||||
|
return ContentPart(
|
||||||
|
type: 'tool',
|
||||||
|
name: name,
|
||||||
|
state: ToolState(
|
||||||
|
status: status,
|
||||||
|
input: {'command': command},
|
||||||
|
metadata: metadata,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('backgroundShellId', () {
|
||||||
|
test('a detached command is completed with a running shell id', () {
|
||||||
|
expect(
|
||||||
|
backgroundShellId(shellCall(metadata: {
|
||||||
|
'status': 'running',
|
||||||
|
'shellID': 'sh_abc',
|
||||||
|
})),
|
||||||
|
'sh_abc',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a foreground command has the id but no detached marker', () {
|
||||||
|
expect(backgroundShellId(shellCall(metadata: {'shellID': 'sh_abc'})),
|
||||||
|
isNull);
|
||||||
|
expect(
|
||||||
|
backgroundShellId(shellCall(
|
||||||
|
status: 'running',
|
||||||
|
metadata: {'status': 'running', 'shellID': 'sh_abc'},
|
||||||
|
)),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('other tools and broken metadata say nothing', () {
|
||||||
|
expect(
|
||||||
|
backgroundShellId(
|
||||||
|
shellCall(name: 'read', metadata: {'status': 'running', 'shellID': 'sh_a'})),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(backgroundShellId(shellCall(metadata: null)), isNull);
|
||||||
|
expect(
|
||||||
|
backgroundShellId(shellCall(metadata: {'status': 'running', 'shellID': ''})),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the transcript gives command and start time for the strip', () {
|
||||||
|
final messages = [
|
||||||
|
Message(id: 'm1', type: 'assistant', created: 1000, content: [
|
||||||
|
shellCall(command: 'sleep 600', metadata: {
|
||||||
|
'status': 'running',
|
||||||
|
'shellID': 'sh_one',
|
||||||
|
}),
|
||||||
|
shellCall(metadata: {'shellID': 'sh_foreground'}),
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
final tasks = backgroundShellsFromMessages(messages, 'ses_x');
|
||||||
|
expect(tasks, hasLength(1));
|
||||||
|
expect(tasks.single.id, 'sh_one');
|
||||||
|
expect(tasks.single.command, 'sleep 600');
|
||||||
|
expect(tasks.single.startedAt, 1000);
|
||||||
|
expect(tasks.single.sessionId, 'ses_x');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the job list gives shell jobs with their shell id and owner', () {
|
||||||
|
final tasks = shellTasksFromJobs({
|
||||||
|
'data': [
|
||||||
|
{
|
||||||
|
'id': 'job_a',
|
||||||
|
'kind': 'shell',
|
||||||
|
'status': 'running',
|
||||||
|
'sessionID': 'ses_a',
|
||||||
|
'shellID': 'sh_a',
|
||||||
|
'command': 'npm run dev',
|
||||||
|
'time': {'started': 1795000000000},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'job_b',
|
||||||
|
'kind': 'image',
|
||||||
|
'status': 'running',
|
||||||
|
'sessionID': 'ses_a',
|
||||||
|
'path': '/tmp/a.png',
|
||||||
|
'model': 'm',
|
||||||
|
'time': {'started': 1795000000000},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'job_c',
|
||||||
|
'kind': 'shell',
|
||||||
|
'status': 'completed',
|
||||||
|
'sessionID': 'ses_a',
|
||||||
|
'shellID': 'sh_c',
|
||||||
|
'command': 'npm test',
|
||||||
|
'time': {'started': 1794000000000},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(tasks, hasLength(1));
|
||||||
|
expect(tasks.single.id, 'sh_a');
|
||||||
|
expect(tasks.single.sessionId, 'ses_a');
|
||||||
|
expect(tasks.single.command, 'npm run dev');
|
||||||
|
expect(tasks.single.startedAt, 1795000000000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a completion note gives the shell id, state and output', () {
|
||||||
|
final note = shellCompletionNote(Message(
|
||||||
|
id: 's',
|
||||||
|
type: 'synthetic',
|
||||||
|
text: '<background-result kind="shell" id="sh_a" state="completed" '
|
||||||
|
'command="echo hi">\nhi\nthere\n</background-result>',
|
||||||
|
));
|
||||||
|
expect(note, isNotNull);
|
||||||
|
expect(note!.shellId, 'sh_a');
|
||||||
|
expect(note.state, 'completed');
|
||||||
|
expect(note.output, 'hi\nthere');
|
||||||
|
expect(note.failed, isFalse);
|
||||||
|
|
||||||
|
final failed = shellCompletionNote(Message(
|
||||||
|
id: 's2',
|
||||||
|
type: 'synthetic',
|
||||||
|
text: '<background-result kind="shell" id="sh_b" state="error">\n'
|
||||||
|
'Shell.NotFoundError\n</background-result>',
|
||||||
|
));
|
||||||
|
expect(failed!.failed, isTrue);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
shellCompletionNote(
|
||||||
|
Message(id: 's3', type: 'synthetic', text: 'plain note')),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
shellCompletionNote(Message(
|
||||||
|
id: 's4',
|
||||||
|
type: 'synthetic',
|
||||||
|
text: '<background-result kind="subagent" id="x" state="completed">'
|
||||||
|
'\ndone\n</background-result>',
|
||||||
|
)),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the newest completion for a shell wins', () {
|
||||||
|
Message note(String id, String output) => Message(
|
||||||
|
id: id,
|
||||||
|
type: 'synthetic',
|
||||||
|
text: '<background-result kind="shell" id="sh_a" '
|
||||||
|
'state="completed">\n$output\n</background-result>',
|
||||||
|
);
|
||||||
|
final found = shellCompletionFor(
|
||||||
|
[note('n1', 'first'), note('n2', 'second')], 'sh_a');
|
||||||
|
expect(found!.output, 'second');
|
||||||
|
expect(shellCompletionFor([note('n1', 'x')], 'sh_other'), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a stop note marks its shells as stopped by the user', () {
|
||||||
|
final messages = [
|
||||||
|
Message(
|
||||||
|
id: 's',
|
||||||
|
type: 'synthetic',
|
||||||
|
text: 'The user stopped the background command `sleep 1`.',
|
||||||
|
metadata: {
|
||||||
|
'openchamber': {
|
||||||
|
'shellStop': {
|
||||||
|
'shellIDs': ['sh_a', 'sh_b'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
Message(id: 'a', type: 'assistant', text: 'ok'),
|
||||||
|
];
|
||||||
|
expect(shellWasStopped(messages, 'sh_a'), isTrue);
|
||||||
|
expect(shellWasStopped(messages, 'sh_b'), isTrue);
|
||||||
|
expect(shellWasStopped(messages, 'sh_c'), isFalse);
|
||||||
|
expect(shellWasStopped(const [], 'sh_a'), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the shell list keeps owner, clock and running state', () {
|
||||||
|
final tasks = shellTasksFromList({
|
||||||
|
'location': {'directory': '/repo'},
|
||||||
|
'data': [
|
||||||
|
{
|
||||||
|
'id': 'sh_a',
|
||||||
|
'status': 'running',
|
||||||
|
'command': 'npm run dev',
|
||||||
|
'metadata': {'sessionID': 'ses_a'},
|
||||||
|
'time': {'started': 1795000000000},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'sh_b',
|
||||||
|
'status': 'exited',
|
||||||
|
'command': 'npm test',
|
||||||
|
'metadata': {},
|
||||||
|
'time': {'started': 1794000000000},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(tasks.map((t) => t.id), ['sh_a', 'sh_b']);
|
||||||
|
expect(tasks.first.running, isTrue);
|
||||||
|
expect(tasks.first.sessionId, 'ses_a');
|
||||||
|
expect(tasks.first.startedAt, 1795000000000);
|
||||||
|
expect(tasks.last.running, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an output page reads text, cursor and size', () {
|
||||||
|
final page = ShellOutputPage.fromJson({
|
||||||
|
'data': {'output': 'one\ntwo\n', 'cursor': 8, 'size': 8, 'truncated': false},
|
||||||
|
});
|
||||||
|
expect(page.output, 'one\ntwo\n');
|
||||||
|
expect(page.cursor, 8);
|
||||||
|
expect(page.size, 8);
|
||||||
|
expect(page.truncated, isFalse);
|
||||||
|
expect(ShellOutputPage.fromJson({}).output, '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('elapsed reads in seconds, minutes and hours', () {
|
||||||
|
expect(formatElapsed(0), '0秒');
|
||||||
|
expect(formatElapsed(12 * 1000), '12秒');
|
||||||
|
expect(formatElapsed(185 * 1000), '3分05秒');
|
||||||
|
expect(formatElapsed(3723 * 1000), '1:02:03');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the stop note names the command and says it was the user', () {
|
||||||
|
final note = stopNote(' pnpm dev ');
|
||||||
|
expect(note, contains('pnpm dev'));
|
||||||
|
expect(note, contains('user stopped'));
|
||||||
|
expect(note, contains('Shell.NotFoundError'));
|
||||||
|
});
|
||||||
|
|
||||||
|
group('ShellTaskBar', () {
|
||||||
|
ShellTask task(String id, {String command = 'pnpm dev', String session = 'ses_a'}) =>
|
||||||
|
ShellTask(
|
||||||
|
id: id,
|
||||||
|
sessionId: session,
|
||||||
|
command: command,
|
||||||
|
startedAt: DateTime.now().millisecondsSinceEpoch - 65000,
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<void> pump(WidgetTester tester, List<ShellTask> tasks,
|
||||||
|
{void Function(ShellTask)? onOpen}) async {
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: Column(
|
||||||
|
children: [
|
||||||
|
ShellTaskBar(
|
||||||
|
tasks: tasks,
|
||||||
|
sessionId: 'ses_a',
|
||||||
|
onOpen: onOpen ?? (_) {},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('one command is its own row, with its clock', (tester) async {
|
||||||
|
ShellTask? opened;
|
||||||
|
await pump(tester, [task('sh_1', command: 'pnpm dev')],
|
||||||
|
onOpen: (t) => opened = t);
|
||||||
|
expect(find.text('pnpm dev'), findsOneWidget);
|
||||||
|
expect(find.text('1分05秒'), findsOneWidget);
|
||||||
|
expect(find.textContaining('正在执行'), findsNothing);
|
||||||
|
// Stopping is in the sheet the row opens, not a button on the bar.
|
||||||
|
expect(find.text('停止'), findsNothing);
|
||||||
|
await tester.tap(find.text('pnpm dev'));
|
||||||
|
expect(opened?.id, 'sh_1');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('two commands share a count header and both show',
|
||||||
|
(tester) async {
|
||||||
|
await pump(tester, [
|
||||||
|
task('sh_1', command: 'pnpm dev'),
|
||||||
|
task('sh_2', command: 'pnpm test', session: 'ses_child'),
|
||||||
|
]);
|
||||||
|
expect(find.text('正在执行 2 条命令'), findsOneWidget);
|
||||||
|
expect(find.text('pnpm dev'), findsOneWidget);
|
||||||
|
expect(find.text('pnpm test'), findsOneWidget);
|
||||||
|
expect(find.text('子代理'), findsOneWidget);
|
||||||
|
expect(find.text('停止'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a long list folds until asked', (tester) async {
|
||||||
|
await pump(tester, [for (var i = 0; i < 4; i++) task('sh_$i', command: 'cmd $i')]);
|
||||||
|
expect(find.text('正在执行 4 条命令'), findsOneWidget);
|
||||||
|
expect(find.text('cmd 0'), findsNothing);
|
||||||
|
await tester.tap(find.text('正在执行 4 条命令'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('cmd 0'), findsOneWidget);
|
||||||
|
expect(find.text('cmd 3'), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/screens/sessions_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
import 'package:openchamber/storage.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('the sidebar footer names the server and opens settings',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
app.conn = Connection(
|
||||||
|
id: 'c1',
|
||||||
|
label: '家里的服务器',
|
||||||
|
url: 'http://127.0.0.1:3000',
|
||||||
|
);
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: SessionListPane(app: app)),
|
||||||
|
));
|
||||||
|
|
||||||
|
expect(find.text('家里的服务器'), findsOneWidget);
|
||||||
|
expect(find.byIcon(Icons.dns_outlined), findsOneWidget);
|
||||||
|
expect(find.byTooltip('全部功能'), findsOneWidget);
|
||||||
|
expect(find.byTooltip('设置'), findsOneWidget);
|
||||||
|
|
||||||
|
// 全部功能 sits left of the settings key and holds the scheduled tasks.
|
||||||
|
await tester.tap(find.byTooltip('全部功能'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('计划任务'), findsOneWidget);
|
||||||
|
await tester.pageBack();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('设置'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
// The settings page replaced the shell.
|
||||||
|
expect(find.text('外观'), findsOneWidget);
|
||||||
|
expect(find.text('聊天'), findsOneWidget);
|
||||||
|
expect(find.text('宠物'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/screens/sessions_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('chat folders group under 聊天, not under session-xxxxx',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
app.chatRoots = const [r'C:\Users\me\.config\openchamber\chats'];
|
||||||
|
final now = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
app.sessions = [
|
||||||
|
Session(
|
||||||
|
id: 'c1',
|
||||||
|
title: 'OpenCode 图像模型配置',
|
||||||
|
location: Location(
|
||||||
|
r'C:\Users\me\.config\openchamber\chats\2026-11-23\session-a'),
|
||||||
|
created: now,
|
||||||
|
updated: now,
|
||||||
|
),
|
||||||
|
Session(
|
||||||
|
id: 'c2',
|
||||||
|
title: 'LC_ALL 环境变量的设置来源',
|
||||||
|
location: Location(
|
||||||
|
r'C:\Users\me\.config\openchamber\chats\2026-11-22\session-b'),
|
||||||
|
created: now - 1000,
|
||||||
|
updated: now - 1000,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: SessionListPane(app: app)),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// One chats group, labelled the same as the first-party sidebar.
|
||||||
|
expect(find.text('聊天'), findsOneWidget);
|
||||||
|
expect(find.byTooltip('新建聊天'), findsOneWidget);
|
||||||
|
expect(find.textContaining('session-'), findsNothing);
|
||||||
|
expect(find.text('OpenCode 图像模型配置'), findsOneWidget);
|
||||||
|
expect(find.text('LC_ALL 环境变量的设置来源'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a subagent session shows nested under its parent and opens',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
final now = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
app.sessions = [
|
||||||
|
Session(
|
||||||
|
id: 'parent',
|
||||||
|
title: '子代理输出 hello',
|
||||||
|
agent: 'build',
|
||||||
|
location: Location('/home/me/Sources/app'),
|
||||||
|
created: now,
|
||||||
|
updated: now,
|
||||||
|
),
|
||||||
|
Session(
|
||||||
|
id: 'child',
|
||||||
|
parentID: 'parent',
|
||||||
|
title: '输出 hello',
|
||||||
|
agent: 'general',
|
||||||
|
location: Location('/home/me/Sources/app'),
|
||||||
|
created: now - 500,
|
||||||
|
updated: now - 500,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: SessionListPane(app: app)),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('子代理输出 hello'), findsOneWidget);
|
||||||
|
// Tree rows start collapsed; the parent alone shows the count.
|
||||||
|
expect(find.text('输出 hello'), findsNothing);
|
||||||
|
expect(find.byTooltip('展开子代理'), findsOneWidget);
|
||||||
|
expect(find.textContaining('1 个子代理'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.byTooltip('展开子代理'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('输出 hello'), findsOneWidget);
|
||||||
|
expect(find.textContaining('子代理 · general'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('输出 hello'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(app.chat?.session.id, 'child');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the project band matches a session row and keeps the keys in line',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
final now = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
app.sessions = [
|
||||||
|
Session(
|
||||||
|
id: 's1',
|
||||||
|
title: '标签页拖拽与分屏',
|
||||||
|
agent: 'build',
|
||||||
|
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
|
||||||
|
created: now,
|
||||||
|
updated: now,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: SessionListPane(app: app)),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// A Windows path names the folder, not the whole path.
|
||||||
|
expect(find.text('pineapple-notepad'), findsOneWidget);
|
||||||
|
|
||||||
|
final header = find.ancestor(
|
||||||
|
of: find.text('pineapple-notepad'),
|
||||||
|
matching: find.byType(ListTile),
|
||||||
|
);
|
||||||
|
final row = find.ancestor(
|
||||||
|
of: find.text('标签页拖拽与分屏'),
|
||||||
|
matching: find.byType(ListTile),
|
||||||
|
);
|
||||||
|
final headerHeight = tester.getSize(header).height;
|
||||||
|
expect(tester.getSize(row).height, headerHeight);
|
||||||
|
// Compact, close to the old 56px project band.
|
||||||
|
expect(headerHeight, lessThanOrEqualTo(58));
|
||||||
|
|
||||||
|
// The project's + and the session's ⋮ share one vertical line.
|
||||||
|
final add = tester.getCenter(find.byTooltip('在此项目新会话'));
|
||||||
|
final menu = tester.getCenter(find.byIcon(Icons.more_vert));
|
||||||
|
expect(add.dx, closeTo(menu.dx, 0.5));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('tree chevrons line up with the folder chevron and titles start alike',
|
||||||
|
(tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
final now = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
app.sessions = [
|
||||||
|
Session(
|
||||||
|
id: 'parent',
|
||||||
|
title: '子代理输出 hello',
|
||||||
|
agent: 'build',
|
||||||
|
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
|
||||||
|
created: now,
|
||||||
|
updated: now,
|
||||||
|
),
|
||||||
|
Session(
|
||||||
|
id: 'child',
|
||||||
|
parentID: 'parent',
|
||||||
|
title: '输出 hello',
|
||||||
|
agent: 'general',
|
||||||
|
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
|
||||||
|
created: now - 500,
|
||||||
|
updated: now - 500,
|
||||||
|
),
|
||||||
|
Session(
|
||||||
|
id: 'plain',
|
||||||
|
title: '无子代理的会话',
|
||||||
|
agent: 'build',
|
||||||
|
location: Location(r'C:\msys64\home\Gary\Sources\pineapple-notepad'),
|
||||||
|
created: now - 1000,
|
||||||
|
updated: now - 1000,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: SessionListPane(app: app)),
|
||||||
|
));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
// The folder chevron and a parent's subagent chevron are on one line.
|
||||||
|
final folder = tester.getCenter(find.byIcon(Icons.expand_more).first);
|
||||||
|
final tree = tester.getCenter(find.byTooltip('展开子代理'));
|
||||||
|
expect(tree.dx, closeTo(folder.dx, 0.5));
|
||||||
|
|
||||||
|
// A session without subagents keeps the chevron column, so its title
|
||||||
|
// starts where a parent's does and loses no width.
|
||||||
|
final parentTitle = tester.getTopLeft(find.text('子代理输出 hello')).dx;
|
||||||
|
final plainTitle = tester.getTopLeft(find.text('无子代理的会话')).dx;
|
||||||
|
expect(plainTitle, closeTo(parentTitle, 0.5));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
/// A relay connection that drops the first session-list read, then works.
|
||||||
|
class _FakeTransport implements Transport {
|
||||||
|
bool failList;
|
||||||
|
bool failArchive;
|
||||||
|
|
||||||
|
_FakeTransport({this.failList = true, this.failArchive = false});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
if (r.path == '/api/session' && failList) {
|
||||||
|
failList = false;
|
||||||
|
return _reply(503, {
|
||||||
|
'error':
|
||||||
|
'Could not connect to the relay: SocketException: Failed host lookup: relay.example'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (r.path == '/api/session') {
|
||||||
|
return _reply(200, {
|
||||||
|
'data': [
|
||||||
|
{
|
||||||
|
'id': 'ses_1',
|
||||||
|
'title': 'Session',
|
||||||
|
'time': {'created': 1, 'updated': 2},
|
||||||
|
'location': {'directory': '/home/me/project'},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (r.path.startsWith('/api/session/') && r.method == 'PATCH') {
|
||||||
|
if (failArchive) {
|
||||||
|
return _reply(500, {'error': 'archive failed'});
|
||||||
|
}
|
||||||
|
return _reply(200, {'data': <String, dynamic>{}});
|
||||||
|
}
|
||||||
|
return _reply(200, <String, dynamic>{});
|
||||||
|
}
|
||||||
|
|
||||||
|
TransportResponse _reply(int status, Object body) => TransportResponse(
|
||||||
|
status,
|
||||||
|
const {'content-type': 'application/json'},
|
||||||
|
Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))),
|
||||||
|
);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a successful session read clears a stale relay error', () async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport();
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
await app.refreshSessions();
|
||||||
|
expect(app.error, contains('relay'));
|
||||||
|
|
||||||
|
// The tunnel came back on its own; the next read succeeds.
|
||||||
|
await app.refreshSessions();
|
||||||
|
expect(app.sessions, hasLength(1));
|
||||||
|
expect(app.error, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the banner Retry reads the list again and clears the error', () async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport();
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
await app.refreshSessions();
|
||||||
|
expect(app.error, isNotNull);
|
||||||
|
|
||||||
|
await app.retryConnection();
|
||||||
|
expect(app.sessions, hasLength(1));
|
||||||
|
expect(app.error, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a session action error is not wiped by a routine refresh', () async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final transport = _FakeTransport(failList: false, failArchive: true);
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: transport);
|
||||||
|
|
||||||
|
await app.setArchived(Session(id: 'ses_2', title: 'Old'), true);
|
||||||
|
expect(app.error, contains('archive failed'));
|
||||||
|
|
||||||
|
await app.refreshSessions();
|
||||||
|
// The banner Retry dismisses action errors; a background refresh does not.
|
||||||
|
expect(app.error, contains('archive failed'));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/l10n.dart';
|
||||||
|
import 'package:openchamber/api/transport.dart';
|
||||||
|
import 'package:openchamber/screens/stats_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
class _FakeTransport implements Transport {
|
||||||
|
final Map<String, dynamic> report;
|
||||||
|
_FakeTransport(this.report);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportResponse> send(TransportRequest r) async {
|
||||||
|
final body = utf8.encode(jsonEncode({'data': report}));
|
||||||
|
return TransportResponse(200, {'content-type': 'application/json'}, Stream.value(Uint8List.fromList(body)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<TransportSocket> webSocket(String path,
|
||||||
|
{String? rawQuery, Map<String, String> headers = const {}}) async =>
|
||||||
|
throw UnimplementedError();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void setBearerToken(String? token) {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _report() => {
|
||||||
|
'range': {'from': 1000, 'to': 2000},
|
||||||
|
'sessions': 2,
|
||||||
|
'subagents': 1,
|
||||||
|
'prompts': 4,
|
||||||
|
'steps': 120,
|
||||||
|
'tokens': {
|
||||||
|
'input': 110000,
|
||||||
|
'output': 52000,
|
||||||
|
'reasoning': 20000,
|
||||||
|
'cache': {'read': 900000, 'write': 5000},
|
||||||
|
},
|
||||||
|
'cost': 0,
|
||||||
|
'activeDays': 2,
|
||||||
|
'streak': 1,
|
||||||
|
'activity': [
|
||||||
|
{'date': '2026-11-24', 'steps': 40},
|
||||||
|
{'date': '2026-11-25', 'steps': 80},
|
||||||
|
],
|
||||||
|
'models': [
|
||||||
|
{
|
||||||
|
'model': {'providerID': 'axonhub', 'id': 'deepseek-flash'},
|
||||||
|
'steps': 100,
|
||||||
|
'tokens': {
|
||||||
|
'input': 56900000,
|
||||||
|
'output': 4000000,
|
||||||
|
'reasoning': 1400000,
|
||||||
|
'cache': {'read': 1266000000, 'write': 0},
|
||||||
|
},
|
||||||
|
'cost': 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'model': {'providerID': 'p2', 'id': 'small'},
|
||||||
|
'steps': 20,
|
||||||
|
'tokens': {
|
||||||
|
'input': 3000,
|
||||||
|
'output': 1000,
|
||||||
|
'reasoning': 500,
|
||||||
|
'cache': {'read': 500, 'write': 0},
|
||||||
|
},
|
||||||
|
'cost': 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'tools': {'mode': 'none'},
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => L10n.instance.apply(AppLanguage.en));
|
||||||
|
tearDown(() => L10n.instance.apply(AppLanguage.zh));
|
||||||
|
|
||||||
|
Future<void> pump(WidgetTester tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||||
|
const MethodChannel('openchamber/device'),
|
||||||
|
(call) async => 'Asia/Shanghai',
|
||||||
|
);
|
||||||
|
app.client = Client(Uri.parse('http://test'), transport: _FakeTransport(_report()));
|
||||||
|
await tester.pumpWidget(MaterialApp(home: StatsScreen(app: app)));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('the tokens model bar paints a share of the row', (tester) async {
|
||||||
|
await pump(tester);
|
||||||
|
|
||||||
|
await tester.scrollUntilVisible(find.text('deepseek-flash'), 300,
|
||||||
|
scrollable: find.byType(Scrollable).last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
const colors = [
|
||||||
|
Color(0xFF7C6CF6),
|
||||||
|
Color(0xFF3FB6A8),
|
||||||
|
Color(0xFFE0A03A),
|
||||||
|
Color(0xFFB06AD6),
|
||||||
|
];
|
||||||
|
double widest = 0;
|
||||||
|
for (final color in colors) {
|
||||||
|
for (final box in tester
|
||||||
|
.renderObjectList<RenderBox>(find.byWidgetPredicate(
|
||||||
|
(w) => w is ColoredBox && w.color == color))) {
|
||||||
|
// A Row of childless ColoredBoxes collapses to zero height unless the
|
||||||
|
// cross axis is stretched; that is what made the bars look empty.
|
||||||
|
expect(box.size.height, greaterThan(0),
|
||||||
|
reason: 'token segments must have height, got ${box.size}');
|
||||||
|
widest = box.size.width > widest ? box.size.width : widest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The top model has most of all tokens, so its fill is hundreds of px.
|
||||||
|
expect(widest, greaterThan(200),
|
||||||
|
reason: 'token-segment fills must paint; widest was $widest');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the metric grid shows the report', (tester) async {
|
||||||
|
await pump(tester);
|
||||||
|
expect(find.text('Prompts'), findsOneWidget);
|
||||||
|
expect(find.text('4'), findsWidgets); // prompts in the report
|
||||||
|
expect(find.text('1.1M'), findsWidgets); // 1100k tokens compact
|
||||||
|
await tester.scrollUntilVisible(find.text('deepseek-flash'), 300,
|
||||||
|
scrollable: find.byType(Scrollable).last);
|
||||||
|
expect(find.text('deepseek-flash'), findsWidgets);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/models.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('subagent chats are read-only unless the server allows prompting them',
|
||||||
|
() {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
final child = Session(id: 'child', title: '输出 hello', parentID: 'parent');
|
||||||
|
|
||||||
|
expect(app.promptReadOnlyFor(child), isTrue);
|
||||||
|
app.allowPromptingSubagentSessions = true;
|
||||||
|
expect(app.promptReadOnlyFor(child), isFalse);
|
||||||
|
|
||||||
|
// A lead's operator worker stays read-only until taken over, whatever the
|
||||||
|
// subagent setting says.
|
||||||
|
final worker = Session(
|
||||||
|
id: 'worker',
|
||||||
|
title: 'worker',
|
||||||
|
metadata: {
|
||||||
|
'openchamber': {'kind': 'operator-child', 'parentID': 'lead'},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(app.promptReadOnlyFor(worker), isTrue);
|
||||||
|
|
||||||
|
final root = Session(id: 'root', title: 'root');
|
||||||
|
expect(app.promptReadOnlyFor(root), isFalse);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/terminal.dart';
|
||||||
|
import 'package:openchamber/storage.dart';
|
||||||
|
import 'package:openchamber/terminal_state.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
ServerTerminal _term(String id,
|
||||||
|
{String status = 'running',
|
||||||
|
int createdAt = 0,
|
||||||
|
String cwd = '/repo',
|
||||||
|
String purpose = 'terminal'}) =>
|
||||||
|
ServerTerminal(
|
||||||
|
sessionId: id,
|
||||||
|
cwd: cwd,
|
||||||
|
status: status,
|
||||||
|
createdAt: createdAt,
|
||||||
|
purpose: purpose);
|
||||||
|
|
||||||
|
SavedTerminalTab _saved(String id, String label) => SavedTerminalTab(id, label);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
group('planTabs', () {
|
||||||
|
test('nothing saved and nothing on the server means one new tab', () {
|
||||||
|
final plans =
|
||||||
|
TerminalWorkspace.planTabs(saved: const [], server: const []);
|
||||||
|
expect(plans, hasLength(1));
|
||||||
|
expect(plans.single.id, isNull);
|
||||||
|
expect(plans.single.label, '终端 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saved labels stick to the sessions that are still there', () {
|
||||||
|
final plans = TerminalWorkspace.planTabs(
|
||||||
|
saved: [_saved('a', '构建'), _saved('b', '日志')],
|
||||||
|
server: [_term('a', createdAt: 1), _term('b', createdAt: 2)],
|
||||||
|
);
|
||||||
|
expect(plans.map((p) => p.id), ['a', 'b']);
|
||||||
|
expect(plans.map((p) => p.label), ['构建', '日志']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a saved session the server no longer has is dropped', () {
|
||||||
|
final plans = TerminalWorkspace.planTabs(
|
||||||
|
saved: [_saved('gone', '终端 1'), _saved('alive', '终端 2')],
|
||||||
|
server: [_term('alive', createdAt: 1)],
|
||||||
|
);
|
||||||
|
expect(plans.map((p) => p.id), ['alive']);
|
||||||
|
expect(plans.single.label, '终端 2');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sessions opened elsewhere become tabs in creation order', () {
|
||||||
|
final plans = TerminalWorkspace.planTabs(
|
||||||
|
saved: const [],
|
||||||
|
server: [
|
||||||
|
_term('new', createdAt: 30),
|
||||||
|
_term('old', createdAt: 10),
|
||||||
|
_term('mid', createdAt: 20),
|
||||||
|
_term('action', createdAt: 5, purpose: 'project-action'),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
expect(plans.map((p) => p.id), ['old', 'mid', 'new']);
|
||||||
|
expect(plans.map((p) => p.label), ['终端 1', '终端 2', '终端 3']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed listing keeps the saved tabs', () {
|
||||||
|
final plans = TerminalWorkspace.planTabs(
|
||||||
|
saved: [_saved('a', '终端 1'), _saved('b', '终端 2')],
|
||||||
|
server: null,
|
||||||
|
);
|
||||||
|
expect(plans.map((p) => p.id), ['a', 'b']);
|
||||||
|
expect(plans.map((p) => p.label), ['终端 1', '终端 2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed listing with nothing saved still opens one tab', () {
|
||||||
|
final plans = TerminalWorkspace.planTabs(saved: const [], server: null);
|
||||||
|
expect(plans, hasLength(1));
|
||||||
|
expect(plans.single.id, isNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('freeLabel', () {
|
||||||
|
test('picks the first unused number so a closed tab frees its name', () {
|
||||||
|
expect(TerminalWorkspace.freeLabel([]), '终端 1');
|
||||||
|
expect(TerminalWorkspace.freeLabel(['终端 1', '终端 3']), '终端 2');
|
||||||
|
expect(TerminalWorkspace.freeLabel(['终端 1', '终端 2']), '终端 3');
|
||||||
|
expect(TerminalWorkspace.freeLabel(['构建']), '终端 1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('terminal tabs are kept per connection and directory', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final storage = Storage();
|
||||||
|
|
||||||
|
expect(await storage.terminalTabs('srv_a', '/repo'), isNull);
|
||||||
|
|
||||||
|
await storage.saveTerminalTabs(
|
||||||
|
'srv_a',
|
||||||
|
'/repo',
|
||||||
|
const SavedTerminalTabs(
|
||||||
|
[SavedTerminalTab('a', '终端 1'), SavedTerminalTab('b', '构建')],
|
||||||
|
'b',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
final loaded = await storage.terminalTabs('srv_a', '/repo');
|
||||||
|
expect(loaded, isNotNull);
|
||||||
|
expect(loaded!.tabs.map((t) => t.id), ['a', 'b']);
|
||||||
|
expect(loaded.tabs.map((t) => t.label), ['终端 1', '构建']);
|
||||||
|
expect(loaded.activeId, 'b');
|
||||||
|
|
||||||
|
// Another server's directory is a different set.
|
||||||
|
expect(await storage.terminalTabs('srv_b', '/repo'), isNull);
|
||||||
|
|
||||||
|
await storage.clearTerminalTabs('srv_a', '/repo');
|
||||||
|
expect(await storage.terminalTabs('srv_a', '/repo'), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a 0.4.2 single-session value is read as one tab', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({
|
||||||
|
'openchamber.terminalSessions.srv_a': '{"\\/repo":"term-1"}',
|
||||||
|
});
|
||||||
|
final loaded = await Storage().terminalTabs('srv_a', '/repo');
|
||||||
|
expect(loaded, isNotNull);
|
||||||
|
expect(loaded!.tabs.single.id, 'term-1');
|
||||||
|
expect(loaded.activeId, 'term-1');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/usage_stats.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a report reads tokens, tools and models', () {
|
||||||
|
final stats = UsageStats.fromJson({
|
||||||
|
'range': {'from': 1000, 'to': 2000},
|
||||||
|
'sessions': 3,
|
||||||
|
'subagents': 5,
|
||||||
|
'prompts': 12,
|
||||||
|
'steps': 240,
|
||||||
|
'tokens': {
|
||||||
|
'input': 100,
|
||||||
|
'output': 40,
|
||||||
|
'reasoning': 10,
|
||||||
|
'cache': {'read': 900, 'write': 50},
|
||||||
|
},
|
||||||
|
'cost': 0.25,
|
||||||
|
'activeDays': 2,
|
||||||
|
'streak': 1,
|
||||||
|
'activity': [
|
||||||
|
{'date': '2026-11-25', 'steps': 40},
|
||||||
|
],
|
||||||
|
'tools': {
|
||||||
|
'mode': 'detail',
|
||||||
|
'totals': {'calls': 9, 'succeeded': 8, 'failed': 1, 'unfinished': 0},
|
||||||
|
'usage': [
|
||||||
|
{
|
||||||
|
'name': 'read',
|
||||||
|
'calls': 4,
|
||||||
|
'succeeded': 4,
|
||||||
|
'failed': 0,
|
||||||
|
'unfinished': 0,
|
||||||
|
'durationP50': 25.5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
'models': [
|
||||||
|
{
|
||||||
|
'model': {'providerID': 'p', 'id': 'm', 'variant': 'high'},
|
||||||
|
'steps': 240,
|
||||||
|
'tokens': {
|
||||||
|
'input': 100,
|
||||||
|
'output': 40,
|
||||||
|
'reasoning': 10,
|
||||||
|
'cache': {'read': 900, 'write': 50},
|
||||||
|
},
|
||||||
|
'cost': 0.25,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(stats.isEmpty, isFalse);
|
||||||
|
expect(stats.sessions, 3);
|
||||||
|
expect(stats.tokens.total, 1100);
|
||||||
|
expect(stats.tokens.produced, 50);
|
||||||
|
expect(stats.tools.hasTotals, isTrue);
|
||||||
|
expect(stats.tools.rows.single.durationP50, 25.5);
|
||||||
|
expect(stats.models.single.variant, 'high');
|
||||||
|
expect(stats.models.single.tokens.cacheRead, 900);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an empty report says so', () {
|
||||||
|
expect(const UsageStats().isEmpty, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ranges start at local midnight', () {
|
||||||
|
final now = DateTime(2026, 11, 26, 15, 30);
|
||||||
|
expect(UsageRange.day.startFrom(now),
|
||||||
|
DateTime(2026, 11, 26).millisecondsSinceEpoch);
|
||||||
|
expect(UsageRange.week.startFrom(now),
|
||||||
|
DateTime(2026, 11, 20).millisecondsSinceEpoch);
|
||||||
|
expect(UsageRange.month.startFrom(now),
|
||||||
|
DateTime(2026, 10, 28).millisecondsSinceEpoch);
|
||||||
|
expect(UsageRange.all.startFrom(now), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('activity fills quiet days and groups long ranges into weeks', () {
|
||||||
|
final from = DateTime(2026, 11, 20).millisecondsSinceEpoch;
|
||||||
|
final to = DateTime(2026, 11, 26).millisecondsSinceEpoch;
|
||||||
|
final series = buildUsageActivity(UsageStats(
|
||||||
|
from: from,
|
||||||
|
to: to,
|
||||||
|
activity: const [
|
||||||
|
UsageActivityDay('2026-11-21', 4),
|
||||||
|
UsageActivityDay('2026-11-24', 6),
|
||||||
|
],
|
||||||
|
));
|
||||||
|
expect(series.weekly, isFalse);
|
||||||
|
expect(series.bars.length, 6);
|
||||||
|
expect(series.bars.map((bar) => bar.steps), [0, 4, 0, 0, 6, 0]);
|
||||||
|
expect(series.max, 6);
|
||||||
|
|
||||||
|
// More than 92 days become weekly bars.
|
||||||
|
final long = buildUsageActivity(UsageStats(
|
||||||
|
from: DateTime(2026, 1, 1).millisecondsSinceEpoch,
|
||||||
|
to: DateTime(2026, 6, 1).millisecondsSinceEpoch,
|
||||||
|
));
|
||||||
|
expect(long.weekly, isTrue);
|
||||||
|
expect(long.bars.length, lessThanOrEqualTo(92));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the number and duration helpers read like the web client', () {
|
||||||
|
expect(usageCompactNumber(999), '999');
|
||||||
|
expect(usageCompactNumber(1234), '1.2K');
|
||||||
|
expect(usageCompactNumber(1234567), '1.2M');
|
||||||
|
expect(usageCompactNumber(123.4), '123');
|
||||||
|
expect(usagePercent(0.1234), '12.3%');
|
||||||
|
expect(usageCost(1.5), r'$1.50');
|
||||||
|
expect(usageDuration(48), '48 ms');
|
||||||
|
expect(usageDuration(1500), '1.5 s');
|
||||||
|
expect(usageDuration(65000), '1 min 5 s');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// Exercises the private relay end to end: parse a pairing link, open the E2EE
|
||||||
|
// tunnel, redeem the one-time secret, then use the client like the app does
|
||||||
|
// (HTTP, SSE, terminal WebSocket).
|
||||||
|
// dart run tool/relay_probe.dart 'openchamber://connect?v=2&p=...'
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:openchamber/api/client.dart';
|
||||||
|
import 'package:openchamber/api/pairing.dart';
|
||||||
|
import 'package:openchamber/api/relay_transport.dart';
|
||||||
|
import 'package:openchamber/api/terminal.dart';
|
||||||
|
|
||||||
|
Future<void> main(List<String> args) async {
|
||||||
|
if (args.isEmpty) {
|
||||||
|
print('usage: dart run tool/relay_probe.dart <pairing link>');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final payload = parsePairingLink(args.first);
|
||||||
|
if (payload == null) {
|
||||||
|
print('invalid pairing link');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
PairingCandidate? relay;
|
||||||
|
for (final candidate in payload.candidates) {
|
||||||
|
if (candidate.isRelay) {
|
||||||
|
relay = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (relay == null) {
|
||||||
|
print('link has no relay candidate');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
print('relay ${relay.relayUrl} server ${relay.serverId}');
|
||||||
|
final transport = RelayTransport(
|
||||||
|
relayUrl: relay.relayUrl,
|
||||||
|
serverId: relay.serverId,
|
||||||
|
hostKey: relay.hostKey!,
|
||||||
|
grant: relay.grant,
|
||||||
|
version: 'probe',
|
||||||
|
);
|
||||||
|
final client = Client(Uri.parse('http://relay.invalid'), transport: transport);
|
||||||
|
try {
|
||||||
|
final redeemed = await client.redeemPairing(
|
||||||
|
pairingId: payload.pairingId,
|
||||||
|
secret: payload.secret,
|
||||||
|
installId: 'relay-probe',
|
||||||
|
clientLabel: 'relay probe',
|
||||||
|
);
|
||||||
|
print('redeem ${redeemed.token.isEmpty ? 'no token' : 'ok'}: '
|
||||||
|
'${redeemed.response['server']}');
|
||||||
|
if (redeemed.token.isEmpty) return;
|
||||||
|
client.token = redeemed.token;
|
||||||
|
|
||||||
|
final status = await client.sessionStatus();
|
||||||
|
print('session ${status['authenticated']}');
|
||||||
|
final page = await client.listSessions(limit: 1);
|
||||||
|
print('sessions ${page.data.length}'
|
||||||
|
'${page.data.isEmpty ? '' : ' first=${page.data.first.id}'}');
|
||||||
|
|
||||||
|
final sse = <String>[];
|
||||||
|
final sub = client.streamEvents(types: const ['session.created']).listen(
|
||||||
|
(event) => sse.add('${event['type']}'),
|
||||||
|
onError: (Object error) => sse.add('error: $error'),
|
||||||
|
);
|
||||||
|
final dir = page.data.isNotEmpty
|
||||||
|
? page.data.first.directory
|
||||||
|
: Directory.current.path;
|
||||||
|
final info = await client.createTerminal(cwd: dir, cols: 80, rows: 24);
|
||||||
|
print('terminal ${info.sessionId}');
|
||||||
|
final terminal = TerminalSocket(
|
||||||
|
transport: transport,
|
||||||
|
headers: client.eventHeaders,
|
||||||
|
sessionId: info.sessionId,
|
||||||
|
onEvent: (event) =>
|
||||||
|
print('terminal event ${event.type} ${event.data.length}'),
|
||||||
|
onState: (state, {detail}) => print('terminal state $state $detail'),
|
||||||
|
);
|
||||||
|
await terminal.connect();
|
||||||
|
await Future<void>.delayed(const Duration(seconds: 3));
|
||||||
|
await sub.cancel();
|
||||||
|
await terminal.dispose();
|
||||||
|
await client.closeTerminal(info.sessionId, directory: dir);
|
||||||
|
print('sse ${sse.take(3).toList()}');
|
||||||
|
} finally {
|
||||||
|
transport.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user