Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Model and thinking level are now one control (ModelPill shows "model · effort"
and the sheet offers the level after choosing a model); Build/Plan is a
separate ModeChip. The draft page uses the same box, with its project chip
above it. 0.3.15 (315).
2026-11-21 17:47:04 +08:00
blumia 7f2f454539 fix: switching a session's model, and put the model row in the composer
- POST /api/session/:id/model takes the reference under `model`; sending it
  at the top level was rejected with "Missing key at [model]".
- The chat now shows the model/agent row above the input (revealed while
  typing or running, as dsh-Go does) instead of in the app bar; the draft
  keeps the same row, with its project chip first.
- Thinking levels: /api/model's variants become a 思考 chip and sheet; the
  choice travels as ModelRef.variant on the switch or the create, and the
  last level per model is remembered on the device.
- The model picker groups providers, adds 收藏 and 最近 (device-local), shows
  each model's context size and reasoning mark, and collapses sections.
- The `/` palette is shared by the chat and the draft (new slash_palette
  widget); the draft lists commands and skills but not the client-local
  /compact, which needs an existing session.
- 0.3.14 (314).
2026-11-21 17:03:22 +08:00
blumia fff6562cbc feat: a new-session draft and a sidebar grouped by project
- Starting a session opens NewSessionScreen instead of a title sheet: a
  project chip (GET /api/project, one row per canonical), a model/agent
  chip, attachments and the composer. Nothing is created on the server
  until the first send, which posts the session with its directory, model
  and agent and then sends that message.
- The draft lives in AppState (memory only): leaving it keeps it; the
  sidebar shows a draft row with its first line and a discard button; a
  failed create stays on the draft with its text.
- The session list groups by project (chat folders under 聊天), dates the
  rows (今天/昨天/本周早些时候/更早), pins through
  session.metadata.openchamber.pinned, archives on demand, pages with
  "载入更多", and swipes to pin/archive/delete (flutter_slidable).
- Child sessions are hidden; a parent's row shows its children's activity.
- The chat app bar follows the live session list, so the title the server
  generates from the first message appears at once.
- Attachments and the model picker move to shared widgets, used by the
  chat and the draft.
- 0.3.13 (313).
2026-11-21 14:29:52 +08:00
blumia 5a371e4faf feat: tabs own the panel header, a Termux key bar, and agent memory
- The panel's top row is now the tab group plus the close button; each tab
  keeps its own header: the files tab has the breadcrumb with new/more (or
  the name and edit/download while previewing), knowledge its search and
  refresh, the terminal its status.
- The key bar is Termux's two rows of seven: ESC / — HOME ↑ END PGUP, then
  TAB CTRL ALT ← ↓ → PGDN; the modifiers still apply to what the phone
  keyboard types.
- The panel is a dialog, so it gives the IME's height back itself
  (viewInsets.bottom). The key bar and the terminal stay above the
  keyboard, and the PTY reflows to the smaller terminal.
- Project knowledge gains the memory tab: both scopes from
  /api/agent-memory/all, absent when the server has memory switched off,
  with type, edit and delete.
- File preview editing passes minLines: null alongside expands.
- 0.3.12 (312).
2026-11-21 11:09:44 +08:00
blumia 5f95e2da97 feat: the terminal, project knowledge, and downloads that can be cancelled
- lib/api/terminal.dart: the PTY protocol (create/resize/restart/close, and
  the /api/terminal/ws binary control frames) with a reconnecting socket
  that replays the server snapshot at the size it was drawn for.
- lib/terminal_state.dart: an xterm model plus that socket, kept per
  workspace on AppState, so closing the panel or switching tabs keeps the
  shell; the app reattaches when it returns from the background.
- lib/screens/terminal_panel.dart: TerminalView, a status bar (keyboard,
  restart, clear, close) and a Termux-style key bar whose CTRL/ALT/SHIFT
  modifiers also apply to what the phone keyboard types.
- lib/screens/knowledge_panel.dart: notes, todos and plans from
  /api/project-context, searchable, with a full page for a plan's Markdown
  and its raw editor.
- Downloads stream with a progress dialog (bytes, total, percent) and a
  cancel that aborts the request; the save dialog only opens on success.
  The request asks for `accept-encoding: identity` so Content-Length exists.
- MarkdownView renders task lists as ✅/⬜ instead of material_ui's
  Checkbox, which wants a material_ui Material ancestor the app lacks.
- Dialogs own their TextEditingControllers, so closing one no longer
  trips a framework assertion in debug builds.
- 0.3.11 (311).
2026-11-21 02:49:07 +08:00
blumia 60d02083d3 feat: a transport seam, image previews, native forms, a phone drawer
- lib/api/transport.dart: TransportRequest/TransportResponse/Transport, with
  DirectTransport holding the old behaviour (HTTP CONNECT, SOCKS5/socks5h,
  self-signed and pinned certificates). Client goes through it, so a relay
  tunnel only adds an implementation.
- User rows decode the server's inline attachment data and open the shared
  image preview on tap; the local path stays the fallback.
- The agent's native forms: models from @opencode/client, the form list,
  replies and cancels, form.* events, and a dock above the composer with
  when-rules and required-field validation (a switch must be on).
- HomeScreen: the session list is the phone's left drawer and a persistent
  column from 840 px, the chat beside it; the newest session opens on start.
- 0.3.10 (310).
2026-11-21 01:16:10 +08:00
blumia 9b53338908 feat: the files sidebar, Markdown thinking, a banner that clears
- The chat's top-right menu only repeated the per-turn menu. It now opens a
  files sidebar that slides in from the right, the way the official client's
  right panel does: browse the session directory with a breadcrumb and an up
  key, filter the current directory, search its subdirectories (bounded,
  skipping .git/node_modules/build and friends), preview text/code/Markdown/
  images, edit and save text files, create files and folders, and download
  any file through the system save dialog.
- The panel's "..." menu carries the official client's "显示被 git 忽略的文件"
  toggle (the listing asks the server to respect gitignore by default) and a
  refresh. 项目知识 and 终端 have their tabs, marked as coming later.
- Thinking blocks are Markdown too (headings, lists, inline code), rendered
  with the shared MarkdownView at a smaller, quieter size.
- The reconnect banner stayed forever: the stream loop sets it when the SSE
  connection drops and nothing cleared it. Any event proves the stream is
  back (the server greets every connection with server.connected), so it now
  clears the message then.
- Markdown rendering moved to lib/widgets/markdown_view.dart, shared by
  messages, thinking, compaction summaries and file previews.
Version 0.3.9 (code 309).
2026-11-20 18:25:28 +08:00
blumia b9433c30cb feat: built-in /compact and compaction rows in the transcript
- /compact is not one of the directory's commands: OpenChamber's own
  client supplies it and runs POST /api/session/:id/compact. The palette now
  starts with that local command (压缩), so picking it compacts without the
  model seeing anything.
- A compaction message (status running/completed/failed, reason, summary,
  tokens) is part of the timeline. It now shows as the official client's
  row: a scissors glyph and "正在压缩对话" / "对话已压缩", a 显示摘要 toggle,
  and the summary as Markdown (revealed with the same height animation as
  the other folds). Failed compactions keep the error block.
- Live compaction events are subscribed: started adds the running record
  (or refreshes the tail when it names no id), delta appends the streaming
  summary, ended/failed fetch the server's settled record.
- Version 0.3.8 (code 308).
2026-11-20 12:26:15 +08:00
blumia fbadf6f858 fix: keep loaded tool output when the tail page only has its shell
List responses ask the server to elide large tool output
(`x-openchamber-part-shells: v1`): the part comes back as an empty text
plus an `openchamberContentShell` marker, and the full text is fetched
when a step is expanded. Every tail refresh (a turn starting, the app
returning) then replaced the loaded message with that shell again, so an
expanded step fell back to "无输出" — the more the session was used, the
more it looked like shell steps never had output.

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

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

- one rounded capsule holding a leading 36px attach key, a borderless
  auto-growing field, the context usage ring and a trailing 36px key that
  sends, or becomes the stop button while a turn runs (the hint says
  "still typing while generating")
- attachment chips show image thumbnails above the capsule
- the app bar shows the current model and agent as a chip that opens the
  model/agent picker, now a segmented control
- light haptic on send
2026-11-18 20:48:12 +08:00
blumia 885a27c6a9 feat: AI-output Markdown, live SSE fixes, faster builds
- render assistant Markdown with gpt_markdown (the same renderer dsh-Go
  uses): streaming, syntax-highlighted code with copy, tables, LaTeX and
  task lists, replacing flutter_markdown
- fix the event stream: Dart's Map collapsed the repeated `types` query
  into one value, so only one event type was subscribed and chats never
  updated; build the query by hand
- keep the optimistic prompt on failure out of the transcript and put the
  text back for a retry
- clamp negative turn durations
- build: Aliyun Maven mirrors, pre-seeded Gradle 9.5.0, and a complete
  NDK 28.2 install to avoid multi-hour downloads
2026-11-18 20:11:49 +08:00
blumia aee560172c feat: port the client to Flutter (0.3.0)
Replace the MyGo/Go app with a Flutter client that keeps the feature set:

- servers: saved servers, passwordless and password login, HTTP/SOCKS5
  proxy via dart:io, self-signed certificates and pinning, tokens in
  flutter_secure_storage (Keystore)
- sessions: list with live events, search, new/rename/archive/delete,
  instance sheet
- chat: streaming Markdown (flutter_markdown), reasoning and tool rows,
  image previews, context usage ring and sheet, model/agent switching,
  fork/revert, attachments (file_picker), permissions
- Android 7.0 (API 24)+, plain http:// works in release (Dart dials
  sockets directly)
- build: China mirrors for Gradle/NDK, Aliyun Maven repositories, and the
  Gradle distribution pre-seeded; release signed with the test keystore

Read-aloud is dropped as requested. Version 0.3.0.
2026-11-18 19:08:06 +08:00
blumia 24a311f234 docs: README and PLAN for the MyGo port; sign 0.3.0 release
- README describes the MyGo toolchain, the third_party fork's minSdk 24
  patch, the cleartext rationale, and the release signing
- PLAN.md records the Asuka 0.2 vs MyGo decision and the 0.3.0 status
- mygo.json signs with the test keystore and sets an adaptive icon
2026-11-18 13:24:05 +08:00
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00
219 changed files with 28717 additions and 7733 deletions

No files matched your search

+21 -4
View File
@@ -1,5 +1,22 @@
dist/
# Flutter / Dart
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
build/
/dist/
# Android
android/local.properties
android/.gradle/
android/app/.cxx/
android/captures/
# IDE
.idea/
*.iml
*.ipr
*.iws
# OS
.DS_Store
*.apk
*.aab
*.jks
+36
View File
@@ -0,0 +1,36 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "ab2912035e160d9cad6306df307576da6128ebdb"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
- platform: android
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
- platform: ios
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
- platform: linux
create_revision: ab2912035e160d9cad6306df307576da6128ebdb
base_revision: ab2912035e160d9cad6306df307576da6128ebdb
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
Whitespace-only changes.
@@ -0,0 +1,2 @@
#Wed Nov 18 12:18:36 CST 2026
gradle.version=8.14.3
Binary file not shown.
Whitespace-only changes.
+65
View File
@@ -0,0 +1,65 @@
// The shell app around a MyGo app. mygo build passes the app's ID, name,
// version, signing key, its Go library for each ABI, its manifest and its
// resources.
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
fun prop(name: String) = providers.gradleProperty(name).orNull
android {
namespace = "dev.mygo.app"
compileSdk = 36
defaultConfig {
applicationId = prop("mygoApplicationId") ?: "dev.mygo.app"
minSdk = (prop("mygoMinSdk") ?: "26").toInt()
targetSdk = 36
versionCode = (prop("mygoVersionCode") ?: "1").toInt()
versionName = prop("mygoVersionName") ?: "1.0"
manifestPlaceholders["mygoAppName"] = prop("mygoAppName") ?: "MyGo"
manifestPlaceholders["mygoIcon"] = prop("mygoIcon") ?: "@android:drawable/sym_def_app_icon"
}
signingConfigs {
create("release") {
prop("mygoKeystore")?.let {
storeFile = file(it)
storePassword = prop("mygoKeystorePassword")
keyAlias = prop("mygoKeyAlias")
keyPassword = prop("mygoKeyPassword") ?: prop("mygoKeystorePassword")
}
}
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
// Go's libraries are stripped; its stack traces need no symbols.
ndk { debugSymbolLevel = "NONE" }
signingConfig = if (prop("mygoKeystore") != null) signingConfigs.getByName("release") else signingConfigs.getByName("debug")
}
}
sourceSets {
getByName("main") {
prop("mygoJniLibs")?.let { jniLibs.srcDir(it) }
prop("mygoAssets")?.let { assets.srcDir(it) }
prop("mygoRes")?.let { res.srcDir(it) }
prop("mygoManifest")?.let { manifest.srcFile(it) }
}
}
packaging { jniLibs { useLegacyPackaging = false } }
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
kotlin { jvmToolchain(17) }
dependencies {
implementation(project(":mygo"))
// The app's native modules' Kotlin (settings.gradle.kts).
providers.gradleProperty("mygoNativeModules").orNull?.split(',')?.filter { it.isNotEmpty() }?.forEach {
implementation(project(":" + it.substringBefore('|')))
}
}
@@ -0,0 +1,23 @@
<!-- The manifest of an app without mygo build's: mygo build writes one
from the app's configuration (permissions, URL schemes). -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="${mygoAppName}"
android:icon="${mygoIcon}"
android:supportsRtl="true"
android:enableOnBackInvokedCallback="true"
android:theme="@style/Theme.MyGo">
<activity
android:name="dev.mygo.MyGoActivity"
android:exported="true"
android:launchMode="singleTask"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|fontScale|density|locale|layoutDirection"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,11 @@
<resources>
<!-- The system's own look, light or dark with the system's setting,
drawn edge to edge: the app's content goes under the bars, and
the insets tell where they are. -->
<style name="Theme.MyGo" parent="@android:style/Theme.DeviceDefault.DayNight">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
</style>
</resources>
+49
View File
@@ -0,0 +1,49 @@
plugins {
id("com.android.application") version "8.12.0" apply false
id("com.android.library") version "8.12.0" apply false
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
}
// The native modules' libraries: their build sets only their namespace and
// dependencies, and this the rest, as the host's own. They build here, as
// a module in Go's module cache is read-only.
val nativeModules = providers.gradleProperty("mygoNativeModules").orNull?.split(',')?.filter { it.isNotEmpty() }?.associate {
val parts = it.split('|')
parts[0] to parts.getOrElse(2) { "" }.split(' ').filter { d -> d.isNotEmpty() }
} ?: emptyMap()
subprojects {
val uses = nativeModules[name] ?: return@subprojects
layout.buildDirectory.set(rootProject.layout.buildDirectory.dir("native/$name"))
plugins.withId("com.android.library") {
extensions.configure<com.android.build.gradle.LibraryExtension> {
compileSdk = 36
defaultConfig {
minSdk = (providers.gradleProperty("mygoMinSdk").orNull ?: "26").toInt()
// C, which a module builds with externalNativeBuild, builds
// for the ABIs that Go does, with the NDK that builds Go.
providers.gradleProperty("mygoAbis").orNull?.let { ndk { abiFilters += it.split(',').filter { a -> a.isNotEmpty() } } }
}
providers.gradleProperty("mygoNdk").orNull?.let { dir ->
ndkPath = dir
ndkVersion = file("$dir/source.properties").readLines().firstNotNullOfOrNull {
it.substringAfter("Pkg.Revision", "").trimStart(' ', '=').takeIf { v -> v.isNotEmpty() }
} ?: ndkVersion
}
externalNativeBuild {
cmake { buildStagingDirectory = rootProject.layout.buildDirectory.dir("native/$name/cxx").get().asFile }
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
add("implementation", project(":mygo"))
uses.forEach { add("implementation", project(":$it")) }
}
}
plugins.withId("org.jetbrains.kotlin.android") {
extensions.configure<org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension> { jvmToolchain(17) }
}
}
+5
View File
@@ -0,0 +1,5 @@
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
org.gradle.caching=true
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+30
View File
@@ -0,0 +1,30 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "dev.mygo"
compileSdk = 36
defaultConfig {
minSdk = (providers.gradleProperty("mygoMinSdk").orNull ?: "26").toInt()
consumerProguardFiles("consumer-rules.pro")
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
kotlin { jvmToolchain(17) }
dependencies {
implementation("androidx.core:core-ktx:1.16.0")
implementation("androidx.activity:activity:1.10.1") // back, edge to edge
implementation("androidx.webkit:webkit:1.14.0") // the web view's document-start scripts
implementation("com.google.android.material:material:1.13.0") // bottom navigation, toolbars
// Native modules' Kotlin: suspend funs and Flows.
api("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
// What the app's plugins bring (mygo-plugin.json).
providers.gradleProperty("mygoPluginDependencies").orNull?.split(',')?.filter { it.isNotEmpty() }?.forEach { implementation(it) }
}
+7
View File
@@ -0,0 +1,7 @@
# JNI reaches these by name.
-keep class dev.mygo.Host { *; }
-keep class dev.mygo.MyGoNative { *; }
-keep class dev.mygo.Native { *; }
# Go loads a native module's Kotlin by its generated object's class.
-keep class * extends dev.mygo.NativeModule { public static ** INSTANCE; }
-keepclassmembers class * { @android.webkit.JavascriptInterface <methods>; }
@@ -0,0 +1,14 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- The files the app shares (Shell.OpenPath). -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.mygo.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/mygo_file_paths" />
</provider>
</application>
</manifest>
@@ -0,0 +1,62 @@
// The way between Go and the host. Go runs on a thread of its own and
// makes its calls (HostCalls) on the UI thread, through Host.call; events
// go to Go through MyGoNative.event.
package dev.mygo
import android.os.Looper
import android.view.Surface
/**
* A new library of the app's Go code, which mygo dev pushed to a debuggable app
* instead of building and installing it again.
*/
object DevLibrary {
var path: String? = null
fun find(c: android.content.Context) {
if (c.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0) return
val f = java.io.File(c.filesDir, "mygo-dev/libmygoapp.so")
if (f.exists()) path = f.absolutePath
}
}
/** The Go library's native methods (jni_android.c in internal/mobile). */
object MyGoNative {
init {
val dev = DevLibrary.path
if (dev != null) System.load(dev) else System.loadLibrary("mygoapp")
}
/** Starts Go's main function on a thread of its own. UI thread, once. */
@JvmStatic external fun start()
/** Sends an encoded event; for an event Go answers, waits for the answer. */
@JvmStatic external fun event(msg: ByteArray, onUI: Boolean): ByteArray?
/** Runs the calls Go made. UI thread. */
@JvmStatic external fun drain()
/** The ANativeWindow of a surface, which Go draws into; 0 for none. */
@JvmStatic external fun nativeWindow(surface: Surface): Long
@JvmStatic external fun releaseNativeWindow(window: Long)
}
/** What JNI calls of the host: Go's calls, on the UI thread. */
object Host {
@JvmStatic
fun call(msg: ByteArray): ByteArray? = dispatchCall(HostImpl, msg)
}
object Go {
private fun onUI() = Looper.myLooper() == Looper.getMainLooper()
/** Sends an event Go does not answer. */
fun send(msg: ByteArray) {
MyGoNative.event(msg, onUI())
}
/** Sends an event and returns Go's answer, null when Go gives none. */
fun ask(msg: ByteArray): WireReader? = MyGoNative.event(msg, onUI())?.let { WireReader(it) }
}
@@ -0,0 +1,895 @@
// The calls Go makes of the host (HostCalls), on the UI thread.
package dev.mygo
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.UiModeManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.MutableContextWrapper
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.provider.OpenableColumns
import android.provider.Settings
import android.system.Os
import android.text.format.DateFormat
import android.util.Log
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.WindowManager
import android.webkit.MimeTypeMap
import android.widget.FrameLayout
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File
import java.util.Calendar
import java.util.Locale
object HostImpl : HostCalls {
/** The Activity showing the app, null while none does. */
var activity: Activity? = null
private set
lateinit var app: Context
private set
/** The context of the views, which follows the Activity. */
private lateinit var context: MutableContextWrapper
lateinit var root: FrameLayout
private set
val windows = HashMap<Long, HostWindow>()
private var started = false
/** Whether Android made the Activity again after ending the process. */
var restoring = false
// What covers the screen's edges, in pixels: the system's bars and
// the cutout, and the keyboard.
var bars = androidx.core.graphics.Insets.NONE
private set
var ime = androidx.core.graphics.Insets.NONE
private set
private const val ASK_NOTIFICATIONS = 0x6d7a
private var pendingNotes = ArrayList<NotifyCall>()
/** Readies what outlives Activities, from the first thing to start the process. */
private fun prepare(c: Context) {
if (::app.isInitialized) return
run {
app = c.applicationContext
context = MutableContextWrapper(c)
root = FrameLayout(context)
ViewCompat.setOnApplyWindowInsetsListener(root) { _, insets ->
bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())
ime = insets.getInsets(WindowInsetsCompat.Type.ime())
Navigation.insetsChanged()
insets
}
root.addOnLayoutChangeListener { _, l, t, r, b, ol, ot, or, ob ->
if (r - l != or - ol || b - t != ob - ot) for (w in windows.values) w.reportSize()
}
}
}
fun attach(a: Activity) {
activity = a
prepare(a)
context.baseContext = a
(root.parent as? android.view.ViewGroup)?.removeView(root)
root.setBackgroundColor(themeColor(android.R.attr.colorBackground))
a.setContentView(root)
ViewCompat.requestApplyInsets(root)
}
fun detach(a: Activity) {
if (activity === a) activity = null
}
/** Starts Go with no window to show, for what runs in the background. */
fun startHeadless(c: Context) {
if (started) return
DevLibrary.find(c)
prepare(c)
startGo(c, null)
}
/** Starts Go once per process, with the environment a launch passes (mygo dev). */
fun startGo(a: Context, intent: Intent?) {
if (started) return
started = true
val files = a.filesDir.absolutePath
val cache = a.cacheDir.absolutePath
// Android sets none of these, which os.UserHomeDir, UserConfigDir,
// UserCacheDir and TempDir read.
app.registerReceiver(object : android.content.BroadcastReceiver() {
override fun onReceive(c: Context, i: Intent) {
// As the system's zone changes, the default of Java keeps the old one.
java.util.TimeZone.setDefault(null)
Go.send(Event.timeZoneChanged(java.util.TimeZone.getDefault().id))
}
}, android.content.IntentFilter(Intent.ACTION_TIMEZONE_CHANGED))
Os.setenv("HOME", files, true)
Os.setenv("XDG_CONFIG_HOME", files, true)
Os.setenv("XDG_CACHE_HOME", cache, true)
Os.setenv("TMPDIR", cache, true)
// Only mygo dev's, in a debug build: the Activity is exported, and any
// app could otherwise set a proxy for this one's traffic.
val debuggable = a.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
if (debuggable) {
intent?.getStringExtra("mygo.env")?.split('\n')?.forEach { line ->
val i = line.indexOf('=')
if (i > 0) Os.setenv(line.substring(0, i), line.substring(i + 1), true)
}
}
registerPlugins()
// The first launch of a version copies the app's resources, which may
// be many: off the UI thread, which Android watches. Events sent
// meanwhile wait for the backend.
val ctx = a.applicationContext
Thread {
val dir = Resources.extract(ctx)
// Not by a view's post: with no Activity, the root is in no window
// and would hold it until one comes.
android.os.Handler(android.os.Looper.getMainLooper()).post {
Os.setenv("MYGO_RESOURCES", dir, true)
MyGoNative.start()
}
}.start()
}
fun themeColor(attr: Int): Int {
val a = (activity ?: context).obtainStyledAttributes(intArrayOf(attr))
val c = a.getColor(0, Color.WHITE)
a.recycle()
return c
}
val density get() = app.resources.displayMetrics.density
/** The window in front: the visible window highest on screen. */
fun front(): HostWindow? = windows.values.filter { it.view.isShown }.maxByOrNull { w ->
var depth = 0
var v: View? = w.view
while (v != null && v !== root) {
val parent = v.parent as? android.view.ViewGroup ?: break
depth = depth * 64 + parent.indexOfChild(v)
v = parent
}
depth
}
/** Hears the system's back, while something in the app takes it. */
var backCallback: androidx.activity.OnBackPressedCallback? = null
/** The system's back goes to the app, or leaves it, as predictive back shows beforehand. */
fun updateBack() {
val f = front()
backCallback?.isEnabled = Navigation.canPop() || (f as? SurfaceWindow)?.backAvailable == true || (f as? WebWindow)?.web?.canGoBack() == true
}
/** Android's back: the window in front's page goes back, or the app takes it. */
fun back(): Boolean {
if (Navigation.back()) return true
val w = front() ?: return false
val r = Go.ask(Event.backPressed(w.id)) ?: return false
return BackPressedReply(r).handled
}
override fun timeZone(): TimeZoneReply {
val r = TimeZoneReply()
r.id = java.util.TimeZone.getDefault().id
return r
}
/** Whether the app has something on screen, which the splash waits for. */
@Volatile var drew = false
override fun firstFrame(c: FirstFrameCall) {
drew = true
}
override fun appInfo(): AppInfoReply {
val r = AppInfoReply()
val pm = app.packageManager
val info = pm.getPackageInfo(app.packageName, 0)
r.name = app.applicationInfo.loadLabel(pm).toString()
r.version = info.versionName ?: ""
r.identifier = app.packageName
r.filesDir = app.filesDir.absolutePath
r.cacheDir = app.cacheDir.absolutePath
r.tempDir = app.cacheDir.absolutePath
r.documentsDir = (app.getExternalFilesDir(null) ?: app.filesDir).absolutePath
r.resourcesDir = Resources.dir(app).absolutePath
val locales = app.resources.configuration.locales
r.languages = (0 until locales.size()).map { locales[it].toLanguageTag() }
val format = Locale.getDefault(Locale.Category.FORMAT)
r.regionLocale = format.toLanguageTag()
r.firstWeekday = (Calendar.getInstance(format).firstDayOfWeek - 1).toLong()
r.hourCycle = if (DateFormat.is24HourFormat(app)) 24L else 12L
r.system = "Android"
r.systemVersion = Build.VERSION.RELEASE
r.model = Build.MODEL
r.restoring = restoring
r.background = activity == null // the system started it for a task
return r
}
override fun theme(): ThemeReply {
val r = ThemeReply()
val c = (activity ?: app).resources.configuration
r.dark = c.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
val accent = if (Build.VERSION.SDK_INT >= 31) app.getColor(android.R.color.system_accent1_600) else themeColor(android.R.attr.colorAccent)
r.accent = argbToRGBA(accent)
r.reduceMotion = Settings.Global.getFloat(app.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f
if (Build.VERSION.SDK_INT >= 34) {
r.increaseContrast = (app.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager).contrast > 0.5f
}
r.textScale = c.fontScale.toDouble()
return r
}
override fun setAppearance(c: SetAppearanceCall) {
if (Build.VERSION.SDK_INT < 31) return
val ui = app.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
ui.setApplicationNightMode(
when (c.source) {
"dark" -> UiModeManager.MODE_NIGHT_YES
"light" -> UiModeManager.MODE_NIGHT_NO
else -> UiModeManager.MODE_NIGHT_AUTO
}
)
}
override fun screen(): ScreenReply {
val r = ScreenReply()
val m = app.resources.displayMetrics
r.width = m.widthPixels / m.density.toDouble()
r.height = m.heightPixels / m.density.toDouble()
r.scale = m.density.toDouble()
return r
}
override fun log(c: LogCall) {
Log.println(if (c.error) Log.ERROR else Log.INFO, "mygo", c.line)
}
// Windows.
override fun createWindow(c: CreateWindowCall): CreateWindowReply {
val r = CreateWindowReply()
try {
val w = when {
c.surface -> SurfaceWindow(context, c.id)
c.viewType.isNotEmpty() -> PluginViewWindow(context, c.id, PluginHost.makeView(c.viewType, context, c.id, c.viewArgs)
?: throw IllegalArgumentException("no view ${c.viewType} in this app"))
else -> WebWindow(context, c)
}
if (c.hasBackground) {
w.fill = rgbaToARGB(c.background)
w.setBackground(w.fill)
}
windows[c.id] = w
if (c.parent != 0L) surface(c.parent)?.hold(w)
} catch (e: Throwable) {
r.error = "mygo: ${e.message ?: e.toString()}"
}
return r
}
override fun placeViews(c: PlaceViewsCall) { surface(c.id)?.placeViews(c.places) }
override fun showWindow(c: ShowWindowCall) {
val w = windows[c.id] ?: return
Navigation.show(w)
w.insetsChanged()
updateBack()
}
override fun hideWindow(c: HideWindowCall) {
val w = windows[c.id] ?: return
Navigation.hide(w)
updateBack()
}
override fun closeWindow(c: CloseWindowCall) {
val w = windows.remove(c.id) ?: return
val holder = w.holder
if (holder != null) {
holder.release(w)
w.close()
return
}
Navigation.hide(w)
Navigation.forget(w)
w.close()
}
override fun setTitle(c: SetTitleCall) { windows[c.id]?.let { Navigation.setTitle(it, c.title) } }
override fun createTabs(c: CreateTabsCall) = Navigation.createTabs(c.id, context)
override fun addTab(c: AddTabCall) { windows[c.window]?.let { Navigation.addTab(c.id, it, c.title, c.icon) } }
override fun showTabs(c: ShowTabsCall) = Navigation.showTabs(c.id)
override fun selectTab(c: SelectTabCall) { Navigation.tabs[c.id]?.select(c.index.toInt()) }
override fun setTabBadge(c: SetTabBadgeCall) = Navigation.setBadge(c.id, c.index.toInt(), c.badge)
override fun closeTabs(c: CloseTabsCall) = Navigation.closeTabs(c.id)
override fun pushWindow(c: PushWindowCall) {
val p = windows[c.parent] ?: return
val w = windows[c.child] ?: return
Navigation.push(w, p, c.title, c.animated)
updateBack()
}
override fun setStack(c: SetStackCall): SetStackReply {
windows[c.id]?.let { Navigation.setStack(it, c.titles) }
return SetStackReply()
}
override fun stackShown(c: StackShownCall) {}
override fun popWindow(c: PopWindowCall) {
windows[c.id]?.let { Navigation.pop(it, c.animated) }
updateBack()
}
override fun setBackground(c: SetBackgroundCall) {
val w = windows[c.id] ?: return
val argb = rgbaToARGB(c.color)
w.fill = argb
w.setBackground(argb)
Navigation.backgroundChanged(w)
}
override fun focus(c: FocusCall) {
windows[c.id]?.view?.requestFocus()
}
// Pages.
private fun web(id: Long) = windows[id] as? WebWindow
override fun loadURL(c: LoadURLCall) { web(c.id)?.load(c.url) }
override fun loadHTML(c: LoadHTMLCall) { web(c.id)?.loadHTML(c.html, c.baseURL) }
override fun reload(c: ReloadCall) {
val w = web(c.id) ?: return
if (c.ignoreCache) w.web.clearCache(false)
w.web.reload()
}
override fun stopLoading(c: StopLoadingCall) { web(c.id)?.web?.stopLoading() }
override fun goBack(c: GoBackCall) { web(c.id)?.web?.goBack() }
override fun goForward(c: GoForwardCall) { web(c.id)?.web?.goForward() }
override fun eval(c: EvalCall) { web(c.id)?.web?.evaluateJavascript(c.js, null) }
override fun callAsync(c: CallAsyncCall) {
val w = web(c.id)
if (w == null) {
Go.send(Event.asyncResult(c.req, "", "mygo: the window is closed"))
return
}
w.callAsync(c.req, c.body)
}
override fun setZoom(c: SetZoomCall) { web(c.id)?.web?.settings?.textZoom = (c.factor * 100).toInt() }
override fun setUserAgent(c: SetUserAgentCall) { web(c.id)?.setUserAgent(c.userAgent) }
override fun setUserScripts(c: SetUserScriptsCall) { web(c.id)?.setScripts(c.scripts, c.scriptFlags) }
override fun capturePage(c: CapturePageCall) {
val w = web(c.id)
if (w == null) {
Go.send(Event.captured(c.req, ByteArray(0), "mygo: the window is closed"))
return
}
w.capture(c.req)
}
override fun userAgent(c: UserAgentCall): UserAgentReply {
val r = UserAgentReply()
r.userAgent = web(c.id)?.web?.settings?.userAgentString ?: ""
return r
}
override fun schemeRespond(c: SchemeRespondCall) = Schemes.respond(c)
override fun schemeData(c: SchemeDataCall) = Schemes.data(c.req, c.data)
override fun schemeFinish(c: SchemeFinishCall) = Schemes.finish(c.req, null)
override fun schemeFail(c: SchemeFailCall) = Schemes.finish(c.req, c.message)
// Dialogs.
override fun messageBox(c: MessageBoxCall) {
val a = activity ?: run {
Go.send(Event.messageBoxResult(c.req, c.cancelID))
return
}
val title = if (c.title.isEmpty()) c.message else c.title
var message = if (c.title.isEmpty()) c.detail else c.message
if (c.title.isNotEmpty() && c.detail.isNotEmpty()) message += "\n\n" + c.detail
var answered = false
fun answer(i: Long) {
if (!answered) {
answered = true
Go.send(Event.messageBoxResult(c.req, i))
}
}
val b = AlertDialog.Builder(a).setTitle(title)
if (message.isNotEmpty()) b.setMessage(message)
// Android's dialogs take three buttons: the default one positive,
// the cancel one negative, another neutral; more make a list.
val buttons = c.buttons
if (buttons.size <= 3) {
val order = buttons.indices.sortedBy { if (it.toLong() == c.defaultID) 0 else if (it.toLong() == c.cancelID) 2 else 1 }
order.forEachIndexed { slot, i ->
val l = { _: android.content.DialogInterface, _: Int -> answer(i.toLong()) }
when {
slot == 0 -> b.setPositiveButton(buttons[i], l)
i.toLong() == c.cancelID || slot == 2 -> b.setNegativeButton(buttons[i], l)
else -> b.setNeutralButton(buttons[i], l)
}
}
} else {
b.setItems(buttons.toTypedArray()) { _, i -> answer(i.toLong()) }
}
b.setOnCancelListener { answer(c.cancelID) }
b.show()
}
override fun openFiles(c: OpenFilesCall) {
val a = activity ?: run {
Go.send(Event.filesResult(c.req, emptyList(), ""))
return
}
val code = nextResultCode()
picks[code] = c.req
val intent = if (c.directories) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
} else {
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
val types = c.extensions.mapNotNull { MimeTypeMap.getSingleton().getMimeTypeFromExtension(it.lowercase()) }.distinct()
type = if (types.size == 1) types[0] else "*/*"
if (types.size > 1) putExtra(Intent.EXTRA_MIME_TYPES, types.toTypedArray())
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, c.multiple)
}
}
@Suppress("DEPRECATION")
a.startActivityForResult(intent, code)
}
fun activityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (PluginHost.activityResult(requestCode, resultCode, data)) return
saves.remove(requestCode)?.let { (req, from) ->
val uri = data?.data
if (resultCode != Activity.RESULT_OK || uri == null) {
Go.send(Event.filesResult(req, emptyList(), ""))
return
}
Thread {
try {
app.contentResolver.openOutputStream(uri)!!.use { out -> File(from).inputStream().use { it.copyTo(out) } }
Go.send(Event.filesResult(req, listOf(uri.toString()), ""))
} catch (e: Exception) {
Go.send(Event.filesResult(req, emptyList(), e.toString()))
}
}.start()
return
}
val req = picks.remove(requestCode)
if (req != null) {
if (resultCode != Activity.RESULT_OK || data == null) {
Go.send(Event.filesResult(req, emptyList(), ""))
return
}
val uris = ArrayList<Uri>()
data.clipData?.let { clip -> for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri) }
if (uris.isEmpty()) data.data?.let { uris.add(it) }
// Copies the app can read by path: phones give apps no paths
// of other apps' documents.
Thread {
try {
val dir = File(app.cacheDir, "picked/${System.nanoTime()}").apply { mkdirs() }
val paths = uris.map { copyToFile(it, dir).absolutePath }
Go.send(Event.filesResult(req, paths, ""))
} catch (e: Exception) {
Go.send(Event.filesResult(req, emptyList(), e.toString()))
}
}.start()
} else {
WebWindow.activityResult(requestCode, resultCode, data)
}
}
fun copyToFile(uri: Uri, dir: File): File {
var name = "file"
app.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
if (it.moveToFirst()) name = it.getString(0) ?: name
}
val f = File(dir, name.replace('/', '_'))
app.contentResolver.openInputStream(uri)!!.use { input -> f.outputStream().use { input.copyTo(it) } }
return f
}
override fun shareFile(c: ShareFileCall) {
val a = activity ?: return
val f = File(c.path)
val uri = FileProvider.getUriForFile(app, app.packageName + ".mygo.files", f)
val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.extension.lowercase()) ?: "application/octet-stream"
val send = Intent(Intent.ACTION_SEND).setType(mime).putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
a.startActivity(Intent.createChooser(send, null))
}
// The system.
private val clipboard get() = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
override fun clipboardText(): ClipboardTextReply {
val r = ClipboardTextReply()
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount > 0) {
r.text = clip.getItemAt(0).coerceToText(app).toString()
r.ok = true
}
return r
}
override fun setClipboardText(c: SetClipboardTextCall) {
clipboard.setPrimaryClip(ClipData.newPlainText(null, c.text))
}
override fun openURL(c: OpenURLCall): OpenURLReply {
val r = OpenURLReply()
try {
val i = Intent(Intent.ACTION_VIEW, Uri.parse(c.url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
(activity ?: app).startActivity(i)
r.ok = true
} catch (e: Exception) {
r.ok = false
}
return r
}
override fun secretGet(c: SecretGetCall): SecretGetReply = Secrets.get(app, c)
override fun secretSet(c: SecretSetCall): SecretSetReply = Secrets.set(app, c)
override fun secretDelete(c: SecretDeleteCall): SecretDeleteReply = Secrets.delete(app, c)
override fun notify(c: NotifyCall) {
val a = activity
if (Build.VERSION.SDK_INT >= 33 && app.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
if (a == null) {
Go.send(Event.notifyDone(c.req, "mygo: notifications are not allowed"))
return
}
pendingNotes.add(c)
if (pendingNotes.size == 1) a.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), ASK_NOTIFICATIONS)
return
}
post(c)
}
fun permissionsResult(requestCode: Int, results: IntArray) {
if (PluginHost.permissionsResult(requestCode, results)) return
if (requestCode == ASK_NOTIFICATIONS) {
val granted = results.isNotEmpty() && results[0] == PackageManager.PERMISSION_GRANTED
val notes = pendingNotes
pendingNotes = ArrayList()
for (c in notes) if (granted) post(c) else Go.send(Event.notifyDone(c.req, "mygo: notifications are not allowed"))
} else {
WebWindow.permissionsResult(requestCode, results)
}
}
private fun post(c: NotifyCall) {
if (Build.VERSION.SDK_INT < 26) { // NotificationChannel needs API 26
Go.send(Event.notifyDone(c.req, "mygo: notifications need Android 8.0"))
return
}
val nm = app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = if (c.silent) "mygo.silent" else "mygo"
if (nm.getNotificationChannel(channel) == null) {
val ch = NotificationChannel(channel, appInfo().name, if (c.silent) NotificationManager.IMPORTANCE_LOW else NotificationManager.IMPORTANCE_DEFAULT)
nm.createNotificationChannel(ch)
}
val id = c.notificationID.ifEmpty { System.nanoTime().toString() }
val open = Intent(app, MyGoActivity::class.java).putExtra("mygo.notification", id).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pi = PendingIntent.getActivity(app, id.hashCode(), open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val b = android.app.Notification.Builder(app, channel)
.setSmallIcon(app.applicationInfo.icon)
.setContentTitle(c.title)
.setContentText(c.body)
.setContentIntent(pi)
.setAutoCancel(true)
if (c.subtitle.isNotEmpty()) b.setSubText(c.subtitle)
if (c.group.isNotEmpty()) b.setGroup(c.group)
nm.notify(id, 0, b.build())
Go.send(Event.notifyDone(c.req, ""))
}
override fun removeNotification(c: RemoveNotificationCall) {
(app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(c.notificationID, 0)
}
override fun removeAllNotifications() {
(app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancelAll()
}
override fun keepAwake(c: KeepAwakeCall) {
val w = activity?.window ?: return
if (c.on) w.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else w.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
// Network and power.
private val connectivity get() = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private var watchingNetwork = false
private fun networkReply(): NetworkStatusReply {
val r = NetworkStatusReply()
val caps = connectivity.getNetworkCapabilities(connectivity.activeNetwork)
r.online = caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
r.metered = connectivity.isActiveNetworkMetered
return r
}
override fun networkStatus(): NetworkStatusReply = networkReply()
override fun watchNetwork() {
if (watchingNetwork) return
watchingNetwork = true
val send = {
val r = networkReply()
Go.send(Event.networkChanged(r.online, r.metered))
}
connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(n: Network) = send()
override fun onLost(n: Network) = send()
override fun onCapabilitiesChanged(n: Network, caps: NetworkCapabilities) = send()
})
}
override fun battery(): BatteryReply {
val r = BatteryReply()
val bm = app.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
r.level = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) / 100.0
r.charging = bm.isCharging
r.lowPower = (app.getSystemService(Context.POWER_SERVICE) as PowerManager).isPowerSaveMode
return r
}
// The system's bars and the screen.
private var barStyle = "auto"
private var barsHidden = false
private var orientationAsked = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
override fun setSystemBars(c: SetSystemBarsCall) {
barStyle = c.style
barsHidden = c.hidden
applyBars()
}
/** Applies what the app asked of the system's bars, to the Activity showing it. */
fun applyBars() {
val a = activity ?: return
val ctl = WindowCompat.getInsetsController(a.window, a.window.decorView)
val darkMode = a.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
val darkIcons = when (barStyle) {
"dark" -> true
"light" -> false
else -> !darkMode
}
ctl.isAppearanceLightStatusBars = darkIcons
ctl.isAppearanceLightNavigationBars = darkIcons
ctl.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
if (barsHidden) ctl.hide(WindowInsetsCompat.Type.systemBars()) else ctl.show(WindowInsetsCompat.Type.systemBars())
a.requestedOrientation = orientationAsked
}
override fun setOrientations(c: SetOrientationsCall) {
val m = c.mask.toInt()
val portrait = m and 3 != 0
val landscape = m and 12 != 0
orientationAsked = when {
m == 0 -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
portrait && landscape -> ActivityInfo.SCREEN_ORIENTATION_FULL_USER
m == 1 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
m == 2 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
m == 3 -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
m == 4 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
m == 8 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
landscape -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
activity?.requestedOrientation = orientationAsked
}
override fun share(c: ShareCall) {
val a = activity ?: run {
Go.send(Event.shareResult(c.req, "mygo: no window to share from"))
return
}
val text = listOf(c.text, c.url).filter { it.isNotEmpty() }.joinToString("\n")
val uris = ArrayList(c.paths.map { FileProvider.getUriForFile(app, app.packageName + ".mygo.files", File(it)) })
val send = when {
uris.size > 1 -> Intent(Intent.ACTION_SEND_MULTIPLE).setType("*/*").putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
uris.size == 1 -> {
val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(File(c.paths[0]).extension.lowercase()) ?: "application/octet-stream"
Intent(Intent.ACTION_SEND).setType(mime).putExtra(Intent.EXTRA_STREAM, uris[0])
}
else -> Intent(Intent.ACTION_SEND).setType("text/plain")
}
if (uris.isNotEmpty()) {
send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
send.clipData = ClipData.newRawUri(null, uris[0]).also { d -> uris.drop(1).forEach { d.addItem(ClipData.Item(it)) } }
}
if (text.isNotEmpty()) send.putExtra(Intent.EXTRA_TEXT, text)
try {
a.startActivity(Intent.createChooser(send, null))
Go.send(Event.shareResult(c.req, ""))
} catch (e: Exception) {
Go.send(Event.shareResult(c.req, e.toString()))
}
}
// What the pickers on screen answer, by their request codes: one tapped
// twice opens two, each answering its own.
private val picks = HashMap<Int, Long>()
private val saves = HashMap<Int, Pair<Long, String>>()
private var lastResultCode = 0
private fun nextResultCode(): Int {
lastResultCode = (lastResultCode + 1) and 0xff
return 0x6e00 + lastResultCode
}
override fun saveFile(c: SaveFileCall) {
val a = activity ?: run {
Go.send(Event.filesResult(c.req, emptyList(), "mygo: no window to save from"))
return
}
val code = nextResultCode()
saves[code] = Pair(c.req, c.path)
val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(File(c.name).extension.lowercase()) ?: "application/octet-stream"
val i = Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(mime).putExtra(Intent.EXTRA_TITLE, c.name)
@Suppress("DEPRECATION")
a.startActivityForResult(i, code)
}
override fun clipboardImage(): ClipboardImageReply {
val r = ClipboardImageReply()
val clip = clipboard.primaryClip ?: return r
if (clip.itemCount == 0) return r
val uri = clip.getItemAt(0).uri ?: return r
val mime = app.contentResolver.getType(uri) ?: return r
if (!mime.startsWith("image/")) return r
try {
val bmp = app.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) } ?: return r
val out = java.io.ByteArrayOutputStream()
bmp.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)
r.png = out.toByteArray()
} catch (_: Exception) {
}
return r
}
override fun setClipboardImage(c: SetClipboardImageCall) {
try {
val dir = File(app.cacheDir, "clipboard").apply { mkdirs() }
val f = File(dir, "image.png")
f.writeBytes(c.png)
val uri = FileProvider.getUriForFile(app, app.packageName + ".mygo.files", f)
clipboard.setPrimaryClip(ClipData.newUri(app.contentResolver, "image", uri))
} catch (_: Exception) {
}
}
/** A menu shown by the app, as a context menu, at a point of the window. */
override fun popupMenu(c: PopupMenuCall) {
val w = surface(c.id)
val a = activity
val host = w?.view ?: front()?.view
if (a == null || host == null) {
Go.send(Event.menuPicked(c.req, 0))
return
}
// Where it shows: a view at the point, gone as the menu goes.
val anchor = View(a)
val d = density
val lp = FrameLayout.LayoutParams(1, 1)
lp.leftMargin = (c.x * d).toInt()
lp.topMargin = (c.y * d).toInt()
root.addView(anchor, lp)
val menu = android.widget.PopupMenu(a, anchor)
val r = WireReader(c.items)
var group = 0
var order = 0
while (!r.done()) {
val id = r.int()
val label = r.string()
val enabled = r.bool()
val checked = r.bool()
if (id == 0L) {
group++
continue
}
val item = menu.menu.add(group, id.toInt(), order++, label)
item.isEnabled = enabled
if (checked) {
item.isCheckable = true
item.isChecked = true
}
}
var picked = 0L
menu.setOnMenuItemClickListener {
picked = it.itemId.toLong()
true
}
menu.setOnDismissListener {
root.removeView(anchor)
Go.send(Event.menuPicked(c.req, picked))
}
root.post { menu.show() }
}
override fun setBarItems(c: SetBarItemsCall) {
windows[c.id]?.let { Navigation.setBarItems(it, c) }
}
override fun pluginCall(c: PluginCallCall) = PluginHost.call(c)
// Sound, called on the audio's thread.
override fun audioOpen(c: AudioOpenCall): AudioOpenReply = Sound.open(c)
override fun audioWrite(c: AudioWriteCall): AudioWriteReply = Sound.write(c)
override fun audioClose(): AudioCloseReply {
Sound.close()
return AudioCloseReply()
}
override fun haptic(c: HapticCall) {
val v: View = front()?.view ?: root
val k = when (c.kind) {
"selection" -> HapticFeedbackConstants.CLOCK_TICK
"light" -> HapticFeedbackConstants.KEYBOARD_TAP
"heavy" -> HapticFeedbackConstants.LONG_PRESS
"medium" -> HapticFeedbackConstants.CONTEXT_CLICK
"success" -> if (Build.VERSION.SDK_INT >= 30) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.VIRTUAL_KEY
"warning", "error" -> if (Build.VERSION.SDK_INT >= 30) HapticFeedbackConstants.REJECT else HapticFeedbackConstants.LONG_PRESS
else -> HapticFeedbackConstants.VIRTUAL_KEY
}
v.performHapticFeedback(k)
}
// Native UI.
private fun surface(id: Long) = windows[id] as? SurfaceWindow
override fun requestFrame(c: RequestFrameCall) { surface(c.id)?.requestFrame() }
override fun setTextInput(c: SetTextInputCall) { surface(c.id)?.setTextInput(c) }
override fun setCursor(c: SetCursorCall) { surface(c.id)?.setCursor(c.cursor) }
override fun accessibilityChanged(c: AccessibilityChangedCall) { surface(c.id)?.accessibilityChanged(c.focus) }
override fun announce(c: AnnounceCall) { (front()?.view ?: root).announceForAccessibility(c.text) }
override fun showMenu(c: ShowMenuCall) { surface(c.id)?.showMenu(c) }
override fun setBackAvailable(c: SetBackAvailableCall) {
surface(c.id)?.backAvailable = c.on
updateBack()
}
override fun showMagnifier(c: ShowMagnifierCall) { surface(c.id)?.showMagnifier(c) }
override fun hideMagnifier(c: HideMagnifierCall) { surface(c.id)?.hideMagnifier() }
override fun textMetrics(c: TextMetricsCall): TextMetricsReply = Text.metrics(c)
override fun measureText(c: MeasureTextCall): MeasureTextReply = Text.measure(c)
override fun textAdvances(c: TextAdvancesCall): TextAdvancesReply = Text.advances(c)
override fun drawText(c: DrawTextCall): DrawTextReply = Text.draw(c)
override fun registerFont(c: RegisterFontCall): RegisterFontReply = Text.register(c)
}
/** 0xRRGGBBAA, as Go writes colors, to Android's 0xAARRGGBB. */
fun rgbaToARGB(v: Long): Int = (((v and 0xff) shl 24) or ((v ushr 8) and 0xffffff)).toInt()
fun argbToRGBA(c: Int): Long = ((c.toLong() and 0xffffff) shl 8) or ((c.toLong() ushr 24) and 0xff)
@@ -0,0 +1,66 @@
package dev.mygo
import android.content.Context
import android.view.View
/**
* A window of the app: a view filling the screen, which shows a page or
* native UI.
*/
abstract class HostWindow(val context: Context, val id: Long) {
abstract val view: View
private var last: DoubleArray? = null
/** The color the window's content fills it with, 0 while unknown. */
var fill = 0
/** The surface showing this window under it, as a web view in native UI. */
var holder: SurfaceWindow? = null
/**
* What covers the window, in pixels: the system's bars and the cutout
* where they cover it, wherever it is on the screen (under a toolbar,
* above a bar of tabs), and the keyboard: top, left, bottom, right,
* keyboard.
*/
fun covered(): IntArray {
val root = HostImpl.root
// Where layout puts it, without the translation of a page sliding
// in, which ends where layout put it.
var x = 0
var y = 0
var v: View? = view
while (v != null && v !== root) {
x += v.left
y += v.top
v = v.parent as? View
}
val w = if (view.width > 0) view.width else root.width
val h = if (view.height > 0) view.height else root.height
val bars = HostImpl.bars
val below = root.height - (y + h)
val right = root.width - (x + w)
return intArrayOf(
maxOf(0, bars.top - y), maxOf(0, bars.left - x), maxOf(0, bars.bottom - below), maxOf(0, bars.right - right),
maxOf(0, HostImpl.ime.bottom - below),
)
}
/** Tells Go the window's size and what covers it, when they changed. */
fun reportSize() {
val root = HostImpl.root
if (root.width == 0) return
val d = HostImpl.density.toDouble()
val w = if (view.width > 0) view.width else root.width
val h = if (view.height > 0) view.height else root.height
val c = if (holder != null) IntArray(5) else covered()
val size = doubleArrayOf(w / d, h / d, d, c[0] / d, c[1] / d, c[2] / d, c[3] / d, c[4] / d)
if (last?.contentEquals(size) == true) return
last = size
Go.send(Event.resized(id, size[0], size[1], size[2], size[3], size[4], size[5], size[6], size[7]))
}
/** The insets changed: lays the window out again and tells Go. */
open fun insetsChanged() = reportSize()
abstract fun setBackground(argb: Int)
open fun close() {}
}
@@ -0,0 +1,150 @@
package dev.mygo
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.BackEventCompat
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.core.view.WindowCompat
/**
* The app's one Activity. Go and the app's windows live in the process,
* not the Activity: an Activity Android makes again takes them over.
*/
class MyGoActivity : ComponentActivity() {
private var lastConfig: Configuration? = null
override fun onCreate(savedInstanceState: Bundle?) {
DevLibrary.find(this)
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
lastConfig = Configuration(resources.configuration)
HostImpl.restoring = HostImpl.restoring || savedInstanceState != null
HostImpl.attach(this)
HostImpl.applyBars()
holdSplash()
val back = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
// Back the app does not take leaves it running, as the
// system's launcher does with apps it goes back from.
if (!HostImpl.back()) moveTaskToBack(true)
}
// Predictive back: the page follows the gesture.
private fun gesture(phase: String, progress: Double) {
(HostImpl.front() as? SurfaceWindow)?.let { Go.send(Event.backGesture(it.id, phase, progress)) }
}
override fun handleOnBackStarted(e: BackEventCompat) = gesture("started", 0.0)
override fun handleOnBackProgressed(e: BackEventCompat) = gesture("progress", e.progress.toDouble())
override fun handleOnBackCancelled() = gesture("cancelled", 0.0)
}
onBackPressedDispatcher.addCallback(this, back)
HostImpl.backCallback = back
HostImpl.updateBack()
HostImpl.startGo(this, intent)
openIntent(intent)
}
/**
* The system's splash stays until the window first draws: holding that back
* until the app has drawn leaves no moment of an empty surface, black on a
* cold start. What shows no first frame goes on after a while.
*/
private fun holdSplash() {
val content = findViewById<android.view.View>(android.R.id.content)
val until = android.os.SystemClock.uptimeMillis() + 4000
content.viewTreeObserver.addOnPreDrawListener(object : android.view.ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (!HostImpl.drew && android.os.SystemClock.uptimeMillis() < until) return false
content.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
})
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
openIntent(intent)
}
private fun openIntent(intent: Intent?) {
intent ?: return
PluginHost.onIntent?.invoke(intent)
// A notification tapped: once, as the Activity is made again with
// the same Intent after Android ends the process.
intent.getStringExtra("mygo.notification")?.let {
intent.removeExtra("mygo.notification")
Go.send(Event.notificationClicked(it))
}
val data = intent.data ?: return
if (intent.action == Intent.ACTION_VIEW) Go.send(Event.openURLs(listOf(data.toString())))
}
override fun onResume() {
super.onResume()
Go.ask(Event.background(false))
Go.send(Event.active(true))
}
override fun onPause() {
Go.send(Event.active(false))
super.onPause()
}
override fun onStop() {
Go.ask(Event.background(true))
super.onStop()
}
override fun onConfigurationChanged(c: Configuration) {
super.onConfigurationChanged(c)
val old = lastConfig
lastConfig = Configuration(c)
if (old == null) return
val diff = old.diff(c)
if (diff and (ActivityInfoChanges.UI_MODE or ActivityInfoChanges.FONT_SCALE) != 0) {
HostImpl.applyBars()
Go.send(Event.themeChanged())
}
if (diff and ActivityInfoChanges.LOCALE != 0) Go.send(Event.localeChanged())
}
override fun onLowMemory() {
super.onLowMemory()
Go.send(Event.memoryWarning())
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
// Running low, or next to be ended in the background.
@Suppress("DEPRECATION")
if (level == TRIM_MEMORY_RUNNING_LOW || level == TRIM_MEMORY_RUNNING_CRITICAL || level >= TRIM_MEMORY_MODERATE) {
Go.send(Event.memoryWarning())
}
}
override fun onDestroy() {
HostImpl.detach(this)
super.onDestroy()
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
HostImpl.activityResult(requestCode, resultCode, data)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, results: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, results)
HostImpl.permissionsResult(requestCode, results)
}
}
/** ActivityInfo's configuration change bits, as Configuration.diff gives them. */
private object ActivityInfoChanges {
const val LOCALE = android.content.pm.ActivityInfo.CONFIG_LOCALE
const val UI_MODE = android.content.pm.ActivityInfo.CONFIG_UI_MODE
const val FONT_SCALE = android.content.pm.ActivityInfo.CONFIG_FONT_SCALE
}
@@ -0,0 +1,565 @@
// Native modules on Android: Go interfaces implemented in Kotlin (see
// docs/native-modules.md). Go calls the module's generated object
// (MygoModule, a NativeModule) through JNI (internal/mobile's
// jni_android.c), on the calling goroutine's thread, as it calls a Swift
// library's functions elsewhere; the module tells Go what happens later
// through Native.send, the callback every module shares.
//
// Values cross in package native's binary encoding: every integer as 8
// bytes, little-endian, floats as a Double's bits, bools as a byte,
// strings, byte arrays, lists and maps as their count then their contents,
// optionals as a bool then the value, structs as their fields, enums as
// their values.
package dev.mygo
import android.os.Handler
import android.os.Looper
import java.lang.ref.PhantomReference
import java.lang.ref.ReferenceQueue
import java.nio.ByteBuffer
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
// What the implementation uses.
/** What the system lacks, such as an API of a newer Android: Go gets errors.ErrUnsupported. */
class NativeUnsupportedException(message: String = "unsupported") : Exception(message)
/** A call of an object that was closed: Go gets native.ErrClosed. */
class NativeClosedException(message: String = "native: object closed") : Exception(message)
/** An error a Go function or method returned. */
class NativeGoException(message: String) : Exception(message)
/**
* An error of a domain of the platform's, as an NSError: Go gets a
* *native.Error with its domain, number and message. Any other exception
* reaches Go with its class as the domain.
*/
open class NativeException(val domain: String, val number: Long, message: String) : Exception(message)
/** A value Go sent that the implementation's types do not have. */
class NativeWireException(message: String) : Exception(message)
/** An error a module declares (native.NewError): Go gets that error. Each module's exception implements it. */
interface NativeCodedError {
val nativeCode: String
}
/** An AutoCloseable that runs a function, once: what a method returning io.Closer returns. */
class NativeCloser(fn: () -> Unit) : AutoCloseable {
private var fn: (() -> Unit)? = fn
override fun close() {
val f = synchronized(this) { fn.also { fn = null } }
f?.invoke()
}
}
/** Memory of Go's that the implementation reads and writes, valid while the call runs: a *native.Buffer. */
class NativeBuffer internal constructor(
/** The address of the memory. */
val address: Long,
/** Its size in bytes. */
val size: Int,
) {
/** The memory, as a direct buffer. */
val bytes: ByteBuffer by lazy { Native.buffer(address, size.toLong()).order(java.nio.ByteOrder.nativeOrder()) }
}
// The encoding.
/** Writes values for Go, after 8 bytes for the status of an answer. */
class NativeWriter {
private var b = ByteArray(64)
private var n = HEAD
private fun room(k: Int) {
if (n + k > b.size) b = b.copyOf(maxOf(b.size * 2, n + k))
}
fun u64(v: Long) {
room(8)
for (i in 0 until 8) b[n + i] = (v ushr (8 * i)).toByte()
n += 8
}
fun i64(v: Long) = u64(v)
fun bool(v: Boolean) { room(1); b[n++] = if (v) 1 else 0 }
fun u8(v: Int) { room(1); b[n++] = v.toByte() }
fun double(v: Double) = u64(v.toRawBits())
fun count(c: Int) = i64(c.toLong())
fun string(v: String) = data(v.toByteArray(Charsets.UTF_8))
fun data(v: ByteArray) {
count(v.size)
room(v.size)
System.arraycopy(v, 0, b, n, v.size)
n += v.size
}
/** A time: seconds and nanoseconds since 1970. */
fun time(v: Instant) { i64(v.epochSecond); i64(v.nano.toLong()) }
fun duration(v: Duration) = i64(v.inWholeNanoseconds)
fun rect(v: android.graphics.RectF) {
double(v.left.toDouble()); double(v.top.toDouble()); double(v.width().toDouble()); double(v.height().toDouble())
}
fun reset() { n = HEAD }
/** The values written. */
fun values(): ByteArray? = if (n == HEAD) null else b.copyOfRange(HEAD, n)
/** The values as an answer of status. */
fun answer(status: Long): ByteArray {
for (i in 0 until 8) b[i] = (status ushr (8 * i)).toByte()
return b.copyOf(n)
}
private companion object {
const val HEAD = 8
}
}
/** Reads the values Go wrote; past them, it throws. */
class NativeReader(private val b: ByteArray, private var p: Int = 0) {
private fun take(k: Int): Int {
if (k < 0 || b.size - p < k) throw NativeWireException("native: a short message")
val at = p
p += k
return at
}
fun u64(): Long {
val at = take(8)
var v = 0L
for (i in 7 downTo 0) v = (v shl 8) or (b[at + i].toLong() and 0xff)
return v
}
fun i64(): Long = u64()
fun u8(): Int = b[take(1)].toInt() and 0xff
fun bool(): Boolean = u8() != 0
fun double(): Double = Double.fromBits(u64())
/** The count of a list or a map, whose elements take a byte each at least. */
fun count(): Int {
val c = i64()
if (c < 0 || c > b.size - p) throw NativeWireException("native: a short message")
return c.toInt()
}
fun string(): String {
val c = count()
val at = take(c)
return String(b, at, c, Charsets.UTF_8)
}
fun data(): ByteArray {
val c = count()
val at = take(c)
return b.copyOfRange(at, at + c)
}
fun time(): Instant {
val s = i64()
val ns = i64()
return Instant.ofEpochSecond(s, ns)
}
fun duration(): Duration = i64().nanoseconds
fun rect(): android.graphics.RectF {
val x = double().toFloat()
val y = double().toFloat()
val w = double().toFloat()
val h = double().toFloat()
return android.graphics.RectF(x, y, x + w, y + h)
}
fun buffer(): NativeBuffer {
val p = u64()
return NativeBuffer(p, i64().toInt())
}
}
/**
* A module's Kotlin, as mygo generates it (its MygoModule object), which
* Go loads by its class's name.
*/
abstract class NativeModule {
/** The module's index, from Go, in the high bits of every id, which makes the ids of continuations unique among modules. */
@Volatile internal var idBase = 0L
private val lastID = AtomicLong()
/** Calls a function: an object's method, a factory (new_T), or close. */
abstract fun invoke(sym: String, h: Long, args: ByteArray, call: Long): ByteArray
/** Calls a method of numbers. */
open fun direct(sym: String, h: Long, args: LongArray): Long = 0
/** The exception of an error the module declares, by its code. */
open fun error(code: String): Throwable? = null
protected fun nextID(): Long = idBase or lastID.incrementAndGet()
/** Runs what returns at once, which writes its result to the writer. */
protected inline fun answer(body: (NativeWriter) -> Unit): ByteArray {
val w = NativeWriter()
return try {
body(w)
w.answer(0)
} catch (e: Throwable) {
w.reset()
Native.writeError(w, e)
w.answer(1)
}
}
/** Runs what starts an asynchronous call or a stream: Go waits for its results through the callback. */
protected inline fun start(body: () -> Unit): ByteArray {
val w = NativeWriter()
return try {
body()
w.answer(2)
} catch (e: Throwable) {
Native.writeError(w, e)
w.answer(1)
}
}
/** Starts the task of an asynchronous call, on the main thread when main. */
protected fun task(call: Long, main: Boolean, body: suspend (NativeWriter) -> Unit) {
val job = Native.scope.launch(if (main) Dispatchers.Main else Dispatchers.Default) {
val w = NativeWriter()
var status = 0L
try {
body(w)
} catch (e: Throwable) {
w.reset()
Native.writeError(w, e)
status = 1
}
Native.tasks.finish(call)
Native.send(KIND_RESULT, call, status, w.values())
}
Native.tasks.put(call, job)
}
/** Starts a stream: each value Go asks for (next), then its end or its error. */
protected fun <T> stream(call: Long, main: Boolean, make: () -> Flow<T>, enc: (NativeWriter, T) -> Unit) {
val demand = Channel<Unit>(Channel.UNLIMITED)
Native.demands[call] = demand
val job = Native.scope.launch(if (main) Dispatchers.Main else Dispatchers.Default) {
val w = NativeWriter()
try {
demand.receive()
make().collect { v ->
w.reset()
enc(w, v)
Native.send(KIND_ITEM, call, 0, w.values() ?: ByteArray(0))
demand.receive()
}
Native.send(KIND_ITEM, call, 3, null)
} catch (e: CancellationException) {
// Go stopped the stream, and hears no more of it.
} catch (e: Throwable) {
w.reset()
Native.writeError(w, e)
Native.send(KIND_ITEM, call, 1, w.values())
} finally {
Native.demands.remove(call)
Native.tasks.finish(call)
}
}
Native.tasks.put(call, job)
}
/** The object of a handle Go passed. */
@Suppress("UNCHECKED_CAST")
protected fun <T> obj(h: Long): T = (Native.objects[h] ?: throw NativeClosedException()) as T
/** Keeps an object for Go: its handle. */
protected fun retain(v: Any): Long = Native.retain(v)
/** Closes an object Go closes, as io.Closer's Close. */
protected fun close(h: Long) {
when (val o = Native.objects[h]) {
is AutoCloseable -> o.close()
is android.view.View -> (o.parent as? android.view.ViewGroup)?.removeView(o)
}
}
/** The view of a window Go passed: the window's own. */
protected fun window(h: Long): android.view.View =
HostImpl.windows[h]?.view ?: throw NativeClosedException("native: the window is closed")
/** A rectangle of native UI, in points from the window's top-left, in the pixels of the window's view. */
protected fun pixels(r: android.graphics.RectF, w: android.view.View): android.graphics.RectF {
val d = w.resources.displayMetrics.density
return android.graphics.RectF(r.left * d, r.top * d, r.right * d, r.bottom * d)
}
protected fun unknown(sym: String): ByteArray = answer { throw NativeUnsupportedException("native: no function $sym: generate the module's Kotlin again") }
/** Calls the method of a value of Go's, which answers at once. */
fun <R> invokeGo(id: Long, w: NativeWriter, read: (NativeReader) -> R): R =
Native.answerOf(this, Native.send(KIND_INVOKE, id, 0, w.values()), read)
/** Calls the method of a value of Go's that takes a context, which the coroutine's cancellation cancels. */
suspend fun <R> invokeGoAsync(id: Long, w: NativeWriter, read: (NativeReader) -> R): R {
val cont = nextID()
val b = try {
suspendCancellableCoroutine<ByteArray?> { c ->
Native.conts[cont] = { b -> c.resume(b) }
c.invokeOnCancellation { Native.send(KIND_CANCEL, cont, 0, null) }
Native.send(KIND_INVOKE_ASYNC, id, cont, w.values())
}
} finally {
Native.conts.remove(cont)
}
return Native.answerOf(this, b, read)
}
/** A Go function the implementation calls, released once nothing holds it. */
fun goFunc(id: Long): GoFunc = GoFunc(this, id)
/** Ties the release of the value of Go's id to the life of holder. */
fun releaseWith(holder: Any, id: Long) = Native.releaseWith(holder, id)
companion object {
const val KIND_RESULT = 1L
const val KIND_ITEM = 2L
const val KIND_NOTIFY = 3L
const val KIND_ASK = 4L
const val KIND_RELEASE = 5L
const val KIND_INVOKE = 6L
const val KIND_INVOKE_ASYNC = 7L
const val KIND_CANCEL = 8L
}
}
/** A Go function the implementation calls: a notification, or a question Go answers at once. */
class GoFunc internal constructor(private val module: NativeModule, val id: Long) {
init {
if (id != 0L) Native.releaseWith(this, id)
}
fun notify(w: NativeWriter) {
if (id != 0L) Native.send(NativeModule.KIND_NOTIFY, id, 0, w.values())
}
fun <R> ask(w: NativeWriter, read: (NativeReader) -> R): R {
if (id == 0L) throw NativeClosedException()
return Native.answerOf(module, Native.send(NativeModule.KIND_ASK, id, 0, w.values()), read)
}
}
/** The runtime of native modules' Kotlin, which Go reaches through JNI. */
object Native {
private val modules = ConcurrentHashMap<String, NativeModule>()
/** The objects Go holds, by handle. */
internal val objects = ConcurrentHashMap<Long, Any>()
private val lastHandle = AtomicLong()
internal val tasks = Tasks()
internal val demands = ConcurrentHashMap<Long, Channel<Unit>>()
internal val conts = ConcurrentHashMap<Long, (ByteArray?) -> Unit>()
/** Where the tasks of asynchronous calls and streams run. */
@JvmField val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val main = Handler(Looper.getMainLooper())
/** The application's context, for a module's Android APIs, from any thread. */
val context: android.content.Context get() = HostImpl.app
/** The activity showing the app, if one is, for what needs one (a dialog, a permission request). Main thread. */
val activity: android.app.Activity? get() = HostImpl.activity
/** Runs body on the main thread, now if this is it, else waiting for it: to make an object there. */
fun <T> onMain(body: () -> T): T {
if (Looper.myLooper() == Looper.getMainLooper()) return body()
var result: Result<T>? = null
val latch = CountDownLatch(1)
main.post {
result = runCatching(body)
latch.countDown()
}
latch.await()
return result!!.getOrThrow()
}
// What Go calls, through JNI.
/** Loads a module's Kotlin: its generated object's class. Returns what went wrong, or null. */
@JvmStatic fun init(name: String, cls: String, idBase: Long): String? = try {
val m = Class.forName(cls).getField("INSTANCE").get(null) as NativeModule
m.idBase = idBase
modules[name] = m
null
} catch (e: ReflectiveOperationException) {
"the app has no Kotlin of the native module $name ($cls): build it with mygo build"
} catch (e: Throwable) {
"loading the Kotlin of the native module $name: $e"
}
@JvmStatic fun invoke(name: String, sym: String, h: Long, args: ByteArray, call: Long): ByteArray {
val m = modules[name] ?: return NativeWriter().also { writeError(it, NativeClosedException("native: $name is not loaded")) }.answer(1)
return m.invoke(sym, h, args, call)
}
@JvmStatic fun direct(name: String, sym: String, h: Long, args: LongArray): Long = modules[name]?.direct(sym, h, args) ?: 0
@JvmStatic fun op(name: String, op: String, a: Long, status: Long, data: ByteArray?) {
when (op) {
"release" -> objects.remove(a)
"cancel" -> tasks.cancel(a)
"next" -> demands[a]?.trySend(Unit)
"resume" -> conts.remove(a)?.invoke(answer(status, data))
}
}
/** Tells Go something; its answer is the status and then the data, null when there is none. */
@JvmStatic external fun send(kind: Long, id: Long, status: Long, data: ByteArray?): ByteArray?
/** The n bytes at p, which Go owns, as a direct buffer. Public, as JNI finds it by its name. */
@JvmStatic external fun buffer(p: Long, n: Long): ByteBuffer
/** The view of a handle, for ui.NativeView. */
internal fun view(h: Long): android.view.View? = objects[h] as? android.view.View
internal fun retain(v: Any): Long {
val h = lastHandle.incrementAndGet()
objects[h] = v
return h
}
private fun answer(status: Long, data: ByteArray?): ByteArray {
val b = ByteArray(8 + (data?.size ?: 0))
for (i in 0 until 8) b[i] = (status ushr (8 * i)).toByte()
data?.copyInto(b, 8)
return b
}
/** Reads an answer of Go's. */
internal fun <R> answerOf(m: NativeModule, b: ByteArray?, read: (NativeReader) -> R): R {
if (b == null || b.size < 8) throw NativeClosedException()
val r = NativeReader(b)
val status = r.u64()
if (status == 1L) throw readError(m, r)
return read(r)
}
// The kinds of errors, as they cross both ways: the kind, then the
// code, domain, number and message.
private const val ERR_OTHER = 0
private const val ERR_CODE = 1
private const val ERR_UNSUPPORTED = 2
private const val ERR_CLOSED = 3
private const val ERR_CANCELED = 4
private const val ERR_GO = 5
fun writeError(w: NativeWriter, e: Throwable) {
var kind = ERR_OTHER
var code = ""
var domain = ""
var number = 0L
var message = e.message ?: e.toString()
when (e) {
is NativeException -> { domain = e.domain; number = e.number }
is NativeCodedError -> { kind = ERR_CODE; code = e.nativeCode }
is NativeUnsupportedException -> kind = ERR_UNSUPPORTED
is NativeClosedException -> kind = ERR_CLOSED
is NativeGoException -> kind = ERR_GO
is CancellationException -> kind = ERR_CANCELED
else -> domain = e.javaClass.name
}
w.u8(kind)
w.string(code)
w.string(domain)
w.i64(number)
w.string(message)
}
private fun readError(m: NativeModule, r: NativeReader): Throwable = try {
val kind = r.u8()
val code = r.string()
r.string()
r.i64()
val message = r.string()
when (kind) {
ERR_CODE -> m.error(code) ?: NativeGoException(message)
ERR_UNSUPPORTED -> NativeUnsupportedException(message)
ERR_CLOSED -> NativeClosedException(message)
ERR_CANCELED -> CancellationException(message)
else -> NativeGoException(message)
}
} catch (e: NativeWireException) {
NativeGoException("an error of Go's that does not decode")
}
// Values of Go's that Kotlin holds, released once it no longer does.
private val collected = ReferenceQueue<Any>()
private val held = ConcurrentHashMap.newKeySet<Held>()
private class Held(holder: Any, val id: Long) : PhantomReference<Any>(holder, collected)
internal fun releaseWith(holder: Any, id: Long) {
held.add(Held(holder, id))
releaser
}
private val releaser: Thread by lazy {
Thread({
while (true) {
val r = collected.remove() as Held
held.remove(r)
send(NativeModule.KIND_RELEASE, r.id, 0, null)
}
}, "mygo-native-release").apply {
isDaemon = true
start()
}
}
/** The tasks of asynchronous calls and streams, by their call, which Go cancels. */
internal class Tasks {
private val jobs = HashMap<Long, Job>()
private val done = HashSet<Long>()
private val canceled = HashSet<Long>()
@Synchronized fun put(call: Long, job: Job) {
if (done.remove(call)) return
if (canceled.remove(call)) job.cancel()
jobs[call] = job
}
@Synchronized fun finish(call: Long) {
if (jobs.remove(call) == null) done.add(call)
canceled.remove(call)
}
fun cancel(call: Long) {
val job = synchronized(this) {
jobs.remove(call).also { if (it == null && !done.remove(call)) canceled.add(call) }
}
job?.cancel()
}
}
}
@@ -0,0 +1,411 @@
// The navigation of phones on Android: each window in a page of a stack,
// whose pages above the first have a toolbar with a back arrow and the
// window's title, and bars of tabs (Material's bottom navigation), a
// stack in each tab, all in the root view, the one shown last in front.
// A window's router may show its pages as a stack of its own (SetStack):
// the window's toolbar then shows the title of the page shown, with a back
// arrow past the first, and the router moves the pages, as Android's apps
// move theirs.
package dev.mygo
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.view.ContextThemeWrapper
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.color.DynamicColors
object Navigation {
/** A window's page in a stack: its toolbar, when it has one, over it. */
class Page(val window: HostWindow, var toolbar: MaterialToolbar?, val view: LinearLayout)
/** A stack of pages: the first is the window it shows, the others pushed over it. */
class Stack(context: Context) : FrameLayout(context) {
val pages = ArrayList<Page>()
var tabs: Tabs? = null
var barAtRoot = ""
}
/** A bar of tabs, a stack in each. */
class Tabs(context: Context, val id: Long) : LinearLayout(context) {
val content = FrameLayout(context)
val stacks = ArrayList<Stack>()
val bar = BottomNavigationView(material(context))
var selected = 0
init {
orientation = VERTICAL
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
addView(bar, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
bar.labelVisibilityMode = BottomNavigationView.LABEL_VISIBILITY_LABELED
bar.setOnItemSelectedListener { item ->
val i = item.itemId
if (i != selected) {
select(i)
Go.send(Event.tabSelected(id, i.toLong()))
}
true
}
}
fun select(i: Int) {
if (i !in stacks.indices) return
selected = i
stacks[i].pages.lastOrNull()?.window?.let { tint(it) }
for ((k, s) in stacks.withIndex()) s.visibility = if (k == i) View.VISIBLE else View.GONE
if (bar.selectedItemId != i) bar.selectedItemId = i
for (p in stacks[i].pages) p.window.reportSize()
}
}
private val stacks = HashMap<Long, Stack>() // by window
val tabs = HashMap<Long, Tabs>()
private val root get() = HostImpl.root
/** A context with Material 3's theme, and the wallpaper's colors where the system has them. */
fun material(context: Context): Context =
DynamicColors.wrapContextIfAvailable(ContextThemeWrapper(context, com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar))
private fun toolbar(w: HostWindow, title: String): MaterialToolbar {
val t = MaterialToolbar(material(w.context))
t.title = title
t.setBackgroundColor(if (w.fill != 0) w.fill else HostImpl.themeColor(android.R.attr.colorBackground))
return t
}
/** back gives a toolbar the back arrow, which runs fn, or (null) takes it away. */
private fun back(t: MaterialToolbar, fn: (() -> Unit)?) {
if (fn == null) {
t.navigationIcon = null
t.setNavigationOnClickListener(null)
return
}
t.setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material)
t.setNavigationContentDescription(androidx.appcompat.R.string.abc_action_bar_up_description)
t.setNavigationOnClickListener { fn() }
}
private fun page(w: HostWindow, title: String?, back: Boolean): Page {
(w.view.parent as? ViewGroup)?.removeView(w.view)
val v = LinearLayout(w.context).apply { orientation = LinearLayout.VERTICAL }
var toolbar: MaterialToolbar? = null
if (title != null) {
val t = toolbar(w, title)
if (back) back(t) { pop(w, true) }
v.addView(t, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
toolbar = t
}
v.addView(w.view, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
w.view.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> w.reportSize() }
return Page(w, toolbar, v)
}
private fun front(v: View) {
(v.parent as? ViewGroup)?.let { if (it !== root) it.removeView(v) }
if (v.parent == null) {
root.addView(v, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
} else {
v.bringToFront()
}
insetsChanged()
arrange()
}
/**
* Only what is in front stays on screen: the surfaces of two windows have
* no order of their own, whatever the order of their views. Not now: Go
* may be waiting for this call, and a surface going waits for Go.
*/
private fun arrange() {
root.post {
val top = root.childCount - 1
for (k in 0..top) {
val v = root.getChildAt(k)
if (v is Stack || v is Tabs) v.visibility = if (k == top) View.VISIBLE else View.INVISIBLE
}
}
}
/** show brings a window to the front: its tab, its stack, or a stack of its own. */
fun show(w: HostWindow) {
val s = stacks[w.id]
if (s != null) {
val t = s.tabs
if (t != null) {
t.select(t.stacks.indexOf(s))
front(t)
} else {
front(s)
}
return
}
val stack = Stack(w.context)
val p = page(w, null, false)
stack.pages.add(p)
stack.addView(p.view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
stacks[w.id] = stack
front(stack)
}
/** hide takes a window off the screen: its stack, or the pages above it in its stack. */
fun hide(w: HostWindow) {
val s = stacks[w.id] ?: return
val i = s.pages.indexOfFirst { it.window === w }
if (i == 0) {
if (s.tabs == null) {
root.removeView(s)
for (p in s.pages) stacks.remove(p.window.id)
arrange()
}
} else if (i > 0) {
truncate(s, i, false)
}
}
fun forget(w: HostWindow) {
routed.remove(w.id)
val s = stacks.remove(w.id) ?: return
s.pages.removeAll { it.window === w }
}
fun push(w: HostWindow, parent: HostWindow, title: String, animated: Boolean) {
val s = stacks[parent.id] ?: run {
show(parent)
stacks[parent.id]!!
}
val at = s.pages.indexOfFirst { it.window === parent }
if (at >= 0 && at < s.pages.size - 1) truncate(s, at + 1, false)
val below = s.pages.lastOrNull()
val p = page(w, title, true)
s.pages.add(p)
stacks[w.id] = s
s.addView(p.view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
insetsChanged()
tint(w)
if (animated && s.width > 0) {
p.view.translationX = s.width.toFloat()
p.view.animate().translationX(0f).setDuration(250).withEndAction { below?.view?.visibility = View.INVISIBLE }.start()
below?.view?.animate()?.translationX(-s.width * 0.25f)?.setDuration(250)?.start()
} else {
below?.view?.visibility = View.INVISIBLE
}
}
fun pop(w: HostWindow, animated: Boolean) {
val s = stacks[w.id] ?: return
val i = s.pages.indexOfFirst { it.window === w }
if (i > 0) truncate(s, i, animated)
}
/** truncate takes the pages from i up off the stack, which tells Go they went. */
private fun truncate(s: Stack, i: Int, animated: Boolean) {
val gone = s.pages.subList(i, s.pages.size).toList()
s.pages.subList(i, s.pages.size).clear()
val below = s.pages.lastOrNull()
below?.view?.visibility = View.VISIBLE
below?.view?.translationX = 0f
below?.window?.let { tint(it) }
for ((k, p) in gone.withIndex()) {
stacks.remove(p.window.id)
val last = k == gone.size - 1
if (animated && last && s.width > 0) {
below?.view?.translationX = -s.width * 0.25f
below?.view?.animate()?.translationX(0f)?.setDuration(220)?.start()
p.view.animate().translationX(s.width.toFloat()).setDuration(220).withEndAction { s.removeView(p.view) }.start()
} else {
s.removeView(p.view)
}
Go.send(Event.popped(p.window.id))
}
HostImpl.updateBack()
}
/** Whether the window in front can go off its stack. */
fun canPop(): Boolean {
for (k in root.childCount - 1 downTo 0) {
val s = when (val v = root.getChildAt(k)) {
is Tabs -> v.stacks.getOrNull(v.selected)
is Stack -> v
else -> null
} ?: continue
return s.pages.size > 1
}
return false
}
/** back pops the window in front off its stack, and reports whether there was one to pop. */
fun back(): Boolean {
for (k in root.childCount - 1 downTo 0) {
val v = root.getChildAt(k)
val s = when (v) {
is Tabs -> v.stacks.getOrNull(v.selected)
is Stack -> v
else -> null
} ?: continue
if (s.pages.size > 1) {
pop(s.pages.last().window, true)
return true
}
return false
}
return false
}
// The pages of routers.
/** A window's router showing its pages in its stack: how deep, the window's title, and whether the toolbar is the router's. */
private class Routed(var depth: Int, val title: String, val added: Boolean)
private val routed = HashMap<Long, Routed>()
/**
* setStack shows the pages of w's router as a stack: the toolbar shows the
* title of the page shown, with a back arrow past the first, which takes
* the router back. No titles take it away.
*/
fun setStack(w: HostWindow, titles: List<String>) {
val s = stacks[w.id] ?: return
val i = s.pages.indexOfFirst { it.window === w }
if (i < 0) return
val p = s.pages[i]
val r = routed[w.id]
if (titles.isEmpty()) {
if (r == null) return
routed.remove(w.id)
val t = p.toolbar ?: return
if (r.added) {
p.view.removeView(t)
p.toolbar = null
} else {
t.title = r.title
back(t, if (i > 0) ({ pop(w, true) }) else null)
}
return
}
var t = p.toolbar
if (r == null) {
val added = t == null
if (t == null) {
t = toolbar(w, titles.last())
p.view.addView(t, 0, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
p.toolbar = t
insetsChanged()
}
routed[w.id] = Routed(titles.size, t.title?.toString() ?: "", added)
}
routed[w.id]?.depth = titles.size
t!!.title = titles.last()
when {
titles.size > 1 -> back(t) {
val d = routed[w.id]?.depth ?: 1
if (d > 1) Go.send(Event.stackPopped(w.id, (d - 1).toLong()))
}
i > 0 -> back(t) { pop(w, true) }
else -> back(t, null)
}
}
// Tabs.
fun createTabs(id: Long, context: Context) {
tabs[id] = Tabs(context, id)
}
fun addTab(id: Long, w: HostWindow, title: String, icon: ByteArray) {
val t = tabs[id] ?: return
stacks[w.id]?.let { old ->
if (old.tabs == null) {
root.removeView(old)
arrange()
}
stacks.remove(w.id)
}
val stack = Stack(w.context)
stack.tabs = t
val p = page(w, title.ifEmpty { null }, false)
stack.pages.add(p)
stack.addView(p.view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
stacks[w.id] = stack
val i = t.stacks.size
t.stacks.add(stack)
t.content.addView(stack, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
val item = t.bar.menu.add(0, i, i, title)
if (icon.isNotEmpty()) {
BitmapFactory.decodeByteArray(icon, 0, icon.size)?.let { item.icon = BitmapDrawable(w.context.resources, it) }
}
}
fun showTabs(id: Long) {
val t = tabs[id] ?: return
t.select(0)
front(t)
}
fun setBadge(id: Long, i: Int, badge: String) {
val t = tabs[id] ?: return
if (badge.isEmpty()) {
t.bar.removeBadge(i)
return
}
val b = t.bar.getOrCreateBadge(i)
badge.toIntOrNull()?.let { b.number = it } ?: run { b.text = badge }
}
fun closeTabs(id: Long) {
val t = tabs.remove(id) ?: return
root.removeView(t)
arrange()
}
/**
* The bars around a window take the color its content fills it with:
* its toolbar, and the bar of tabs while it is in front of its tab.
*/
fun backgroundChanged(w: HostWindow) {
val s = stacks[w.id] ?: return
s.pages.firstOrNull { it.window === w }?.toolbar?.setBackgroundColor(w.fill)
val t = s.tabs ?: return
if (t.stacks.getOrNull(t.selected) === s && s.pages.lastOrNull()?.window === w) tint(w)
}
private fun tint(w: HostWindow) {
if (w.fill == 0) return
val s = stacks[w.id] ?: return
s.tabs?.bar?.setBackgroundColor(w.fill)
}
/** Buttons at the end of the window's toolbar. */
fun setBarItems(w: HostWindow, c: SetBarItemsCall) {
val t = stacks[w.id]?.pages?.firstOrNull { it.window === w }?.toolbar ?: return
t.menu.clear()
c.titles.forEachIndexed { i, title ->
val item = t.menu.add(0, i, i, title)
val icon = android.util.Base64.decode(c.icons[i], android.util.Base64.DEFAULT)
if (icon.isNotEmpty()) {
BitmapFactory.decodeByteArray(icon, 0, icon.size)?.let { item.icon = BitmapDrawable(w.context.resources, it) }
}
item.setShowAsAction(android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM)
}
t.setOnMenuItemClickListener {
Go.send(Event.barItemClicked(c.id, it.itemId.toLong()))
true
}
}
fun setTitle(w: HostWindow, title: String) {
if (w.id in routed) return // the router's page has the toolbar's title
stacks[w.id]?.pages?.firstOrNull { it.window === w }?.toolbar?.title = title
}
/** The toolbars at the top of the screen take the status bar's room. */
fun insetsChanged() {
val top = HostImpl.bars.top
for (s in stacks.values.toSet()) for (p in s.pages) p.toolbar?.setPadding(0, top, 0, 0)
for (w in HostImpl.windows.values) w.insetsChanged()
}
}
@@ -0,0 +1,6 @@
// Written by mygo build: the plugins the app's packages name.
package dev.mygo
internal fun registerPlugins() {
PluginHost.register("tts", TTSPlugin())
}
@@ -0,0 +1,51 @@
package dev.mygo
import android.speech.tts.TextToSpeech
import org.json.JSONObject
import java.util.Locale
class TTSPlugin : MyGoPlugin {
private var engine: TextToSpeech? = null
private var ready = false
private var pending: Pair<String, PluginReply>? = null
override fun call(method: String, args: JSONObject, reply: PluginReply) {
when (method) {
"speak" -> {
val text = args.optString("text").ifEmpty { return reply.failure(PluginFailure("Empty", "no text")) }
if (ready) {
engine?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
reply.success(null)
} else {
pending = text to reply
init()
}
}
"stop" -> {
engine?.stop()
reply.success(null)
}
else -> reply.failure(PluginFailure("NoMethod", method))
}
}
private fun init() {
if (engine != null) return
engine = TextToSpeech(PluginHost.context) { status ->
if (status == TextToSpeech.SUCCESS) {
engine?.setLanguage(Locale.getDefault())
ready = true
val p = pending
pending = null
if (p != null) {
engine?.speak(p.first, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
p.second.success(null)
}
} else {
val p = pending
pending = null
if (p != null) p.second.failure(PluginFailure("Init", "text-to-speech is unavailable"))
}
}
}
}
@@ -0,0 +1,156 @@
// Plugins' native code. A plugin brings Kotlin that implements MyGoPlugin
// (mygo-plugin.json names the class), which mygo build compiles into the app
// and registers by the plugin's id; Go calls it with mygo.Native(id).Call. It
// runs on the UI thread.
package dev.mygo
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
/** An error of a plugin's native code, with a code Go can tell apart. */
class PluginFailure(val code: String, message: String = "") : Exception(message)
/** The answer of a plugin's method: call success or failure once, from any thread. */
interface PluginReply {
fun success(result: Any?)
fun failure(error: PluginFailure)
}
/** A plugin's native code. */
interface MyGoPlugin {
/** Runs a method with its arguments, from JSON, on the UI thread. It may answer later. */
fun call(method: String, args: JSONObject, reply: PluginReply)
}
/** What plugins have of the host. */
object PluginHost {
private val plugins = HashMap<String, MyGoPlugin>()
private var nextCode = 0x7000
private val onResults = HashMap<Int, (Int, Intent?) -> Unit>()
private val onPermissions = HashMap<Int, (Boolean) -> Unit>()
private val viewMakers = HashMap<String, (Context, Long, JSONObject) -> android.view.View>()
fun register(id: String, plugin: MyGoPlugin) { plugins[id] = plugin }
/** Registers a type of view that mygo.NewPluginView makes: make gets the number that calls about the view name it, and the arguments. */
fun registerView(type: String, make: (context: Context, id: Long, args: JSONObject) -> android.view.View) {
viewMakers[type] = make
}
internal fun makeView(type: String, context: Context, id: Long, args: String): android.view.View? {
// A native module's view, which ui.NativeView shows: its handle.
if (type == "mygo.native") return Native.view(args.toLongOrNull() ?: 0)
val a = (if (args.isEmpty()) null else runCatching { JSONTokener(args).nextValue() as? JSONObject }.getOrNull()) ?: JSONObject()
return viewMakers[type]?.invoke(context, id, a)
}
/** Hears the Intents that open the app, for what a plugin's own open it with. */
var onIntent: ((Intent) -> Unit)? = null
/** The app's context, which outlives Activities. */
val context: Context get() = HostImpl.app
/** The Activity showing the app, null while none does. */
val activity: Activity? get() = HostImpl.activity
/** Sends an event to Go (mygo.Native(id).On), from any thread. */
fun emit(plugin: String, name: String, data: Any? = null) {
Go.send(Event.pluginEvent(plugin, name, encode(data)))
}
/** Starts an Activity for its result. */
fun startForResult(intent: Intent, done: (resultCode: Int, data: Intent?) -> Unit) {
val a = activity
if (a == null) {
done(Activity.RESULT_CANCELED, null)
return
}
val code = nextCode++
onResults[code] = done
@Suppress("DEPRECATION")
a.startActivityForResult(intent, code)
}
/** Has the system ask the user for permissions the app lacks, and tells whether it has them all. */
fun requestPermissions(permissions: Array<String>, done: (granted: Boolean) -> Unit) {
val a = activity
if (a == null) {
done(false)
return
}
val missing = permissions.filter { a.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) {
done(true)
return
}
val code = nextCode++
onPermissions[code] = done
a.requestPermissions(missing.toTypedArray(), code)
}
internal fun activityResult(code: Int, result: Int, data: Intent?): Boolean {
val f = onResults.remove(code) ?: return false
f(result, data)
return true
}
internal fun permissionsResult(code: Int, results: IntArray): Boolean {
val f = onPermissions.remove(code) ?: return false
f(results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED })
return true
}
/** JSON of what org.json can write. */
internal fun encode(v: Any?): String = when (v) {
null -> "null"
is JSONObject, is JSONArray -> v.toString()
is Map<*, *> -> JSONObject(v).toString()
is Collection<*> -> JSONArray(v).toString()
else -> JSONObject.wrap(v)?.let { w -> JSONArray().put(w).toString().let { it.substring(1, it.length - 1) } } ?: "null"
}
internal fun call(c: PluginCallCall) {
val p = plugins[c.plugin]
if (p == null) {
Go.send(Event.pluginResult(c.req, "", "no plugin ${c.plugin} in this app", "NoPlugin"))
return
}
val args = (if (c.args.isEmpty()) null else runCatching { JSONTokener(c.args).nextValue() as? JSONObject }.getOrNull()) ?: JSONObject()
var answered = false
val reply = object : PluginReply {
override fun success(result: Any?) {
if (answered) return
val text = try {
encode(result)
} catch (e: Exception) {
failure(PluginFailure("Encoding", e.toString()))
return
}
answered = true
Go.send(Event.pluginResult(c.req, text, "", ""))
}
override fun failure(error: PluginFailure) {
if (answered) return
answered = true
Go.send(Event.pluginResult(c.req, "", error.message ?: "", error.code))
}
}
try {
p.call(c.method, args, reply)
} catch (e: Exception) {
reply.failure(PluginFailure("Exception", e.toString()))
}
}
}
/** A window showing a plugin's view, which a surface holds. */
internal class PluginViewWindow(context: Context, id: Long, override val view: android.view.View) : HostWindow(context, id) {
override fun setBackground(argb: Int) = view.setBackgroundColor(argb)
}
@@ -0,0 +1,42 @@
package dev.mygo
import android.content.Context
import android.content.pm.PackageManager
import java.io.File
/**
* The app's resources (mygo.PathResources): mygo build puts them in the
* APK's assets, under resources/, which are no files. They are copied
* into the app's files once per version of the app, for Go to read them
* by path.
*/
object Resources {
fun dir(c: Context) = File(c.filesDir, "mygo-resources")
fun extract(c: Context): String {
val dir = dir(c)
val info = c.packageManager.getPackageInfo(c.packageName, 0)
val stamp = File(dir, ".version")
val version = "${info.longVersionCode}-${info.lastUpdateTime}"
if (stamp.exists() && stamp.readText() == version) return dir.absolutePath
dir.deleteRecursively()
dir.mkdirs()
copy(c, "resources", dir)
stamp.writeText(version)
return dir.absolutePath
}
private fun copy(c: Context, path: String, to: File) {
val names = c.assets.list(path) ?: return
for (n in names) {
val p = "$path/$n"
val sub = c.assets.list(p)
if (sub != null && sub.isNotEmpty()) {
File(to, n).mkdirs()
copy(c, p, File(to, n))
} else {
c.assets.open(p).use { input -> File(to, n).outputStream().use { input.copyTo(it) } }
}
}
}
}
@@ -0,0 +1,68 @@
package dev.mygo
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* Secrets, encrypted with an AES key of Android's keystore, which never
* leaves it, and kept in the app's shared preferences.
*/
object Secrets {
private const val KEY = "mygo.secrets"
private fun key(): SecretKey {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(ks.getEntry(KEY, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
gen.init(
KeyGenParameterSpec.Builder(KEY, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
return gen.generateKey()
}
private fun prefs(c: Context) = c.getSharedPreferences(KEY, Context.MODE_PRIVATE)
private fun name(service: String, account: String) = service + "\u0000" + account
fun get(c: Context, call: SecretGetCall): SecretGetReply {
val r = SecretGetReply()
val stored = prefs(c).getString(name(call.service, call.account), null) ?: return r
try {
val data = Base64.decode(stored, Base64.NO_WRAP)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, data, 0, 12))
r.value = cipher.doFinal(data, 12, data.size - 12)
r.found = true
} catch (e: Exception) {
r.error = "mygo: keystore: ${e.message}"
}
return r
}
fun set(c: Context, call: SecretSetCall): SecretSetReply {
val r = SecretSetReply()
try {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val data = cipher.iv + cipher.doFinal(call.value)
prefs(c).edit().putString(name(call.service, call.account), Base64.encodeToString(data, Base64.NO_WRAP)).apply()
} catch (e: Exception) {
r.error = "mygo: keystore: ${e.message}"
}
return r
}
fun delete(c: Context, call: SecretDeleteCall): SecretDeleteReply {
prefs(c).edit().remove(name(call.service, call.account)).apply()
return SecretDeleteReply()
}
}
@@ -0,0 +1,57 @@
package dev.mygo
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* The sound of package audio, through AudioTrack: Go's output writes from a
* thread of its own, which AudioTrack makes wait while it holds enough.
*/
object Sound {
private var track: AudioTrack? = null
fun open(c: AudioOpenCall): AudioOpenReply {
val r = AudioOpenReply()
try {
val format = AudioFormat.Builder().setSampleRate(c.rate.toInt()).setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT).build()
val least = AudioTrack.getMinBufferSize(c.rate.toInt(), AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_FLOAT)
val asked = (c.rate * c.ahead / 1000 * 8).toInt()
val t = AudioTrack.Builder()
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build())
.setAudioFormat(format).setBufferSizeInBytes(maxOf(least, asked)).setTransferMode(AudioTrack.MODE_STREAM)
.setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY).build()
t.play()
track = t
} catch (e: Exception) {
r.error = "audio: $e"
}
return r
}
fun write(c: AudioWriteCall): AudioWriteReply {
val r = AudioWriteReply()
val t = track
if (t == null) {
r.error = "audio: closed"
return r
}
val b = ByteBuffer.wrap(c.samples).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
val a = FloatArray(b.remaining())
b.get(a)
val n = t.write(a, 0, a.size, AudioTrack.WRITE_BLOCKING)
if (n < 0) r.error = "audio: AudioTrack error $n"
return r
}
fun close() {
track?.run {
stop()
release()
}
track = null
}
}
@@ -0,0 +1,808 @@
package dev.mygo
import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.text.InputType
import android.view.Choreographer
import android.view.InputDevice
import android.view.ActionMode
import android.view.KeyEvent
import android.widget.Magnifier
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.PointerIcon
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.view.accessibility.AccessibilityNodeProvider
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
/**
* A window showing native UI, which Go draws with OpenGL ES into the
* surface's ANativeWindow. The view gives Go the display's refreshes
* (Choreographer), the fingers, a hardware keyboard, the soft keyboard
* (an InputConnection, with the composing text of input methods) and
* TalkBack's questions.
*/
class SurfaceWindow(context: Context, id: Long) : HostWindow(context, id) {
/** The window's number, which views' own id would shadow. */
private val wid: Long = id
private val surface = Surface(context)
/** The surface, and under it the views it holds. */
private val box = android.widget.FrameLayout(context).apply {
addView(surface, android.widget.FrameLayout.LayoutParams(android.widget.FrameLayout.LayoutParams.MATCH_PARENT, android.widget.FrameLayout.LayoutParams.MATCH_PARENT))
}
override val view: View get() = box
private var native = 0L
private var framePending = false
private val frame = Choreographer.FrameCallback {
framePending = false
Go.send(Event.frame(wid))
}
// The input being edited, as Go last told it (SetTextInput): the text
// around the selection, from base, and offsets in UTF-16 units of the
// document, as InputConnection counts.
private var input = SetTextInputCall(markStart = -1, markEnd = -1)
private val editing get() = input.active
private var nodes: List<Node>? = null
/** Whether the content takes the system's back. */
var backAvailable = false
// A SurfaceView's background would draw over its surface, hiding the
// frames: the page around it takes the color.
override fun setBackground(argb: Int) {
box.setBackgroundColor(argb)
}
/** A view the surface holds, in a view that clips it. */
private class Held(val window: HostWindow, val clip: android.widget.FrameLayout) {
var box = Rect()
var covers = emptyList<Rect>()
fun takes(x: Int, y: Int) = clip.visibility == View.VISIBLE && box.contains(x, y) && covers.none { it.contains(x, y) }
}
private val held = ArrayList<Held>()
/**
* Holds a view under the surface, whose frames are transparent where the
* content shows it: the surface goes over the window, which it does only as
* it is made, so it is made again the first time.
*/
fun hold(w: HostWindow) {
w.holder = this
(w.view.parent as? android.view.ViewGroup)?.removeView(w.view)
val clip = android.widget.FrameLayout(context)
clip.clipChildren = true
clip.visibility = View.GONE
clip.addView(w.view, android.widget.FrameLayout.LayoutParams(0, 0))
box.addView(clip, 0, android.widget.FrameLayout.LayoutParams(0, 0))
if (held.isEmpty()) {
// Not now: Go waits for this call, and the surface going waits
// for Go.
box.post {
surface.setZOrderOnTop(true)
surface.holder.setFormat(android.graphics.PixelFormat.TRANSLUCENT)
box.removeView(surface)
box.addView(surface, android.widget.FrameLayout.LayoutParams(android.widget.FrameLayout.LayoutParams.MATCH_PARENT, android.widget.FrameLayout.LayoutParams.MATCH_PARENT))
}
}
held.add(Held(w, clip))
}
fun release(w: HostWindow) {
val i = held.indexOfFirst { it.window === w }
if (i < 0) return
box.removeView(held[i].clip)
held.removeAt(i)
}
fun placeViews(places: ByteArray) {
val r = WireReader(places)
val d = density
fun rect(): Rect {
val x = r.float()
val y = r.float()
val w = r.float()
val h = r.float()
return Rect((x * d).toInt(), (y * d).toInt(), ((x + w) * d).toInt(), ((y + h) * d).toInt())
}
val shown = HashSet<Held>()
var order = 0
while (!r.done()) {
val id = r.int()
val frame = rect()
val clip = rect()
val covers = List(r.int().toInt()) { rect() }
val h = held.firstOrNull { it.window.id == id } ?: continue
val lp = h.clip.layoutParams as android.widget.FrameLayout.LayoutParams
lp.leftMargin = clip.left
lp.topMargin = clip.top
lp.width = clip.width()
lp.height = clip.height()
h.clip.layoutParams = lp
val vp = h.window.view.layoutParams as android.widget.FrameLayout.LayoutParams
vp.leftMargin = frame.left - clip.left
vp.topMargin = frame.top - clip.top
vp.width = frame.width()
vp.height = frame.height()
h.window.view.layoutParams = vp
h.window.view.post { h.window.reportSize() }
h.box = clip
h.covers = covers
h.clip.visibility = View.VISIBLE
if (box.indexOfChild(h.clip) != order) {
box.removeView(h.clip)
box.addView(h.clip, order)
}
order++
shown.add(h)
}
for (h in held) if (h !in shown) h.clip.visibility = View.GONE
}
/** A finger going down on a view it holds, which gets it: the content hears of it. */
private fun heldTakes(e: MotionEvent): Boolean {
val x = e.x.toInt()
val y = e.y.toInt()
if (held.asReversed().none { it.takes(x, y) }) return false
if (e.actionMasked == MotionEvent.ACTION_DOWN) Go.send(Event.viewPressed(wid, e.x / density, e.y / density))
return true
}
fun requestFrame() {
if (framePending) return
framePending = true
Choreographer.getInstance().postFrameCallback(frame)
}
override fun close() {
if (framePending) Choreographer.getInstance().removeFrameCallback(frame)
releaseNative()
}
private fun releaseNative() {
if (native != 0L) {
Go.ask(Event.surfaceDestroyed(wid))
MyGoNative.releaseNativeWindow(native)
native = 0
}
}
private val density get() = HostImpl.density.toDouble()
/** The virtual view that stands for the input in focus, to autofill. */
private val autofillNode = 1
fun setTextInput(c: SetTextInputCall) {
val was = input
input = c
tellAutofill(was, c)
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val traits = was.multiline != c.multiline || was.secure != c.secure || was.keyboard != c.keyboard || was.returnKey != c.returnKey ||
was.capitalize != c.capitalize || was.autocorrect != c.autocorrect || was.autofill != c.autofill
when {
c.active && (!was.active || traits || c.serial != was.serial) -> {
surface.requestFocus()
imm.restartInput(surface)
imm.showSoftInput(surface, 0)
}
!c.active && was.active -> {
imm.hideSoftInputFromWindow(surface.windowToken, 0)
imm.restartInput(surface)
}
c.active -> {
if (c.show != was.show) imm.showSoftInput(surface, 0)
if (c.selStart != was.selStart || c.selEnd != was.selEnd || c.markStart != was.markStart || c.markEnd != was.markEnd) {
imm.updateSelection(surface, c.selStart.toInt(), c.selEnd.toInt(), c.markStart.toInt(), c.markEnd.toInt())
}
}
}
}
/** Sends an edit and takes the state after it, which the keyboard goes on to read at once. */
private fun edit(msg: ByteArray) {
val r = Go.ask(msg) ?: return
val st = TextStateReply(r)
val c = input
val changed = st.selStart != c.selStart || st.selEnd != c.selEnd || st.markStart != c.markStart || st.markEnd != c.markEnd
c.text = st.text
c.base = st.base
c.length = st.length
c.selStart = st.selStart
c.selEnd = st.selEnd
c.markStart = st.markStart
c.markEnd = st.markEnd
if (autofillHint(c) != null) {
context.getSystemService(android.view.autofill.AutofillManager::class.java)
?.notifyValueChanged(surface, autofillNode, android.view.autofill.AutofillValue.forText(wholeText(c)))
}
if (changed) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.updateSelection(surface, c.selStart.toInt(), c.selEnd.toInt(), c.markStart.toInt(), c.markEnd.toInt())
}
}
/** The part of the document from a to b, the host's copy holding it or not. */
private fun document(a: Int, b: Int): CharSequence {
val c = input
val lo = a - c.base.toInt()
val hi = b - c.base.toInt()
if (lo >= 0 && hi <= c.text.length && lo <= hi) return c.text.substring(lo, hi)
val r = Go.ask(Event.textRange(wid, a.toLong(), b.toLong())) ?: return ""
return TextRangeReply(r).text
}
/** A mouse's pointer, on a Chromebook or a tablet with one. */
fun setCursor(cursor: String) {
val kind = when (cursor) {
"text" -> PointerIcon.TYPE_TEXT
"pointer" -> PointerIcon.TYPE_HAND
"move" -> PointerIcon.TYPE_ALL_SCROLL
"resizeX" -> PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW
"resizeY" -> PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW
"grab" -> PointerIcon.TYPE_GRAB
"grabbing" -> PointerIcon.TYPE_GRABBING
"crosshair" -> PointerIcon.TYPE_CROSSHAIR
"notAllowed" -> PointerIcon.TYPE_NO_DROP
"none" -> PointerIcon.TYPE_NULL
else -> PointerIcon.TYPE_DEFAULT
}
surface.pointerIcon = PointerIcon.getSystemIcon(context, kind)
}
private var actionMode: ActionMode? = null
/** The system's floating menu of the editing commands asked for. */
fun showMenu(c: ShowMenuCall) {
actionMode?.finish()
val d = density
val at = Rect((c.x * d).toInt(), (c.y * d).toInt(), (c.x * d).toInt() + 1, (c.y * d).toInt() + 1)
actionMode = surface.startActionMode(object : ActionMode.Callback2() {
override fun onCreateActionMode(m: ActionMode, menu: Menu): Boolean {
val labels = mapOf("cut" to android.R.string.cut, "copy" to android.R.string.copy,
"paste" to android.R.string.paste, "selectAll" to android.R.string.selectAll)
c.actions.forEachIndexed { i, name -> labels[name]?.let { menu.add(0, i, i, it) } }
return true
}
override fun onPrepareActionMode(m: ActionMode, menu: Menu) = false
override fun onActionItemClicked(m: ActionMode, item: MenuItem): Boolean {
c.actions.getOrNull(item.itemId)?.let { edit(Event.textCommand(wid, it)) }
m.finish()
return true
}
override fun onDestroyActionMode(m: ActionMode) { actionMode = null }
override fun onGetContentRect(m: ActionMode, v: View, out: Rect) { out.set(at) }
}, ActionMode.TYPE_FLOATING)
}
private var magnifier: Magnifier? = null // API 28
/** The system's magnifier of what is at a point. */
fun showMagnifier(c: ShowMagnifierCall) {
if (android.os.Build.VERSION.SDK_INT < 28) return
val m = magnifier ?: Magnifier.Builder(surface).build().also { magnifier = it }
m.show((c.x * density).toFloat(), (c.y * density).toFloat())
}
fun hideMagnifier() {
if (android.os.Build.VERSION.SDK_INT >= 28) magnifier?.dismiss()
}
fun accessibilityChanged(focus: Long) {
nodes = null
surface.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)
}
private fun tree(): List<Node> {
nodes?.let { return it }
val r = Go.ask(Event.accessibilityTree(wid)) ?: return emptyList()
val n = Node.decode(AccessibilityTreeReply(r).nodes)
nodes = n
return n
}
private inner class Surface(context: Context) : SurfaceView(context), SurfaceHolder.Callback {
init {
holder.addCallback(this)
isFocusable = true
isFocusableInTouchMode = true
}
override fun surfaceCreated(h: SurfaceHolder) {
native = MyGoNative.nativeWindow(h.surface)
val hz = display?.supportedModes?.maxOfOrNull { it.refreshRate }?.toDouble() ?: display?.refreshRate?.toDouble() ?: 60.0
Go.send(Event.surfaceChanged(wid, native, width / density, height / density, density, hz))
}
override fun surfaceChanged(h: SurfaceHolder, format: Int, w: Int, ht: Int) {
preferFastest(h)
reportSize()
requestFrame()
}
/** Asks the display for its fastest refresh, which Choreographer then gives. */
private fun preferFastest(h: SurfaceHolder) {
if (android.os.Build.VERSION.SDK_INT < 30) return
val modes = display?.supportedModes ?: return
val hz = modes.maxOfOrNull { it.refreshRate } ?: return
runCatching { h.surface.setFrameRate(hz, android.view.Surface.FRAME_RATE_COMPATIBILITY_DEFAULT) }
}
// A mouse's pointer hovers.
override fun onHoverEvent(e: MotionEvent): Boolean {
val d = density
val phase = if (e.actionMasked == MotionEvent.ACTION_HOVER_EXIT) "cancel" else "move"
Go.send(Event.touch(wid, 0, phase, "mouse", e.x / d, e.y / d, 0.0, 0, e.eventTime / 1000.0))
return true
}
override fun surfaceDestroyed(h: SurfaceHolder) = releaseNative()
// A finger on a view it holds passes through to it, under this view.
override fun dispatchTouchEvent(e: MotionEvent): Boolean {
if (e.actionMasked == MotionEvent.ACTION_DOWN && heldTakes(e)) return false
return super.dispatchTouchEvent(e)
}
override fun onTouchEvent(e: MotionEvent): Boolean {
val d = density
fun send(i: Int, phase: String) {
val kind = when (e.getToolType(i)) {
MotionEvent.TOOL_TYPE_MOUSE -> "mouse"
MotionEvent.TOOL_TYPE_STYLUS -> "pen"
else -> "touch"
}
Go.send(Event.touch(wid, e.getPointerId(i).toLong(), phase, kind, e.getX(i) / d, e.getY(i) / d,
e.getPressure(i).toDouble(), e.buttonState.toLong().coerceAtLeast(1), e.eventTime / 1000.0))
}
when (e.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> send(e.actionIndex, "down")
MotionEvent.ACTION_MOVE -> for (i in 0 until e.pointerCount) send(i, "move")
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> send(e.actionIndex, "up")
MotionEvent.ACTION_CANCEL -> for (i in 0 until e.pointerCount) send(i, "cancel")
}
return true
}
override fun onGenericMotionEvent(e: MotionEvent): Boolean {
if (e.isFromSource(InputDevice.SOURCE_CLASS_POINTER) && e.actionMasked == MotionEvent.ACTION_SCROLL) {
val d = density
val line = 48.0
Go.send(Event.scroll(wid, e.x / d, e.y / d, -e.getAxisValue(MotionEvent.AXIS_HSCROLL) * line,
-e.getAxisValue(MotionEvent.AXIS_VSCROLL) * line, false, ""))
return true
}
return super.onGenericMotionEvent(e)
}
private fun key(code: Int, e: KeyEvent, down: Boolean): Boolean {
val name = keyNames[code] ?: e.unicodeChar.takeIf { it > 0 }?.let { String(Character.toChars(it)) } ?: return false
var mods = 0L
if (e.isShiftPressed) mods = mods or 1
if (e.isCtrlPressed) mods = mods or 2
if (e.isAltPressed) mods = mods or 4
if (e.isMetaPressed) mods = mods or 8
val text = if (e.unicodeChar > 0) String(Character.toChars(e.unicodeChar)) else ""
val r = Go.ask(Event.key(wid, down, name, text, mods, e.repeatCount > 0)) ?: return false
val handled = KeyReply(r).handled
// Keys typing text type it, which the content takes as text.
if (!handled && down && editing && text.isNotEmpty() && keyNames[code] == null) {
edit(Event.textReplace(wid, false, 0, 0, text))
return true
}
return handled
}
override fun onKeyDown(code: Int, e: KeyEvent) = key(code, e, true) || super.onKeyDown(code, e)
override fun onKeyUp(code: Int, e: KeyEvent) = key(code, e, false) || super.onKeyUp(code, e)
override fun onCheckIsTextEditor() = editing
override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
if (!editing) return null
val c = input
info.inputType = inputType(c)
info.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN or when (c.returnKey) {
"go" -> EditorInfo.IME_ACTION_GO
"next" -> EditorInfo.IME_ACTION_NEXT
"search" -> EditorInfo.IME_ACTION_SEARCH
"send" -> EditorInfo.IME_ACTION_SEND
"done" -> EditorInfo.IME_ACTION_DONE
else -> if (c.multiline) EditorInfo.IME_ACTION_NONE else EditorInfo.IME_ACTION_DONE
}
if (c.multiline && c.returnKey.isEmpty()) info.imeOptions = info.imeOptions or EditorInfo.IME_FLAG_NO_ENTER_ACTION
info.initialSelStart = c.selStart.toInt()
info.initialSelEnd = c.selEnd.toInt()
info.packageName = context.packageName
return Connection(this)
}
override fun getAccessibilityNodeProvider(): AccessibilityNodeProvider = Provider()
// Autofill: to the system, the input in focus is the one field of a
// form of its own. The window's surface draws it: only this says what
// it is, so that saved passwords and codes from SMS reach it.
override fun onProvideAutofillVirtualStructure(s: android.view.ViewStructure, flags: Int) {
s.setClassName(javaClass.name)
val c = input
val hint = autofillHint(c)
if (!editing || hint == null) return
val child = s.newChild(s.addChildCount(1))
child.setAutofillId(s.autofillId!!, autofillNode)
child.setClassName("android.widget.EditText")
child.setAutofillType(AUTOFILL_TYPE_TEXT)
child.setAutofillHints(arrayOf(hint))
child.setInputType(inputType(c))
child.setDataIsSensitive(c.secure)
child.setVisibility(VISIBLE)
child.setFocused(true)
child.setFocusable(true)
child.setEnabled(true)
child.setDimens((c.x * density).toInt(), (c.y * density).toInt(), 0, 0, (c.width * density).toInt(), (c.height * density).toInt())
child.setAutofillValue(android.view.autofill.AutofillValue.forText(wholeText(c)))
}
override fun autofill(values: android.util.SparseArray<android.view.autofill.AutofillValue>) {
val v = values.get(autofillNode) ?: return
if (!editing || !v.isText) return
edit(Event.textReplace(wid, true, 0, input.length, v.textValue.toString()))
}
}
/** The hint of Android's autofill for an input's traits, null for none. */
private fun autofillHint(c: SetTextInputCall): String? = when (c.autofill) {
"username" -> View.AUTOFILL_HINT_USERNAME
"password", "newPassword" -> View.AUTOFILL_HINT_PASSWORD
"oneTimeCode" -> "smsOTPCode" // androidx.autofill's HintConstants
"email" -> View.AUTOFILL_HINT_EMAIL_ADDRESS
"name" -> View.AUTOFILL_HINT_NAME
"phone" -> View.AUTOFILL_HINT_PHONE
"address" -> View.AUTOFILL_HINT_POSTAL_ADDRESS
"postalCode" -> View.AUTOFILL_HINT_POSTAL_CODE
"creditCard" -> View.AUTOFILL_HINT_CREDIT_CARD_NUMBER
else -> null
}
/** The input's whole text, which the host's copy may hold only part of. */
private fun wholeText(c: SetTextInputCall): String =
if (c.base == 0L && c.text.length.toLong() == c.length) c.text else document(0, c.length.toInt()).toString()
/** Tells the system's autofill what the input did, for those it knows of. */
private fun tellAutofill(was: SetTextInputCall, c: SetTextInputCall) {
val am = context.getSystemService(android.view.autofill.AutofillManager::class.java) ?: return
val had = was.active && autofillHint(was) != null
val has = c.active && autofillHint(c) != null
val another = c.serial != was.serial || !was.active
if (had && (!c.active || another)) {
am.notifyViewExited(surface, autofillNode)
// A form sent or left: the system may offer to save what it holds.
if (was.secure && was.length > 0 && !has) am.commit()
}
if (has && (!had || another)) {
val at = IntArray(2)
surface.getLocationOnScreen(at)
val x = at[0] + (c.x * density).toInt()
val y = at[1] + (c.y * density).toInt()
val r = Rect(x, y, x + (c.width * density).toInt(), y + (c.height * density).toInt())
surface.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES
am.notifyViewEntered(surface, autofillNode, r)
}
}
/** The inputType of EditorInfo for an input's traits. */
private fun inputType(c: SetTextInputCall): Int {
var t = when (c.keyboard) {
"number" -> InputType.TYPE_CLASS_NUMBER
"decimal" -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
"phone" -> InputType.TYPE_CLASS_PHONE
"email" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
"url" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
else -> InputType.TYPE_CLASS_TEXT
}
if (c.secure) {
t = if (t and InputType.TYPE_MASK_CLASS == InputType.TYPE_CLASS_NUMBER) {
InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
} else {
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
}
return t
}
if (t and InputType.TYPE_MASK_CLASS != InputType.TYPE_CLASS_TEXT) return t
if (c.multiline) t = t or InputType.TYPE_TEXT_FLAG_MULTI_LINE
val plain = c.keyboard.isEmpty() || c.keyboard == "search"
t = t or when (c.capitalize) {
"characters" -> InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
"words" -> InputType.TYPE_TEXT_FLAG_CAP_WORDS
"sentences" -> InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
"none" -> 0
else -> if (plain) InputType.TYPE_TEXT_FLAG_CAP_SENTENCES else 0
}
t = t or when (c.autocorrect) {
"off" -> InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
"on" -> InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
else -> if (plain) InputType.TYPE_TEXT_FLAG_AUTO_CORRECT else 0
}
return t
}
/** The soft keyboard's edits, to Go. */
private inner class Connection(v: View) : BaseInputConnection(v, false) {
override fun commitText(t: CharSequence, newCursorPosition: Int): Boolean {
edit(Event.textReplace(wid, false, 0, 0, t.toString()))
placeCursor(t.length, newCursorPosition)
return true
}
override fun commitCompletion(c: android.view.inputmethod.CompletionInfo): Boolean {
c.text?.let { edit(Event.textReplace(wid, false, 0, 0, it.toString())) }
return true
}
override fun commitCorrection(c: android.view.inputmethod.CorrectionInfo): Boolean {
val at = c.offset.toLong()
edit(Event.textReplace(wid, true, at, at + c.oldText.length, c.newText.toString()))
return true
}
override fun setComposingText(t: CharSequence, newCursorPosition: Int): Boolean {
// The selection in the text composed, from the cursor Android
// places relative to it: past it, the common case, or before.
val n = t.length.toLong()
val at = if (newCursorPosition > 0) n else 0L
edit(Event.textMark(wid, false, 0, 0, t.toString(), at, at))
return true
}
override fun setComposingRegion(start: Int, end: Int): Boolean {
val a = minOf(start, end).coerceAtLeast(0)
val b = maxOf(start, end).coerceAtMost(input.length.toInt())
val text = document(a, b).toString()
val n = text.length.toLong()
edit(Event.textMark(wid, true, a.toLong(), b.toLong(), text, n, n))
return true
}
override fun finishComposingText(): Boolean {
edit(Event.textUnmark(wid))
return true
}
override fun deleteSurroundingText(before: Int, after: Int): Boolean {
edit(Event.textDelete(wid, before.toLong(), after.toLong()))
return true
}
override fun deleteSurroundingTextInCodePoints(before: Int, after: Int): Boolean {
// Units of the text around the selection.
val a = minOf(input.selStart, input.selEnd).toInt()
val b = maxOf(input.selStart, input.selEnd).toInt()
val head = document(maxOf(0, a - 2 * before), a).toString()
val tail = document(b, minOf(input.length.toInt(), b + 2 * after)).toString()
val units = head.length - head.offsetByCodePoints(head.length, -minOf(before, head.codePointCount(0, head.length)))
val unitsAfter = tail.offsetByCodePoints(0, minOf(after, tail.codePointCount(0, tail.length)))
edit(Event.textDelete(wid, units.toLong(), unitsAfter.toLong()))
return true
}
override fun setSelection(start: Int, end: Int): Boolean {
edit(Event.textSelect(wid, start.toLong(), end.toLong()))
return true
}
private fun placeCursor(committed: Int, newCursorPosition: Int) {
// Past the text, as nearly all input methods ask, is where the
// insertion leaves it.
if (newCursorPosition == 1) return
val end = input.selEnd.toInt()
val at = if (newCursorPosition > 0) end + newCursorPosition - 1 else end - committed + newCursorPosition
val p = at.coerceIn(0, input.length.toInt()).toLong()
edit(Event.textSelect(wid, p, p))
}
override fun sendKeyEvent(e: KeyEvent): Boolean {
if (e.action == KeyEvent.ACTION_DOWN) when (e.keyCode) {
KeyEvent.KEYCODE_DEL -> edit(Event.textCommand(wid, "deleteBackward"))
KeyEvent.KEYCODE_FORWARD_DEL -> edit(Event.textCommand(wid, "deleteForward"))
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> edit(Event.textCommand(wid, "newline"))
KeyEvent.KEYCODE_TAB -> edit(Event.textCommand(wid, "tab"))
KeyEvent.KEYCODE_DPAD_LEFT -> edit(Event.textCommand(wid, "left"))
KeyEvent.KEYCODE_DPAD_RIGHT -> edit(Event.textCommand(wid, "right"))
KeyEvent.KEYCODE_DPAD_UP -> edit(Event.textCommand(wid, "up"))
KeyEvent.KEYCODE_DPAD_DOWN -> edit(Event.textCommand(wid, "down"))
else -> if (e.unicodeChar > 0) edit(Event.textReplace(wid, false, 0, 0, String(Character.toChars(e.unicodeChar))))
}
return true
}
override fun performEditorAction(action: Int): Boolean {
edit(Event.textCommand(wid, "newline"))
return true
}
override fun performContextMenuAction(action: Int): Boolean {
when (action) {
android.R.id.selectAll -> edit(Event.textCommand(wid, "selectAll"))
android.R.id.cut -> edit(Event.textCommand(wid, "cut"))
android.R.id.copy -> edit(Event.textCommand(wid, "copy"))
android.R.id.paste -> edit(Event.textCommand(wid, "paste"))
else -> return false
}
return true
}
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence {
val a = minOf(input.selStart, input.selEnd).toInt()
return document(maxOf(0, a - n), a)
}
override fun getTextAfterCursor(n: Int, flags: Int): CharSequence {
val b = maxOf(input.selStart, input.selEnd).toInt()
return document(b, minOf(input.length.toInt(), b + n))
}
override fun getSelectedText(flags: Int): CharSequence? {
val a = minOf(input.selStart, input.selEnd).toInt()
val b = maxOf(input.selStart, input.selEnd).toInt()
return if (a == b) null else document(a, b)
}
override fun getExtractedText(req: android.view.inputmethod.ExtractedTextRequest?, flags: Int): android.view.inputmethod.ExtractedText {
val c = input
return android.view.inputmethod.ExtractedText().apply {
text = c.text
startOffset = c.base.toInt()
selectionStart = c.selStart.toInt() - c.base.toInt()
selectionEnd = c.selEnd.toInt() - c.base.toInt()
}
}
override fun getCursorCapsMode(reqModes: Int): Int {
val a = minOf(input.selStart, input.selEnd).toInt()
return android.text.TextUtils.getCapsMode(document(maxOf(0, a - 64), a).toString(), minOf(a, 64), reqModes)
}
}
/** The element TalkBack's cursor is on. */
private var accessFocus = View.NO_ID
private fun sendVirtual(id: Int, type: Int) {
val e = AccessibilityEvent(type)
e.packageName = context.packageName
e.setSource(surface, id)
(surface.parent as? android.view.ViewGroup)?.requestSendAccessibilityEvent(surface, e)
}
/** TalkBack's view of the elements of native UI, as virtual views. */
private inner class Provider : AccessibilityNodeProvider() {
override fun createAccessibilityNodeInfo(virtualId: Int): AccessibilityNodeInfo? {
val nodes = tree()
if (virtualId == View.NO_ID) {
val info = AccessibilityNodeInfo.obtain(surface)
surface.onInitializeAccessibilityNodeInfo(info)
for (n in nodes) info.addChild(surface, n.id.toInt())
return info
}
val n = nodes.firstOrNull { it.id.toInt() == virtualId } ?: return null
val info = AccessibilityNodeInfo.obtain(surface, virtualId)
info.setParent(surface)
info.packageName = context.packageName
info.className = n.className
if (n.role == 9L) {
// A text field: its text, under its name's hint, as EditText.
info.isEditable = true
info.text = n.value.ifEmpty { null }
info.hintText = n.label
info.isShowingHintText = n.value.isEmpty()
info.isPassword = n.states and 128 != 0L
} else {
info.text = n.label.ifEmpty { null }
if (n.value.isNotEmpty()) info.stateDescription = n.value
}
if (n.hint.isNotEmpty()) info.tooltipText = n.hint
val d = density
val box = Rect((n.x * d).toInt(), (n.y * d).toInt(), ((n.x + n.w) * d).toInt(), ((n.y + n.h) * d).toInt())
val loc = IntArray(2)
surface.getLocationOnScreen(loc)
box.offset(loc[0], loc[1])
info.setBoundsInScreen(box)
info.isEnabled = n.states and 2 == 0L
info.isChecked = n.states and 4 != 0L
info.isCheckable = n.role in longArrayOf(4, 5, 6, 31)
info.isSelected = n.states and 16 != 0L
info.isHeading = n.role == 43L
info.isVisibleToUser = true
info.isFocusable = true
info.isAccessibilityFocused = accessFocus == virtualId
info.addAction(if (accessFocus == virtualId) AccessibilityNodeInfo.AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS
else AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS)
if (n.actions and 1 != 0L) {
info.isClickable = true
info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK)
}
if (n.actions and 4 != 0L) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD)
if (n.actions and 8 != 0L) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD)
return info
}
override fun performAction(virtualId: Int, action: Int, args: Bundle?): Boolean {
val name = when (action) {
AccessibilityNodeInfo.ACTION_CLICK -> "press"
AccessibilityNodeInfo.ACTION_SCROLL_FORWARD -> "increment"
AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD -> "decrement"
AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS -> {
if (accessFocus != virtualId) {
val old = accessFocus
accessFocus = virtualId
if (old != View.NO_ID) sendVirtual(old, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)
sendVirtual(virtualId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED)
}
return true
}
AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS -> {
if (accessFocus == virtualId) {
accessFocus = View.NO_ID
sendVirtual(virtualId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)
}
return true
}
else -> return false
}
val r = Go.ask(Event.accessibilityAction(wid, virtualId.toLong(), name)) ?: return false
return AccessibilityActionReply(r).handled
}
}
companion object {
private val keyNames = mapOf(
KeyEvent.KEYCODE_ENTER to "Enter", KeyEvent.KEYCODE_ESCAPE to "Escape", KeyEvent.KEYCODE_DEL to "Backspace",
KeyEvent.KEYCODE_TAB to "Tab", KeyEvent.KEYCODE_SPACE to "Space", KeyEvent.KEYCODE_FORWARD_DEL to "Delete",
KeyEvent.KEYCODE_MOVE_HOME to "Home", KeyEvent.KEYCODE_MOVE_END to "End", KeyEvent.KEYCODE_PAGE_UP to "PageUp",
KeyEvent.KEYCODE_PAGE_DOWN to "PageDown", KeyEvent.KEYCODE_DPAD_LEFT to "ArrowLeft",
KeyEvent.KEYCODE_DPAD_RIGHT to "ArrowRight", KeyEvent.KEYCODE_DPAD_UP to "ArrowUp", KeyEvent.KEYCODE_DPAD_DOWN to "ArrowDown",
)
}
}
/** An element of native UI, as Go encodes it (AccessibilityTree). */
class Node(
val id: Long, val parent: Long, val role: Long, val label: String, val value: String, val hint: String,
val x: Double, val y: Double, val w: Double, val h: Double, val states: Long, val actions: Long,
) {
val className: String
get() = when (role) {
2L, 31L, 40L, 18L -> "android.widget.Button"
4L -> "android.widget.CheckBox"
5L -> "android.widget.RadioButton"
6L -> "android.widget.Switch"
7L -> "android.widget.SeekBar"
8L -> "android.widget.ProgressBar"
9L -> "android.widget.EditText"
10L -> "android.widget.ImageView"
else -> "android.view.View"
}
companion object {
fun decode(b: ByteArray): List<Node> {
val r = WireReader(b)
val out = ArrayList<Node>()
while (true) {
val n = Node(r.int(), r.int(), r.int(), r.string(), r.string(), r.string(),
r.float(), r.float(), r.float(), r.float(), r.int(), r.int())
r.int() // the level
if (n.id == 0L) break
// Groups without a name hold others, which TalkBack reads.
if (n.role == 0L && n.label.isEmpty() && n.value.isEmpty()) continue
out.add(n)
}
return out
}
}
}
@@ -0,0 +1,182 @@
package dev.mygo
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.os.Build
import java.io.File
import java.nio.ByteBuffer
import kotlin.math.ceil
import kotlin.math.floor
/**
* Text of native UI, measured and drawn as a TextView measures and draws
* it: Minikin lays it out, Skia draws it. Go breaks lines itself and asks
* how wide words are (getTextRunAdvances) and what a cluster looks like
* (drawText).
*/
object Text {
private val registered = HashMap<String, Typeface>()
private val faces = HashMap<String, Typeface>()
private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)
private val bounds = Rect()
private var bitmap: Bitmap? = null
/** The typeface of a CSS-like list of families, at a weight. */
private fun typeface(families: String, weight: Long, italic: Boolean): Typeface {
val key = "$families|$weight|$italic"
faces[key]?.let { return it }
var base: Typeface? = null
for (raw in families.split(',')) {
val f = raw.trim().trim('"', '\'')
base = registered[f] ?: when (f.lowercase()) {
"", "system-ui", "sans-serif", "ui-sans-serif", "-apple-system" -> Typeface.SANS_SERIF
"serif", "ui-serif" -> Typeface.SERIF
"monospace", "ui-monospace" -> Typeface.MONOSPACE
else -> Typeface.create(f, Typeface.NORMAL).takeIf { it != Typeface.DEFAULT }
}
if (base != null) break
}
val face = if (Build.VERSION.SDK_INT >= 28) {
Typeface.create(base ?: Typeface.SANS_SERIF, weight.toInt().coerceIn(1, 1000), italic)
} else {
Typeface.create(base ?: Typeface.SANS_SERIF, (if (weight >= 600) Typeface.BOLD else 0) or (if (italic) Typeface.ITALIC else 0))
}
if (faces.size > 256) faces.clear()
faces[key] = face
return face
}
private fun set(family: String, size: Double, weight: Long, italic: Boolean, noKern: Boolean = false): Paint {
paint.typeface = typeface(family, weight, italic)
paint.textSize = size.toFloat()
// Go draws clusters alone, which ligatures would join: "fl" would
// take the advance of both, and draw as an f before a gap.
paint.fontFeatureSettings = if (noKern) "'liga' 0, 'clig' 0, 'kern' 0" else "'liga' 0, 'clig' 0"
paint.color = Color.WHITE
return paint
}
@Synchronized
fun metrics(c: TextMetricsCall): TextMetricsReply {
val p = set(c.family, c.size, c.weight, c.italic)
val m = p.fontMetrics
val r = TextMetricsReply()
r.ascent = -m.ascent.toDouble()
r.descent = m.descent.toDouble()
p.getTextBounds("x", 0, 1, bounds)
r.xHeight = -bounds.top.toDouble()
if (Build.VERSION.SDK_INT >= 29) {
r.underlinePosition = p.underlinePosition.toDouble()
r.underlineThickness = p.underlineThickness.toDouble()
r.strikePosition = -p.strikeThruPosition.toDouble()
} else {
r.underlinePosition = c.size / 10
r.underlineThickness = maxOf(c.size / 14, 1.0)
r.strikePosition = r.xHeight / 2
}
return r
}
@Synchronized
fun measure(c: MeasureTextCall): MeasureTextReply {
val p = set(c.family, c.size, c.weight, c.italic, c.noKern)
val r = MeasureTextReply()
r.widths = DoubleArray(c.texts.size) { i ->
val t = c.texts[i]
p.getRunAdvance(t, 0, t.length, 0, t.length, false, t.length).toDouble()
}
return r
}
@Synchronized
fun advances(c: TextAdvancesCall): TextAdvancesReply {
val p = set(c.family, c.size, c.weight, c.italic, c.noKern)
val chars = c.text.toCharArray()
val out = FloatArray(chars.size)
p.getTextRunAdvances(chars, 0, chars.size, 0, chars.size, c.rtl, out, 0)
val r = TextAdvancesReply()
r.advances = DoubleArray(out.size) { out[it].toDouble() }
return r
}
@Synchronized
fun draw(c: DrawTextCall): DrawTextReply {
val r = DrawTextReply()
if (c.text.isBlank()) return r
// The font at the size text was measured at, the canvas scaled, as
// the measurements were made.
val p = set(c.family, c.size, c.weight, c.italic)
p.getTextBounds(c.text, 0, c.text.length, bounds)
val s = c.scale
val pad = 2
val left = floor(bounds.left * s + c.dx).toInt() - pad
val right = ceil(bounds.right * s + c.dx).toInt() + pad
val top = floor(bounds.top * s).toInt() - pad
val bottom = ceil(bounds.bottom * s).toInt() + pad
val w = right - left
val h = bottom - top
if (w <= 2 * pad || h <= 2 * pad || w > 2048 || h > 2048) return r
var bm = bitmap
if (bm == null || bm.width < w || bm.height < h) {
bm?.recycle()
bm = Bitmap.createBitmap(maxOf(w, bm?.width ?: 0, 64), maxOf(h, bm?.height ?: 0, 64), Bitmap.Config.ARGB_8888)
bitmap = bm
}
bm!!.eraseColor(Color.TRANSPARENT)
val canvas = Canvas(bm)
canvas.translate((c.dx - left).toFloat(), (-top).toFloat())
canvas.scale(s.toFloat(), s.toFloat())
canvas.drawText(c.text, 0f, 0f, p)
val buf = ByteBuffer.allocate(bm.byteCount)
bm.copyPixelsToBuffer(buf)
val px = buf.array()
val stride = bm.width * 4
// White text is as covered as it is opaque; other colors are an
// emoji's.
var color = false
loop@ for (y in 0 until h) for (x in 0 until w) {
val i = y * stride + x * 4
val a = px[i + 3].toInt() and 0xff
if (a > 32) {
val far = { v: Int -> v < a - 24 }
if (far(px[i].toInt() and 0xff) || far(px[i + 1].toInt() and 0xff) || far(px[i + 2].toInt() and 0xff)) {
color = true
break@loop
}
}
}
r.left = left.toLong()
r.top = top.toLong()
r.width = w.toLong()
r.height = h.toLong()
r.color = color
r.pixels = if (color) {
ByteArray(w * h * 4).also { out -> for (y in 0 until h) System.arraycopy(px, y * stride, out, y * w * 4, w * 4) }
} else {
ByteArray(w * h) { k -> px[(k / w) * stride + (k % w) * 4 + 3] }
}
return r
}
@Synchronized
fun register(c: RegisterFontCall): RegisterFontReply {
val r = RegisterFontReply()
try {
val f = File.createTempFile("font", ".ttf", HostImpl.app.cacheDir)
f.writeBytes(c.data)
val face = Typeface.createFromFile(f)
f.delete()
val family = c.family.ifEmpty { "font${registered.size + 1}" }
registered[family] = face
faces.clear()
r.family = family
} catch (e: Exception) {
r.error = "mygo: ${e.message}"
}
return r
}
}
@@ -0,0 +1,499 @@
// Windows showing web pages, in Android's WebView.
package dev.mygo
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.PermissionRequest
import android.webkit.RenderProcessGoneDetail
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.webkit.ScriptHandler
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
class WebWindow(context: Context, c: CreateWindowCall) : HostWindow(context, c.id) {
private val frame = FrameLayout(context)
override val view: View get() = frame
val web = WebView(context)
private val schemes = c.schemes.toSet()
private var scripts = ArrayList<ScriptHandler>()
private var defaultUA = ""
private var suffix = c.userAgentSuffix
private val ui = Handler(Looper.getMainLooper())
init {
val s = web.settings
s.javaScriptEnabled = true
s.domStorageEnabled = true
s.databaseEnabled = true
s.mediaPlaybackRequiresUserGesture = !c.autoplay
s.setSupportMultipleWindows(true)
s.javaScriptCanOpenWindowsAutomatically = true
s.setSupportZoom(c.pinchZoom)
s.builtInZoomControls = c.pinchZoom
s.displayZoomControls = false
defaultUA = s.userAgentString
setUserAgent(c.userAgent)
WebView.setWebContentsDebuggingEnabled(c.inspectable)
web.addJavascriptInterface(Bridge(this), "mygoAndroid")
web.webViewClient = Client()
web.webChromeClient = Chrome()
setScripts(c.scripts, c.scriptFlags)
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
WebViewCompat.addDocumentStartJavaScript(web, Schemes.bodyScript, setOf("*"))
}
// The web view's own background, which the bars around it take,
// until the app gives one.
val dark = context.resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK ==
android.content.res.Configuration.UI_MODE_NIGHT_YES
fill = if (dark) 0xFF121212.toInt() else android.graphics.Color.WHITE
frame.addView(web, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
}
/** Lays the page out inside the system's bars and above the keyboard. */
override fun insetsChanged() {
val c = covered()
val lp = web.layoutParams as FrameLayout.LayoutParams
if (lp.leftMargin != c[1] || lp.topMargin != c[0] || lp.rightMargin != c[3] || lp.bottomMargin != maxOf(c[2], c[4])) {
lp.setMargins(c[1], c[0], c[3], maxOf(c[2], c[4]))
web.layoutParams = lp
}
reportSize()
}
override fun setBackground(argb: Int) {
frame.setBackgroundColor(argb)
web.setBackgroundColor(argb)
}
fun setUserAgent(ua: String) {
var v = ua.ifEmpty { defaultUA }
if (suffix.isNotEmpty()) v += " $suffix"
web.settings.userAgentString = v
}
fun setScripts(sources: List<String>, flags: List<String>) {
for (h in scripts) h.remove()
scripts = ArrayList()
if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) return
for ((i, src) in sources.withIndex()) {
val f = flags.getOrElse(i) { "" }
var js = src
if (f.contains('e')) js = "document.readyState==='loading'?document.addEventListener('DOMContentLoaded',function(){$js},{once:true}):(function(){$js})();"
if (!f.contains('a')) js = "if(window===window.top){$js}"
scripts.add(WebViewCompat.addDocumentStartJavaScript(web, js, setOf("*")))
}
}
fun load(url: String) {
web.loadUrl(url)
}
fun loadHTML(html: String, base: String) {
web.loadDataWithBaseURL(base.ifEmpty { null }, html, "text/html", "utf-8", null)
}
fun callAsync(req: Long, body: String) {
val js = "(function(){var r=$req;try{var F=Object.getPrototypeOf(async function(){}).constructor;" +
"new F(${JSONObject.quote(body)})().then(function(v){mygoAndroid.asyncResult(r,String(v),'')}," +
"function(e){mygoAndroid.asyncResult(r,'',String(e&&e.message||e))})}catch(e){mygoAndroid.asyncResult(r,'',String(e&&e.message||e))}})()"
web.evaluateJavascript(js, null)
}
fun capture(req: Long) {
if (web.width == 0 || web.height == 0) {
Go.send(Event.captured(req, ByteArray(0), "mygo: the page shows nothing"))
return
}
val bmp = Bitmap.createBitmap(web.width, web.height, Bitmap.Config.ARGB_8888)
web.draw(Canvas(bmp))
val out = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
bmp.recycle()
Go.send(Event.captured(req, out.toByteArray(), ""))
}
override fun close() {
web.stopLoading()
web.removeJavascriptInterface("mygoAndroid")
web.destroy()
}
private fun reportState() {
Go.send(Event.pageState(id, web.url ?: "", web.title ?: "", web.progress < 100, web.canGoBack(), web.canGoForward()))
HostImpl.updateBack()
}
/** Whether url is one of the app's schemes, served at https://<scheme>.localhost. */
private fun appHost(url: Uri): Boolean {
val host = url.host ?: return false
if (url.scheme != "https" || !host.endsWith(".localhost")) return false
val rest = host.removeSuffix(".localhost")
return schemes.any { rest == it || rest.endsWith(".$it") }
}
private class Bridge(val w: WebWindow) {
@JavascriptInterface
fun postMessage(text: String) = Go.send(Event.message(w.id, text))
@JavascriptInterface
fun asyncResult(req: Long, result: String, error: String) = Go.send(Event.asyncResult(req, result, error))
/** The body of a request to the app's schemes, which Android does not give shouldInterceptRequest. */
@JavascriptInterface
fun putBody(id: String, base64: String) = Schemes.putBody(id, base64)
}
private inner class Client : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, r: WebResourceRequest): Boolean {
val url = r.url
val scheme = url.scheme?.lowercase()
if (scheme != "http" && scheme != "https" && scheme != "about" && scheme != "data" && scheme != "blob" && scheme != "javascript") {
// mailto:, tel:, other apps' links.
try {
(HostImpl.activity ?: context).startActivity(Intent(Intent.ACTION_VIEW, url))
} catch (_: Exception) {
}
return true
}
if (!r.isForMainFrame) return false
val reply = Go.ask(Event.willNavigate(id, url.toString(), true, r.hasGesture(), r.isRedirect, false))
return reply != null && !WillNavigateReply(reply).allow
}
// Android's web view starts a page as it commits it: the page's
// scripts run after, and the core trusts them by the committed URL.
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
Go.send(Event.navigationStarted(id, url))
Go.send(Event.navigationCommitted(id, url))
reportState()
}
override fun onPageCommitVisible(view: WebView, url: String) {
HostImpl.drew = true
}
override fun onPageFinished(view: WebView, url: String) {
reportState()
Go.send(Event.loadFinished(id))
}
override fun doUpdateVisitedHistory(view: WebView, url: String, isReload: Boolean) = reportState()
override fun onReceivedError(view: WebView, r: WebResourceRequest, e: WebResourceError) {
if (r.isForMainFrame) Go.send(Event.loadFailed(id, r.url.toString(), e.errorCode.toLong(), e.description.toString()))
}
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
Go.send(Event.processGone(id, if (detail.didCrash()) "crashed" else "killed"))
return true
}
override fun shouldInterceptRequest(view: WebView, r: WebResourceRequest): WebResourceResponse? {
if (!appHost(r.url)) return null
return Schemes.request(id, r)
}
}
private inner class Chrome : WebChromeClient() {
override fun onReceivedTitle(view: WebView, title: String?) = reportState()
// The page's console, in the app's log, as the inspector shows it.
override fun onConsoleMessage(m: android.webkit.ConsoleMessage): Boolean {
val level = when (m.messageLevel()) {
android.webkit.ConsoleMessage.MessageLevel.ERROR -> android.util.Log.ERROR
android.webkit.ConsoleMessage.MessageLevel.WARNING -> android.util.Log.WARN
else -> android.util.Log.INFO
}
android.util.Log.println(level, "mygo", "console: ${m.message()} (${m.sourceId()}:${m.lineNumber()})")
return true
}
override fun onCreateWindow(view: WebView, dialog: Boolean, gesture: Boolean, msg: Message): Boolean {
// The page's new window: its URL comes with the first load of a
// web view made for it, which the app's window then takes.
val probe = WebView(view.context)
probe.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(v: WebView, r: WebResourceRequest): Boolean {
val url = r.url.toString()
val reply = Go.ask(Event.newWindow(id, url, gesture))
if (reply == null || !NewWindowReply(reply).handled) {
if (gesture) try {
(HostImpl.activity ?: context).startActivity(Intent(Intent.ACTION_VIEW, r.url))
} catch (_: Exception) {
}
}
v.destroy()
return true
}
}
(msg.obj as WebView.WebViewTransport).webView = probe
msg.sendToTarget()
return true
}
override fun onCloseWindow(window: WebView) {
Go.send(Event.closedByPage(id))
}
override fun onPermissionRequest(request: PermissionRequest) {
val kinds = request.resources.mapNotNull {
when (it) {
PermissionRequest.RESOURCE_VIDEO_CAPTURE -> "camera"
PermissionRequest.RESOURCE_AUDIO_CAPTURE -> "microphone"
else -> null
}
}
val reply = Go.ask(Event.permissionRequested(id, kinds, request.origin.toString()))
if (reply == null || !PermissionRequestedReply(reply).allow) {
request.deny()
return
}
// The system's permissions too, which the app's manifest declares.
val need = kinds.map { if (it == "camera") Manifest.permission.CAMERA else Manifest.permission.RECORD_AUDIO }
.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
val a = HostImpl.activity
if (need.isEmpty() || a == null) {
if (need.isEmpty()) request.grant(request.resources) else request.deny()
return
}
pendingPermission = request
a.requestPermissions(need.toTypedArray(), ASK_MEDIA)
}
// navigator.geolocation: the app's handler says, then the system's
// permission, which the app's manifest declares.
override fun onGeolocationPermissionsShowPrompt(origin: String, callback: android.webkit.GeolocationPermissions.Callback) {
val reply = Go.ask(Event.permissionRequested(id, listOf("geolocation"), origin))
if (reply == null || !PermissionRequestedReply(reply).allow) {
callback.invoke(origin, false, false)
return
}
PluginHost.requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)) {
callback.invoke(origin, it, false)
}
}
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
val a = HostImpl.activity ?: return false
fileCallback?.onReceiveValue(null)
fileCallback = callback
return try {
@Suppress("DEPRECATION")
a.startActivityForResult(params.createIntent().putExtra(Intent.EXTRA_ALLOW_MULTIPLE, params.mode == FileChooserParams.MODE_OPEN_MULTIPLE), CHOOSE_FILE)
true
} catch (e: Exception) {
fileCallback = null
false
}
}
}
companion object {
private const val CHOOSE_FILE = 0x6d7b
private const val ASK_MEDIA = 0x6d7c
private var fileCallback: ValueCallback<Array<Uri>>? = null
private var pendingPermission: PermissionRequest? = null
fun activityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode != CHOOSE_FILE) return
fileCallback?.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data))
fileCallback = null
}
fun permissionsResult(requestCode: Int, results: IntArray) {
if (requestCode != ASK_MEDIA) return
val r = pendingPermission ?: return
pendingPermission = null
if (results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED }) r.grant(r.resources) else r.deny()
}
}
}
/**
* The app's schemes: Android's web view loads none of its own, so they
* are served at https://<scheme>.localhost, whose requests go to Go
* (shouldInterceptRequest, on a thread of the web view's), which answers
* with SchemeRespond, SchemeData and SchemeFinish. Android gives no body
* of a request: fetch and XMLHttpRequest put theirs aside (bodyScript).
*/
object Schemes {
private val next = AtomicLong()
private val pending = java.util.concurrent.ConcurrentHashMap<Long, Pending>()
private val bodies = java.util.concurrent.ConcurrentHashMap<String, ByteArray>()
private const val BODY_HEADER = "X-MyGo-Body"
fun putBody(id: String, base64: String) {
if (bodies.size > 64) bodies.clear() // bodies of requests that never came
bodies[id] = android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)
}
/**
* Puts the bodies of fetch's and XMLHttpRequest's requests to the app's
* schemes (https URLs of the hosts under localhost) aside through putBody, and has the
* requests name them in a header, which request takes them back by.
*/
val bodyScript = """
(() => {
if (!window.mygoAndroid || window.__mygoBodies) return;
window.__mygoBodies = true;
const app = (u) => { try { const x = new URL(u, location.href); return x.protocol === 'https:' && x.hostname.endsWith('.localhost'); } catch (e) { return false; } };
const put = (buf) => {
const b = new Uint8Array(buf);
let s = '';
for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode.apply(null, b.subarray(i, i + 0x8000));
const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
window.mygoAndroid.putBody(id, btoa(s));
return id;
};
const fetch0 = window.fetch;
window.fetch = async function (input, init) {
const req = new Request(input, init);
if (!app(req.url) || req.method === 'GET' || req.method === 'HEAD' || req.body === null) return fetch0.call(this, input, init);
const headers = new Headers(req.headers);
headers.set('$BODY_HEADER', put(await req.arrayBuffer()));
return fetch0.call(this, req.url, { method: req.method, headers, credentials: req.credentials, cache: req.cache,
redirect: req.redirect, referrer: req.referrer, signal: req.signal, mode: req.mode });
};
const open0 = XMLHttpRequest.prototype.open, send0 = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url, async) {
this.__mygo = { method: String(method).toUpperCase(), url: String(url), async: async !== false };
return open0.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function (body) {
const m = this.__mygo;
if (!m || !m.async || body == null || m.method === 'GET' || m.method === 'HEAD' || !app(m.url)) return send0.call(this, body);
const r = new Response(body), type = r.headers.get('content-type');
r.arrayBuffer().then((buf) => {
if (type) try { this.setRequestHeader('Content-Type', type); } catch (e) {}
this.setRequestHeader('$BODY_HEADER', put(buf));
send0.call(this);
});
};
})();
"""
private class Pending {
val responded = CountDownLatch(1)
var status = 200
var header = HashMap<String, String>()
val body = BodyStream()
}
fun request(window: Long, r: WebResourceRequest): WebResourceResponse {
val req = next.incrementAndGet()
val p = Pending()
pending[req] = p
val header = ArrayList<String>()
var body: ByteArray? = null
for ((k, v) in r.requestHeaders) {
if (k.equals(BODY_HEADER, true)) {
body = bodies.remove(v)
continue
}
header.add(k)
header.add(v)
}
Go.send(Event.schemeRequest(window, req, r.method, r.url.toString(), header, body ?: ByteArray(0), body != null))
if (!p.responded.await(60, TimeUnit.SECONDS)) {
pending.remove(req)
Go.send(Event.schemeCancel(req))
return WebResourceResponse("text/plain", "utf-8", 504, "Gateway Timeout", emptyMap(), "".byteInputStream())
}
val type = p.header.entries.firstOrNull { it.key.equals("Content-Type", true) }?.value ?: "application/octet-stream"
val mime = type.substringBefore(';').trim()
val charset = Regex("charset=([^;]+)", RegexOption.IGNORE_CASE).find(type)?.groupValues?.get(1)?.trim()
// A WebResourceResponse takes no redirect.
val status = if (p.status in 300..399) 200 else p.status
return WebResourceResponse(mime, charset, status, reason(status), p.header, p.body)
}
private fun reason(status: Int) = when (status) {
200 -> "OK"; 204 -> "No Content"; 206 -> "Partial Content"; 304 -> "Not Modified"
400 -> "Bad Request"; 403 -> "Forbidden"; 404 -> "Not Found"; 500 -> "Internal Server Error"
else -> "Status $status"
}
fun respond(c: SchemeRespondCall) {
val p = pending[c.req] ?: return
p.status = c.status.toInt()
var i = 0
while (i + 1 < c.header.size) {
val k = c.header[i]
p.header[k] = p.header[k]?.let { it + ", " + c.header[i + 1] } ?: c.header[i + 1]
i += 2
}
p.responded.countDown()
}
fun data(req: Long, data: ByteArray) {
pending[req]?.body?.queue?.put(data)
}
fun finish(req: Long, error: String?) {
val p = pending.remove(req) ?: return
if (p.responded.count > 0) {
p.status = 500
p.responded.countDown()
}
p.body.queue.put(ByteArray(0))
}
/** The body of a response, as Go writes it; an empty piece ends it. */
private class BodyStream : InputStream() {
val queue = LinkedBlockingQueue<ByteArray>()
private var cur = ByteArray(0)
private var at = 0
private var done = false
private fun fill(): Boolean {
while (at >= cur.size) {
if (done) return false
cur = queue.take()
at = 0
if (cur.isEmpty()) {
done = true
return false
}
}
return true
}
override fun read(): Int = if (fill()) cur[at++].toInt() and 0xff else -1
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (len == 0) return 0
if (!fill()) return -1
val n = minOf(len, cur.size - at)
System.arraycopy(cur, at, b, off, n)
at += n
return n
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,5 @@
<paths>
<files-path name="files" path="." />
<cache-path name="cache" path="." />
<external-files-path name="external" path="." />
</paths>
+28
View File
@@ -0,0 +1,28 @@
// MyGo's Android host: the `mygo` library (the bridge to Go, the views,
// the web view, native modules' runtime), `app`, the shell app mygo build
// makes for each app, and the app's native modules' Kotlin.
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "mygo-android"
include(":mygo", ":app")
// The Kotlin of the app's native modules, a Gradle library each, which
// mygo build names (mygoNativeModules: name|directory|the modules it uses,
// by comma).
providers.gradleProperty("mygoNativeModules").orNull?.split(',')?.filter { it.isNotEmpty() }?.forEach {
val (name, dir) = it.split('|')
include(":$name")
project(":$name").projectDir = file(dir)
}
+400 -5
View File
@@ -1,13 +1,407 @@
# OpenChamber 手机客户端(asuka/Go)调研与开发计划
# OpenChamber 手机客户端(Flutter / Dart)开发计划
> 调研对象:asuka(Go + 原生控件)v0.1.1 / main,OpenChamber 2.7.0,opencode v2.2.7
> 调研对象:Flutter 3.50(stable)、OpenChamber 2.7.0、opencode v2.2.7
> 目标:Android 优先的手机客户端,MVP = 输入地址 + 密码连接(可选 http/socks5 代理),浏览并操作现有会话
---
## 0. 结论
## 0.4.5 扫码配对(分支 `flutter`)
**可行,且 asuka 的覆盖度比预期好。** 但真正的风险不在 UI,而在三处:
| 项 | 结果 |
| --- | --- |
| 扫码入口 | 「配对链接」对话框新增「扫码」:全屏相机 + 取景框 + 手电筒;扫到配对链接直接开始配对,不再要求按第二个按钮 |
| 解码 | 用 `camera` 0.12 + `zxing2` 0.2(纯 Dart,不依赖 ML Kit / Google Play 服务)。Android 取 YUV420 的 Y 平面直接作为亮度;BGRA(iOS/部分相机)按绿加权转亮度。解码放在 `compute` isolate,每帧不阻塞 UI,同一时间只解一帧 |
| 取景 | 后置相机优先、480p 预览、覆盖率/圆角遮罩 + 四角标记;非配对二维码提示「这不是 OpenChamber 配对二维码」并继续扫;无相机/权限被拒给出说明与重试 |
| 权限 | AndroidManifest 增加 CAMERA 权限;camera 硬件声明为非必需,没相机的设备仍可安装 |
| 测试 | `test/qr_scan_test.dart`:用 `qr` 生成配对链接二维码,渲染成 Y 平面(含 rowStride 内边距)后由 `decodeQrLuminance` 解出原文;空白帧、过短/非法尺寸返回 null |
| 版本 | **0.4.5(code 405)** |
---
## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 配对链接 | 服务器列表新增「配对链接」:粘贴 `openchamber://connect?v=2&p=…`,解析一次性密钥与候选地址(lan / tunnel / relay,按 priority 先直连后 Relay),用第一个能连上的候选兑换设备 token 并保存 |
| 端到端加密 | 新增 `relay_crypto.dart`:P-256 ECDH + HKDF-SHA256(salt = 握手 nonce,info = `openchamber-relay-v1`)派生两条 AES-256-GCM 方向密钥;帧 = 版本 + 12 字节 IV(4 随机前缀 + 8 字节计数器)+ 密文 + GCM tag,计数器严格递增,失败即关闭。与官方 `packages/ui/src/lib/relay/crypto.ts` 字节兼容 |
| 隧道 | 新增 `relay_tunnel.dart`:连 `wss://…/ws?v=1&role=client&serverId=…`,明文 hello/ready 握手,之后是加密的 mux 帧(HttpRequest/Body/Response/StreamEnd/Abort、WsOpen/Opened/Text/Binary/Close、Ping/Pong)。大消息按 64 KiB 分片与重组,断线不自动重拉(下一次请求重连,SSE 自己的重试循环会恢复) |
| Transport | `Transport.webSocket` 改为返回 `TransportSocket`(直连包装 WebSocket,Relay 用子流);新增 `RelayTransport` 实现同一接口,所有 HTTP/SSE 走隧道。Relay 下的终端 WebSocket 先经隧道 `POST /auth/url-token` 换取短时 token,附到 `oc_url_token` 查询参数 |
| 连接模型 | `Connection` 增加 `relayUrl/serverId/hostKey/grant` 与 `isRelay`;直连字段不变。配对成功的连接与设备 token 一起保存,之后启动/重连直接用 token,不再需要配对链接 |
| 未协商 | 不声明 batch、下行 flow control 与响应 gzip,走宿主端的 legacy 路径(一帧一条消息、明文响应体),先保证正确性 |
| 切换 | 已连接时配对会先断开旧服务器(关闭旧 shell、事件流),再切到新连接;`ChatScreen` 现在持有自己的 `ChatState`,不再在 dispose/计时器里读已清空的 `app.chat!`(修掉切换服务器时的一个空指针崩溃) |
| 测试 | `test/relay_crypto_test.dart`(JWK 往返、双方派生一致、方向密钥、重放/篡改失败、base64url)、`test/pairing_test.dart`(直连优先、relay-only、grant、过期/非法/裸 payload);`tool/relay_probe.dart` 对真实 relay 做了握手、兑换、/api/version、会话列表、SSE 与终端快照的端到端验证;模拟器上从「配对链接」粘贴 relay-only 链接、重启后自动重连、终端命令输入输出都通过 |
| 版本 | **0.4.4(code 404)** |
---
## 0.4.3 终端多标签:下拉切换、新建、按标签恢复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 多标签 | 每个目录一个 `TerminalWorkspace`,持有多个 `TerminalTab`(各自的 xterm 模型与 socket)。切换标签时旧标签 detach、新标签 attach,不同时占用多条 WebSocket;后台输出由服务端 snapshot 在切回时重放 |
| 下拉 | 状态条左侧变成标签下拉:显示「终端 N · 运行中」,菜单列出所有标签(当前项打勾)与「新建终端」。新建的标签自动用最小的空闲编号(终端 1、终端 2…) |
| 关闭/重启 | ⋮ 菜单改为「关闭此终端」,关掉当前标签并 DELETE;关掉最后一个会自动留一个新标签。重启只作用于当前标签,死会话在原标签内换成新会话 |
| 恢复 | 本机按连接 + 目录保存标签列表(id + 名称 + 活动标签)。启动后首次打开:`GET /api/terminal/sessions?cwd=` 与服务端对账,仍存在的会话按保存的顺序和名称还原,服务端新出现的会话(网页端开的)按创建时间追加成标签,服务端已没有的标签丢弃;一个都没有才新建。兼容 0.4.2 的单会话存档 |
| 过滤 | 只把 interactive 会话算作标签,project-action 的命令运行器不显示 |
| 测试 | `test/terminal_restore_test.dart`:标签对账(顺序、名称、丢弃、列表失败的兜底、过滤 action)、编号复用、按连接+目录保存标签与活动项、0.4.2 存档迁移 |
| 版本 | **0.4.3(code 403)** |
---
## 0.4.2 终端恢复:重启后接回原来的 shell(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 之前 `sessionId` 只在内存里:每次启动 App 后第一次打开终端都走 `POST /api/terminal/create`,旧 shell 还留在服务器上(无连接时 30 分钟空闲回收),只是再也接不回去 |
| 恢复 | 按连接 + 目录记住最后一次的终端 id(`openchamber.terminalSessions.<connId>`)。首次打开终端先 `GET /api/terminal/sessions?cwd=`:记得的 id 还在就直接 attach(服务端 snapshot 重放历史);不在了就采用该目录最新的运行中会话;一个都没有才新建 |
| 关闭 | 「关闭终端」先 DELETE 并忘掉记录,再用 `fresh` 新建,避免又接回刚关掉的会话;断开连接/切换服务器时照旧关闭 shell |
| 失效 | attach 收到 fatal `SESSION_NOT_FOUND`(例如服务端在中间重启过)时清掉记录并自动新建,不留死面板 |
| 单终端 | 仍是每个目录一个终端视图,不是多标签;同目录的其它会话保留给网页端,不会被删除 |
| 测试 | `test/terminal_restore_test.dart`:恢复优先级(记得的 > 最新运行中 > 最新)、按连接+目录保存与清除 |
| 版本 | **0.4.2(code 402)** |
---
## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 不再占位 | `PetSlot` 换成 `PetLayer`:宠物画在消息列表的 Stack 上层,列表恢复完整高度,字会从宠物四周透出来,不再有一条空白带把最后一行截掉 |
| 透明 | 只有精灵本身作画;画布其余部分不填充。命中测试只认 `contentBox`(外扩 4px),点空白处仍然滚动/点消息 |
| 拖动 | 按住身体左右拖,脚沿输入框上沿移动;松手保存在本机(`pet.x.v1`,0–1 的比例),重启后回到同一位置,窄屏/旋转按比例换算并夹在两端内 |
| 拖动反馈 | 拖动时抬升 6px,并播放包里的 `drag`(`react-drag`)动画;没有该动画就保持当前状态,松手回到聊天状态 |
| 点击 | 从 `onTapDown` 改为 `onTapUp`,拖动不再误触发左右半区的 `tapLeft/tapRight` |
| 测试 | `test/pet_layer_test.dart`:空白处点击穿透、身体吃掉点击、拖动改位置并写入 prefs、无宠物时不画 |
| 版本 | **0.4.1(code 401)** |
---
## 0.4.0 输入框宠物:导入宠物包、精灵动画与状态(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 默认无宠物 | 不内置任何宠物;设置 → 宠物 显示「尚未导入宠物」和导入按钮,导入后才启用 |
| 宠物包 | 兼容 dsh-Go 的 PNG 精灵包:zip 内 `pack.json` + 各动画的 sprite sheet。解析 canvas / anchor / contentBox / animations(frames, cols, box) / states / reactions;导入时校验 `pack.json` 与每张精灵图,解压到应用文档目录 `pets/<id>/`,支持更换、启用/关闭、大小(40 / 52 / 64)与移除 |
| 渲染 | 新增 `PetSlot` / `PetSprite`:按 `anchor` 让宠物站在输入框上方(运行时有活动条则站在活动条顶边);按状态播放 `idle / thinking / working / error`;点击左右半区播放 `react-left / react-right`。图片一次只解码当前动画,切换时释放上一张 |
| 状态 | 活动条是「思考中」→ thinking,其余运行状态(回复中、调用工具)→ working,最后一轮失败 → error,空闲 → idle;草稿页显示 idle |
| 示例包 | `dist/deepy-whale-pet.zip`(dsh-Go 的 Deepy 小鲸鱼,保留包内 name/author/license) |
| 测试 | `test/pet_pack_test.dart`(真实 deepy pack 解析、帧与状态映射)、`test/pet_import_test.dart`(zip 解包、嵌套目录、缺少 pack.json 拒绝) |
| 版本 | **0.4.0(code 400)** |
---
## 0.3.21 侧栏行更紧凑(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 行高 | 项目条和会话行都改为 `dense: true` + `minTileHeight: 56`,实测都是 54(此前是 72);标题 14 / 项目名 14.5,路径与副标题保持较小字号 |
| 对齐 | 仍然等高等宽;`+` 与会话 `⋮` 的 x 中心保持对齐(测试断言) |
| 版本 | **0.3.21(code 321)** |
---
## 0.3.20 侧栏项目/会话行等高与右对齐、活动条改为 dsh-Go 胶囊(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏等高 | 项目分组头改用与会话行相同的 `ListTile`(标题 + 副标题),两者高度都是 72;分组的 8px 外边距由 ListTile 的内边距补偿,`+` 与会话的 `⋮` 落在同一竖线上 |
| 活动条 | 改为 dsh-Go 风格的全宽胶囊:左侧「标题 + 步骤摘要」,右侧等宽数字计时 `m:ss`(不足一分钟也显示 `0:03`),半透明 surface 背景,最小高度 36;去掉条内的转圈。胶囊顶边就是之后输入框宠物的栖息位置 |
| 版本 | **0.3.20(code 320)** |
---
## 0.3.19 输入框环居中、运行状态条、侧栏项目层级与 Windows 路径(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 上下文环 | 单行输入框用 `CrossAxisAlignment.end`,16px 的环贴着底部而按键是 36px;给环加 10px 底边距,与按键同一中轴(有焦点时的两行布局本来就是居中,未改) |
| 运行中的尾部 | 运行中不再显示上一轮的 footer(模型 · 模式 · 用时,以及“复制回答 / 从这里分叉”菜单):`_turnRows` 在 `chat.running` 为真时不加 footer。改为在输入框上方显示 dsh-Go 风格的活动条:「思考中 / 正在回复 / 正在读取 · …」加当前步骤摘要和秒表,每秒刷新 |
| 侧栏项目 | 项目分组头改成带底色的圆角条,最小高度 56,加文件夹图标;标题 13.5 粗体、路径作副标题,与会话行的层级更清楚 |
| Windows 路径 | 项目名只取路径最后一段,`/` 与 `\` 都识别;同一项目的比较统一分隔符(盘符路径忽略大小写),分组键也统一分隔符,避免一个项目被拆成两组 |
| 版本 | **0.3.19(code 319)** |
---
## 0.3.18 需要密码的服务器无法输入密码(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 「添加服务器」表单的密码框只在编辑已保存服务器时显示(`!_editNew`)。新服务器首次连接被 401 拒绝后只提示「需要密码或已保存的凭据」,却没有输入密码的地方 |
| 修复 | 密码框始终显示,文案为「密码(如果需要)」,提示服务器未设置可留空;连接失败且错误提示需要密码时自动聚焦密码框;服务端返回 `Invalid credentials` 时显示为「密码错误,请重试」。新增 `test/servers_form_test.dart` 覆盖新服务器表单含密码框 |
| 版本 | **0.3.18(code 318)** |
---
## 0.3.17 设置页、侧栏底部服务器栏与追问处理行为(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 设置页 | 新增 `lib/screens/settings_screen.dart`,分「外观 / 聊天 / 宠物」三组 |
| 侧栏 | 服务器切换从顶部移到底部:左侧是当前服务器名(点击打开服务器面板),右侧齿轮进入设置页,和原版手机端侧栏一致 |
| 外观 | 主题模式(跟随系统 / 浅色 / 深色)与主题色(8 个种子色);`lib/appearance_prefs.dart` 存本机 `shared_preferences`,明确不同步服务端;`main.dart` 的 `ThemeData` 读取它 |
| 聊天 | 「追问处理行为」:转向 / 排队。读写服务端 `GET/PUT /api/config/settings?surface=mobile` 的 `followUpBehavior`(profile 级、跨 surface 共享,默认 queue)。运行中短按发送按该设置执行,长按「发送方式」可临时选另一种并标出默认项。连接成功、设置页打开、应用回到前台时重新读取 |
| 宠物 | 仅占位,显示「暂未提供设置」 |
| 版本 | **0.3.17(code 317)** |
---
## 0.3.16 输入法收起、模式面板与排队消息(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框收起 | 手机返回手势关闭输入法(焦点仍在)时,输入框也收回单行:dsh-Go 用键盘高度判断;`Scaffold` 会从 body 去掉底部 viewInsets,所以由 `HomeScreen`(Scaffold 之上)读取键盘高度,经 `ChatScreen` / `NewSessionScreen` 传给 `ComposerBox`。键盘升到过的峰值一半以下即视为收起,再次唤起时展开。新增 `test/composer_box_test.dart` 覆盖 |
| 模式面板 | 「模式」(Build / Plan)chip 由下拉框改为底部面板:标题、图标、说明、当前项打勾;仍与模型/思考强度分开 |
| 排队消息 | 运行中短按发送默认「转向」(`delivery: steer`),长按发送键弹出「转向当前回合 / 排队」,只用服务端支持的 steer/queue。排队或转向的消息不乐观写入对话,而是显示为末尾的待发气泡(半透明 + 状态:正在转入 / 已排队 / 未发送),可「改为排队 / 转为转向」与「撤回」(`DELETE /api/session/:id/inbox/:id`,文本放回输入框)。打开会话与前台恢复时 `GET /api/session/:id/inbox`;订阅 `session.inbox.enqueued / delivered / cancelled / delivery.changed`,送达时刷新尾部。运行且输入框有文字时发送键显示为发送(dsh-Go 行为),空输入时才显示停止 |
| 版本 | **0.3.16(code 316)** |
---
## 0.3.15 输入框两行折叠、模型与思考成组、模式独立(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框折叠动画 | 新增 `lib/widgets/composer_box.dart`:未获焦点时是单行(附件键在左、输入框、上下文环、发送键在右),获得焦点时平滑展开为两行(上为输入框,下为附件键/模型/模式/环/发送键),失焦后收回单行;输入框用 `GlobalKey` 在两种布局间搬移,保留焦点与输入连接。参照 dsh-Go `Composer` 的 `footer` + `_ComposerRows` + `AnimationController` 做法 |
| 模型与思考强度成组 | 模型 chip 直接显示 `模型 · 思考档位`(如 `deepseek-flash · 高`),点开同一个面板:选模型后若该模型有 variants,底部出现思考强度选择,选完一次提交;最近使用的档位记在本机。草稿页与聊天页共用 `ModelPill` |
| 模式独立 | 原「智能体」chip 改为独立的 `ModeChip`(Build / Plan),与模型 chip 并列,不再把智能体与模型放在同一行组里;仍通过 `switchAgent` / 草稿的 `agent` 提交 |
| 草稿页 | 同样使用两行折叠 `ComposerBox`;项目 chip 单独在输入框上方始终可见(草稿页没有会话,模型/模式放在折叠的第二行);斜杠面板、快捷键保持不变 |
| 版本 | **0.3.15(code 315)** |
---
## 0.3.14 模型切换修复、输入框模型行、思考强度与模型面板(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 切换模型报错 | `POST /api/session/:id/model` 的 body 应为 `{model: {id, providerID, variant?}}`,之前把模型对象直接放在顶层,服务端报 `Missing key at ["model"]`;已修正并实测切换成功 |
| 输入框模型行 | 参照 dsh-Go:聊天页把模型/智能体从顶栏移到输入框上方,输入框获得焦点、有草稿文字或正在生成时显示;草稿页始终显示同一行(左侧多一个项目 chip)。聊天顶栏只留文件按钮 |
| 思考强度 | `/api/model` 的每个模型带 `variants`(v2 的 `{id, settings.reasoningEffort}`)。输入框行在模型有档位时显示「思考·默认/低/中/高/极高」,点开选档;选择以 `ModelRef.variant` 随 `POST /session/:id/model` 或建会话时提交,实测会话的 `model.variant` 变为 `high`。每个模型上次的档位记在本机 |
| 模型面板 | 重做 `lib/widgets/model_picker.dart`:按 provider 分组(可折叠)、「收藏」「最近」分组(本机 `shared_preferences`,收藏用星标切换)、每个模型标注上下文大小(如 `200K 上下文`)、推理能力标记、搜索、当前项打勾;智能体分段保留 |
| 草稿斜杠 | 斜杠面板抽成共享的 `lib/widgets/slash_palette.dart`(匹配、排序、面板、快捷键),草稿页与聊天页共用;草稿只列 `/api/command` 与 `/api/skill` 的结果,不含需要已有会话的客户端内置 `/compact`;无参命令选中即发送(先建会话再执行命令),带参命令补全名称 |
| 版本 | **0.3.14(code 314)** |
---
## 0.3.13 草稿会话与分组侧栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 新会话 = 草稿 | 左侧栏 `+` 不再弹「标题」底部框,而是进入 `NewSessionScreen`:大标题「我们今天要做什么?」、项目 chip(`GET /api/project`,按 canonical 去重)、模型/智能体 chip(与聊天共用新的 `lib/widgets/model_picker.dart`)、附件与输入框。**发送前不创建会话**:第一次发送才 `POST /api/session`(带 `location.directory`、`model`、`agent`),随后 `openChat` 并发出这条消息 |
| 草稿生命周期 | 草稿只存内存(`AppState.draft` + `draftOpen`):未发送就离开时保留,侧栏顶部出现「草稿 · 项目名」一行(笔图标、首行、× 丢弃),点它回到草稿;发送成功即清空,创建失败留在草稿并显示错误。第二期接服务端 `/api/session-drafts`(已记入项目待办) |
| 侧栏分组 | 会话按 `location.directory` 分组(`.openchamber/chats` 归为「聊天」),组头是项目名 + 路径 + 折叠 + 「在此项目新会话」;组内按 `updated` 倒序并插「今天 / 昨天 / 本周早些时候 / 更早」小标题;默认过滤子会话(`parentID`),父会话的运行点会带上子会话的活动 |
| 置顶 | 写进 `session.metadata.openchamber.pinned`(`PATCH /api/session/:id {metadata}`,合并原有 metadata),跨客户端可见;置顶的会话收进顶部「已置顶」区,不再重复出现在项目组里 |
| 归档 | 主列表请求 `archived=false`;底部「显示已归档」按需拉 `archived=true`,展开后可取消归档(事件 `session.archived/unarchived` 同步) |
| 行操作 | 左滑(`flutter_slidable`,DrawerMotion)露出置顶 / 归档 / 删除;`⋮` 菜单有重命名、置顶、归档、删除、复制会话 ID;选中行有底色与加粗 |
| 其它 | 会话列表支持「载入更多」(cursor 分页);聊天页标题改为跟随 `AppState.sessions`,服务端根据首条消息生成的标题会即时显示;附件选择与缩略图抽到 `lib/widgets/composer_attachment.dart`,与草稿页共用 |
| 版本 | **0.3.13(code 313)** |
---
## 0.3.12 侧栏头部、Termux 按键栏、键盘避让与记忆(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏头部 | 顶部一行改成「标签组 + 关闭按钮」,标题/目录副标题去掉(目录本来就在面包屑里);文件/项目知识/终端各自的功能按钮下沉到标签自己的头部行——文件页是面包屑右侧的「+ / ⋯」(预览时是「编辑 / 下载」),项目知识页是搜索框 + 刷新,终端页是状态 + 键盘/重启/菜单 |
| 按键栏 | 按 Termux 改成两行七列等宽:`ESC / — HOME ↑ END PGUP`、`TAB CTRL ALT ← ↓ → PGDN`(左下角是 **TAB**,不是收起按钮);CTRL/ALT 修饰对手机输入法的字符仍然生效 |
| 键盘避让 | 侧栏是对话框,不会自己随输入法缩小;现在给底部加上 `MediaQuery.viewInsets.bottom` 的内边距,终端连同按键栏一起抬到键盘上方,`TerminalView` 随之减少行数并把新尺寸回传给 PTY |
| 记忆 | 项目知识新增「记忆」标签:`GET /api/agent-memory/all` 一次取全局与项目两份,服务端把功能关掉时(404)整个标签不出现;卡片显示标题、类型(事实/偏好/参考)、内容,可编辑(标题/类型/正文)与删除,搜索也覆盖记忆 |
| 顺带修复 | 文件预览的编辑框 `expands: true` 缺 `minLines: null`,进编辑会触发断言 |
| 版本 | **0.3.12(code 312)** |
---
## 0.3.11 终端、项目知识与下载进度(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 终端 | 右侧栏「终端」页:`POST /api/terminal/create` 建 PTY(cwd = 会话目录),`/api/terminal/ws` 走二进制控制帧(`0x01` + JSON:hello/attach/write/ping,snapshot/output/restart/exit/error)。渲染用 **xterm 4.0.0**(`Terminal` 模型 + `TerminalView`),断线按 500ms 起指数退避重连、重连后按服务端快照重放(先 `resize` 到快照尺寸再写历史);`/api/terminal/:id/resize` 做 250ms 去抖;App 回前台时自动重连 |
| 底栏 | 仿 Termux 的按键条(横向滚动):CTRL / ALT / SHIFT 修饰键,ESC、TAB、方向键、HOME/END/PGUP/PGDN/DEL,以及 `/ - \| ~ * $ # _ = + : ; " ' ( ) [ ] { } < > ? ! & \ ^ % @`;修饰键对**手机输入法**输入的字符同样生效(在 `onOutput` 里把下一个可打印字符映射成控制字符/ESC 前缀),按一次即清除 |
| 状态 | 状态条显示「运行中 / 正在连接 / 已退出(退出码)/ 连接失败」,并提供键盘、重启、清屏、关闭终端;终端会话按目录保存在 `AppState.terminals`,关面板不断 shell,切换服务器时显式关闭 |
| 项目知识 | 右侧栏「项目知识」页:`/api/project-context/:projectId`(projectId = `path_` + 目录 base64url);笔记(新建/编辑/置顶/删除)、待办(勾选、新建、删除,完成项沉底)、计划(新建、置顶、删除、打开全文);搜索框跨三种记录即时过滤;计划详情是全屏页(Markdown 渲染 + 编辑原文 + 保存) |
| 下载进度 | `/api/fs/raw` 改为流式:`downloadFile` 带 `onProgress` 与 `CancelToken`,请求头 `accept-encoding: identity` 以拿到 `Content-Length`(gzip 会让响应变成 chunked,进度只能是不确定态);下载中弹「正在下载」对话框显示已下载/总量/百分比,取消即中止连接并丢弃结果;完成后才弹保存对话框 |
| 修复 | `MarkdownView` 里的任务列表不再用 `material_ui` 的 Checkbox(它会找 `material_ui` 的 Material 祖先,应用里没有),改为 `✅`/`⬜` 文本;对话框里的 `TextEditingController` 改由对话框自身持有,避免关闭动画期间 dispose 触发框架断言 |
| 版本 | **0.3.11(code 311)** |
---
## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| Transport | 新增 `lib/api/transport.dart`:`TransportRequest`(method/path/query/rawQuery/headers/body)、`TransportResponse`(状态码/头/`Stream<List<int>>`,SSE 与文件下载仍可流式读)、`abstract Transport`;`DirectTransport` 就是原来的直连实现(HTTP CONNECT、SOCKS5/socks5h、自签与指纹固定、SHA-256 内置实现),`Client` 只保留业务方法,构造时可注入别的 Transport。行为与之前逐字节一致,后续 Private Relay 只需再加一个 `RelayTransport` |
| 历史图片 | 用户消息里的 `files` 现在从服务端读 `data`(base64)并缓存解码结果;气泡内显示缩略图,点按打开图片预览(与工具行读图共用同一个对话框)。无内联图片时仍回退到刚发送时的本地路径 |
| 原生表单 | `FormInfo`/`AgentFormField`/`FormOption`/`FormWhen` 按 `@opencode/client` 2.2.7 的 schema 建模;`GET /api/session/:id/form` 拉取待答问题,`POST …/form/:fid/reply` 提交、`DELETE …/form/:fid` 取消;订阅 `form.created/replied/cancelled`。输入框上方是表单卡片:string(带 options 时用 chip + 「其他…」)、multiselect、boolean(开关)、number/integer、external(链接确认);`when` 控制字段显隐,必填项(含「必须打开」的开关)不满足时提示并阻止发送,最多 360 px 内部滚动 |
| 左右分栏 | 新增 `lib/screens/home_screen.dart`:手机(< 840 px)把会话列表放进左侧 Drawer、聊天占满屏幕、顶栏是菜单键;宽屏(平板/桌面)左侧常驻 320 px 会话列 + 聊天。两者共用同一个 `SessionListPane`(会话选中高亮、搜索、新建、服务器、重命名/归档/删除)。启动时若还没有打开的会话,自动打开最新一条(与官方手机端一致) |
| 版本 | **0.3.10(code 310)** |
---
## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
**背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo;
按评估结论改用 Flutter 做同功能重写,验证其移动端 UI 成熟度。
| 项 | 结果 |
| --- | --- |
| 环境 | Flutter **3.50.0 stable** 装在 `~/SDK/flutter`;`FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn`、`PUB_HOSTED_URL=https://pub.flutter-io.cn` |
| 构建坑 | Gradle 发行包(gradle-9.5.0-all,230MB)从 services.gradle.org/GitHub 下载一小时级 → 用腾讯镜像预置;AGP 又重装 NDK 28.2(688MB,dl.google.com 慢)→ 腾讯 AndroidSDK 镜像重装完整 NDK;另在 settings/build.gradle.kts 前加**阿里云 Maven 镜像** |
| 依赖坑 | file_picker 8.x 硬编码 compileSdk 34,与 flutter_plugin_android_lifecycle 要求的 36 冲突 → 升 file_picker 13.4(联邦版 API)+ flutter_secure_storage 11.2 |
| 复用 | Go 客户端无法复用;`lib/api/` 按同一协议重写(HTTP/SOCKS5 代理、自签/pinning、SSE、part-shells);聊天 Markdown 直接采用 **dsh-Go 同款的 `gpt_markdown`**(BSD-3,流式、代码高亮/复制、表格、LaTeX、任务列表) |
| 踩坑 | SSE 的 `types` 是重复 query 参数,Dart 的 `Map` 会把它压成最后一个 → 只订阅到一种事件、聊天不更新;改为手动拼 query 后实时流恢复 |
| 可继续复用 | dsh-Go 的 `app/lib/ui/chat/render/`(markdown_body、code_block、markdown_blocks 等)文件头多为 MIT,可保留 SPDX 头后搬运,但依赖其 Riverpod/DSH 协议类型;`scrollable_positioned_list`、`xterm` 等 pub 包也可直接用 |
| 输入区(参考 dsh-Go) | 圆角胶囊 + 左侧 36 圆附件键 + 无边框自动增高输入 + 上下文占用环 + 右侧 36 圆发送/停止键(运行中变为停止、hint 变「生成中,仍可输入…」);附件以缩略图 chip 展开在胶囊上方;顶栏模型 chip(点击打开模型/智能体分段选择) |
| 最低 Android | **24(7.0)** |
| 明文 HTTP | Dart `HttpClient` 直接建 socket,release 连 `http://` 无需 cleartext 开关(已实测) |
| 模拟器实测 | 服务器列表→添加/连接(无密码自动跳过)→会话列表(运行点/模型·时间)→聊天:流式 Markdown(gpt_markdown,代码块/表格实测)、思考/工具行、页脚、上下文占用环、输入与实时回复(SSE) |
| 产物 | `dist/OpenChamber-0.3.0-flutter-release.apk`(0.3.0 / code 300,`~/SDK/test-upload.jks` 签名,`OPENCHAMBER_KEYSTORE*` 可覆盖) |
| 未做 | 朗读(按需求去掉)、附件/图片预览虽已实现但未逐项点验、i18n、启动图;APK 71MB(gpt_markdown 带字体/LaTeX,后续可按 ABI 拆分) |
---
## 0.3.9 文件侧栏、思考 Markdown 与重连提示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 文件侧栏 | 会话顶栏原来的 ⋮(和每轮底部的菜单重复)换成侧栏按钮,从右侧滑出面板:目录浏览、面包屑、上一级、搜索(当前目录即时过滤 + 子目录递归搜索,跳过 .git/node_modules/build 等,最多 400 个目录/200 条结果)、新建文件/文件夹、刷新 |
| 预览 | 文本与代码等宽显示;Markdown 按 Markdown 渲染(共用聊天那套主题修正);图片用 InteractiveViewer 缩放;二进制提示无法预览。文本可切到编辑并保存(`/api/fs/write`) |
| 下载 | `/api/fs/raw` 取原始字节,交给系统保存对话框(Android SAF / 桌面对话框) |
| 显示被忽略的文件 | 「⋯」菜单里的开关(`respectGitignore=false`),默认按下图与官方一致的行为隐藏 git 忽略项;另含刷新 |
| 占位页 | 「项目知识」「终端」两个页签已在位,内容标注「即将支持」 |
| 思考 Markdown | 展开思考块时不再按纯文本渲染,改用与回答一致的 Markdown 渲染(字号更小、颜色更淡) |
| 重连提示 | 事件流恢复(服务端每个连接都会先发 `server.connected`)即清除「连接中断,正在重连…」,不再一直挂着 |
| 版本 | **0.3.9(code 309)** |
---
## 0.3.8 内置 `/compact` 与压缩记录(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| `/compact` | 官方客户端的内置指令不在 `/api/command` 里,是客户端自己提供的;现在面板会先列出本地指令(`compact`,中文名「压缩」),选中即执行 `POST /api/session/:id/compact`,不需要模型参与 |
| 其它内置 | 看了 opencode 官方实现:`undo`/`redo`(撤回语义)、`timeline`(时间线视图)、`btw`(临时子会话)、`fork`、`handoff-review`,以及 `summary`/`workspace-review`/`plan-feature`/`craft-goal`/`schedule-task`/`catch-up`/`debug`/`weigh`/`explore`(成对的可见提示 + 隐藏指令)。本轮只做 `/compact`;其余需要对应 UI 或官方提示词文本,未加 |
| 压缩记录 | 消息列表里的 `compaction` 消息(`status` running/completed/failed、`reason`、`summary`、`tokens`)现在会显示成一行「正在压缩对话 / 对话已压缩」+「显示摘要」,展开是 Markdown 摘要;运行中有转圈,结束后自动换成完成态 |
| 实时 | 订阅 `session.compaction.started/delta/ended/failed`:开始时插入运行中的记录或拉一次尾部,delta 追加到摘要,结束/失败时拉一次服务端版本(摘要、token、错误都齐) |
| 失败 | 压缩失败仍用错误块显示(「压缩失败:…」+ 原始响应详情) |
| 版本 | **0.3.8(code 308)** |
---
## 0.3.7 工具输出被“壳”覆盖(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 现象 | 会话列表接口带 `x-openchamber-part-shells: v1` 时,大一点的工具输出只给一个空壳:`content:[{type:'text',text:''}]` + `metadata.openchamberContentShell`。展开步骤时客户端会单条拉完整消息(`/message/:id`,不带壳),输出就出来了 |
| 根因 | 每次 `reloadTail()`(每轮 `execution.started`、回到前台等)都用**带壳**的列表覆盖本地消息,把刚加载出来的输出又盖回空壳,于是展开着的那一步变回「无输出」——看起来就像“始终无输出” |
| 修复 | `reloadTail` 合并消息时,如果服务端给的是壳、本地这一条已经加载过完整内容,就保留本地那条(按 part 顺序与 call id 对齐),不再降级;真没有输出的命令仍然显示「无输出」 |
| 提示 | 壳还没加载完时不再显示「无输出」,而是「输出较大,正在载入…」 |
| 版本 | **0.3.7(code 307)** |
---
## 0.3.6 斜杠指令与错误显示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| `/` 指令面板 | 输入框以 `/` 开头且还没打空格时,在输入条上方弹出(dsh-Go 的样子:图标 + 中文名 + `/name` + 一行说明,最多 5.5 行,首条高亮,右侧 ↵)。来源是这个会话目录的 `GET /api/command` 与 `GET /api/skill`,第一次打开时加载并缓存;支持按名称/说明过滤,↑/↓ 选择、回车选中、Esc 关闭 |
| 选中行为 | 说明里带 `[…]` 参数形式的指令补全成 `/name ` 并等待参数;没有参数的(如 `/init`)立即执行;技能补全为文本随下一条消息发出。未知的 `/xxx` 仍是普通消息 |
| 发送路由 | 指令走 `POST /api/session/:id/command`(`{name, text}`,服务端展开模板并写用户消息);技能走普通 `/prompt` 并附 `skills: [{id}]`;失败时保留草稿 |
| 错误显示 | 解析消息上的 `error`(`provider.*`、`provider.auth`、`MessageAbortedError` 等):只显示结束这一轮的那一步的错误(被后续步骤接上的失败不算),另外显示失败的压缩消息和未被助手消息覆盖的 idle 错误。样式为浅红圆角块 + 图标 + 中文说明(认证失败、重试中、已停止、发送失败),provider 的原始响应放在「显示详情」里(美化过的 JSON) |
| 刷新 | `session.execution.started` 时拉一次尾部:指令这条由服务端写入的用户消息(以及别的客户端发的消息)能立刻出现,不用重进会话 |
| 版本 | **0.3.6(code 306)** |
---
## 0.3.5 折叠动画与流式修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 折叠定位 | 照 dsh-Go 的 `ExpandReveal`/`_holdHeader` 重做:内容用 `SizeTransition` 从顶部往下长、同时淡入,280ms `easeInOutCubic`;每一帧在**布局之前**把长出来的高度补进滚动位置,表头因此停在手指按下的位置。列表两端补不动时停在边界;看不见的折叠(历史里自动收起的一轮)直接换尺寸,不做动画、不拽视图 |
| 默认折叠 | 与 dsh-Go 一致:**已结束的一轮收成一行摘要**(`已完成 · N 次工具调用`),运行中的保持展开;点一下记住你的选择(手动展开的在结束后也不会自动收起) |
| 工具详情 | 不再铺请求 JSON:`运行` 是完整命令 + 其余参数 + 输出(空则「无输出」),其它工具是摘要之外的参数 + 结果;`toolOutput` 在 `content` 为空时回退 `metadata` 的 output/result/stdout |
| 图片读取 | `读取`/`写入`/`编辑` 指向图片时该行不可折叠,路径直接点开大图;读取失败的行仍是普通可折叠步骤 |
| 流式工具名 | 事件里只有工具 id 和 input,没有名字,直播中的步骤只能显示「工具」。现在每一步结束(`session.step.ended`)后用 `getMessage` 换回服务端那条消息:名字、完整输入、附件都齐了,标签立刻变成 `运行`/`读取` 等 |
| 会话自动刷新 | SSE 30s 无数据(服务端有 `: heartbeat`)即判定断线并重连;回到前台重开事件流、刷新会话列表并合并 `reloadTail()` |
| 版本 | **0.3.5(code 305)** |
---
## 0.3.4 主题与工具细节(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 暗色主题代码块/行内代码 | `gpt_markdown` 用的是它自带的 `material_ui` 移植版 Material,`Theme.of` 找不到宿主主题时回落成**亮色**,于是代码块面板亮、正文黑。现在渲染前用同一套亮/暗 `mui.ThemeData` 包一层,面板、行内代码、表格、语法配色都跟随应用主题 |
| 折叠时视口跳动 | 折叠/展开会改变分组高度:现在记录表头在屏幕上的位置,重建后按差值补偿滚动;若因列表边界补不回来,就把表头停到列表顶部。展开时始终看到分组头部,不再落到分组末尾 |
| 工具详情 | 不再直接铺请求 JSON:`运行` 显示完整命令(可选中、换行)+ 输出,其它工具显示摘要之外的参数与结果;输出为空时显示「无输出」。`toolOutput` 在 `content` 为空时回退到 `metadata` 的 output/result/stdout |
| 图片读取 | `读取`/`写入`/`编辑` 指向图片时,该行不再展开,路径直接可点,打开大图预览 |
| 会话不自动刷新 | SSE 增加 30s 心跳超时(服务端每几秒发 `: heartbeat`),断流会被发现并重连;应用回到前台时重开事件流、刷新会话列表并 `reloadTail()`(合并而不是替换已加载的历史页) |
| 「载入更早」误显示 | 服务端对已经包含全部内容的页也会给 cursor,现在短于一页即视为没有更早内容 |
| openui-lang | 暂未渲染:pub 上的 `openui_lang` 0.18.2 组件签名与 OpenChamber 的 DSL 不一致(`Card` 首参是 children 而非标题,且没有 `Badge`/`KeyValue`/`Stat`/`Details`),接入需要一层组件映射;本轮先跳过 |
| 版本 | **0.3.4(code 304)** |
---
## 0.3.3 工具调用展示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 为什么要改 | 旧版每个 reasoning/tool part 只显示一行「已思考 ▸ / ✓ shell ▸」,既没有概要也不能整组收起,长回合里几乎不可读 |
| 分组依据 | 服务端每个 step 各写一条 assistant 消息,所以按**消息**分组会得到「5 组」;现在按**回合**(连续的 assistant 消息)分组,`text` 分隔出新的组。与 dsh-Go 一致:一组一个「已完成 · N 次工具调用」表头 |
| 表头 | 左侧状态图标(进行中转圈 / 完成对勾 / 失败警告),「已完成 · N 次工具调用」/「执行中 · …」/「有步骤失败 · …」;只有一个思考步骤时不显示表头,直接显示「思考」行;纯思考的组显示「思考过程」 |
| 每行 | 26px 圆角图标 + 名称 + 「· 概要」+ 展开箭头;图标按工具类型(思考=psychology、运行=terminal、读取=description、写入/编辑/补丁、搜索、抓取、任务、技能…),未知工具用工具名 |
| 概要 | bash=命令、read/write/edit=文件路径、grep/glob=模式、webfetch=URL、task=描述、skill=id,其余取 description/path/command/query/url/pattern/name/id,再退化为紧凑 JSON |
| 展开 | 单行展开后显示推理全文或工具的 input/输出(等宽、可选中);图片引用仍以 🖼 行列出,点击预览 |
| 版本 | **0.3.3(code 303)** |
---
## 0.3.2 修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 会话历史只加载一段 | 两个原因:`order=desc` 的“更早”方向是 `cursor.next`(此前用了 `previous`,取到 0 条),以及服务端拒绝 `cursor` 与 `order` 同时出现(`InvalidCursorError`)。现在首次加载记下 `next`,后续只带 `cursor`。`tool/history_probe.dart` 对 1698 条的会话验证 30 条/页翻到最早一条,无缺口 |
| 加载时视图跳动 | 消息列表改为 `reverse: true`(最新在底部,偏移 0),更早的页追加在上方,视口自然保持不动;接近顶部自动加载,并提供「载入更早的消息」按钮 |
| 智能体列表 | 过滤 `hidden`(Compaction/Title/Summary 是 `mode=primary` 但 `hidden=true`),只留 Build/Plan;模型与智能体列表用对勾标出当前选中项,切换后由 SSE 事件与本状态同步 |
| 用量环 | 点击打开「上下文占用」详情(模型、已用 tokens、上限、输出预留、百分比);此前被 `_usageOpen` 守卫拦掉 |
| 图片预览 | 对话框改为自加载的 StatefulWidget(此前预览流程在 widget 重建后失去状态);图片直接 `Image.memory(bytes)`,不再落盘。`path_provider_android 2.3.1` 在本机模拟器上抛 `ClassNotFoundException: Landroid/content/Context;`,因此移除 path_provider(附件缓存改用 `Directory.systemTemp`)。经 SOCKS5/HTTP 代理取 `/api/fs/raw` 均可预览 |
| 已连接时添加服务器 | 服务器面板的「添加服务器」此前只关闭面板;现在打开表单,连接成功后回到会话列表 |
| 版本 | **0.3.2(code 302)** |
| 测试环境 | 新增 Linux 桌面目标(`flutter create --platforms=linux`),本机 clang 从 `clang-17` 包解出、libsecret/jsoncpp 头文件解出,配合 Xvfb + xdotool/ffmpeg 截图自测,比模拟器快很多 |
---
## 0.3.1 修复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 代理 | 支持 `http://`、`https://`(`HttpClient.findProxy`)与 `socks5://`、`socks5h://`(`socks5_proxy` 包为 `HttpClient` 建 SOCKS 隧道,统一在代理解析域名),可带 `user:pass@`。此前 `socks5` 直接塞进 `findProxy` 导致 “Invalid proxy configuration”,`socks5h` 被当成 HTTP 代理导致 “Invalid request method” |
| 验证 | `tool/proxy_probe.dart` 对本机服务器 + 本地 SOCKS5(1080)/HTTP(8081) 测试代理跑通 direct / socks5 / socks5h / http 与 SSE;模拟器上分别用 `socks5://127.0.0.1:1080` 和 `http://127.0.0.1:8081` 连上并列出会话 |
| 失败不落库 | 连接成功才保存(`_connected` upsert);失败的尝试留在表单并显示简短原因(如「连接被拒绝:服务器或代理未启动,或端口不对」),返回列表后不残留错误 |
| 包名 | `net.blumia.openchamber.flutter`(namespace、applicationId、MainActivity、iOS bundle id 同步) |
| 版本 | **0.3.1(code 301)** |
| 小改进 | 实例/服务器列表显示「经由 <代理>」,区分同地址不同代理;连接错误中文化 |
---
## 0.2 迁移到 MyGo(2026-11-18,分支 `mygo`,0.3.0)
**背景**:Asuka 0.2 把应用语言从 Go 换成了自研 Asuka 语言(C 内核、无 Go 运行时),继续留在 Go 线已没有上游维护;
同一作者的 **MyGo 0.10.0 在 2026-11-17 发布了手机端支持**(iOS/Android,纯 Go,GPU 自绘 UI)。评估后选择迁移到 MyGo。
**结论与现状**:
| 项 | 结果 |
| --- | --- |
| Go | mise 升级到 **1.27.4**(MyGo 要求 1.27.3+);`GOROOT` 必须 unset(环境里有旧的 1.26.3 全局 GOROOT) |
| 最低 Android | **24(Android 7.0)**:MyGo 宿主默认 26,`third_party/mygo`(本地 fork)把宿主库的 `minSdk` 改为读 `mygoMinSdk` 属性,并给通知加 API<26 守卫 |
| 复用 | `internal/ocapi`(约 1800 行纯 Go)**原样保留**;`storage` 改为 `connections.json` + `mygo.Secrets`;`appui` 按 MyGo 的 ui API 重写(视图=状态的每帧函数,非信号模型) |
| 明文 HTTP | Go 的 net/http 直接建 socket,绕开 Android 的 cleartext 策略,**release 连 `http://` LAN 服务器无需 manifest 开关**(已实测) |
| 构建 | `go tool mygo build -platform android` 产出 `dist/android/openchamber-0.3.0.apk/.aab`(v0.3.0 / code 300,签名 `~/SDK/test-upload.jks`) |
| 模拟器实测 | 服务器列表→添加/连接(无密码服务器自动跳过密码)→会话列表(搜索/新建/实例切换)→聊天(流式 Markdown、工具行、页脚菜单、上下文占用 Sheet、工具图片预览)全部跑通 |
| 终端 | 暂不做;MyGo 的 Terminal 插件只支持桌面(libghostty-vt 无 Android 库),后续走 native module(Kotlin)或 WebView + xterm.js |
| TTS | MyGo 无朗读 API;`internal/tts` 是一个 Kotlin TextToSpeech 插件(mygo-plugin.json),朗读/停止已接通 |
| a11y | uiautomator 的树在 Android 上只反映首帧(MyGo 宿主同步问题),验证靠截图 + 坐标点击 |
**为什么不是 Asuka 0.2**:0.2 换语言(Go → Asuka DSL)+ C 内核,等于全量重写一门 alpha 语言;MyGo 保住 Go 和 ocapi,
手机端刚发布(一天)但与我们已验证的 asuka Go 版同样新,且 minSdk 更低、生态(markdown、native module、自动化测试)更贴本项目。
---
## 0.1 前情(Asuka/Go,2026-11-15 ~ 11-17,`main` 分支 0.2.x)
> 以下为 asuka 时期的调研与进度,供参考;0.3 起已迁 MyGo。
**结论**:asuka(Go + 原生控件)可用来实现本项目,真实风险在三处:
1. **Android 构建链**:本机没有 JDK / Android SDK / NDK。asuka 要求每个平台自己的工具链,第一次搭环境要花半天,且 **asuka v0.1.1 在 Linux 上 `go install` 会编译失败**(`syscall.SO_REUSEPORT`),必须从 `main` 安装。
2. **release 版默认禁止明文 HTTP**:asuka 只在 debug manifest 里开 `usesCleartextTraffic`。连 `http://192.168.x.x:3000` 这类自建服务需要额外处理(加一个只声明 manifest 的 native 包,或统一走 HTTPS)。
@@ -19,7 +413,8 @@
---
## 0.1 进展(2026-11-15)
### 0.1 进展(2026-11-15)
M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行的 OpenChamber 2.7.0(无密码):
+93 -58
View File
@@ -1,77 +1,112 @@
# OpenChamber Native
A lightweight OpenChamber client for phones, written in Go with
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
A lightweight OpenChamber client for phones, written in **Flutter** (Dart).
Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity.
Status: 0.2.2 — multiple saved servers with a connect list (add, edit,
delete, switch; password prompt; HTTP or SOCKS5 proxy and self-signed
certificates per server), session search, live session list, chat with
streaming Markdown, image and file attachments with inline previews, a
context usage ring with a detail sheet, previews of images named by tool
calls, permissions, model/agent switching, turn and prompt actions (copy,
fork, revert, read aloud), new sessions, archive/delete/rename, the
OpenChamber icon, and a UI-independent API client.
Status: 0.4.5 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a
context usage ring with a detail sheet, model/agent switching (Build/Plan only,
current one checked), copy / fork / revert, attachments (photos/files, kept
after a reload), the agent's native forms, permissions. The files sidebar also
carries the project knowledge (notes, todos, plans, and agent memory when the
server enables it) and a full terminal with a Termux-style key bar; downloads
show their progress and can be cancelled. The terminal holds several tabs per
project, switched from a dropdown next to the status (new tab included), and
remembers them per connection and directory: reopening after an app restart
attaches to the shells the server still holds instead of starting new ones. The panel is a tab row with its own
close button, and each tab has its own header row. Starting a session opens a
draft that only creates the session on the first send; the session list is
grouped by project with date captions, pins, archive and swipe actions. The
composer folds to one line when unfocused (or when the keyboard is dismissed)
and opens into two rows on focus, as in dsh-Go: the model and its thinking level
form one pill, the Build/Plan mode a separate chip (picked from a sheet). A
message sent while a turn runs can steer it or queue for its end, and waits as a
pending bubble that can be withdrawn; while a turn runs, an activity strip above
the input names the current step and its clock instead of the finished turn's
footer. Pets are opt-in: nothing is built in, and a dsh-Go sprite pack (a zip
with pack.json) is imported from Settings → 宠物 to stand above the input and
react to the turn's mood. The pet floats over the messages (only its body
takes touches) and can be dragged along the input's top edge; the spot is
remembered on the device. The picker groups providers, favourites,
recents and context size. The sidebar footer names the connected server (tap to
switch) beside a settings key; settings holds appearance (theme mode and seed
colour, device-local), the server's follow-up behavior (steer or queue on a send
while a turn runs) and a pet placeholder. A
phone opens the session list as the left drawer and a wide window (tablet,
desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop
target used for local testing.
## What is here
| Path | What |
| --- | --- |
| `internal/ocapi/` | OpenChamber HTTP client: auth (password → device token), sessions, messages, prompt/interrupt/model/agent, permissions, SSE events, HTTP/SOCKS5 proxy, certificate pinning |
| `internal/storage/` | Saved servers in `asuka/sdk/store`, one device token per server in `asuka/sdk/secure` (Android Keystore), per-install id for device dedupe, migration from the single-server record |
| `internal/appui/` | Screens: connect, sessions, chat (streaming Markdown, reasoning/tool folding, permissions) |
| `cmd/ocprobe/` | Terminal probe used to validate the API without a device |
| `PLAN.md` | Research, API contract, architecture, milestones, risks |
| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, forms, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; every request goes through `Transport` (today `DirectTransport`: HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback`), so a relay tunnel only adds an implementation |
| `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) |
| `lib/state.dart` | The app state: connections, live sessions, the open chat, the server's follow-up behavior, and SSE event folding |
| `lib/appearance_prefs.dart` | Device-local theme mode and seed colour (`shared_preferences`) |
| `lib/pets/` | Imported pet packs: the dsh-Go `pack.json` sprite format, unpacked into the app's documents, plus the one-sheet image cache |
| `lib/widgets/pet_sprite.dart` | The pet strip above the composer and its sprite player (frames, moods, tap reactions) |
| `lib/terminal_state.dart` | Terminal workspaces and tabs: each tab is an xterm model plus its `/api/terminal/ws` socket; switching detaches the old tab, the saved tab list lets a restart reattach |
| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar with the knowledge and terminal tabs); the message list is reversed so older pages grow above without moving the viewport |
| `lib/widgets/` | The context usage ring |
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
that [dsh-Go](https://github.com/ccch1mneyyy/dsh-go) uses: streaming-friendly,
syntax-highlighted code blocks with copy, tables, LaTeX and task lists. The input
bar and the model chip follow dsh-Go's composer design (MIT, referenced rather
than copied): a rounded capsule, a leading attach key, an auto-growing borderless
field, the usage ring, and a 36px send/stop key that morphs while a turn runs.
Read-aloud (TTS) is intentionally **not** implemented (matching the original).
## Run
```bash
# terminal probe against a running server
go run ./cmd/ocprobe -url http://127.0.0.1:3000 health
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -limit 5 sessions
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -password secret sessions
go run ./cmd/ocprobe -url http://127.0.0.1:3000 -seconds 20 events
# the app on this computer (browser / GTK window)
asuka dev --platform web
asuka dev
# headless tests, including the UI
go test ./... -race
```
`asuka` must be installed from `main`; the v0.1.1 release does not build on
Linux:
```bash
go install github.com/egoist/asuka/cmd/asuka@main
```
## Android
The SDK lives at `~/SDK/AndroidSDK`, the JDKs at `~/SDK/jdk-21` (Gradle) and
`~/SDK/jdk-17` (the Android toolchain; registered in
`~/.gradle/gradle.properties` via `org.gradle.java.installations.paths`).
Flutter 3.50 (stable) lives at `~/SDK/flutter`; artifacts use the China
mirrors.
```bash
export PATH=$HOME/SDK/flutter/bin:$PATH
export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn
export PUB_HOSTED_URL=https://pub.flutter-io.cn
export ANDROID_HOME=$HOME/SDK/AndroidSDK
export JAVA_HOME=$HOME/SDK/jdk-21
export PATH=$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$JAVA_HOME/bin:$PATH
asuka dev --platform android --device emulator-5554 # hot reload
asuka dev --platform android --once --no-vet # build in, launch once
# release: a keystore is required
export ASUKA_KEYSTORE=$HOME/SDK/test-upload.jks ASUKA_KEY_ALIAS=upload
export ASUKA_KEYSTORE_PASSWORD=… ASUKA_KEY_PASSWORD=…
asuka build --platform android # dist/OpenChamber.aab
flutter pub get
flutter test
flutter build apk --release # dist artifacts in build/app/outputs/flutter-apk
flutter build linux --debug # faster UI checks on the desktop
```
`netcfg/` is a native module whose only job is the Android manifest: it merges
`android:usesCleartextTraffic="true"` into **release** builds too, because
self-hosted OpenChamber servers are often plain HTTP on a LAN. Asuka enables it
for debug only. Delete the package (and its blank import in `main.go`) to
require HTTPS everywhere.
The Linux build only needs a C toolchain and GTK 3 development headers; on
this machine `clang` was extracted into `~/SDK/localbin` (from the
`clang-17` package) and the two missing `-dev` files (`libsecret-1-dev`,
`libjsoncpp-dev`) into `~/SDK/linuxdev`, so:
Proxies are entered as `http://host:port` or `socks5://host:port`
(no proxy authentication). Plain `http://` works in debug builds; the release
cleartext policy is decided in M5 (see `PLAN.md`).
```bash
export PATH=$HOME/SDK/localbin:$HOME/SDK/flutter/bin:$PATH
export PKG_CONFIG_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu/pkgconfig
export LIBRARY_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu
flutter build linux --debug
DISPLAY=:99 GDK_BACKEND=x11 ./build/linux/x64/debug/bundle/openchamber
```
`tool/history_probe.dart` pages a session exactly as the chat does and reports
whether every message is reached.
`android/app/build.gradle.kts` sets the application id
`net.blumia.openchamber.flutter`, `minSdk 24`, and signs releases with
`~/SDK/test-upload.jks` (override via `OPENCHAMBER_KEYSTORE*` env). Dart's
`HttpClient` dials sockets itself, so plain `http://` LAN servers work in
release without a cleartext manifest flag, as with the Go clients. Only a
working connection is saved: a failed attempt stays in the form.
Proxies accept `http://`, `https://`, `socks5://` and `socks5h://` (the
last two resolve names at the proxy). `tool/proxy_probe.dart` checks the
client against a live server through local test proxies.
Earlier attempts: `main` (Asuka/Go, 0.2.x) and `mygo` (MyGo, 0.3.0).
+35
View File
@@ -0,0 +1,35 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- build/**
- android/**
- ios/**
- linux/**
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
+14
View File
@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks
+53
View File
@@ -0,0 +1,53 @@
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "net.blumia.openchamber.flutter"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
applicationId = "net.blumia.openchamber.flutter"
minSdk = 24
targetSdk = flutter.targetSdkVersion
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
// flag during build.
versionCode = flutter.versionCode
versionName = flutter.versionName
}
signingConfigs {
create("release") {
storeFile = file(System.getenv("OPENCHAMBER_KEYSTORE") ?: "/home/blumia/SDK/test-upload.jks")
storePassword = System.getenv("OPENCHAMBER_KEYSTORE_PASSWORD") ?: "testpass"
keyAlias = System.getenv("OPENCHAMBER_KEY_ALIAS") ?: "upload"
keyPassword = System.getenv("OPENCHAMBER_KEY_PASSWORD") ?: "testpass"
}
}
buildTypes {
release {
signingConfig = signingConfigs.getByName("release")
}
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source = "../.."
}
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
+53
View File
@@ -0,0 +1,53 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<!-- The camera plugin declares audio for video; the scanner only reads
frames, so the app must not end up asking for the microphone. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<application
android:label="OpenChamber"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
@@ -0,0 +1,21 @@
package net.blumia.openchamber.flutter
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
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()
}
}
}
}
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
+27
View File
@@ -0,0 +1,27 @@
allprojects {
repositories {
// China mirrors first, then the canonical repositories.
maven { url = uri("https://maven.aliyun.com/repository/google") }
maven { url = uri("https://maven.aliyun.com/repository/central") }
google()
mavenCentral()
}
}
val newBuildDir: Directory =
rootProject.layout.buildDirectory
.dir("../../build")
.get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}
+6
View File
@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false
# This builtInKotlin flag was added by the Flutter template
android.builtInKotlin=false
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip
+30
View File
@@ -0,0 +1,30 @@
pluginManagement {
val flutterSdkPath =
run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
// China mirrors first, then the canonical repositories.
maven { url = uri("https://maven.aliyun.com/repository/google") }
maven { url = uri("https://maven.aliyun.com/repository/central") }
maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") }
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.3.1" apply false
id("org.jetbrains.kotlin.android") version "2.4.20" apply false
}
include(":app")
-11
View File
@@ -1,11 +0,0 @@
{
"name": "OpenChamber",
"id": "com.openchamber.native",
"version": "0.2.2",
"build": 16,
"orientations": [
"portrait",
"landscape"
],
"icon": "assets/icon.png"
}
-222
View File
@@ -1,222 +0,0 @@
// Command ocprobe exercises the OpenChamber API from a terminal. It is the
// M0 probe: no UI, just the same client the app uses.
//
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 health
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 -password secret sessions
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 messages ses_123
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 events -seconds 20
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func main() {
var (
base = flag.String("url", "http://127.0.0.1:3000", "OpenChamber server URL")
password = flag.String("password", "", "UI password (empty for a passwordless server)")
proxy = flag.String("proxy", "", "optional HTTP(S) or SOCKS5 proxy URL")
insecure = flag.Bool("insecure", false, "skip TLS verification")
fp = flag.String("fingerprint", "", "pin the server certificate (SHA-256 hex)")
timeout = flag.Duration("timeout", 20*time.Second, "request timeout")
limit = flag.Int("limit", 20, "page size for sessions/messages")
seconds = flag.Int("seconds", 10, "how long to watch events")
types = flag.String("types", "", "comma-separated event types for events")
)
flag.Parse()
if flag.NArg() == 0 {
usage()
}
cmd := flag.Arg(0)
client, err := ocapi.New(*base, ocapi.Options{
Proxy: *proxy,
InsecureSkipVerify: *insecure,
CertFingerprint: *fp,
Timeout: *timeout,
})
if err != nil {
fail(err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Every command except health authenticates first.
if cmd != "health" {
if err := authenticate(ctx, client, *password); err != nil {
fail(err)
}
}
switch cmd {
case "health":
h, err := client.Health(ctx)
if err != nil {
fail(err)
}
printJSON(h)
fmt.Fprintf(os.Stderr, "server %s, openchamber %s, opencode ready=%v\n", client.BaseURL(), h.OpenChamberVersion, h.IsOpenCodeReady)
case "status":
st, err := client.SessionStatus(ctx)
if err != nil {
fail(err)
}
printJSON(st)
case "sessions":
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: *limit, Order: "desc"})
if err != nil {
fail(err)
}
printJSON(page)
fmt.Fprintf(os.Stderr, "%d sessions, next=%q\n", len(page.Data), page.Cursor.Next)
case "messages":
if flag.NArg() < 2 {
fail(fmt.Errorf("messages needs a session id"))
}
page, err := client.ListMessages(ctx, flag.Arg(1), ocapi.ListMessagesOptions{Limit: *limit, Order: "desc"})
if err != nil {
fail(err)
}
printJSON(page)
fmt.Fprintf(os.Stderr, "%d messages, next=%q\n", len(page.Data), page.Cursor.Next)
case "raw":
if flag.NArg() < 2 {
fail(fmt.Errorf("raw needs an absolute file path, and optionally a directory"))
}
dir := ""
if flag.NArg() > 2 {
dir = flag.Arg(2)
}
data, mime, err := client.RawFile(ctx, flag.Arg(1), dir)
if err != nil {
fail(err)
}
fmt.Fprintf(os.Stderr, "%d bytes, %s\n", len(data), mime)
case "prompt":
if flag.NArg() < 3 {
fail(fmt.Errorf("prompt needs a session id and text"))
}
if err := client.Prompt(ctx, flag.Arg(1), ocapi.PromptOptions{Text: strings.Join(flag.Args()[2:], " ")}); err != nil {
fail(err)
}
fmt.Fprintln(os.Stderr, "prompt accepted; watch `events` for the reply")
case "interrupt":
if flag.NArg() < 2 {
fail(fmt.Errorf("interrupt needs a session id"))
}
ok, err := client.Interrupt(ctx, flag.Arg(1), "")
if err != nil {
fail(err)
}
fmt.Fprintf(os.Stderr, "interrupted=%v\n", ok)
case "events":
var list []string
if strings.TrimSpace(*types) != "" {
for _, t := range strings.Split(*types, ",") {
if t = strings.TrimSpace(t); t != "" {
list = append(list, t)
}
}
}
ectx, cancel := context.WithTimeout(ctx, time.Duration(*seconds)*time.Second)
defer cancel()
fmt.Fprintf(os.Stderr, "watching events for %ds…\n", *seconds)
err := client.StreamEvents(ectx, list, func(ev ocapi.Event) error {
fmt.Printf("%s %s %s\n", time.UnixMilli(ev.Created).Format("15:04:05"), ev.Type, string(ev.Data))
return nil
})
if err != nil && ectx.Err() == nil {
fail(err)
}
default:
usage()
}
}
func authenticate(ctx context.Context, c *ocapi.Client, password string) error {
st, err := c.SessionStatus(ctx)
if err == nil {
if !st.Authenticated {
return fmt.Errorf("server did not accept the request")
}
return nil
}
if !ocapi.IsUnauthorized(err) {
return err
}
if strings.TrimSpace(password) == "" {
return fmt.Errorf("this server requires a password; pass -password")
}
res, err := c.Login(ctx, ocapi.LoginRequest{
Password: password,
DedupeKey: probeDedupeKey(),
ClientLabel: "OpenChamber Probe",
ClientKind: "desktop",
DevicePlatform: "cli",
})
if err != nil {
if wait, ok := ocapi.IsRateLimited(err); ok {
return fmt.Errorf("%w (retry after %s)", err, wait)
}
return err
}
if res.ClientToken == "" {
return fmt.Errorf("login returned no client token")
}
return nil
}
func probeDedupeKey() string {
host, err := os.Hostname()
if err != nil || host == "" {
return "ocprobe"
}
return "ocprobe-" + host
}
func printJSON(v any) {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(v)
}
func usage() {
fmt.Fprint(os.Stderr, `usage: ocprobe [flags] <command>
commands:
health server health (no auth)
status probe /auth/session
sessions list sessions (newest first)
messages <session-id> latest messages of a session
raw <path> [directory] fetch a file the server can read
prompt <session-id> <text> send a message
interrupt <session-id> stop the running turn
events watch the event stream
`)
flag.PrintDefaults()
os.Exit(2)
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "ocprobe:", err)
os.Exit(1)
}
-13
View File
@@ -1,13 +0,0 @@
module github.com/openchamber/openchamber-native
go 1.26.3
require (
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66
golang.org/x/net v0.62.0
)
require (
github.com/ebitengine/purego v0.11.2 // indirect
golang.org/x/text v0.43.0 // indirect
)
-16
View File
@@ -1,16 +0,0 @@
github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66 h1:jhKkamv03qrVjkWGz0vmZtWVoX1sXBF/xOCuG0vNQOc=
github.com/egoist/asuka v0.1.2-0.20261114215826-2602a98fec66/go.mod h1:BDM4nmtZiJ7SqoPnagKW2z5vHAus2Y4Mllg0NtBaKVo=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
-225
View File
@@ -1,225 +0,0 @@
package appui
import (
"encoding/base64"
"fmt"
"mime"
"os"
"path/filepath"
"strings"
"time"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/sdk/device"
"github.com/egoist/asuka/sdk/store"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// maxAttachmentBytes bounds one file: prompts carry their files inline, and
// a huge photo would make the send slow and may exceed what the server
// accepts.
const maxAttachmentBytes = 10 << 20
// attachment is a picked file waiting to ride with the next prompt.
type attachment struct {
Name string
MIME string
DataURL string
Size int64
LocalPath string // a copy in the app's data dir, for inline preview
}
func (ch *chat) attachMenu() {
ui.Alert(ui.AlertProps{
Title: "添加附件",
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("照片"), Icon: "photo", OnPress: ch.pickPhotos},
{Title: ui.Val("文件"), Icon: ui.IconFolder, OnPress: ch.pickFiles},
{Title: ui.Val("取消"), Role: ui.ActionCancel},
},
})
}
func (ch *chat) pickPhotos() {
ch.attaching.Set(true)
device.PickPhotos(5, func(paths []string, err error) {
ch.attaching.Set(false)
if err != nil {
ui.Snackbar(ui.SnackbarProps{Message: "无法选择照片:" + err.Error()})
return
}
for _, path := range paths {
mimeType := mime.TypeByExtension(strings.ToLower(filepath.Ext(path)))
if !strings.HasPrefix(mimeType, "image/") {
mimeType = "image/jpeg"
}
ch.readAttachment(path, filepath.Base(path), mimeType)
}
})
}
func (ch *chat) pickFiles() {
ch.attaching.Set(true)
device.PickFiles(device.FileOptions{Multiple: true}, func(files []device.File, err error) {
ch.attaching.Set(false)
if err != nil {
ui.Snackbar(ui.SnackbarProps{Message: "无法选择文件:" + err.Error()})
return
}
for _, f := range files {
mimeType := f.Type
if mimeType == "" {
mimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(f.Name)))
}
if mimeType == "" {
mimeType = "application/octet-stream"
}
name := f.Name
if name == "" {
name = filepath.Base(f.Path)
}
ch.readAttachment(f.Path, name, mimeType)
}
})
}
// readAttachment reads a picked file off the main thread and hands the
// composer a data URL.
func (ch *chat) readAttachment(path, name, mimeType string) {
go func() {
info, err := os.Stat(path)
if err != nil {
ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) })
return
}
if info.Size() > maxAttachmentBytes {
ui.Post(func() {
ui.Snackbar(ui.SnackbarProps{Message: fmt.Sprintf("%s 超过 10 MB,未添加", name)})
})
return
}
data, err := os.ReadFile(path)
if err != nil {
ui.Post(func() { ui.Snackbar(ui.SnackbarProps{Message: "无法读取 " + name}) })
return
}
url := "data:" + mimeType + ";base64," + base64.StdEncoding.EncodeToString(data)
kept := ""
if strings.HasPrefix(mimeType, "image/") {
kept = keepImage(path, name)
}
ui.Post(func() {
list := ch.attachments.Peek()
next := make([]attachment, len(list), len(list)+1)
copy(next, list)
next = append(next, attachment{Name: name, MIME: mimeType, DataURL: url, Size: info.Size(), LocalPath: kept})
ch.attachments.Set(next)
})
}()
}
func (ch *chat) removeAttachment(index int) {
list := ch.attachments.Peek()
if index < 0 || index >= len(list) {
return
}
next := make([]attachment, 0, len(list)-1)
next = append(next, list[:index]...)
next = append(next, list[index+1:]...)
ch.attachments.Set(next)
}
// attachmentRow shows the files the next prompt will carry.
func (ch *chat) attachmentRow() ui.Node {
return ui.Show(signal.Func(func() bool { return len(ch.attachments.Get()) > 0 }),
func() ui.Node {
return ui.Scroll(
ui.ScrollProps{Horizontal: true, Style: ui.Style{},
ContentStyle: ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6}},
ui.For(ch.attachments, func(a attachment) string { return a.Name + a.DataURL[:24] },
func(a signal.Accessor[attachment], index signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{
Style: ui.Style{Padding: ui.Symmetric(6, 10), CornerRadius: 8,
Background: colors.SecondaryBackground, Align: ui.AlignCenter},
},
ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter},
ui.Symbol("paperclip", ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
ui.Text(signal.Func(func() string {
a := a.Get()
return fmt.Sprintf("%s · %s", a.Name, humanSize(a.Size))
}), ui.Style{Font: fonts.Caption, Lines: 1}),
ui.Button(ui.ButtonProps{Icon: ui.IconClose, Label: ui.Val("移除附件"),
OnPress: func() { ch.removeAttachment(index.Get()) }}),
),
)
}),
)
})
}
func (ch *chat) attachmentFiles() []ocapi.PromptFile {
list := ch.attachments.Peek()
out := make([]ocapi.PromptFile, 0, len(list))
for _, a := range list {
out = append(out, ocapi.PromptFile{URI: a.DataURL, Name: a.Name})
}
return out
}
func (ch *chat) optimisticFiles() []ocapi.FileAttachment {
list := ch.attachments.Peek()
out := make([]ocapi.FileAttachment, 0, len(list))
for _, a := range list {
out = append(out, ocapi.FileAttachment{URI: a.DataURL, Name: a.Name, MIME: a.MIME})
}
return out
}
// keepImage copies a picked image into the app's data dir so the sent
// message can show it inline after a reload clears the caches copy.
func keepImage(source, name string) string {
dir := filepath.Join(store.Dir(), "attachments")
_ = os.MkdirAll(dir, 0o700)
dst := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), sanitizeName(name)))
if err := copyFile(source, dst); err != nil {
return ""
}
return dst
}
func sanitizeName(name string) string {
clean := strings.Map(func(r rune) rune {
switch r {
case '/', '\\', ':', '*', '?', '"', '<', '>', '|':
return '_'
}
return r
}, name)
if clean == "" {
return "image"
}
return clean
}
func copyFile(src, dst string) error {
data, err := os.ReadFile(src)
if err != nil {
return err
}
return os.WriteFile(dst, data, 0o600)
}
func humanSize(bytes int64) string {
switch {
case bytes >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(bytes)/(1<<20))
case bytes >= 1<<10:
return fmt.Sprintf("%.0f KB", float64(bytes)/(1<<10))
default:
return fmt.Sprintf("%d B", bytes)
}
}
File diff suppressed because it is too large. Load diff
-457
View File
@@ -1,457 +0,0 @@
package appui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/egoist/asuka/ui"
"github.com/egoist/asuka/uitest"
)
// chatServer serves one session with a short transcript, and records the
// prompt a test sends.
type chatServer struct {
*httptest.Server
prompts chan map[string]any
replies chan map[string]any
models chan map[string]any
created chan map[string]any
forked chan map[string]any
reverted chan map[string]any
events chan string
ready chan struct{}
readyOne sync.Once
}
func (cs *chatServer) push(ev string) {
select {
case cs.events <- ev:
case <-time.After(2 * time.Second):
panic("event stream is not consuming")
}
}
func newChatServer(t *testing.T) *chatServer {
t.Helper()
cs := &chatServer{
prompts: make(chan map[string]any, 1),
replies: make(chan map[string]any, 1),
models: make(chan map[string]any, 1),
created: make(chan map[string]any, 1),
forked: make(chan map[string]any, 1),
reverted: make(chan map[string]any, 2),
events: make(chan string, 8),
ready: make(chan struct{}),
}
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true}`)
})
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
})
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":{}}`)
})
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[]}`)
})
mux.HandleFunc("/api/session/ses_1/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"msg_1","type":"user","text":"What is this?","time":{"created":10}},
{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
"time":{"created":11,"completed":12000},"cost":0.02,
"tokens":{"input":100500,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
"content":[{"type":"text","text":"**Hello** from the agent"},
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",
"input":{"command":"echo hi"},"content":[],
"metadata":{"openchamberContentShell":{}}}},
{"type":"tool","id":"call_2","name":"read","state":{"status":"completed",
"input":{"filePath":"/home/me/project/shot.png"},"content":[],
"attachments":[{"type":"file","mime":"image/png","filename":"shot.png",
"url":"data:image/png;base64,iVBORw0KGgo="}]}}]}
],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_new/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_1/prompt", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.prompts <- body:
default:
}
cs.events <- `{"id":"evt_2","created":100,"type":"session.step.started","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream"}}`
cs.events <- `{"id":"evt_3","created":101,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream","ordinal":0,"delta":"streamed"}}`
fmt.Fprint(w, `{"data":{}}`)
})
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
})
mux.HandleFunc("/api/model", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"gpt-4","providerID":"openai","name":"GPT-4","limit":{"context":200000,"output":64000}},
{"id":"claude","providerID":"anthropic","name":"Claude","limit":{"context":200000,"output":32000}}]}`)
})
mux.HandleFunc("/api/agent", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[
{"id":"build","name":"Build","mode":"primary"},
{"id":"plan","name":"Plan","mode":"primary"},
{"id":"general","name":"General","mode":"subagent","hidden":false},
{"id":"explore","name":"Explore","mode":"subagent"}]}`)
})
mux.HandleFunc("/api/session/ses_1/model", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.models <- body:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"First session","time":{"created":1,"updated":2},
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`)
return
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.created <- body:
default:
}
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3},
"location":{"directory":"/home/me/project"}}}`)
})
mux.HandleFunc("/api/session/ses_1/message/msg_2", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"id":"msg_2","type":"assistant","agent":"build","model":{"id":"gpt-4","providerID":"openai"},
"time":{"created":11,"completed":12000},"cost":0.02,
"tokens":{"input":100500,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
"content":[{"type":"text","text":"**Hello** from the agent"},
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",
"input":{"command":"echo hi"},"content":[{"type":"text","text":"tool output here"}]}},
{"type":"tool","id":"call_2","name":"read","state":{"status":"completed",
"input":{"filePath":"/home/me/project/shot.png"},"content":[],
"attachments":[{"type":"file","mime":"image/png","filename":"shot.png",
"url":"data:image/png;base64,iVBORw0KGgo="}]}}]}`)
})
mux.HandleFunc("/api/session/ses_1/revert/stage", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.reverted <- body:
default:
}
fmt.Fprint(w, `{"data":{"messageID":"msg_1"}}`)
})
mux.HandleFunc("/api/session/ses_1/revert/commit", func(w http.ResponseWriter, r *http.Request) {
select {
case cs.reverted <- map[string]any{"commit": true}:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/session/ses_1/fork", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.forked <- body:
default:
}
fmt.Fprint(w, `{"data":{"id":"ses_fork","title":"Forked","time":{"created":20,"updated":20},
"location":{"directory":"/home/me/project"}}}`)
})
mux.HandleFunc("/api/session/ses_fork/message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[],"cursor":{}}`)
})
mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
select {
case cs.replies <- body:
default:
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
cs.readyOne.Do(func() { close(cs.ready) })
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
for {
select {
case ev := <-cs.events:
fmt.Fprintf(w, "data: %s\n\n", ev)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
case <-r.Context().Done():
return
}
}
})
cs.Server = httptest.NewServer(mux)
t.Cleanup(cs.Close)
return cs
}
func TestOpenSessionAndSend(t *testing.T) {
srv := newChatServer(t)
st := &memStore{}
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
select {
case <-srv.ready:
case <-time.After(5 * time.Second):
t.Fatal("the event stream was never opened")
}
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Expect("What is this?")
a.Type("发消息…", "ping")
a.Tap("发送")
a.WaitFor("ping")
a.WaitFor("streamed")
select {
case body := <-srv.prompts:
if body["text"] != "ping" {
t.Errorf("prompt text = %v", body["text"])
}
if id, _ := body["id"].(string); len(id) < 5 || id[:4] != "msg_" {
t.Errorf("prompt id = %v", body["id"])
}
default:
t.Fatal("no prompt reached the server")
}
}
func TestPermissionCardAndReply(t *testing.T) {
srv := newChatServer(t)
// The session list's pending-permission read.
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
select {
case <-srv.ready:
case <-time.After(5 * time.Second):
t.Fatal("no event stream")
}
a.Tap("First session")
a.WaitFor("Hello from the agent")
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
a.Settle()
a.WaitFor("需要权限:bash")
a.Expect("npm test")
a.Tap("允许一次")
select {
case body := <-srv.replies:
if body["decision"] != "once" {
t.Errorf("decision = %v", body["decision"])
}
case <-time.After(3 * time.Second):
t.Fatal("no permission reply reached the server")
}
}
func TestSwitchModel(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("模型")
a.WaitFor("GPT-4")
a.Tap("GPT-4")
select {
case body := <-srv.models:
model, _ := body["model"].(map[string]any)
if model["id"] != "gpt-4" || model["providerID"] != "openai" {
t.Errorf("model switch = %v", body)
}
case <-time.After(3 * time.Second):
t.Fatal("no model switch reached the server")
}
}
func TestCreateSession(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("新建")
a.WaitFor("新建会话")
a.Type("标题(可选,留空由服务端生成)", "Test chat")
a.Tap("创建")
a.WaitFor("New chat")
select {
case body := <-srv.created:
if body["title"] != "Test chat" {
t.Errorf("created title = %v", body["title"])
}
loc, _ := body["location"].(map[string]any)
if loc["directory"] != "/home/me/project" {
t.Errorf("created location = %v", body["location"])
}
case <-time.After(3 * time.Second):
t.Fatal("no create request reached the server")
}
}
func TestAgentPickerSkipsSubagents(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("Agent")
a.WaitFor("Build")
a.Expect("Plan")
a.ExpectNo("General")
a.ExpectNo("Explore")
}
func TestTurnFooter(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// The footer names the model, the agent and how long the turn took.
a.WaitFor("GPT-4 · build · 12.0s")
a.Tap("更多操作")
a.WaitFor("复制回答")
a.Expect("从这里分叉")
a.Back()
}
func TestForkFromTurnFooter(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.Tap("更多操作")
a.Tap("从这里分叉")
a.WaitFor("Forked")
select {
case body := <-srv.forked:
if _, ok := body["before"]; ok {
t.Errorf("fork sent a before id for the last message: %v", body)
}
case <-time.After(3 * time.Second):
t.Fatal("no fork request reached the server")
}
}
func TestUserMessageActions(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("What is this?")
a.Expect("复制消息")
a.Tap("消息操作")
a.WaitFor("从这里分叉")
a.Expect("复制消息")
a.Back()
}
func TestToolResultLoadsOnExpand(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// The list page shells the tool result; opening the row fetches it.
a.ExpectNo("tool output here")
a.Tap("✓ shell echo hi ▸")
a.WaitFor("tool output here")
}
func TestRevertFromUserMessage(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("What is this?")
a.Tap("消息操作")
a.Tap("撤回此消息及之后")
a.WaitFor("撤回消息?")
a.Tap("撤回")
stage := <-srv.reverted
if _, ok := stage["commit"]; ok {
t.Fatalf("unexpected first message: %v", stage)
}
if stage["messageID"] != "msg_1" {
t.Errorf("stage messageID = %v", stage["messageID"])
}
commit := <-srv.reverted
if _, ok := commit["commit"]; !ok {
t.Errorf("commit not sent: %v", commit)
}
}
func TestContextUsageRingAndSheet(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
// 100500 tokens over 200000 - min(64000, 32000).
a.WaitFor("59.8%")
a.Tap("上下文占用")
a.WaitFor("上下文上限")
a.WaitFor("200.0K")
a.WaitFor("64.0K")
}
func TestToolImagePreviewSheet(t *testing.T) {
srv := newChatServer(t)
a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid))
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("First session")
a.WaitFor("Hello from the agent")
a.WaitFor("预览 shot.png")
a.Tap("预览 shot.png")
a.WaitFor("图片预览")
}
-368
View File
@@ -1,368 +0,0 @@
package appui
import (
"strings"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/storage"
)
// connectionsScreen is the first screen: the saved servers, or the
// introduction when there are none. It mirrors the first-party client: the
// server last used leads, the others follow, and adding is one tap away.
func (c *controller) connectionsScreen() ui.Node {
return ui.Dynamic(func() ui.Node {
list := c.connections.Get()
if len(list) == 0 {
return c.firstRun()
}
lead := list[0]
for _, conn := range list {
if conn.ID == c.activeID.Get() && c.connected.Get() {
lead = conn
}
}
others := make([]storage.Connection, 0, len(list))
for _, conn := range list {
if conn.ID != lead.ID {
others = append(others, conn)
}
}
return ui.Scroll(
ui.ScrollProps{
Style: ui.Style{Grow: 1},
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
},
ui.StaticText("OpenChamber", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
c.leadCard(lead),
ui.Show(signal.Func(func() bool { return len(c.connections.Get()) > 1 }), func() ui.Node {
return ui.Column(ui.Style{Gap: 6},
ui.StaticText("其他服务器", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
ui.For(c.otherConnections(lead.ID), func(conn storage.Connection) string { return conn.ID },
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
return c.connectionRow(conn)
}),
)
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("添加服务器"),
Icon: ui.IconPlus,
Variant: ui.ButtonTinted,
OnPress: c.openAddForm,
}),
)
})
}
func (c *controller) otherConnections(leadID string) signal.Accessor[[]storage.Connection] {
return signal.Func(func() []storage.Connection {
out := make([]storage.Connection, 0, len(c.connections.Get()))
for _, conn := range c.connections.Get() {
if conn.ID != leadID {
out = append(out, conn)
}
}
return out
})
}
func (c *controller) firstRun() ui.Node {
return ui.Scroll(
ui.ScrollProps{
Style: ui.Style{Grow: 1},
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
},
ui.StaticText("OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
ui.StaticText("连接到正在运行的 OpenChamber 服务器。保存过的服务器会出现在这里,可以随时切换。",
ui.Style{Color: colors.SecondaryLabel}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("手动输入地址"),
Icon: "link",
Variant: ui.ButtonFilled,
OnPress: c.openAddForm,
}),
)
}
func (c *controller) leadCard(conn storage.Connection) ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.All(16), Gap: 8, CornerRadius: 14,
Background: colors.SecondaryBackground}},
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
OnPress: func() { c.connectionActions(conn) }}),
),
ui.Show(signal.Func(func() bool { return c.activeID.Get() == conn.ID && c.connected.Get() }),
func() ui.Node {
return ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
CornerRadius: 4, Background: colors.Accent}}),
ui.StaticText("已连接", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
},
func() ui.Node {
return ui.Show(signal.Func(func() bool { return c.connecting.Get() == conn.ID }),
func() ui.Node {
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignCenter},
ui.Activity(), ui.StaticText("连接中…", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}))
},
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("连接"),
Variant: ui.ButtonFilled,
OnPress: func() { c.connectTo(conn, "", true) },
})
})
}),
)
}
func (c *controller) connectionRow(conn signal.Accessor[storage.Connection]) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() { c.selectConnection(conn.Get()) },
Style: ui.Style{Padding: ui.Symmetric(10, 12), CornerRadius: 10, Gap: 6},
}, ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.Text(signal.Func(func() string { return c.labelOf(conn.Get()) }), ui.Style{Font: fonts.Body, Lines: 1}),
ui.Text(signal.Func(func() string { return conn.Get().URL }),
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
OnPress: func() { c.connectionActions(conn.Get()) }}),
))
}
func (c *controller) selectConnection(conn storage.Connection) {
c.instancesOpen.Set(false)
if conn.ID == c.activeID.Peek() && c.connected.Peek() {
return
}
if c.connected.Peek() {
c.logout("")
}
c.connectTo(conn, "", true)
}
func (c *controller) connectionActions(conn storage.Connection) {
ui.Alert(ui.AlertProps{
Title: c.labelOf(conn),
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("连接"), Icon: "play", OnPress: func() { c.selectConnection(conn) }},
{Title: ui.Val("编辑"), Icon: "pencil", OnPress: func() { c.openEditForm(conn) }},
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDeleteConnection(conn) }},
},
})
}
func (c *controller) confirmDeleteConnection(conn storage.Connection) {
ui.Alert(ui.AlertProps{
Title: "删除服务器?",
Message: "只会删除这个客户端里保存的连接,服务器上的数据不受影响。",
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
OnPress: func() { c.deleteConnection(conn) }},
},
})
}
func (c *controller) deleteConnection(conn storage.Connection) {
if c.activeID.Peek() == conn.ID {
c.logout("")
}
list := c.connections.Peek()
next := make([]storage.Connection, 0, len(list))
for _, saved := range list {
if saved.ID != conn.ID {
next = append(next, saved)
}
}
c.st.SaveConnections(next)
c.connections.Set(next)
go func() { _ = c.st.ClearToken(conn) }()
}
// formSheet is the add/edit form, a full-screen sheet like the first-party
// client's panel.
func (c *controller) formSheet() ui.Node {
title := "添加服务器"
if c.formEditID != "" {
title = "编辑服务器"
}
submit := "连接"
if c.connected.Peek() {
submit = "保存"
}
return ui.Sheet(ui.SheetProps{
Open: c.formOpen,
FullScreen: true,
Content: func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Scroll(
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14}},
ui.Row(ui.Style{Align: ui.AlignCenter},
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.closeForm}),
),
ui.TextField(ui.TextFieldProps{
Value: c.formLabel,
Placeholder: ui.Val("名称(可选)"),
}),
ui.TextField(ui.TextFieldProps{
Value: c.url,
Placeholder: ui.Val("http://192.168.1.5:3000"),
Keyboard: ui.KeyboardURL,
ContentType: "url",
Autocapitalize: ui.CapitalizeNone,
Autocorrect: ui.AutocorrectNo,
ReturnKey: ui.ReturnNext,
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("使用代理", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.formUseProxy}),
),
ui.Show(c.formUseProxy, func() ui.Node {
return ui.TextField(ui.TextFieldProps{
Value: c.formProxy,
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
Keyboard: ui.KeyboardURL,
Autocapitalize: ui.CapitalizeNone,
Autocorrect: ui.AutocorrectNo,
})
}),
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
ui.Toggle(ui.ToggleProps{Value: c.formInsecure}),
),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val(submit),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool { return c.connecting.Get() != "" }),
OnPress: c.submitForm,
}),
),
)
},
})
}
func (c *controller) passwordSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.passwordOpen,
Detents: ui.DetentMedium,
Grabber: true,
OnDismiss: c.cancelPassword,
Content: func() ui.Node {
conn := c.passwordFor
for _, saved := range c.connections.Peek() {
if saved.ID == conn.ID {
conn = saved
}
}
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14},
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
ui.StaticText("这台服务器需要密码。", ui.Style{Color: colors.SecondaryLabel}),
ui.TextField(ui.TextFieldProps{
Value: c.passwordText,
Placeholder: ui.Val("密码"),
Secure: true,
ContentType: ui.ContentPassword,
ReturnKey: ui.ReturnGo,
OnSubmit: c.submitPassword,
}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.Row(ui.Style{Justify: ui.JustifyEnd, Gap: 8},
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.cancelPassword}),
ui.Button(ui.ButtonProps{
Title: ui.Val("解锁"),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool {
return c.passwordBusy.Get() || strings.TrimSpace(c.passwordText.Get()) == ""
}),
OnPress: c.submitPassword,
}),
),
)
},
})
}
// instancesSheet is the switcher while connected: the same list, in a sheet.
func (c *controller) instancesSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.instancesOpen,
FullScreen: true,
Content: func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Scroll(
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 12}},
ui.Row(ui.Style{Align: ui.AlignCenter},
ui.StaticText("实例", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
ui.Button(ui.ButtonProps{Title: ui.Val("关闭"),
OnPress: func() { c.instancesOpen.Set(false) }}),
),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
}),
ui.For(c.connections, func(conn storage.Connection) string { return conn.ID },
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
return ui.Column(ui.Style{Gap: 4},
c.connectionRow(conn),
ui.Show(signal.Func(func() bool {
return conn.Get().ID == c.activeID.Get() && c.connected.Get()
}), func() ui.Node {
return ui.StaticText("当前连接", ui.Style{Font: fonts.Footnote,
Color: colors.SecondaryLabel, Padding: ui.Symmetric(0, 12)})
}),
)
}),
ui.Show(signal.Func(func() bool { return c.connected.Get() }),
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("断开当前连接"),
Variant: ui.ButtonGray,
OnPress: func() {
c.instancesOpen.Set(false)
c.disconnect()
},
})
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("添加服务器"),
Icon: ui.IconPlus,
Variant: ui.ButtonTinted,
OnPress: func() {
c.instancesOpen.Set(false)
c.openAddForm()
},
}),
),
)
},
})
}
-198
View File
@@ -1,198 +0,0 @@
package appui
import (
"fmt"
"math"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// modelLimit is a model's context and output window.
type modelLimit struct {
Context int
Output int
}
// usageReading is the context window of the last assistant message that
// reported tokens, as the first-party client shows it. The output
// reservation is capped at 32k tokens, matching its calculation.
type usageReading struct {
Used int
Limit int
Output int
Pct float64
Known bool
Cost float64
Model string
}
func (ch *chat) usageReading(msgs []ocapi.Message) usageReading {
var last *ocapi.Message
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Type == "assistant" && msgs[i].Tokens != nil {
last = &msgs[i]
break
}
}
if last == nil {
return usageReading{}
}
// A message the event stream added has no model yet; the session's model
// is the latest one any message reports.
model := last.Model
for i := len(msgs) - 1; i >= 0 && model == nil; i-- {
if msgs[i].Type == "assistant" && msgs[i].Model != nil {
model = msgs[i].Model
}
}
if model == nil {
return usageReading{}
}
var r usageReading
t := last.Tokens
if t.Total > 0 {
r.Used = int(t.Total)
} else {
r.Used = int(t.Input + t.Output + t.Reasoning + t.Cache.Read + t.Cache.Write)
}
lim := ch.modelLimit(model)
r.Limit, r.Output = lim.Context, lim.Output
r.Model = ch.modelName(model)
// The turn's cost is every step after its prompt.
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Type == "user" {
break
}
if msgs[i].Type == "assistant" {
r.Cost += msgs[i].Cost
}
}
if r.Limit <= 0 || r.Used <= 0 {
return r
}
reserve := r.Output
if reserve > 32000 {
reserve = 32000
}
threshold := r.Limit - reserve
if threshold < 1 {
threshold = 1
}
r.Pct = math.Min(100, float64(r.Used)/float64(threshold)*100)
r.Known = true
return r
}
func (ch *chat) contextUsage() usageReading {
return ch.usageReading(ch.msgs.Peek())
}
func (ch *chat) modelLimit(m *ocapi.ModelRef) modelLimit {
if m == nil {
return modelLimit{}
}
limits := ch.modelLimits.Get()
if l, ok := limits[m.ProviderID+"/"+m.ID]; ok {
return l
}
return limits[m.ID]
}
func formatTokens(n int) string {
switch {
case n >= 1_000_000:
return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
case n >= 1_000:
return fmt.Sprintf("%.1fK", float64(n)/1_000)
default:
return fmt.Sprintf("%d", n)
}
}
// usageTone follows the first-party thresholds: 75% warns, 90% errors.
func usageTone(pct float64) ui.Color {
switch {
case pct >= 90:
return colors.Red
case pct >= 75:
return colors.Orange
default:
return colors.Green
}
}
// usageButton is the composer's context ring and percentage.
func (ch *chat) usageButton() ui.Node {
return ui.Dynamic(func() ui.Node {
r := ch.usageReading(ch.msgs.Get())
if !r.Known {
return ui.View(ui.ViewProps{})
}
progress := signal.Func(func() float64 { return r.Pct / 100 })
return ui.View(ui.ViewProps{
OnPress: func() { ch.usageOpen.Set(true) },
Label: ui.Val("上下文占用"),
Hint: ui.Val("查看上下文详情"),
Style: ui.Style{Padding: ui.All(4), Align: ui.AlignCenter},
}, ui.Row(ui.Style{Gap: 4, Align: ui.AlignCenter},
ui.ProgressRing(progress, ui.Style{Width: ui.Pt(18), Height: ui.Pt(18), Color: usageTone(r.Pct)}),
ui.StaticText(fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999)),
ui.Style{Font: fonts.Caption, Color: colors.SecondaryLabel}),
))
})
}
func (ch *chat) usageSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: ch.usageOpen,
Detents: ui.DetentMedium,
Grabber: true,
OnDismiss: func() { ch.usageOpen.Set(false) },
Content: func() ui.Node {
return ui.Dynamic(func() ui.Node {
r := ch.usageReading(ch.msgs.Get())
rows := []ui.Node{usageRow("模型", r.Model)}
if r.Known {
rows = append(rows,
usageRow("已用 tokens", formatTokens(r.Used)),
usageRow("上下文上限", formatTokens(r.Limit)),
usageRow("输出预留", formatTokens(r.Output)),
usageRow("占用", fmt.Sprintf("%.1f%%", math.Min(r.Pct, 999))),
)
} else {
rows = append(rows,
usageRow("已用 tokens", formatTokens(r.Used)),
usageRow("上下文上限", "未知"),
)
}
if r.Cost > 0 {
rows = append(rows, usageRow("本轮费用", formatCost(r.Cost)))
}
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 10},
ui.StaticText("上下文占用", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.Column(ui.Style{Gap: 10}, rows...),
ui.StaticText("输出预留按最多 32K tokens 计算,与官方客户端一致。",
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
})
},
})
}
func formatCost(v float64) string {
if v < 0.01 {
return fmt.Sprintf("$%.4f", v)
}
return fmt.Sprintf("$%.2f", v)
}
func usageRow(label, value string) ui.Node {
return ui.Row(ui.Style{Gap: 12, Align: ui.AlignCenter},
ui.StaticText(label, ui.Style{Font: fonts.Body, Color: colors.SecondaryLabel, Grow: 1}),
ui.StaticText(value, ui.Style{Font: fonts.Body}),
)
}
-91
View File
@@ -1,91 +0,0 @@
package appui
import (
"math"
"testing"
"github.com/egoist/asuka/signal"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func usageTestChat(limits map[string]modelLimit) *chat {
return &chat{
modelLimits: signal.NewFunc(limits, nil),
modelNames: signal.NewFunc(map[string]string{}, nil),
}
}
func TestUsageReadingCapsOutputReserve(t *testing.T) {
ch := usageTestChat(map[string]modelLimit{
"p/m": {Context: 200_000, Output: 64_000},
})
msgs := []ocapi.Message{{
Type: "assistant",
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: &ocapi.TokenUsage{Total: 50_000},
Cost: 0.02,
}}
r := ch.usageReading(msgs)
if !r.Known {
t.Fatal("usage should be known")
}
if r.Limit != 200_000 || r.Output != 64_000 || r.Used != 50_000 {
t.Errorf("reading = %+v", r)
}
// 200k - min(64k, 32k) = 168k; 50k / 168k = 29.76%
want := 50_000.0 / 168_000.0 * 100
if math.Abs(r.Pct-want) > 1e-9 {
t.Errorf("pct = %v, want %v", r.Pct, want)
}
if r.Cost != 0.02 {
t.Errorf("cost = %v", r.Cost)
}
}
func TestUsageReadingFallsBackToFieldSum(t *testing.T) {
ch := usageTestChat(map[string]modelLimit{
"p/m": {Context: 100_000, Output: 8_000},
})
tokens := &ocapi.TokenUsage{Input: 10, Output: 20, Reasoning: 30}
tokens.Cache.Read = 40
tokens.Cache.Write = 50
r := ch.usageReading([]ocapi.Message{{
Type: "assistant",
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: tokens,
}})
if r.Used != 150 {
t.Errorf("used = %d, want 150", r.Used)
}
if want := 150.0 / 92_000.0 * 100; math.Abs(r.Pct-want) > 1e-9 {
t.Errorf("pct = %v, want %v", r.Pct, want)
}
}
func TestUsageReadingUnknownWithoutLimit(t *testing.T) {
ch := usageTestChat(nil)
r := ch.usageReading([]ocapi.Message{{
Type: "assistant",
Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: &ocapi.TokenUsage{Total: 500},
}})
if r.Known || r.Pct != 0 {
t.Errorf("reading = %+v, want unknown", r)
}
}
func TestUsageReadingBorrowsModelFromEarlierMessage(t *testing.T) {
ch := usageTestChat(map[string]modelLimit{
"p/m": {Context: 100_000, Output: 8_000},
})
msgs := []ocapi.Message{
{Type: "assistant", Model: &ocapi.ModelRef{ID: "m", ProviderID: "p"},
Tokens: &ocapi.TokenUsage{Total: 1_000}},
// Added by the event stream: tokens, but no model yet.
{Type: "assistant", Tokens: &ocapi.TokenUsage{Total: 2_000}},
}
r := ch.usageReading(msgs)
if !r.Known || r.Used != 2_000 || r.Limit != 100_000 {
t.Errorf("reading = %+v", r)
}
}
-305
View File
@@ -1,305 +0,0 @@
package appui
import (
"context"
"encoding/json"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// eventTypes are the event kinds the list and chat read. Sending the filter
// keeps a phone's stream small; server.connected always arrives.
var eventTypes = []string{
"session.created",
"session.renamed",
"session.archived",
"session.unarchived",
"session.deleted",
"session.moved",
"session.model.selected",
"session.agent.selected",
"session.metadata.updated",
"session.execution.started",
"session.execution.succeeded",
"session.execution.failed",
"session.execution.interrupted",
"session.step.started",
"session.step.ended",
"session.step.failed",
"session.text.started",
"session.text.delta",
"session.text.ended",
"session.reasoning.started",
"session.reasoning.delta",
"session.reasoning.ended",
"session.tool.called",
"session.tool.success",
"session.tool.failed",
"permission.asked",
"permission.replied",
}
type sessionCreatedData struct {
SessionID string `json:"sessionID"`
ProjectID string `json:"projectID"`
Title string `json:"title"`
Agent string `json:"agent"`
Model *ocapi.ModelRef `json:"model"`
Location *ocapi.Location `json:"location"`
Subpath string `json:"subpath"`
Metadata json.RawMessage `json:"metadata"`
}
type sessionRenamedData struct {
SessionID string `json:"sessionID"`
Title string `json:"title"`
}
type sessionRefData struct {
SessionID string `json:"sessionID"`
}
type sessionModelData struct {
SessionID string `json:"sessionID"`
Model *ocapi.ModelRef `json:"model"`
}
type sessionAgentData struct {
SessionID string `json:"sessionID"`
Agent string `json:"agent"`
}
type permissionData struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Action string `json:"action"`
Resources []string `json:"resources"`
}
// startEvents subscribes to the server's event stream for the given client.
// It must run on the main thread (it writes the cancel function).
func (c *controller) startEvents(client *ocapi.Client) {
if c.cancelSSE != nil {
c.cancelSSE()
}
ctx, cancel := context.WithCancel(context.Background())
c.cancelSSE = cancel
// A stream that reconnects lost events; a fresh connection (the one
// made when connecting) is the list's first read, not a gap.
wasDown := false
sub := ocapi.Subscription{
Types: eventTypes,
OnEvent: func(ev ocapi.Event) {
ui.Post(func() {
if c.client != client {
return
}
c.applyEvent(ev)
})
},
OnState: func(st ocapi.SubscriptionState, err error) {
switch st {
case ocapi.Disconnected:
wasDown = true
ui.Post(func() {
if c.client != client {
return
}
c.status.Set("连接中断,正在重连…")
})
case ocapi.Subscribed:
if !wasDown {
return
}
wasDown = false
// Events missed while the stream was down are gone;
// re-read the list and the open chat's tail.
ui.Post(func() {
if c.client != client {
return
}
c.refresh()
if c.chat != nil {
c.chat.reloadTail()
}
})
}
},
}
go client.Subscribe(ctx, sub)
}
// applyEvent folds one server event into the list state. Main thread.
func (c *controller) applyEvent(ev ocapi.Event) {
if c.chat != nil {
var ref struct {
SessionID string `json:"sessionID"`
}
if ev.UnmarshalData(&ref) == nil && ref.SessionID == c.chat.id {
c.chat.handleEvent(ev)
}
}
switch ev.Type {
case "session.created":
var d sessionCreatedData
if ev.UnmarshalData(&d) != nil || d.SessionID == "" {
return
}
list := c.sessions.Peek()
for _, s := range list {
if s.ID == d.SessionID {
return
}
}
next := make([]ocapi.Session, 0, len(list)+1)
next = append(next, ocapi.Session{
ID: d.SessionID,
ProjectID: d.ProjectID,
Title: d.Title,
Agent: d.Agent,
Model: d.Model,
Location: d.Location,
Time: ocapi.SessionTime{Created: ev.Created, Updated: ev.Created},
})
c.sessions.Set(append(next, list...))
case "session.renamed":
var d sessionRenamedData
if ev.UnmarshalData(&d) != nil {
return
}
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Title = d.Title })
case "session.model.selected":
var d sessionModelData
if ev.UnmarshalData(&d) != nil {
return
}
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Model = d.Model })
case "session.agent.selected":
var d sessionAgentData
if ev.UnmarshalData(&d) != nil {
return
}
c.patchSession(d.SessionID, func(s *ocapi.Session) { s.Agent = d.Agent })
case "session.archived":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.removeSession(d.SessionID)
case "session.deleted":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.removeSession(d.SessionID)
case "session.unarchived", "session.moved":
// The event carries no full record; a list read is the truth.
c.refresh()
case "session.execution.started":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.setActive(d.SessionID, true)
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
var d sessionRefData
if ev.UnmarshalData(&d) != nil {
return
}
c.setActive(d.SessionID, false)
case "permission.asked":
var d permissionData
if ev.UnmarshalData(&d) != nil || d.ID == "" {
return
}
list := c.perms.Peek()
for _, p := range list {
if p.ID == d.ID {
return
}
}
next := make([]ocapi.PermissionRequest, len(list), len(list)+1)
copy(next, list)
next = append(next, ocapi.PermissionRequest{
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
})
c.perms.Set(next)
if c.chat != nil {
c.chat.syncPerms()
}
case "permission.replied":
var d struct {
RequestID string `json:"requestID"`
}
if ev.UnmarshalData(&d) != nil || d.RequestID == "" {
return
}
list := c.perms.Peek()
next := make([]ocapi.PermissionRequest, 0, len(list))
for _, p := range list {
if p.ID != d.RequestID {
next = append(next, p)
}
}
if len(next) != len(list) {
c.perms.Set(next)
if c.chat != nil {
c.chat.syncPerms()
}
}
}
}
func (c *controller) patchSession(id string, patch func(*ocapi.Session)) {
list := c.sessions.Peek()
next := make([]ocapi.Session, len(list))
copy(next, list)
for i := range next {
if next[i].ID == id {
patch(&next[i])
c.sessions.Set(next)
return
}
}
}
func (c *controller) removeSession(id string) {
list := c.sessions.Peek()
next := make([]ocapi.Session, 0, len(list))
for _, s := range list {
if s.ID != id {
next = append(next, s)
}
}
if len(next) != len(list) {
c.sessions.Set(next)
}
}
func (c *controller) setActive(id string, on bool) {
cur := c.active.Peek()
if cur[id] == on {
return
}
next := make(map[string]bool, len(cur)+1)
for k, v := range cur {
next[k] = v
}
if on {
next[id] = true
} else {
delete(next, id)
}
c.active.Set(next)
}
-30
View File
@@ -1,30 +0,0 @@
package appui
import (
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/sdk/svg"
"github.com/egoist/asuka/ui"
)
// serverIcon is a rack, drawn as vector paths: Asuka's built-in symbols
// have no server glyph on Android, and an SVG keeps it crisp at any size.
var serverIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/></svg>`)
// sparklesIcon marks the turn footer. Drawn here for the same reason as
// the server icon: not every platform's symbol set has the name.
var sparklesIcon = svg.MustParse(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l1.7 4.3L18 9l-4.3 1.7L12 15l-1.7-4.3L6 9l4.3-1.7L12 3z"/><path d="M19 15l.8 1.9L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-1.1L19 15z"/></svg>`)
// instancesButton opens the server list: one button, because picking a
// server is also how the live one is replaced.
func (c *controller) instancesButton() ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() { c.instancesOpen.Set(true) },
Label: ui.Val("实例"),
Hint: ui.Val("打开服务器列表"),
Style: ui.Style{Padding: ui.All(8)},
}, svg.View(svg.Props{
Icon: serverIcon,
Color: ui.Val(colors.Accent),
Style: ui.Style{Width: ui.Pt(22), Height: ui.Pt(22)},
}))
}
-264
View File
@@ -1,264 +0,0 @@
package appui
import (
"context"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/sdk/store"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
var imagePathPattern = regexp.MustCompile(`(/[^\s"'` + "`" + `()\[\]{}<>]+\.(?:png|jpg|jpeg|gif|webp|bmp|avif))`)
var imageExtensions = map[string]bool{
".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
".webp": true, ".bmp": true, ".avif": true,
}
// imageRef is one previewable image a tool call names: the Source is an
// absolute path or a data URL, the Label what its row shows.
type imageRef struct {
Source string
Label string
}
func isImagePath(path string) bool {
return imageExtensions[strings.ToLower(filepath.Ext(path))]
}
// toolImages lists the images a tool call names: its file input, file parts
// in its output (data URLs from a read, for example), and paths in its text
// output. Relative paths resolve against the session's directory.
func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef {
seen := map[string]bool{}
out := make([]imageRef, 0, 2)
hasLabel := func(label string) bool {
for _, ref := range out {
if ref.Label == label {
return true
}
}
return false
}
add := func(source, label string) {
source = strings.TrimSpace(source)
if strings.HasPrefix(source, "file://") {
source = strings.TrimPrefix(source, "file://")
}
if source == "" || seen[source] {
return
}
if !strings.HasPrefix(source, "data:") {
if strings.Contains(source, "://") {
return
}
if !strings.HasPrefix(source, "/") {
if ch.dir == "" {
return
}
source = filepath.Join(ch.dir, source)
}
if !isImagePath(source) {
return
}
if label == "" {
label = filepath.Base(source)
}
}
if label == "" {
label = "图片"
}
seen[source] = true
out = append(out, imageRef{Source: source, Label: label})
}
addPath := func(path string) {
path = strings.TrimSpace(path)
if strings.HasPrefix(path, "file://") {
path = strings.TrimPrefix(path, "file://")
} else if strings.Contains(path, "://") {
return
}
if !strings.HasPrefix(path, "/") {
if ch.dir == "" {
return
}
path = filepath.Join(ch.dir, path)
}
if !isImagePath(path) || hasLabel(filepath.Base(path)) {
return
}
add(path, "")
}
attachments := 0
if p.State != nil {
// Server-projected tool attachments carry the image itself, so they
// come first: a read of an image needs no file request.
for _, group := range [][]ocapi.ContentPart{p.State.Attachments, p.State.Content} {
for _, c := range group {
switch c.Type {
case "file":
source := c.URL
if source == "" {
source = c.URI
}
if source != "" && strings.HasPrefix(c.MIME, "image/") {
attachments++
add(source, c.Filename)
}
case "text":
for _, m := range imagePathPattern.FindAllString(c.Text, -1) {
addPath(m)
}
}
}
}
// The attachment already is the image the call named.
if attachments == 0 {
for _, key := range []string{"filePath", "path", "file", "file_path", "sourcePath"} {
if v, ok := p.State.Input[key].(string); ok {
addPath(v)
}
}
}
}
return out
}
func (ch *chat) toolImageAccessor(part signal.Accessor[ocapi.ContentPart]) signal.Accessor[[]imageRef] {
return signal.Func(func() []imageRef { return ch.toolImages(part.Get()) })
}
// previewKey names a cached preview: a hash keeps data URLs out of the map.
func previewKey(source string) string {
sum := sha1.Sum([]byte(source))
return hex.EncodeToString(sum[:])
}
func (ch *chat) previewImage(ref imageRef) {
ch.previewSeq++
seq := ch.previewSeq
ch.previewTitle.Set(ref.Label)
ch.previewPath.Set("")
ch.previewLoading.Set(true)
ch.previewOpen.Set(true)
key := previewKey(ref.Source)
if local, ok := ch.previewCache[key]; ok {
ch.previewPath.Set(local)
ch.previewLoading.Set(false)
return
}
go func() {
data, err := ch.loadPreview(ref.Source)
if err != nil {
ui.Post(func() {
if seq != ch.previewSeq {
return
}
ch.previewLoading.Set(false)
ch.previewOpen.Set(false)
ui.Snackbar(ui.SnackbarProps{Message: "无法预览:" + friendlyError(err)})
})
return
}
dir := filepath.Join(store.Dir(), "previews")
_ = os.MkdirAll(dir, 0o700)
name := strings.Map(func(r rune) rune {
if r == '/' || r == '\\' || r == ':' || r < ' ' {
return '_'
}
return r
}, ref.Label)
local := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), name))
if err := os.WriteFile(local, data, 0o600); err != nil {
ui.Post(func() {
if seq != ch.previewSeq {
return
}
ch.previewLoading.Set(false)
ch.previewOpen.Set(false)
ui.Snackbar(ui.SnackbarProps{Message: "无法保存预览"})
})
return
}
ui.Post(func() {
if seq != ch.previewSeq {
return
}
ch.previewCache[key] = local
ch.previewPath.Set(local)
ch.previewLoading.Set(false)
})
}()
}
// loadPreview reads a data URL itself or asks the server for the file.
func (ch *chat) loadPreview(source string) ([]byte, error) {
if strings.HasPrefix(source, "data:") {
comma := strings.IndexByte(source, ',')
if comma < 0 {
return nil, fmt.Errorf("malformed data URL")
}
meta := source[len("data:"):comma]
if !strings.Contains(meta, ";base64") {
return nil, fmt.Errorf("unsupported data URL")
}
return base64.StdEncoding.DecodeString(source[comma+1:])
}
client := ch.client()
if client == nil {
return nil, fmt.Errorf("not connected")
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
data, _, err := client.RawFile(ctx, source, ch.dir)
return data, err
}
func (ch *chat) previewSheet() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: ch.previewOpen,
Detents: ui.DetentLarge,
Grabber: true,
OnDismiss: func() { ch.previewOpen.Set(false) },
Content: func() ui.Node {
return ui.View(ui.ViewProps{Label: ui.Val("图片预览"), Style: ui.Style{Grow: 1}},
ui.SafeArea(ui.Style{Padding: ui.All(16), Gap: 10},
ui.Text(ch.previewTitle, ui.Style{Font: fonts.Headline, Lines: 2}),
ui.Show(ch.previewLoading,
func() ui.Node { return ui.Activity() },
func() ui.Node {
return ui.Image(ui.ImageProps{
Source: ch.previewPath,
Mode: ui.ImageFit,
Style: ui.Style{Width: ui.Pct(100), Height: ui.Pt(420), CornerRadius: 10},
})
}),
),
)
},
})
}
// imageLinkRow is one previewable image under a tool call.
func (ch *chat) imageLinkRow(ref imageRef) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() { ch.previewImage(ref) },
Label: ui.Val("预览 " + ref.Label),
Style: ui.Style{Padding: ui.Symmetric(3, 0)},
}, ui.Row(ui.Style{Gap: 6, Align: ui.AlignCenter},
ui.Symbol("photo", ui.Style{Font: fonts.Caption, Color: colors.Accent}),
ui.StaticText(ref.Label, ui.Style{Font: fonts.Caption, Color: colors.Accent, Lines: 1}),
))
}
-102
View File
@@ -1,102 +0,0 @@
package appui
import (
"bytes"
"testing"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func TestToolImagesFromOutput(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Input: map[string]any{"path": "shots/a.png"},
Content: []ocapi.ContentPart{
{Type: "text", Text: "wrote /work/shots/a.png and /work/notes.txt"},
{Type: "file", MIME: "image/png", URL: "data:image/png;base64,AAAA", Filename: "b.png"},
},
},
}
refs := ch.toolImages(part)
if len(refs) != 2 {
t.Fatalf("refs = %+v", refs)
}
if refs[0].Source != "/work/shots/a.png" || refs[0].Label != "a.png" {
t.Errorf("first = %+v", refs[0])
}
if refs[1].Source != "data:image/png;base64,AAAA" || refs[1].Label != "b.png" {
t.Errorf("second = %+v", refs[1])
}
}
func TestToolImagesPrefersReadAttachment(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Input: map[string]any{"filePath": "/tmp/upload.png"},
Attachments: []ocapi.ContentPart{{
Type: "file", MIME: "image/png", Filename: "upload.png",
URL: "data:image/png;base64,AAAA",
}},
},
}
refs := ch.toolImages(part)
if len(refs) != 1 || refs[0].Source != "data:image/png;base64,AAAA" {
t.Errorf("refs = %+v", refs)
}
}
func TestToolImagesUsesURIFileContent(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Content: []ocapi.ContentPart{{
Type: "file", MIME: "image/jpeg", Name: "shot.jpg",
URI: "file:///work/shot.jpg",
}},
},
}
refs := ch.toolImages(part)
if len(refs) != 1 || refs[0].Source != "/work/shot.jpg" || refs[0].Label != "shot.jpg" {
t.Errorf("refs = %+v", refs)
}
}
func TestToolImagesSkipsNonImages(t *testing.T) {
ch := &chat{dir: "/work"}
part := ocapi.ContentPart{
Type: "tool",
State: &ocapi.ToolState{
Input: map[string]any{"path": "/work/main.go"},
Content: []ocapi.ContentPart{
{Type: "text", Text: "read /work/main.go and /work/logo.webp"},
},
},
}
refs := ch.toolImages(part)
if len(refs) != 1 || refs[0].Source != "/work/logo.webp" {
t.Errorf("refs = %+v", refs)
}
}
func TestLoadPreviewDataURL(t *testing.T) {
ch := &chat{}
data, err := ch.loadPreview("data:image/png;base64,iVBORw0KGgo=")
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")) {
t.Errorf("data = %x", data)
}
}
func TestLoadPreviewRejectsPlainDataURL(t *testing.T) {
ch := &chat{}
if _, err := ch.loadPreview("data:text/plain,hello"); err == nil {
t.Fatal("expected an error for a non-base64 data URL")
}
}
-648
View File
@@ -1,648 +0,0 @@
// Package appui holds the OpenChamber screens and their state.
package appui
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
"github.com/openchamber/openchamber-native/internal/storage"
)
// Root is the app's root component.
func Root() ui.Node {
return rootWithStore(storage.New())
}
func rootWithStore(st storage.Store) ui.Node {
_, node := newApp(st)
return node
}
func newApp(st storage.Store) (*controller, ui.Node) {
c := newController(st)
signal.OnCleanup(c.shutdown)
return c, c.screen()
}
type controller struct {
st storage.Store
connections *signal.Signal[[]storage.Connection]
url *signal.Signal[string]
sessionQuery *signal.Signal[string]
searchOpen *signal.Signal[bool]
status *signal.Signal[string]
errorMsg *signal.Signal[string]
formOpen *signal.Signal[bool]
formConnecting bool
formEditID string
formLabel *signal.Signal[string]
formUseProxy *signal.Signal[bool]
formProxy *signal.Signal[string]
formInsecure *signal.Signal[bool]
passwordOpen *signal.Signal[bool]
passwordFor storage.Connection
passwordText *signal.Signal[string]
passwordBusy *signal.Signal[bool]
instancesOpen *signal.Signal[bool]
server *signal.Signal[string]
connected *signal.Signal[bool]
busy *signal.Signal[bool]
connecting *signal.Signal[string]
activeID *signal.Signal[string]
sessions *signal.Signal[[]ocapi.Session]
active *signal.Signal[map[string]bool]
perms *signal.Signal[[]ocapi.PermissionRequest]
defaultDir *signal.Signal[string]
newOpen *signal.Signal[bool]
newTitle *signal.Signal[string]
newDir *signal.Signal[int]
creating *signal.Signal[bool]
client *ocapi.Client
cancelSSE context.CancelFunc
chat *chat
nav *ui.Navigator
}
func newController(st storage.Store) *controller {
conns := st.Connections()
sort.SliceStable(conns, func(i, j int) bool { return conns[i].LastUsedAt > conns[j].LastUsedAt })
c := &controller{
st: st,
connections: signal.NewFunc(conns, nil),
url: signal.New(""),
sessionQuery: signal.New(""),
searchOpen: signal.New(false),
status: signal.New(""),
errorMsg: signal.New(""),
formOpen: signal.New(false),
formLabel: signal.New(""),
formUseProxy: signal.New(false),
formProxy: signal.New(""),
formInsecure: signal.New(false),
passwordOpen: signal.New(false),
passwordText: signal.New(""),
passwordBusy: signal.New(false),
instancesOpen: signal.New(false),
server: signal.New(""),
connected: signal.New(false),
busy: signal.New(false),
connecting: signal.New(""),
activeID: signal.New(""),
sessions: signal.NewFunc([]ocapi.Session{}, nil),
active: signal.NewFunc(map[string]bool{}, nil),
perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
defaultDir: signal.New(""),
newOpen: signal.New(false),
newTitle: signal.New(""),
newDir: signal.New(0),
creating: signal.New(false),
}
// Come back to the server last used, as the first-party client does.
if len(conns) > 0 {
c.connectTo(conns[0], "", false)
}
return c
}
// screen is the app's tree: a navigation stack while connected (its bar
// holds the session actions), and the bare server list while not, so the
// list is not framed by a bar whose buttons would do nothing.
func (c *controller) screen() ui.Node {
return ui.Column(ui.Style{Grow: 1},
ui.Show(c.connected,
func() ui.Node {
return ui.Stack(c.sessionsScreen, ui.ScreenOptions{
Title: ui.Val("OpenChamber"),
Actions: c.barActions(),
}, ui.Style{Grow: 1})
},
func() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1}, c.connectionsScreen())
}),
c.formSheet(),
c.passwordSheet(),
c.instancesSheet(),
c.newSessionSheetNode(),
)
}
func (c *controller) barActions() []ui.Action {
return []ui.Action{
{
Title: ui.Val("新建"),
Icon: ui.IconPlus,
OnPress: c.openNewSession,
},
{
Title: ui.Val("刷新"),
Icon: ui.IconRefresh,
Disabled: signal.Func(func() bool { return c.busy.Get() }),
OnPress: c.refresh,
},
}
}
func (c *controller) shutdown() {
if c.cancelSSE != nil {
c.cancelSSE()
c.cancelSSE = nil
}
c.client = nil
}
// connectTo starts a connection attempt off the main thread. password is
// the one the user typed, if any; explicit marks a tap (a password may be
// asked for), while the launch reconnect stays quiet.
func (c *controller) connectTo(conn storage.Connection, password string, explicit bool) {
if c.connecting.Peek() != "" {
return
}
c.connecting.Set(conn.ID)
c.errorMsg.Set("")
go func() {
c.establish(conn, password, explicit)
}()
}
// establish runs the whole connect sequence: health, token probe, optional
// password login, first page of sessions.
func (c *controller) establish(conn storage.Connection, password string, explicit bool) {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
fail := func(err error) {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set(friendlyError(err))
if c.formConnecting {
// The connect came from the add/edit form: bring it back
// with what the user typed so it can be fixed.
c.formConnecting = false
c.formOpen.Set(true)
}
})
}
if !strings.Contains(conn.URL, "://") {
normalized, err := ocapi.NormalizeBaseURL(conn.URL)
if err != nil {
fail(err)
return
}
conn.URL = normalized
}
client, err := ocapi.New(conn.URL, ocapi.Options{Proxy: conn.Proxy, InsecureSkipVerify: conn.Insecure})
if err != nil {
fail(err)
return
}
health, err := client.Health(ctx)
if err != nil {
fail(err)
return
}
if health.OpenChamberVersion == "" {
fail(errors.New("这个地址不是 OpenChamber 服务器"))
return
}
token := ""
if !conn.Passwordless {
if t, ok, err := c.st.LoadToken(conn); err == nil && ok {
token = t
client.SetToken(t)
}
}
passwordless := conn.Passwordless
auth, authErr := client.SessionStatus(ctx)
switch {
case authErr == nil:
passwordless = auth.Disabled
case ocapi.IsUnauthorized(authErr):
if strings.TrimSpace(password) == "" {
if explicit {
ui.Post(func() {
c.connecting.Set("")
c.askPassword(conn)
})
} else {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set("登录已失效,请重新输入密码")
c.askPassword(conn)
})
}
if token != "" {
go func() { _ = c.st.ClearToken(conn) }()
}
return
}
res, err := client.Login(ctx, ocapi.LoginRequest{
Password: password,
DedupeKey: c.st.InstallID(),
ClientLabel: "OpenChamber Native",
ClientKind: "mobile",
DevicePlatform: "android",
})
if err != nil {
ui.Post(func() {
c.connecting.Set("")
c.errorMsg.Set(friendlyError(err))
c.passwordBusy.Set(false)
c.passwordOpen.Set(true)
})
return
}
if res.ClientToken == "" {
fail(errors.New("登录没有返回设备 token"))
return
}
_ = c.st.SaveToken(conn.ID, res.ClientToken)
passwordless = false
default:
fail(authErr)
return
}
if loc, err := client.Location(ctx); err == nil && loc.Directory != "" {
ui.Post(func() { c.defaultDir.Set(loc.Directory) })
}
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"})
if err != nil {
fail(err)
return
}
active, _ := client.ActiveSessions(ctx)
running := make(map[string]bool, len(active))
for id := range active {
running[id] = true
}
perms, _ := client.PendingPermissions(ctx, "")
info := fmt.Sprintf("%s · OpenChamber %s", c.labelOf(conn), health.OpenChamberVersion)
if !health.IsOpenCodeReady {
info += " · OpenCode 未就绪"
}
conn.URL = client.BaseURL()
if conn.Label == "" {
conn.Label = hostOf(conn.URL)
}
conn.ServerID = health.ServerID
conn.Passwordless = passwordless
conn.LastUsedAt = time.Now().UnixMilli()
ui.Post(func() {
c.connecting.Set("")
c.saveConnection(conn)
c.activeID.Set(conn.ID)
c.client = client
c.sessions.Set(page.Data)
c.active.Set(running)
c.perms.Set(perms)
c.server.Set(info)
c.connected.Set(true)
c.busy.Set(false)
c.formConnecting = false
c.formOpen.Set(false)
c.passwordOpen.Set(false)
c.passwordText.Set("")
c.passwordBusy.Set(false)
c.instancesOpen.Set(false)
c.errorMsg.Set("")
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
c.startEvents(client)
})
}
func (c *controller) saveConnection(conn storage.Connection) {
conns := c.connections.Peek()
found := false
next := make([]storage.Connection, 0, len(conns)+1)
for _, existing := range conns {
if existing.ID == conn.ID {
next = append(next, conn)
found = true
} else {
next = append(next, existing)
}
}
if !found {
if conn.ID == "" {
conn.ID = storage.NewID()
}
next = append(next, conn)
}
sort.SliceStable(next, func(i, j int) bool { return next[i].LastUsedAt > next[j].LastUsedAt })
c.st.SaveConnections(next)
c.connections.Set(next)
}
func (c *controller) labelOf(conn storage.Connection) string {
label := strings.TrimSpace(conn.Label)
if label != "" && label != conn.URL {
return label
}
if host := hostOf(conn.URL); host != "" {
return host
}
return label
}
// searchSessions runs the query the search field holds.
func (c *controller) searchSessions(q string) {
if c.client == nil || c.busy.Peek() {
return
}
c.busy.Set(true)
client := c.client
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc", Search: q})
ui.Post(func() {
c.busy.Set(false)
if err != nil {
c.errorMsg.Set(friendlyError(err))
return
}
c.sessions.Set(page.Data)
if q == "" {
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
} else {
c.status.Set(fmt.Sprintf("找到 %d 个会话", len(page.Data)))
}
})
}()
}
func (c *controller) refresh() {
if c.client == nil || c.busy.Peek() {
return
}
c.busy.Set(true)
client := c.client
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{
Limit: 50, Order: "desc", Search: c.sessionQuery.Peek(),
})
active, aerr := client.ActiveSessions(ctx)
running := make(map[string]bool, len(active))
for id := range active {
running[id] = true
}
perms, perr := client.PendingPermissions(ctx, "")
ui.Post(func() {
c.busy.Set(false)
if err != nil {
if ocapi.IsUnauthorized(err) {
c.logout("登录已失效,请输入密码重新连接")
return
}
c.errorMsg.Set(friendlyError(err))
return
}
c.sessions.Set(page.Data)
if aerr == nil {
c.active.Set(running)
}
if perr == nil {
c.perms.Set(perms)
}
c.status.Set(fmt.Sprintf("已更新,%d 个会话", len(page.Data)))
})
}()
}
// logout drops the live session but keeps the saved servers.
func (c *controller) logout(reason string) {
if c.cancelSSE != nil {
c.cancelSSE()
c.cancelSSE = nil
}
var conn storage.Connection
if id := c.activeID.Peek(); id != "" {
for _, saved := range c.connections.Peek() {
if saved.ID == id {
conn = saved
}
}
}
c.client = nil
c.connected.Set(false)
c.activeID.Set("")
c.sessions.Set(nil)
c.active.Set(map[string]bool{})
c.perms.Set(nil)
c.server.Set("")
c.sessionQuery.Set("")
c.searchOpen.Set(false)
c.errorMsg.Set(reason)
if conn.ID != "" && reason != "" {
go func() { _ = c.st.ClearToken(conn) }()
}
}
func (c *controller) disconnect() {
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
c.chat.nav.Pop()
}
c.logout("")
}
// --- form ---------------------------------------------------------------
func (c *controller) openAddForm() {
c.formEditID = ""
c.url.Set("")
c.formLabel.Set("")
c.formUseProxy.Set(false)
c.formProxy.Set("")
c.formInsecure.Set(false)
c.errorMsg.Set("")
c.formOpen.Set(true)
}
func (c *controller) openEditForm(conn storage.Connection) {
c.formEditID = conn.ID
c.url.Set(conn.URL)
c.formLabel.Set(conn.Label)
c.formUseProxy.Set(conn.Proxy != "")
c.formProxy.Set(conn.Proxy)
c.formInsecure.Set(conn.Insecure)
c.errorMsg.Set("")
c.formOpen.Set(true)
}
func (c *controller) closeForm() {
c.formOpen.Set(false)
c.errorMsg.Set("")
}
func (c *controller) submitForm() {
raw := strings.TrimSpace(c.url.Peek())
if raw == "" {
c.errorMsg.Set("请输入服务器地址")
return
}
normalized, err := ocapi.NormalizeBaseURL(raw)
if err != nil {
c.errorMsg.Set(friendlyError(err))
return
}
conn := storage.Connection{ID: c.formEditID, URL: normalized, Label: strings.TrimSpace(c.formLabel.Peek())}
if c.formUseProxy.Peek() {
conn.Proxy = strings.TrimSpace(c.formProxy.Peek())
}
conn.Insecure = c.formInsecure.Peek()
if conn.ID != "" {
for _, saved := range c.connections.Peek() {
if saved.ID == conn.ID {
conn.ServerID = saved.ServerID
conn.Passwordless = saved.Passwordless
conn.LastUsedAt = saved.LastUsedAt
}
}
}
if conn.ID == "" {
conn.ID = storage.NewID()
}
c.saveConnection(conn)
c.formOpen.Set(false)
if !c.connected.Peek() {
c.formConnecting = true
c.connectTo(conn, "", true)
return
}
c.status.Set("已保存")
}
// --- password -----------------------------------------------------------
func (c *controller) askPassword(conn storage.Connection) {
c.passwordFor = conn
c.passwordText.Set("")
c.passwordBusy.Set(false)
c.passwordOpen.Set(true)
}
func (c *controller) submitPassword() {
if c.passwordBusy.Peek() {
return
}
pw := c.passwordText.Peek()
if strings.TrimSpace(pw) == "" {
return
}
conn := c.passwordFor
c.passwordBusy.Set(true)
c.passwordOpen.Set(false)
c.connectToPassword(conn, pw)
}
func (c *controller) connectToPassword(conn storage.Connection, password string) {
if c.connecting.Peek() != "" {
return
}
c.connecting.Set(conn.ID)
c.errorMsg.Set("")
go func() { c.establish(conn, password, true) }()
}
func (c *controller) cancelPassword() {
c.passwordOpen.Set(false)
c.passwordText.Set("")
c.passwordBusy.Set(false)
}
var errUnauthorized = errors.New("这个服务器需要密码")
func friendlyError(err error) string {
if err == nil {
return ""
}
if wait, ok := ocapi.IsRateLimited(err); ok {
secs := int(wait.Seconds() + 0.5)
if secs <= 0 {
secs = 30
}
return fmt.Sprintf("尝试过于频繁,请 %d 秒后重试", secs)
}
if ocapi.IsUnauthorized(err) {
return "密码错误"
}
if errors.Is(err, errUnauthorized) {
return "该服务器需要密码"
}
msg := err.Error()
switch {
case strings.Contains(msg, "certificate"):
return "TLS 证书校验失败:" + msg
case strings.Contains(msg, "no such host"):
return "找不到这个地址:" + msg
case strings.Contains(msg, "connection refused"):
return "连接被拒绝,请确认服务器地址与端口"
case strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline exceeded"):
return "连接超时,请检查网络或代理"
case strings.Contains(msg, "proxy"):
return "代理连接失败:" + msg
}
return msg
}
func hostOf(raw string) string {
s := strings.TrimSpace(raw)
if i := strings.Index(s, "://"); i >= 0 {
s = s[i+3:]
}
if i := strings.IndexByte(s, '/'); i >= 0 {
s = s[:i]
}
return s
}
func shortPath(p string) string {
p = strings.TrimRight(p, "/")
if p == "" {
return ""
}
if i := strings.LastIndex(p, "/"); i >= 0 && i+1 < len(p) {
return p[i+1:]
}
return p
}
func relativeTime(ms int64) string {
if ms <= 0 {
return ""
}
d := time.Since(time.UnixMilli(ms))
switch {
case d < time.Minute:
return "刚刚"
case d < time.Hour:
return fmt.Sprintf("%d 分钟前", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%d 小时前", int(d.Hours()))
default:
return fmt.Sprintf("%d 天前", int(d.Hours()/24))
}
}
-355
View File
@@ -1,355 +0,0 @@
package appui
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/egoist/asuka/ui"
"github.com/egoist/asuka/uitest"
"github.com/openchamber/openchamber-native/internal/storage"
)
// memStore is a storage.Store that keeps everything in memory.
type memStore struct {
mu sync.Mutex
conns []storage.Connection
tokens map[string]string
id string
}
func (m *memStore) Connections() []storage.Connection {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]storage.Connection, len(m.conns))
copy(out, m.conns)
return out
}
func (m *memStore) SaveConnections(list []storage.Connection) {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]storage.Connection, len(list))
copy(out, list)
m.conns = out
}
func (m *memStore) InstallID() string {
m.mu.Lock()
defer m.mu.Unlock()
if m.id == "" {
m.id = "test-install"
}
return m.id
}
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tokens[c.ID]
return t, ok, nil
}
func (m *memStore) SaveToken(id, token string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.tokens == nil {
m.tokens = map[string]string{}
}
m.tokens[id] = token
return nil
}
func (m *memStore) ClearToken(c storage.Connection) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.tokens, c.ID)
return nil
}
func (m *memStore) token(id string) string {
m.mu.Lock()
defer m.mu.Unlock()
return m.tokens[id]
}
func (m *memStore) connections() []storage.Connection {
return m.Connections()
}
// fakeServer stands in for OpenChamber: /health, /auth/session and the
// session list. An empty password makes it passwordless.
func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httptest.Server {
t.Helper()
if sessionTitle == "" {
sessionTitle = "First session"
}
mux := http.NewServeMux()
authorized := func(r *http.Request) bool {
if validToken == "" {
return true
}
return r.Header.Get("Authorization") == "Bearer "+validToken
}
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","isOpenCodeReady":true,"serverId":"srv_1"}`)
})
mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) {
if password == "" {
fmt.Fprint(w, `{"authenticated":true,"disabled":true}`)
return
}
switch r.Method {
case http.MethodGet:
if authorized(r) {
fmt.Fprint(w, `{"authenticated":true,"scope":"client"}`)
return
}
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
case http.MethodPost:
var body struct {
Password string `json:"password"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Password != password {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"error":"Invalid credentials"}`)
return
}
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
}
})
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if !authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
title := sessionTitle
if q := r.URL.Query().Get("search"); q != "" {
title = "Found " + q
}
fmt.Fprintf(w, `{"data":[{"id":"ses_1","title":%q,"time":{"created":1,"updated":2},
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, title)
})
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
})
mux.HandleFunc("/api/permission/request", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"data":[]}`)
})
mux.HandleFunc("/api/event", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"id\":\"evt_1\",\"type\":\"server.connected\",\"data\":{}}\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
<-r.Context().Done()
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func mount(t *testing.T, st *memStore) *uitest.App {
t.Helper()
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
}
// connectViaForm adds a server from the first screen (or the saved list)
// and taps Connect.
func connectViaForm(t *testing.T, a *uitest.App, url string) {
t.Helper()
if a.Has("手动输入地址") {
a.Tap("手动输入地址")
} else {
a.Tap("添加服务器")
}
a.Type("http://192.168.1.5:3000", url)
a.Tap("连接")
}
// disconnectViaInstances opens the instance list and drops the live
// connection from there; the sessions header has only the list button.
func disconnectViaInstances(t *testing.T, a *uitest.App) {
t.Helper()
a.Tap("实例")
a.Tap("断开当前连接")
}
func unlockWith(t *testing.T, a *uitest.App, password string) {
t.Helper()
a.WaitFor("这台服务器需要密码。")
a.Type("密码", password)
a.Tap("解锁")
}
func TestConnectWithPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
unlockWith(t, a, "secret")
a.WaitFor("First session")
conns := st.connections()
if len(conns) != 1 || conns[0].URL != srv.URL {
t.Fatalf("connections = %+v", conns)
}
if got := st.token(conns[0].ID); got != "oc_client_test" {
t.Errorf("token = %q", got)
}
if conns[0].Passwordless {
t.Error("password server marked passwordless")
}
}
func TestWrongPasswordThenRetry(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
unlockWith(t, a, "nope")
a.WaitFor("密码错误")
// The prompt stays up so the password can be retried.
a.Type("密码", "secret")
a.Tap("解锁")
a.WaitFor("First session")
}
func TestAutoReconnectWithStoredToken(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
tokens: map[string]string{"a": "oc_client_test"},
}
a := mount(t, st)
a.WaitFor("First session")
a.ExpectNo("手动输入地址")
a.ExpectNo("这台服务器需要密码。")
}
func TestExpiredTokenAsksForPassword(t *testing.T) {
srv := fakeServer(t, "secret", "oc_client_test", "")
st := &memStore{
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
tokens: map[string]string{"a": "revoked"},
}
a := mount(t, st)
a.WaitFor("登录已失效,请重新输入密码")
a.Until("the revoked token to be dropped", func() bool { return st.token("a") == "" })
unlockWith(t, a, "secret")
a.WaitFor("First session")
}
func TestPasswordlessServer(t *testing.T) {
srv := fakeServer(t, "", "", "")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
conns := st.connections()
if len(conns) != 1 || !conns[0].Passwordless {
t.Fatalf("connections = %+v", conns)
}
if got := st.token(conns[0].ID); got != "" {
t.Errorf("unexpected token %q", got)
}
}
func TestMultipleConnectionsAndSwitch(t *testing.T) {
srvA := fakeServer(t, "", "", "Session A")
srvB := fakeServer(t, "", "", "Session B")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 2},
{ID: "b", URL: srvB.URL, Label: "B", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Expect("A")
a.Expect("B")
a.Tap("B")
a.WaitFor("Session B")
}
func TestAddAnotherConnection(t *testing.T) {
srvA := fakeServer(t, "", "", "Session A")
srvB := fakeServer(t, "", "", "Session B")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Tap("添加服务器")
a.Type("http://192.168.1.5:3000", srvB.URL)
a.Type("名称(可选)", "B")
a.Tap("连接")
a.WaitFor("Session B")
if conns := st.connections(); len(conns) != 2 {
t.Fatalf("connections = %+v", conns)
}
}
func TestDeleteConnection(t *testing.T) {
srv := fakeServer(t, "", "", "Session A")
st := &memStore{conns: []storage.Connection{
{ID: "a", URL: srv.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
}}
a := mount(t, st)
a.WaitFor("Session A")
disconnectViaInstances(t, a)
a.Tap("操作")
a.Tap("删除")
a.Tap("删除")
a.Until("the connection list to empty", func() bool { return len(st.connections()) == 0 })
a.Expect("手动输入地址")
}
func TestLabelFallsBackToHost(t *testing.T) {
c := &controller{}
conn := storage.Connection{URL: "http://192.168.1.5:3000", Label: "http://192.168.1.5:3000"}
if got := c.labelOf(conn); got != "192.168.1.5:3000" {
t.Fatalf("label = %q", got)
}
conn.Label = "Home"
if got := c.labelOf(conn); got != "Home" {
t.Fatalf("label = %q", got)
}
}
func TestFailedAddReopensTheForm(t *testing.T) {
a := mount(t, &memStore{})
a.Tap("手动输入地址")
a.Type("http://192.168.1.5:3000", "http://127.0.0.1:1")
a.Tap("连接")
a.WaitFor("连接被拒绝,请确认服务器地址与端口")
a.Expect("添加服务器")
a.Expect("取消")
}
func TestSessionSearch(t *testing.T) {
srv := fakeServer(t, "", "", "First session")
st := &memStore{}
a := mount(t, st)
connectViaForm(t, a, srv.URL)
a.WaitFor("First session")
a.Tap("搜索会话")
a.Type("输入关键词搜索", "deploy")
a.WaitFor("Found deploy")
a.Tap("清除")
a.WaitFor("First session")
}
-137
View File
@@ -1,137 +0,0 @@
package appui
import (
"strings"
"time"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func (c *controller) sessionsScreen() ui.Node {
nav := ui.UseNavigator()
c.nav = nav
// Live search: typing settles for a moment, then the server is asked.
signal.Effect(func() {
q := c.sessionQuery.Get()
if !c.searchOpen.Get() {
return
}
t := time.AfterFunc(350*time.Millisecond, func() {
ui.Post(func() { c.searchSessions(q) })
})
signal.OnCleanup(func() { t.Stop() })
})
return ui.SafeArea(ui.Style{Grow: 1}, ui.Column(ui.Style{Grow: 1},
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter},
ui.Column(ui.Style{Grow: 1, Gap: 2},
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
func() ui.Node {
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red, Lines: 2})
}),
),
ui.Button(ui.ButtonProps{Icon: ui.IconSearch, Label: ui.Val("搜索会话"),
OnPress: func() {
open := !c.searchOpen.Peek()
c.searchOpen.Set(open)
if !open {
c.sessionQuery.Set("")
c.searchSessions("")
}
}}),
c.instancesButton(),
),
ui.Show(c.searchOpen, func() ui.Node {
return ui.Row(ui.Style{Padding: ui.Symmetric(0, 12), Gap: 6, Align: ui.AlignCenter},
ui.TextField(ui.TextFieldProps{
Value: c.sessionQuery,
Placeholder: ui.Val("输入关键词搜索"),
ReturnKey: ui.ReturnSearch,
OnSubmit: func() { c.searchSessions(c.sessionQuery.Peek()) },
Style: ui.Style{Grow: 1},
}),
ui.Button(ui.ButtonProps{Title: ui.Val("清除"), OnPress: func() {
c.sessionQuery.Set("")
c.searchSessions("")
}}),
)
}),
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
func() ui.Node {
return ui.Column(ui.Style{Padding: ui.All(20), Gap: 8},
ui.StaticText("还没有会话", ui.Style{Font: fonts.Headline}),
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
)
}),
ui.List(ui.ListProps{
Appearance: ui.ListPlain,
OnRefresh: c.refresh,
Refreshing: c.busy,
SwipeActions: func(i int) []ui.Action {
sess := c.sessions.Peek()[i]
return []ui.Action{{Title: ui.Val("归档"), Icon: "archivebox",
OnPress: func() { c.archiveSession(sess) }}}
},
LeadingSwipeActions: func(i int) []ui.Action {
sess := c.sessions.Peek()[i]
return []ui.Action{{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDelete(sess) }}}
},
}, c.sessions, func(s ocapi.Session) string { return s.ID },
func(s signal.Accessor[ocapi.Session], idx signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{
OnPress: func() {
sess := s.Get()
ch := c.openChat(&sess, nav)
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)})
},
OnLongPress: func() { c.sessionMenu(s.Get()) },
}, c.sessionRow(s, idx))
}),
))
}
func (c *controller) sessionRow(s signal.Accessor[ocapi.Session], _ signal.Accessor[int]) ui.Node {
return ui.Row(ui.Style{Gap: 10, Padding: ui.Symmetric(10, 16), Align: ui.AlignCenter},
ui.Show(signal.Func(func() bool { return c.active.Get()[s.Get().ID] }),
func() ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
CornerRadius: 4, Background: colors.Accent}})
}),
ui.Column(ui.Style{Gap: 3, Grow: 1},
ui.Text(signal.Func(func() string {
if t := strings.TrimSpace(s.Get().Title); t != "" {
return t
}
return "(未命名会话)"
}), ui.Style{Font: fonts.Headline, Lines: 2}),
ui.Text(signal.Func(func() string {
sess := s.Get()
dir := ""
if sess.Location != nil {
dir = sess.Location.Directory
}
updated := sess.Time.Updated
if sess.Time.Busy > updated {
updated = sess.Time.Busy
}
model := ""
if sess.Model != nil {
model = sess.Model.ID
}
parts := []string{shortPath(dir), relativeTime(updated), model}
out := make([]string, 0, len(parts))
for _, p := range parts {
if p != "" {
out = append(out, p)
}
}
return strings.Join(out, " · ")
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
),
)
}
-241
View File
@@ -1,241 +0,0 @@
package appui
import (
"context"
"strings"
"time"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func (c *controller) sessionMenu(s ocapi.Session) {
ui.Alert(ui.AlertProps{
Title: "会话",
ActionSheet: true,
Actions: []ui.Action{
{Title: ui.Val("重命名"), Icon: "pencil", OnPress: func() { c.renameSession(s) }},
{Title: ui.Val("归档"), Icon: "archivebox", OnPress: func() { c.archiveSession(s) }},
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
OnPress: func() { c.confirmDelete(s) }},
},
})
}
func (c *controller) renameSession(s ocapi.Session) {
name := signal.New(s.Title)
ui.Alert(ui.AlertProps{
Title: "重命名会话",
Message: "标题留空时,服务端不会自动生成新标题。",
Fields: []ui.AlertField{{Text: name, Placeholder: "标题"}},
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("保存"), Role: ui.ActionDefault,
Disabled: signal.Func(func() bool { return strings.TrimSpace(name.Get()) == "" }),
OnPress: func() { c.patchSessionOnServer(s, name.Get()) }},
},
})
}
func (c *controller) patchSessionOnServer(s ocapi.Session, title string) {
client := c.client
if client == nil {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
t := strings.TrimSpace(title)
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Title: &t})
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.sessions.Update(func(list []ocapi.Session) []ocapi.Session {
next := make([]ocapi.Session, len(list))
copy(next, list)
for i := range next {
if next[i].ID == s.ID {
next[i].Title = t
}
}
return next
})
})
}()
}
func (c *controller) archiveSession(s ocapi.Session) {
client := c.client
if client == nil {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
archived := true
err := client.UpdateSession(ctx, s.ID, dir, ocapi.SessionPatch{Archived: &archived})
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.removeSession(s.ID)
})
}()
}
func (c *controller) confirmDelete(s ocapi.Session) {
ui.Alert(ui.AlertProps{
Title: "删除会话?",
Message: "会话及其子会话会被永久删除,无法撤销。",
Actions: []ui.Action{
{Title: ui.Val("取消"), Role: ui.ActionCancel},
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
OnPress: func() { c.deleteSession(s) }},
},
})
}
func (c *controller) deleteSession(s ocapi.Session) {
client := c.client
if client == nil {
return
}
dir := sessionDir(s)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err := client.DeleteSession(ctx, s.ID, dir)
ui.Post(func() {
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.removeSession(s.ID)
})
}()
}
func sessionDir(s ocapi.Session) string {
if s.Location != nil {
return s.Location.Directory
}
return ""
}
// directories lists the working directories a new session can use: the
// server's default, then every directory the loaded sessions live in.
func (c *controller) directories() signal.Accessor[[]string] {
return signal.Func(func() []string {
seen := map[string]bool{}
out := make([]string, 0, 4)
add := func(d string) {
if d == "" || seen[d] {
return
}
seen[d] = true
out = append(out, d)
}
add(c.defaultDir.Get())
for _, s := range c.sessions.Get() {
if s.Location != nil {
add(s.Location.Directory)
}
}
return out
})
}
func chatActions(ch *chat) []ui.Action {
return []ui.Action{
{Title: ui.Val("模型"), OnPress: ch.openModelPicker},
{Title: ui.Val("Agent"), OnPress: ch.openAgentPicker},
}
}
func (c *controller) openNewSession() {
if c.client == nil {
return
}
c.newTitle.Set("")
c.newDir.Set(0)
c.creating.Set(false)
c.newOpen.Set(true)
}
func (c *controller) newSessionSheetNode() ui.Node {
return ui.Sheet(ui.SheetProps{
Open: c.newOpen,
Detents: ui.DetentLarge,
Grabber: true,
Content: c.newSessionSheet,
OnDismiss: func() { c.creating.Set(false) },
})
}
func (c *controller) newSessionSheet() ui.Node {
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14, Grow: 1},
ui.StaticText("新建会话", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.TextField(ui.TextFieldProps{
Value: c.newTitle,
Placeholder: ui.Val("标题(可选,留空由服务端生成)"),
ReturnKey: ui.ReturnGo,
OnSubmit: c.createSession,
}),
ui.Picker(ui.PickerProps{
Items: c.directories(),
Selected: c.newDir,
Label: ui.Val("工作目录"),
}),
ui.Button(ui.ButtonProps{
Title: ui.Val("创建"),
Variant: ui.ButtonFilled,
Disabled: c.creating,
OnPress: c.createSession,
}),
ui.Show(c.creating, func() ui.Node { return ui.Activity() }),
)
}
func (c *controller) createSession() {
client := c.client
nav := c.nav
if client == nil || c.creating.Peek() {
return
}
dirs := signal.Untrack(func() []string { return c.directories().Get() })
dir := ""
if idx := c.newDir.Peek(); idx >= 0 && idx < len(dirs) {
dir = dirs[idx]
}
title := strings.TrimSpace(c.newTitle.Peek())
c.creating.Set(true)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
s, err := client.CreateSession(ctx, ocapi.CreateSessionOptions{Directory: dir, Title: title})
ui.Post(func() {
c.creating.Set(false)
if err != nil {
c.status.Set(friendlyError(err))
return
}
c.newOpen.Set(false)
c.sessions.Update(func(list []ocapi.Session) []ocapi.Session {
next := make([]ocapi.Session, 0, len(list)+1)
next = append(next, s)
return append(next, list...)
})
if nav != nil {
ch := c.openChat(&s, nav)
nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)})
}
})
}()
}
-220
View File
@@ -1,220 +0,0 @@
package ocapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestCatalogAndPermissions(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/model":
if got := r.URL.Query().Get("location[directory]"); got != "/home/me/p" {
t.Errorf("model directory = %q", got)
}
fmt.Fprint(w, `{"data":[{"id":"gpt","providerID":"openai","name":"GPT"}]}`)
case "/api/agent":
fmt.Fprint(w, `{"data":[{"id":"build","name":"Build","mode":"primary"}]}`)
case "/api/permission/request":
fmt.Fprint(w, `{"data":[{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf x"]}]}`)
case "/api/session/ses_1/permission/per_1/reply":
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["decision"] != "always" || body["message"] != "ok" {
t.Errorf("reply body = %v", body)
}
w.WriteHeader(http.StatusNoContent)
case "/api/session/ses_1/model":
var body struct {
Model ModelRef `json:"model"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Model.ID != "gpt" || body.Model.ProviderID != "openai" {
t.Errorf("model switch = %+v", body.Model)
}
w.WriteHeader(http.StatusNoContent)
case "/api/session/ses_1/agent":
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["agent"] != "plan" {
t.Errorf("agent switch = %v", body)
}
w.WriteHeader(http.StatusNoContent)
case "/api/session/ses_1":
if r.Method != http.MethodPatch {
t.Errorf("method = %s", r.Method)
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["title"] != "renamed" {
t.Errorf("patch = %v", body)
}
w.WriteHeader(http.StatusNoContent)
default:
t.Errorf("unexpected path %q", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
ctx := context.Background()
c, _ := New(srv.URL, Options{})
models, err := c.Models(ctx, "/home/me/p")
if err != nil || len(models) != 1 || models[0].ID != "gpt" {
t.Fatalf("models: %+v %v", models, err)
}
agents, err := c.Agents(ctx, "")
if err != nil || len(agents) != 1 || agents[0].ID != "build" {
t.Fatalf("agents: %+v %v", agents, err)
}
perms, err := c.PendingPermissions(ctx, "")
if err != nil || len(perms) != 1 || perms[0].Action != "bash" {
t.Fatalf("permissions: %+v %v", perms, err)
}
if err := c.ReplyPermission(ctx, "ses_1", "per_1", PermissionAlways, "ok"); err != nil {
t.Fatal(err)
}
if err := c.SwitchModel(ctx, "ses_1", "", ModelRef{ID: "gpt", ProviderID: "openai"}); err != nil {
t.Fatal(err)
}
if err := c.SwitchAgent(ctx, "ses_1", "", "plan"); err != nil {
t.Fatal(err)
}
title := "renamed"
if err := c.UpdateSession(ctx, "ses_1", "", SessionPatch{Title: &title}); err != nil {
t.Fatal(err)
}
}
func TestCreateAndDeleteSession(t *testing.T) {
var createBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/session" && r.Method == http.MethodPost:
_ = json.NewDecoder(r.Body).Decode(&createBody)
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New","time":{"created":1,"updated":1}}}`)
case r.URL.Path == "/api/session/ses_new" && r.Method == http.MethodDelete:
w.WriteHeader(http.StatusNoContent)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
s, err := c.CreateSession(context.Background(), CreateSessionOptions{Directory: "/p", Title: "New"})
if err != nil || s.ID != "ses_new" {
t.Fatalf("create: %+v %v", s, err)
}
if loc, _ := createBody["location"].(map[string]any); loc["directory"] != "/p" {
t.Errorf("create location: %v", createBody)
}
if err := c.DeleteSession(context.Background(), "ses_new", ""); err != nil {
t.Fatal(err)
}
}
func TestWaitReady(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query().Get("wait"); got != "1500" {
t.Errorf("wait = %q", got)
}
fmt.Fprint(w, `{"healthy":true}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
if err := c.WaitReady(context.Background(), 1500*time.Millisecond); err != nil {
t.Fatal(err)
}
}
func TestCertificateFingerprint(t *testing.T) {
// A TLS server with a self-signed certificate; pinning its fingerprint
// (or skipping verification) is the only way to reach it.
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok"}`)
}))
defer srv.Close()
if _, err := New(srv.URL, Options{}); err != nil {
t.Fatal(err)
}
c, _ := New(srv.URL, Options{})
if _, err := c.Health(context.Background()); err == nil {
t.Fatal("self-signed certificate accepted without opting in")
}
c2, _ := New(srv.URL, Options{InsecureSkipVerify: true})
if _, err := c2.Health(context.Background()); err != nil {
t.Fatalf("insecure option did not work: %v", err)
}
}
func TestPartShellsHeaderAndGetMessage(t *testing.T) {
var gotHeader string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/session/ses_1/message":
gotHeader = r.Header.Get("x-openchamber-part-shells")
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{},"content":[],"metadata":{"openchamberContentShell":{}}}}]}],"cursor":{}}`)
case "/api/session/ses_1/message/msg_1":
fmt.Fprint(w, `{"id":"msg_1","type":"assistant","content":[
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{},"content":[{"type":"text","text":"full output"}]}}]}`)
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 10, PartShells: true})
if err != nil {
t.Fatal(err)
}
if gotHeader != "v1" {
t.Errorf("header = %q", gotHeader)
}
if len(page.Data) != 1 || len(page.Data[0].Content[0].State.Content) != 0 {
t.Fatalf("page = %+v", page)
}
msg, err := c.GetMessage(context.Background(), "ses_1", "msg_1", "")
if err != nil {
t.Fatal(err)
}
if got := msg.Content[0].State.Content[0].Text; got != "full output" {
t.Fatalf("message = %+v", msg)
}
}
func TestRevertEndpoints(t *testing.T) {
var staged map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/session/ses_1/revert/stage":
_ = json.NewDecoder(r.Body).Decode(&staged)
fmt.Fprint(w, `{"data":{"messageID":"msg_1"}}`)
case "/api/session/ses_1/revert/commit":
w.WriteHeader(http.StatusNoContent)
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
if err := c.StageRevert(context.Background(), "ses_1", "", "msg_1"); err != nil {
t.Fatal(err)
}
if staged["messageID"] != "msg_1" {
t.Errorf("staged = %v", staged)
}
if err := c.CommitRevert(context.Background(), "ses_1", ""); err != nil {
t.Fatal(err)
}
}
-385
View File
@@ -1,385 +0,0 @@
package ocapi
import (
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
xproxy "golang.org/x/net/proxy"
)
// Options configures a Client.
type Options struct {
// Proxy is an optional HTTP(S) or SOCKS5 proxy URL, e.g.
// "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080". No proxy
// authentication is supported.
Proxy string
// InsecureSkipVerify disables certificate verification. Prefer
// CertFingerprint for a self-signed server.
InsecureSkipVerify bool
// CertFingerprint pins the server's leaf certificate: the SHA-256 of
// its DER bytes, as hex, with or without colons.
CertFingerprint string
// Timeout bounds normal requests. Streaming requests ignore it.
Timeout time.Duration
// UserAgent is sent on every request.
UserAgent string
// HTTPClient replaces the constructed client (tests).
HTTPClient *http.Client
}
// Client talks to one OpenChamber server.
type Client struct {
base *url.URL
token string
http *http.Client
ua string
}
// New builds a client for base. A base without a scheme gets https, except
// for loopback and private addresses, which get http.
func New(base string, opts Options) (*Client, error) {
normalized, err := NormalizeBaseURL(base)
if err != nil {
return nil, err
}
u, err := url.Parse(normalized)
if err != nil {
return nil, fmt.Errorf("ocapi: invalid server URL: %w", err)
}
ua := opts.UserAgent
if ua == "" {
ua = "OpenChamber-Native/0.1"
}
hc := opts.HTTPClient
if hc == nil {
tr, err := newTransport(opts)
if err != nil {
return nil, err
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = 30 * time.Second
}
hc = &http.Client{Transport: tr, Timeout: timeout}
}
return &Client{base: u, http: hc, ua: ua}, nil
}
// NormalizeBaseURL trims a user-entered server address, adds a scheme when
// missing, and drops trailing slashes.
func NormalizeBaseURL(raw string) (string, error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", errors.New("ocapi: server URL is empty")
}
if !strings.Contains(s, "://") {
if isPrivateHost(s) {
s = "http://" + s
} else {
s = "https://" + s
}
}
u, err := url.Parse(s)
if err != nil {
return "", fmt.Errorf("ocapi: invalid server URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", fmt.Errorf("ocapi: unsupported scheme %q", u.Scheme)
}
if u.Host == "" {
return "", errors.New("ocapi: server URL has no host")
}
u.Path = strings.TrimRight(u.Path, "/")
return u.String(), nil
}
func isPrivateHost(s string) bool {
host := s
if h, _, err := net.SplitHostPort(s); err == nil {
host = h
}
host = strings.Trim(host, "[]")
if host == "localhost" || strings.HasSuffix(host, ".local") {
return true
}
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
}
func newTransport(opts Options) (*http.Transport, error) {
tr := &http.Transport{
// No overall dial timeout for streaming; normal requests carry a
// per-request deadline through context.
DialContext: (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 15 * time.Second,
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
}
if raw := strings.TrimSpace(opts.Proxy); raw != "" {
pu, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("ocapi: invalid proxy URL: %w", err)
}
switch pu.Scheme {
case "http", "https":
tr.Proxy = http.ProxyURL(pu)
case "socks5", "socks5h":
dialer, err := xproxy.SOCKS5("tcp", pu.Host, nil, xproxy.Direct)
if err != nil {
return nil, fmt.Errorf("ocapi: socks5 proxy: %w", err)
}
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
type ctxDialer interface {
DialContext(context.Context, string, string) (net.Conn, error)
}
if cd, ok := dialer.(ctxDialer); ok {
return cd.DialContext(ctx, network, addr)
}
return dialer.Dial(network, addr)
}
tr.Proxy = nil
default:
return nil, fmt.Errorf("ocapi: unsupported proxy scheme %q", pu.Scheme)
}
}
if opts.InsecureSkipVerify || opts.CertFingerprint != "" {
cfg := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: opts.InsecureSkipVerify}
if fp := normalizeFingerprint(opts.CertFingerprint); fp != "" {
cfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return errors.New("ocapi: server sent no certificate")
}
sum := sha256.Sum256(rawCerts[0])
if got := hex.EncodeToString(sum[:]); got != fp {
return fmt.Errorf("ocapi: certificate fingerprint mismatch: got %s", formatFingerprint(got))
}
return nil
}
}
tr.TLSClientConfig = cfg
}
return tr, nil
}
func normalizeFingerprint(s string) string {
clean := strings.ToLower(strings.NewReplacer(":", "", " ", "").Replace(strings.TrimSpace(s)))
if clean == "" {
return ""
}
if _, err := hex.DecodeString(clean); err != nil || len(clean) != 64 {
return ""
}
return clean
}
func formatFingerprint(hexString string) string {
var b strings.Builder
for i := 0; i < len(hexString); i += 2 {
if i > 0 {
b.WriteByte(':')
}
b.WriteString(strings.ToUpper(hexString[i : i+2]))
}
return b.String()
}
// SetToken sets the bearer token used for subsequent requests.
func (c *Client) SetToken(token string) { c.token = strings.TrimSpace(token) }
// Token returns the current bearer token.
func (c *Client) Token() string { return c.token }
// BaseURL returns the client's base URL.
func (c *Client) BaseURL() string { return c.base.String() }
// APIError is a non-2xx answer.
type APIError struct {
Status int
Message string
RetryAfter time.Duration
Locked bool
Raw string
}
func (e *APIError) Error() string {
if e.Message != "" {
return fmt.Sprintf("ocapi: %s (HTTP %d)", e.Message, e.Status)
}
return fmt.Sprintf("ocapi: HTTP %d", e.Status)
}
// IsUnauthorized reports whether err is a 401 (token expired or wrong).
func IsUnauthorized(err error) bool {
var apiErr *APIError
return errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized
}
// IsRateLimited reports whether err is a 429, and how long to wait.
func IsRateLimited(err error) (time.Duration, bool) {
var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests {
return apiErr.RetryAfter, true
}
return 0, false
}
type requestOptions struct {
directory string
query url.Values
rawQuery bool
}
func (c *Client) buildURL(path string, ro requestOptions) string {
u := *c.base
u.Path = strings.TrimRight(u.Path, "/") + "/" + strings.TrimLeft(path, "/")
q := u.Query()
for k, vs := range ro.query {
for _, v := range vs {
q.Add(k, v)
}
}
u.RawQuery = q.Encode()
return u.String()
}
func (c *Client) newRequest(ctx context.Context, method, path string, ro requestOptions, body any) (*http.Request, error) {
var rdr io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return nil, err
}
rdr = strings.NewReader(string(buf))
}
req, err := http.NewRequestWithContext(ctx, method, c.buildURL(path, ro), rdr)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.ua)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
if ro.directory != "" {
req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory))
req.Header.Set("x-opencode-directory-encoding", "uri")
}
return req, nil
}
func (c *Client) do(ctx context.Context, method, path string, ro requestOptions, body, out any) error {
req, err := c.newRequest(ctx, method, path, ro, body)
if err != nil {
return err
}
return c.send(req, out)
}
// send performs an already-built request and decodes it.
func (c *Client) send(req *http.Request, out any) error {
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16))
apiErr := &APIError{Status: res.StatusCode, Raw: string(raw)}
var payload struct {
Error string `json:"error"`
Locked bool `json:"locked"`
RetryAfter json.RawMessage `json:"retryAfter"`
}
if json.Unmarshal(raw, &payload) == nil {
apiErr.Message = payload.Error
apiErr.Locked = payload.Locked
apiErr.RetryAfter = parseRetryAfter(payload.RetryAfter, res.Header.Get("Retry-After"))
}
return apiErr
}
if out == nil || res.StatusCode == http.StatusNoContent {
_, _ = io.Copy(io.Discard, res.Body)
return nil
}
dec := json.NewDecoder(io.LimitReader(res.Body, 64<<20))
if err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("ocapi: decode response: %w", err)
}
return nil
}
func parseRetryAfter(raw json.RawMessage, header string) time.Duration {
if len(raw) > 0 {
var secs float64
if json.Unmarshal(raw, &secs) == nil && secs > 0 {
return time.Duration(secs * float64(time.Second))
}
var text string
if json.Unmarshal(raw, &text) == nil {
if n, err := strconv.Atoi(strings.TrimSpace(text)); err == nil && n > 0 {
return time.Duration(n) * time.Second
}
}
}
if n, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && n > 0 {
return time.Duration(n) * time.Second
}
return 0
}
// Health reads the server's unauthenticated health document.
func (c *Client) Health(ctx context.Context) (Health, error) {
var h Health
err := c.do(ctx, http.MethodGet, "/health", requestOptions{}, nil, &h)
return h, err
}
// SessionStatus probes /auth/session.
func (c *Client) SessionStatus(ctx context.Context) (AuthStatus, error) {
var s AuthStatus
err := c.do(ctx, http.MethodGet, "/auth/session", requestOptions{}, nil, &s)
return s, err
}
// Login exchanges the UI password for a device client token and stores it.
func (c *Client) Login(ctx context.Context, req LoginRequest) (LoginResult, error) {
if !req.TrustDevice {
req.TrustDevice = true
}
if !req.IssueClientToken {
req.IssueClientToken = true
}
if req.ClientKind == "" {
req.ClientKind = "mobile"
}
if req.ClientLabel == "" {
req.ClientLabel = "OpenChamber Native"
}
var out LoginResult
if err := c.do(ctx, http.MethodPost, "/auth/session", requestOptions{}, req, &out); err != nil {
return LoginResult{}, err
}
if out.ClientToken != "" {
c.SetToken(out.ClientToken)
}
return out, nil
}
-309
View File
@@ -1,309 +0,0 @@
package ocapi
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestNormalizeBaseURL(t *testing.T) {
cases := []struct {
in, want string
}{
{"127.0.0.1:3000", "http://127.0.0.1:3000"},
{"192.168.1.5:3000/", "http://192.168.1.5:3000"},
{"http://host:3000/", "http://host:3000"},
{"https://oc.example.com", "https://oc.example.com"},
{"oc.example.com", "https://oc.example.com"},
}
for _, c := range cases {
got, err := NormalizeBaseURL(c.in)
if err != nil {
t.Fatalf("NormalizeBaseURL(%q): %v", c.in, err)
}
if got != c.want {
t.Errorf("NormalizeBaseURL(%q) = %q, want %q", c.in, got, c.want)
}
}
if _, err := NormalizeBaseURL(" "); err == nil {
t.Error("empty URL accepted")
}
if _, err := NormalizeBaseURL("ftp://host"); err == nil {
t.Error("ftp scheme accepted")
}
}
func TestHealth(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/health" {
t.Errorf("path = %q", r.URL.Path)
}
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","serverId":"abc","isOpenCodeReady":true}`)
}))
defer srv.Close()
c, err := New(srv.URL, Options{})
if err != nil {
t.Fatal(err)
}
h, err := c.Health(context.Background())
if err != nil {
t.Fatal(err)
}
if h.OpenChamberVersion != "2.7.0" || h.ServerID != "abc" || !h.IsOpenCodeReady {
t.Fatalf("unexpected health: %+v", h)
}
}
func TestSessionStatusAndLogin(t *testing.T) {
var loginBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/auth/session":
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
return
}
if err := json.NewDecoder(r.Body).Decode(&loginBody); err != nil {
t.Errorf("login body: %v", err)
}
fmt.Fprint(w, `{"authenticated":true,"clientToken":"oc_client_test"}`)
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
_, err := c.SessionStatus(context.Background())
if !IsUnauthorized(err) {
t.Fatalf("want 401, got %v", err)
}
res, err := c.Login(context.Background(), LoginRequest{Password: "pw", DedupeKey: "install-1"})
if err != nil {
t.Fatal(err)
}
if res.ClientToken != "oc_client_test" || c.Token() != "oc_client_test" {
t.Fatalf("token not stored: %+v, %q", res, c.Token())
}
if loginBody["trustDevice"] != true || loginBody["issueClientToken"] != true {
t.Errorf("login defaults missing: %v", loginBody)
}
if loginBody["clientKind"] != "mobile" || loginBody["password"] != "pw" {
t.Errorf("login body: %v", loginBody)
}
}
func TestListSessionsScoped(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/session" {
t.Errorf("path = %q", r.URL.Path)
}
if got := r.URL.Query().Get("directory"); got != "/home/me/proj" {
t.Errorf("directory query = %q", got)
}
if got := r.Header.Get("x-opencode-directory"); got != "%2Fhome%2Fme%2Fproj" {
t.Errorf("directory header = %q", got)
}
if got := r.Header.Get("x-opencode-directory-encoding"); got != "uri" {
t.Errorf("directory encoding = %q", got)
}
if got := r.URL.Query().Get("limit"); got != "50" {
t.Errorf("limit = %q", got)
}
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"Hi","time":{"created":1,"updated":2},"location":{"directory":"/home/me/proj"}}],"cursor":{"next":"n1"}}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
page, err := c.ListSessions(context.Background(), ListSessionsOptions{Directory: "/home/me/proj", Limit: 50})
if err != nil {
t.Fatal(err)
}
if len(page.Data) != 1 || page.Data[0].ID != "ses_1" || page.Cursor.Next != "n1" {
t.Fatalf("unexpected page: %+v", page)
}
}
func TestMessagesAndTurn(t *testing.T) {
var promptBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/session/ses_1/message":
if got := r.URL.Query().Get("order"); got != "desc" {
t.Errorf("order = %q", got)
}
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[{"type":"text","text":"hello"}]}],"cursor":{"next":"m1"}}`)
case "/api/session/ses_1/prompt":
_ = json.NewDecoder(r.Body).Decode(&promptBody)
fmt.Fprint(w, `{"data":{}}`)
case "/api/session/ses_1/interrupt":
fmt.Fprint(w, `{"interrupted":true}`)
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 20, Order: "desc"})
if err != nil {
t.Fatal(err)
}
if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" {
t.Fatalf("unexpected messages: %+v", page)
}
if err := c.Prompt(context.Background(), "ses_1", PromptOptions{
Text: "ping", MessageID: "msg_9",
Files: []PromptFile{{URI: "data:text/plain;base64,aGk=", Name: "note.txt"}},
}); err != nil {
t.Fatal(err)
}
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
t.Errorf("prompt body: %v", promptBody)
}
files, _ := promptBody["files"].([]any)
if len(files) != 1 {
t.Fatalf("prompt files: %v", promptBody["files"])
}
file, _ := files[0].(map[string]any)
if file["name"] != "note.txt" || file["uri"] != "data:text/plain;base64,aGk=" {
t.Errorf("prompt file: %v", file)
}
ok, err := c.Interrupt(context.Background(), "ses_1", "")
if err != nil || !ok {
t.Fatalf("interrupt: %v %v", ok, err)
}
}
func TestRateLimit(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTooManyRequests)
fmt.Fprint(w, `{"error":"Too many login attempts, please try again later","retryAfter":12}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
_, err := c.Login(context.Background(), LoginRequest{Password: "x"})
wait, ok := IsRateLimited(err)
if !ok || wait != 12*time.Second {
t.Fatalf("rate limit: %v %v", wait, err)
}
}
func TestStreamEvents(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query()["types"]; len(got) != 2 {
t.Errorf("types = %v", got)
}
w.Header().Set("Content-Type", "text/event-stream")
flusher := w.(http.Flusher)
// Split an event across writes and use two data lines, which
// SSE joins with a newline.
fmt.Fprint(w, "event: message\n")
flusher.Flush()
fmt.Fprint(w, "data: {\"id\":\"evt_1\",")
flusher.Flush()
fmt.Fprint(w, "\"type\":\"session.text.delta\",")
flusher.Flush()
fmt.Fprint(w, "\"data\":{\"delta\":\"hi\"}}\n\n")
flusher.Flush()
<-r.Context().Done()
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
got := make(chan Event, 1)
go func() {
_ = c.StreamEvents(ctx, []string{"session.text.delta", "permission.asked"}, func(ev Event) error {
got <- ev
cancel()
return nil
})
}()
select {
case ev := <-got:
if ev.ID != "evt_1" || ev.Type != "session.text.delta" {
t.Fatalf("event: %+v", ev)
}
var data SessionEventData
if err := ev.UnmarshalData(&data); err != nil || data.Delta != "hi" {
t.Fatalf("data: %+v %v", data, err)
}
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for an event")
}
}
func TestProxyDialer(t *testing.T) {
// A SOCKS5 address is accepted; the connection itself is not made.
c, err := New("http://127.0.0.1:3000", Options{Proxy: "socks5://127.0.0.1:1080"})
if err != nil {
t.Fatal(err)
}
if c.http.Transport == nil {
t.Fatal("no transport")
}
if _, err := New("http://127.0.0.1:3000", Options{Proxy: "ftp://x"}); err == nil {
t.Fatal("unsupported proxy scheme accepted")
}
}
func TestDecodeMessageContent(t *testing.T) {
body := `{"data":[{"id":"msg_1","type":"assistant","content":[
{"type":"reasoning","text":"think"},
{"type":"text","text":"answer"},
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"a.txt"}]}}]}]}`
var page MessagePage
if err := json.Unmarshal([]byte(body), &page); err != nil {
t.Fatal(err)
}
m := page.Data[0]
if len(m.Content) != 3 || m.Content[2].State == nil || m.Content[2].State.Status != "completed" {
t.Fatalf("content: %+v", m.Content)
}
if m.Content[2].State.Input["command"] != "ls" {
t.Fatalf("input: %+v", m.Content[2].State.Input)
}
if m.Content[2].State.Content[0].Text != "a.txt" {
t.Fatalf("tool content: %+v", m.Content[2].State.Content)
}
}
func TestErrorBodyKept(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"error":"bad thing"}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
err := c.DeleteSession(context.Background(), "ses_x", "")
var apiErr *APIError
if !strings.Contains(err.Error(), "bad thing") || !asAPIError(err, &apiErr) || apiErr.Status != 400 {
t.Fatalf("error: %v", err)
}
}
func asAPIError(err error, target **APIError) bool {
for err != nil {
if e, ok := err.(*APIError); ok {
*target = e
return true
}
u, ok := err.(interface{ Unwrap() error })
if !ok {
return false
}
err = u.Unwrap()
}
return false
}
-180
View File
@@ -1,180 +0,0 @@
package ocapi
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
)
// StreamEvents subscribes to GET /api/event and calls fn for each event
// until ctx is done or the connection fails. types filters the event
// types; nil means every type.
func (c *Client) StreamEvents(ctx context.Context, types []string, fn func(Event) error) error {
return c.streamEvents(ctx, types, nil, fn)
}
func (c *Client) streamEvents(ctx context.Context, types []string, onOpen func(), fn func(Event) error) error {
q := url.Values{}
for _, t := range types {
q.Add("types", t)
}
req, err := c.newRequest(ctx, http.MethodGet, "/api/event", requestOptions{query: q}, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Cache-Control", "no-cache")
// A streaming request must not inherit the client's overall timeout.
hc := *c.http
hc.Timeout = 0
res, err := hc.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
return &APIError{Status: res.StatusCode, Raw: string(raw), Message: strings.TrimSpace(string(raw))}
}
if onOpen != nil {
onOpen()
}
reader := bufio.NewReaderSize(res.Body, 64<<10)
var data []byte
for {
line, err := reader.ReadString('\n')
if err != nil {
if errors.Is(err, io.EOF) || ctx.Err() != nil {
return ctx.Err()
}
return err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
if len(data) == 0 {
continue
}
var ev Event
parseErr := json.Unmarshal(data, &ev)
data = data[:0]
if parseErr != nil {
continue
}
if err := fn(ev); err != nil {
return err
}
continue
}
if strings.HasPrefix(line, "data:") {
chunk := strings.TrimPrefix(line, "data:")
chunk = strings.TrimPrefix(chunk, " ")
if len(data) > 0 {
data = append(data, '\n')
}
data = append(data, chunk...)
}
}
}
// SubscriptionState reports the event stream's connection state.
type SubscriptionState int
const (
Subscribing SubscriptionState = iota
Subscribed
Disconnected
)
// Subscription is a resilient event stream.
type Subscription struct {
Types []string
OnEvent func(Event)
OnState func(SubscriptionState, error)
// MinBackoff and MaxBackoff bound the reconnect delay.
MinBackoff time.Duration
MaxBackoff time.Duration
}
// Subscribe keeps an event stream open until ctx is done, reconnecting with
// exponential backoff. It blocks, so run it in a goroutine.
func (c *Client) Subscribe(ctx context.Context, s Subscription) {
minB, maxB := s.MinBackoff, s.MaxBackoff
if minB <= 0 {
minB = time.Second
}
if maxB <= 0 {
maxB = 30 * time.Second
}
state := func(st SubscriptionState, err error) {
if s.OnState != nil {
s.OnState(st, err)
}
}
backoff := minB
for ctx.Err() == nil {
state(Subscribing, nil)
started := time.Now()
err := c.streamEvents(ctx, s.Types, func() {
state(Subscribed, nil)
}, func(ev Event) error {
if s.OnEvent != nil {
s.OnEvent(ev)
}
return nil
})
if ctx.Err() != nil {
return
}
state(Disconnected, err)
// A stream that stayed up for a while restarts at the minimum
// delay; a failing one backs off.
if time.Since(started) > 30*time.Second {
backoff = minB
}
delay := backoff/2 + time.Duration(rand.Int63n(int64(backoff/2+1)))
select {
case <-ctx.Done():
return
case <-time.After(delay):
}
if backoff < maxB {
backoff *= 2
if backoff > maxB {
backoff = maxB
}
}
}
}
// WaitReady polls /api/opencode/health until OpenCode is ready or ctx ends.
func (c *Client) WaitReady(ctx context.Context, wait time.Duration) error {
if wait <= 0 {
wait = 20 * time.Second
}
q := url.Values{}
q.Set("wait", fmt.Sprint(wait.Milliseconds()))
var payload struct {
Healthy bool `json:"healthy"`
Error string `json:"error"`
}
if err := c.do(ctx, http.MethodGet, "/api/opencode/health", requestOptions{query: q}, nil, &payload); err != nil {
return err
}
if !payload.Healthy {
if payload.Error != "" {
return fmt.Errorf("ocapi: opencode not ready: %s", payload.Error)
}
return errors.New("ocapi: opencode not ready")
}
return nil
}
-39
View File
@@ -1,39 +0,0 @@
package ocapi
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
)
// RawFile reads a file the server can see, for previews. content is the
// server's Content-Type; the body is bounded to 32 MiB. Paths outside the
// session's workspace are allowed: the tool call already read the file, and
// the preview shows the same one.
func (c *Client) RawFile(ctx context.Context, path, directory string) ([]byte, string, error) {
q := url.Values{}
q.Set("path", path)
q.Set("allowOutsideWorkspace", "true")
req, err := c.newRequest(ctx, http.MethodGet, "/api/fs/raw", requestOptions{directory: directory, query: q}, nil)
if err != nil {
return nil, "", err
}
hc := *c.http
hc.Timeout = 0
res, err := hc.Do(req)
if err != nil {
return nil, "", err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
return nil, "", &APIError{Status: res.StatusCode, Raw: string(raw), Message: fmt.Sprintf("HTTP %d", res.StatusCode)}
}
data, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
if err != nil {
return nil, "", err
}
return data, res.Header.Get("Content-Type"), nil
}
-62
View File
@@ -1,62 +0,0 @@
package ocapi
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
func TestRawFile(t *testing.T) {
var gotPath, gotDir string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/fs/raw" {
t.Errorf("path = %q", r.URL.Path)
}
if got := r.Header.Get("x-opencode-directory-encoding"); got != "uri" {
t.Errorf("directory encoding = %q", got)
}
gotPath = r.URL.Query().Get("path")
if got := r.URL.Query().Get("allowOutsideWorkspace"); got != "true" {
t.Errorf("allowOutsideWorkspace = %q", got)
}
gotDir, _ = url.PathUnescape(r.Header.Get("x-opencode-directory"))
w.Header().Set("Content-Type", "image/png")
fmt.Fprint(w, "PNGDATA")
}))
defer srv.Close()
c, err := New(srv.URL, Options{})
if err != nil {
t.Fatal(err)
}
data, mime, err := c.RawFile(context.Background(), "/work/a.png", "/work")
if err != nil {
t.Fatal(err)
}
if string(data) != "PNGDATA" {
t.Errorf("data = %q", data)
}
if mime != "image/png" {
t.Errorf("mime = %q", mime)
}
if gotPath != "/work/a.png" {
t.Errorf("query path = %q", gotPath)
}
if gotDir != "/work" {
t.Errorf("directory = %q", gotDir)
}
}
func TestRawFileError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "nope", http.StatusNotFound)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
if _, _, err := c.RawFile(context.Background(), "/work/missing.png", ""); err == nil {
t.Fatal("expected an error")
}
}
-316
View File
@@ -1,316 +0,0 @@
package ocapi
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strconv"
)
// ListSessionsOptions configures ListSessions.
type ListSessionsOptions struct {
// Directory scopes the list to one absolute path. Empty means all
// projects (each Session carries its own Location).
Directory string
Limit int
Cursor string
Order string // "asc" or "desc"
Search string
ParentID string
Archived *bool
}
// ListSessions lists sessions, newest first by default.
func (c *Client) ListSessions(ctx context.Context, o ListSessionsOptions) (SessionPage, error) {
q := url.Values{}
if o.Limit > 0 {
q.Set("limit", strconv.Itoa(o.Limit))
}
if o.Directory != "" {
q.Set("directory", o.Directory)
}
if o.Cursor != "" {
q.Set("cursor", o.Cursor)
}
if o.Order != "" {
q.Set("order", o.Order)
}
if o.Search != "" {
q.Set("search", o.Search)
}
if o.ParentID != "" {
q.Set("parentID", o.ParentID)
}
if o.Archived != nil {
q.Set("archived", strconv.FormatBool(*o.Archived))
}
var page SessionPage
err := c.do(ctx, http.MethodGet, "/api/session", requestOptions{directory: o.Directory, query: q}, nil, &page)
return page, err
}
// ActiveSessions returns the sessions running right now, keyed by id.
func (c *Client) ActiveSessions(ctx context.Context) (map[string]string, error) {
var payload struct {
Data map[string]struct {
Type string `json:"type"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/session/active", requestOptions{}, nil, &payload); err != nil {
return nil, err
}
out := make(map[string]string, len(payload.Data))
for id, v := range payload.Data {
out[id] = v.Type
}
return out, nil
}
// GetSession reads one session.
func (c *Client) GetSession(ctx context.Context, id, directory string) (Session, error) {
var payload struct {
Data Session `json:"data"`
}
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, &payload)
return payload.Data, err
}
// CreateSessionOptions configures CreateSession.
type CreateSessionOptions struct {
Directory string
Title string
Agent string
Model *ModelRef
}
// CreateSession makes a new session, optionally in a directory.
func (c *Client) CreateSession(ctx context.Context, o CreateSessionOptions) (Session, error) {
body := map[string]any{}
if o.Title != "" {
body["title"] = o.Title
}
if o.Agent != "" {
body["agent"] = o.Agent
}
if o.Model != nil {
body["model"] = o.Model
}
if o.Directory != "" {
body["location"] = map[string]string{"directory": o.Directory}
}
var payload struct {
Data Session `json:"data"`
}
err := c.do(ctx, http.MethodPost, "/api/session", requestOptions{directory: o.Directory}, body, &payload)
return payload.Data, err
}
// SessionPatch is PATCH /api/session/{id}: both fields are optional.
type SessionPatch struct {
Title *string `json:"title,omitempty"`
Archived *bool `json:"archived,omitempty"`
}
// UpdateSession renames or archives one session.
func (c *Client) UpdateSession(ctx context.Context, id, directory string, patch SessionPatch) error {
return c.do(ctx, http.MethodPatch, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, patch, nil)
}
// DeleteSession removes a session and its children.
func (c *Client) DeleteSession(ctx context.Context, id, directory string) error {
return c.do(ctx, http.MethodDelete, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, nil)
}
// ListMessagesOptions configures ListMessages.
type ListMessagesOptions struct {
Directory string
Limit int
Cursor string
Order string // "asc" or "desc"
// PartShells asks OpenChamber to leave finished tool results out of the
// page, which is most of a long session's bytes. Fetch the message with
// GetMessage when a row expands.
PartShells bool
}
// ListMessages reads one page of a session's messages. Newest first by
// default, which is what a chat pages backwards with.
func (c *Client) ListMessages(ctx context.Context, id string, o ListMessagesOptions) (MessagePage, error) {
q := url.Values{}
if o.Limit > 0 {
q.Set("limit", strconv.Itoa(o.Limit))
}
if o.Cursor != "" {
q.Set("cursor", o.Cursor)
}
if o.Order != "" {
q.Set("order", o.Order)
}
req, err := c.newRequest(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
requestOptions{directory: o.Directory, query: q}, nil)
if err != nil {
return MessagePage{}, err
}
if o.PartShells {
req.Header.Set("x-openchamber-part-shells", "v1")
}
var page MessagePage
if err := c.send(req, &page); err != nil {
return MessagePage{}, err
}
return page, nil
}
// GetMessage reads one whole message, including tool results a shelled list
// page left out.
func (c *Client) GetMessage(ctx context.Context, sessionID, messageID, directory string) (Message, error) {
var msg Message
path := "/api/session/" + url.PathEscape(sessionID) + "/message/" + url.PathEscape(messageID)
err := c.do(ctx, http.MethodGet, path, requestOptions{directory: directory}, nil, &msg)
return msg, err
}
// ModelInfo is one model the server offers.
type ModelInfo struct {
ID string `json:"id"`
ProviderID string `json:"providerID"`
Name string `json:"name"`
Variant string `json:"variant"`
Limit struct {
Context int `json:"context"`
Output int `json:"output"`
} `json:"limit"`
}
// Models lists the models the server offers for a directory.
func (c *Client) Models(ctx context.Context, directory string) ([]ModelInfo, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []ModelInfo `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/model", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
return payload.Data, nil
}
// ProviderInfo is one provider the server offers, with its display name.
type ProviderInfo struct {
ID string `json:"id"`
Name string `json:"name"`
}
// Providers lists the providers available for a directory.
func (c *Client) Providers(ctx context.Context, directory string) ([]ProviderInfo, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []ProviderInfo `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/provider", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
return payload.Data, nil
}
// ServerLocation is the server's default working directory.
type ServerLocation struct {
Directory string `json:"directory"`
ProjectID string `json:"projectID"`
}
// Location reads the server's default location, which a new session uses
// when the user does not pick one.
func (c *Client) Location(ctx context.Context) (ServerLocation, error) {
var payload struct {
Directory string `json:"directory"`
Project struct {
ID string `json:"id"`
} `json:"project"`
}
if err := c.do(ctx, http.MethodGet, "/api/location", requestOptions{}, nil, &payload); err != nil {
return ServerLocation{}, err
}
return ServerLocation{Directory: payload.Directory, ProjectID: payload.Project.ID}, nil
}
// AgentInfo is one entry of GET /api/agent.
type AgentInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Mode string `json:"mode"`
Hidden bool `json:"hidden"`
}
// Agents lists the agents available for a directory.
func (c *Client) Agents(ctx context.Context, directory string) ([]AgentInfo, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []AgentInfo `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/agent", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
return payload.Data, nil
}
// PermissionRequest is a pending tool permission.
type PermissionRequest struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Action string `json:"action"`
Resources []string `json:"resources"`
Message string `json:"message,omitempty"`
}
// PendingPermissions lists the pending permission requests for a directory.
func (c *Client) PendingPermissions(ctx context.Context, directory string) ([]PermissionRequest, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []PermissionRequest `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/permission/request", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
return payload.Data, nil
}
// PermissionDecision is how a permission request is answered.
type PermissionDecision string
const (
PermissionOnce PermissionDecision = "once"
PermissionAlways PermissionDecision = "always"
PermissionReject PermissionDecision = "reject"
)
// ReplyPermission answers a pending permission request.
func (c *Client) ReplyPermission(ctx context.Context, sessionID, requestID string, decision PermissionDecision, message string) error {
body := map[string]any{"decision": decision}
if message != "" {
body["message"] = message
}
path := "/api/session/" + url.PathEscape(sessionID) + "/permission/" + url.PathEscape(requestID) + "/reply"
return c.do(ctx, http.MethodPost, path, requestOptions{}, body, nil)
}
// EventData unmarshals an event's payload into v.
func (e Event) UnmarshalData(v any) error {
if len(e.Data) == 0 {
return nil
}
return json.Unmarshal(e.Data, v)
}
-84
View File
@@ -1,84 +0,0 @@
package ocapi
import (
"context"
"net/http"
"net/url"
)
// PromptOptions configures Prompt.
type PromptOptions struct {
Directory string
// MessageID is an optional client-minted id (msg_…), which makes a
// retry after a lost response a no-op instead of a duplicate.
MessageID string
Text string
// Files ride with the prompt as data URLs (or URIs the server can
// read), as the web client sends them.
Files []PromptFile
}
// Prompt sends a user message to a session. The reply arrives through the
// event stream, not this call.
func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) error {
body := map[string]any{"text": o.Text}
if o.MessageID != "" {
body["id"] = o.MessageID
}
if len(o.Files) > 0 {
body["files"] = o.Files
}
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
}
// StageRevert marks a reversible boundary at a message: everything after it
// can be dropped with CommitRevert.
func (c *Client) StageRevert(ctx context.Context, sessionID, directory, messageID string) error {
path := "/api/session/" + url.PathEscape(sessionID) + "/revert/stage"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory},
map[string]any{"messageID": messageID}, nil)
}
// CommitRevert drops the messages a staged revert marked.
func (c *Client) CommitRevert(ctx context.Context, sessionID, directory string) error {
path := "/api/session/" + url.PathEscape(sessionID) + "/revert/commit"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, nil)
}
// ForkSession copies the session's history before a message into a new
// session. An empty before copies the whole history.
func (c *Client) ForkSession(ctx context.Context, sessionID, directory, before string) (Session, error) {
body := map[string]any{}
if before != "" {
body["before"] = before
}
var payload struct {
Data Session `json:"data"`
}
path := "/api/session/" + url.PathEscape(sessionID) + "/fork"
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, body, &payload)
return payload.Data, err
}
// Interrupt stops the turn the session is running.
func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) {
var payload struct {
Interrupted bool `json:"interrupted"`
}
path := "/api/session/" + url.PathEscape(sessionID) + "/interrupt"
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, &payload)
return payload.Interrupted, err
}
// SwitchModel changes the model later turns run on.
func (c *Client) SwitchModel(ctx context.Context, sessionID, directory string, model ModelRef) error {
path := "/api/session/" + url.PathEscape(sessionID) + "/model"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"model": model}, nil)
}
// SwitchAgent changes the agent later turns run with.
func (c *Client) SwitchAgent(ctx context.Context, sessionID, directory, agent string) error {
path := "/api/session/" + url.PathEscape(sessionID) + "/agent"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"agent": agent}, nil)
}
-232
View File
@@ -1,232 +0,0 @@
// Package ocapi is a small HTTP client for the OpenChamber server API
// (which proxies OpenCode v2 under /api/*). It has no UI dependencies, so
// it can be tested with httptest and reused by the CLI probe.
package ocapi
import "encoding/json"
// Health is GET /health.
type Health struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
OpenChamberVersion string `json:"openchamberVersion"`
Runtime string `json:"runtime"`
ServerID string `json:"serverId"`
IsOpenCodeReady bool `json:"isOpenCodeReady"`
OpenCodePort int `json:"openCodePort"`
Compatibility struct {
APIVersion int `json:"apiVersion"`
MinClientAPIVersion int `json:"minClientApiVersion"`
Capabilities []string `json:"capabilities"`
} `json:"compatibility"`
}
// AuthStatus is GET /auth/session.
type AuthStatus struct {
Authenticated bool `json:"authenticated"`
Disabled bool `json:"disabled"`
Locked bool `json:"locked"`
Scope string `json:"scope"`
ClientAuthRequired bool `json:"clientAuthRequired"`
}
// LoginRequest is POST /auth/session. Password is the only secret; the rest
// names this device so repeated logins collapse into one server-side record.
type LoginRequest struct {
Password string `json:"password"`
TrustDevice bool `json:"trustDevice"`
IssueClientToken bool `json:"issueClientToken"`
ClientLabel string `json:"clientLabel,omitempty"`
ClientKind string `json:"clientKind,omitempty"`
DeviceName string `json:"deviceName,omitempty"`
DevicePlatform string `json:"devicePlatform,omitempty"`
DeviceModel string `json:"deviceModel,omitempty"`
AppVersion string `json:"appVersion,omitempty"`
DedupeKey string `json:"dedupeKey,omitempty"`
}
// LoginResult is the answer to POST /auth/session.
type LoginResult struct {
Authenticated bool `json:"authenticated"`
ClientToken string `json:"clientToken"`
Client json.RawMessage `json:"client"`
}
// ModelRef identifies a model as OpenCode names it.
type ModelRef struct {
ID string `json:"id"`
ProviderID string `json:"providerID"`
Variant string `json:"variant,omitempty"`
}
// TokenUsage is a session's or message's token counters.
type TokenUsage struct {
Total int64 `json:"total,omitempty"`
Input int64 `json:"input"`
Output int64 `json:"output"`
Reasoning int64 `json:"reasoning"`
Cache struct {
Read int64 `json:"read"`
Write int64 `json:"write"`
} `json:"cache"`
}
// Location is where a session lives.
type Location struct {
Directory string `json:"directory"`
ProjectID string `json:"projectID"`
Subpath string `json:"subpath,omitempty"`
}
// SessionTime carries the millisecond timestamps OpenCode reports.
type SessionTime struct {
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Busy int64 `json:"busy,omitempty"`
Idle int64 `json:"idle,omitempty"`
Viewed int64 `json:"viewed,omitempty"`
Archived int64 `json:"archived,omitempty"`
}
// Session is one entry of GET /api/session.
type Session struct {
ID string `json:"id"`
ParentID string `json:"parentID,omitempty"`
ProjectID string `json:"projectID"`
Title string `json:"title"`
Agent string `json:"agent,omitempty"`
Model *ModelRef `json:"model,omitempty"`
Cost float64 `json:"cost"`
Tokens *TokenUsage `json:"tokens,omitempty"`
Time SessionTime `json:"time"`
Location *Location `json:"location,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
// PageCursor is the opaque pagination cursor of session and message lists.
type PageCursor struct {
Next string `json:"next,omitempty"`
Previous string `json:"previous,omitempty"`
}
// SessionPage is GET /api/session.
type SessionPage struct {
Data []Session `json:"data"`
Cursor PageCursor `json:"cursor"`
}
// Message is one entry of GET /api/session/{id}/message. The server's union
// is wide; fields the client does not need stay zero.
type Message struct {
ID string `json:"id"`
Type string `json:"type"`
Time MessageTime `json:"time"`
Agent string `json:"agent,omitempty"`
Model *ModelRef `json:"model,omitempty"`
Content []ContentPart `json:"content,omitempty"`
Text string `json:"text,omitempty"`
Files []FileAttachment `json:"files,omitempty"`
Finish string `json:"finish,omitempty"`
Cost float64 `json:"cost,omitempty"`
Tokens *TokenUsage `json:"tokens,omitempty"`
Error json.RawMessage `json:"error,omitempty"`
// Shell messages
Command string `json:"command,omitempty"`
Status string `json:"status,omitempty"`
Exit *int `json:"exit,omitempty"`
Output string `json:"output,omitempty"`
}
// MessageTime carries the millisecond timestamps of a message.
type MessageTime struct {
Created int64 `json:"created"`
Streamed int64 `json:"streamed,omitempty"`
Completed int64 `json:"completed,omitempty"`
}
// ContentPart is a block of an assistant message.
type ContentPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
State *ToolState `json:"state,omitempty"`
Time *PartTime `json:"time,omitempty"`
MIME string `json:"mime,omitempty"`
URL string `json:"url,omitempty"`
URI string `json:"uri,omitempty"`
Filename string `json:"filename,omitempty"`
}
// PartTime is when a reasoning/text block was written.
type PartTime struct {
Created int64 `json:"created,omitempty"`
Completed int64 `json:"completed,omitempty"`
}
// ToolState is a tool call's state machine.
type ToolState struct {
Status string `json:"status"`
Input map[string]any `json:"input,omitempty"`
Content []ContentPart `json:"content,omitempty"`
Attachments []ContentPart `json:"attachments,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Error json.RawMessage `json:"error,omitempty"`
}
// PromptFile is a file riding with a prompt: a data URL or a URI the
// server can read, and its name.
type PromptFile struct {
URI string `json:"uri"`
Name string `json:"name,omitempty"`
}
// FileAttachment is a file attached to a user prompt.
type FileAttachment struct {
URI string `json:"uri"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
MIME string `json:"mime,omitempty"`
}
// MessagePage is GET /api/session/{id}/message.
type MessagePage struct {
Data []Message `json:"data"`
Cursor PageCursor `json:"cursor"`
}
// Event is one server-sent event of GET /api/event.
type Event struct {
ID string `json:"id"`
Created int64 `json:"created"`
Type string `json:"type"`
Location *Location `json:"location,omitempty"`
Durable *EventDurable `json:"durable,omitempty"`
Data json.RawMessage `json:"data"`
}
// EventDurable is the durable envelope some events carry.
type EventDurable struct {
AggregateID string `json:"aggregateID"`
Seq int64 `json:"seq"`
Version int `json:"version"`
}
// SessionEventData covers the payload fields this client reads. Use
// Event.UnmarshalData into a wider struct when more is needed.
type SessionEventData struct {
SessionID string `json:"sessionID"`
AssistantMessageID string `json:"assistantMessageID"`
Ordinal int `json:"ordinal"`
Delta string `json:"delta"`
Text string `json:"text"`
MessageID string `json:"messageID"`
PartID string `json:"partID"`
Agent string `json:"agent"`
Model *ModelRef `json:"model"`
RequestID string `json:"requestID"`
Reply string `json:"reply"`
Action string `json:"action"`
Resources []string `json:"resources"`
}
-160
View File
@@ -1,160 +0,0 @@
// Package storage keeps saved servers in the app's store and their device
// tokens in the platform's secure storage.
package storage
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/url"
"sort"
"github.com/egoist/asuka/sdk/secure"
"github.com/egoist/asuka/sdk/store"
"github.com/egoist/asuka/signal"
)
// Connection is one saved server.
type Connection struct {
ID string `json:"id"`
Label string `json:"label"`
URL string `json:"url"`
Proxy string `json:"proxy,omitempty"`
Insecure bool `json:"insecure,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
ServerID string `json:"serverId,omitempty"`
Passwordless bool `json:"passwordless,omitempty"`
LastUsedAt int64 `json:"lastUsedAt,omitempty"`
}
// Store is the persistence the UI needs. Tests use a memory store.
type Store interface {
Connections() []Connection
SaveConnections([]Connection)
InstallID() string
LoadToken(c Connection) (string, bool, error)
SaveToken(id, token string) error
ClearToken(c Connection) error
}
// Persistent is the app's store: servers in store.json, tokens in the
// Android Keystore / Keychain.
type Persistent struct {
conns *signal.Signal[[]Connection]
installID *signal.Signal[string]
}
const (
connectionsKey = "openchamber.connections"
installIDKey = "openchamber.installId"
// legacyKey is the single-server record earlier versions wrote.
legacyKey = "openchamber.connection"
)
// New makes the persistent store. Call it on the main thread, while a
// component builds, as any signal.
func New() *Persistent {
conns := store.Signal(connectionsKey, []Connection{})
list := conns.Get()
if len(list) == 0 {
list = migrateLegacy()
if len(list) > 0 {
conns.Set(list)
}
}
p := &Persistent{
conns: conns,
installID: store.Signal(installIDKey, ""),
}
return p
}
// migrateLegacy turns the old single-connection record into a list entry.
func migrateLegacy() []Connection {
var raw string
if !store.Get(legacyKey, &raw) || raw == "" {
return nil
}
var old Connection
if json.Unmarshal([]byte(raw), &old) != nil || old.URL == "" {
return nil
}
if old.ID == "" {
old.ID = newID()
}
if old.Label == "" || old.Label == old.URL {
if u, err := url.Parse(old.URL); err == nil && u.Host != "" {
old.Label = u.Host
} else {
old.Label = old.URL
}
}
// Clear it so the next launch does not migrate again.
_ = store.Set(legacyKey, "")
return []Connection{old}
}
func (p *Persistent) Connections() []Connection {
list := p.conns.Get()
out := make([]Connection, len(list))
copy(out, list)
return out
}
func (p *Persistent) SaveConnections(list []Connection) {
sort.SliceStable(list, func(i, j int) bool { return list[i].LastUsedAt > list[j].LastUsedAt })
p.conns.Set(list)
}
// InstallID is a stable random id for this installation. It names the
// device when logging in, so repeated logins reuse one device record.
func (p *Persistent) InstallID() string {
if id := p.installID.Get(); id != "" {
return id
}
id := newID()
p.installID.Set(id)
return id
}
func (p *Persistent) tokenKey(id string) string {
sum := sha256.Sum256([]byte(id))
return "openchamber.token." + hex.EncodeToString(sum[:12])
}
// legacyTokenKey is where earlier versions kept a token: by server URL.
func legacyTokenKey(url string) string {
sum := sha256.Sum256([]byte(url))
return "openchamber.token." + hex.EncodeToString(sum[:12])
}
func (p *Persistent) LoadToken(c Connection) (string, bool, error) {
if tok, ok, err := secure.Get(p.tokenKey(c.ID)); err != nil || ok {
return tok, ok, err
}
// A connection migrated from the single-server record keeps its token
// under the old URL-based key.
return secure.Get(legacyTokenKey(c.URL))
}
func (p *Persistent) SaveToken(id, token string) error {
return secure.Set(p.tokenKey(id), token)
}
func (p *Persistent) ClearToken(c Connection) error {
err := secure.Delete(p.tokenKey(c.ID))
_ = secure.Delete(legacyTokenKey(c.URL))
return err
}
func newID() string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "srv_" + hex.EncodeToString(b[:4])
}
return "srv_" + hex.EncodeToString(b[:])
}
// NewID returns a fresh connection id.
func NewID() string { return newID() }
+34
View File
@@ -0,0 +1,34 @@
**/dgph
*.mode1v3
*.mode2v3
*.moved-aside
*.pbxuser
*.perspectivev3
**/*sync/
.sconsign.dblite
.tags*
**/.vagrant/
**/DerivedData/
Icon?
**/Pods/
**/.symlinks/
profile
xcuserdata
**/.generated/
Flutter/App.framework
Flutter/Flutter.framework
Flutter/Flutter.podspec
Flutter/Generated.xcconfig
Flutter/ephemeral/
Flutter/app.flx
Flutter/app.zip
Flutter/flutter_assets/
Flutter/flutter_export_environment.sh
ServiceDefinitions.json
Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!default.mode1v3
!default.mode2v3
!default.pbxuser
!default.perspectivev3
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
</dict>
</plist>
+1
View File
@@ -0,0 +1 @@
#include "Generated.xcconfig"
+1
View File
@@ -0,0 +1 @@
#include "Generated.xcconfig"
+647
View File
@@ -0,0 +1,647 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 97C146E61CF9000F007C117D /* Project object */;
proxyType = 1;
remoteGlobalIDString = 97C146ED1CF9000F007C117D;
remoteInfo = Runner;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
9705A1C41CF9048500538489 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
97C146EB1CF9000F007C117D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
331C8082294A63A400263BE5 /* RunnerTests */ = {
isa = PBXGroup;
children = (
331C807B294A618700263BE5 /* RunnerTests.swift */,
);
path = RunnerTests;
sourceTree = "<group>";
};
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
9740EEB31CF90195004384FC /* Generated.xcconfig */,
);
name = Flutter;
sourceTree = "<group>";
};
97C146E51CF9000F007C117D = {
isa = PBXGroup;
children = (
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
331C8082294A63A400263BE5 /* RunnerTests */,
);
sourceTree = "<group>";
};
97C146EF1CF9000F007C117D /* Products */ = {
isa = PBXGroup;
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
331C8081294A63A400263BE5 /* RunnerTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
);
path = Runner;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
331C8080294A63A400263BE5 /* RunnerTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
buildPhases = (
331C807D294A63A400263BE5 /* Sources */,
331C807F294A63A400263BE5 /* Resources */,
);
buildRules = (
);
dependencies = (
331C8086294A63A400263BE5 /* PBXTargetDependency */,
);
name = RunnerTests;
productName = RunnerTests;
productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
97C146ED1CF9000F007C117D /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
);
buildRules = (
);
dependencies = (
);
name = Runner;
packageProductDependencies = (
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
);
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97C146E61CF9000F007C117D /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastUpgradeCheck = 1510;
ORGANIZATIONNAME = "";
TargetAttributes = {
331C8080294A63A400263BE5 = {
CreatedOnToolsVersion = 14.0;
TestTargetID = 97C146ED1CF9000F007C117D;
};
97C146ED1CF9000F007C117D = {
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
packageReferences = (
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,
);
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
97C146ED1CF9000F007C117D /* Runner */,
331C8080294A63A400263BE5 /* RunnerTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
331C807F294A63A400263BE5 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
97C146EC1CF9000F007C117D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${TARGET_BUILD_DIR}/${INFOPLIST_PATH}",
);
name = "Thin Binary";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
331C807D294A63A400263BE5 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
97C146EA1CF9000F007C117D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
331C8086294A63A400263BE5 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 97C146ED1CF9000F007C117D /* Runner */;
targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
97C146FA1CF9000F007C117D /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C146FB1CF9000F007C117D /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C147001CF9000F007C117D /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
249021D3217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Profile;
};
249021D4217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Profile;
};
331C8088294A63A400263BE5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
};
name = Debug;
};
331C8089294A63A400263BE5 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
};
name = Release;
};
331C808A294A63A400263BE5 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
};
name = Profile;
};
97C147031CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
97C147041CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SUPPORTED_PLATFORMS = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
97C147061CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
97C147071CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.blumia.openchamber.flutter;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
331C8088294A63A400263BE5 /* Debug */,
331C8089294A63A400263BE5 /* Release */,
331C808A294A63A400263BE5 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147031CF9000F007C117D /* Debug */,
97C147041CF9000F007C117D /* Release */,
249021D3217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147061CF9000F007C117D /* Debug */,
97C147071CF9000F007C117D /* Release */,
249021D4217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
isa = XCSwiftPackageProductDependency;
productName = FlutterGeneratedPluginSwiftPackage;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
Loaded 100 of 219 files, more files were not shown because too many files have changed in this diff. Show more