Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

0.4.8 (408).
2026-11-23 17:42:49 +08:00
blumia 91bf5e5b81 fix: make the pairing QR scanner actually see dense codes
The scanner read frames at 480p, which is thin for the web UI's dense
pairing QR (1024px, low error correction, a two-module quiet zone), and it
rejected a Y plane whose last row has no padding even though some cameras
return exactly rowStride * (height - 1) + width bytes — on those devices
every frame was dropped, so nothing ever reacted.

Frames are now requested at 720p and fall back to 480p only when the device
refuses the higher analysis size; a stream that fails to start reports an
error instead of leaving a silent preview. Decoding runs with zxing's
tryHarder hint and retries an inverted frame for light-on-dark codes.

The screen also reports what it sees: resolution/format and a live
"frames scanned / decode attempts" line, a one-time log of the first frame's
planes, row stride and byte count, a no-frames hint after four seconds, and a
"move closer" hint when frames decode but no QR is found.

0.4.6 (406).
2026-11-23 12:26:16 +08:00
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
blumia 2fb4a8ea79 feat: context usage ring and tool image previews
- the composer shows a context ring and percentage from the last
  token-bearing assistant message, toned at 75% and 90%; tapping opens a
  sheet with the model, used tokens, limits, output reserve and turn cost
- images a tool call names (read attachments as data URLs, input paths,
  and image paths in output text) get a link under the tool row; tapping
  previews it from the data URL or /api/fs/raw, allowing paths outside
  the workspace
- directory-scoped requests now send x-opencode-directory-encoding: uri,
  which scoped routes such as /api/fs/raw need to decode the header
- ocprobe gains a raw file command for checking previews

Bump version to 0.2.2 (build 16).
2026-11-18 02:15:11 +08:00
blumia dc3730eba7 feat: inline image previews, revert, and the official icon
- sent images keep a local copy and render as rounded thumbnails in the
  message, surviving later page reloads
- a prompt's menu can revert it and everything after it: confirm, then
  stage and commit the server-side revert
- the app icon is OpenChamber's own (packages/mobile/assets/icon-only.png)
- document a terminal assessment (native view vs Go ANSI vs xterm.js in
  a WebView) for the next decision

Bump version to 0.2.1 (build 15).
2026-11-17 23:46:06 +08:00
blumia 72119b73e8 feat: search sessions, attach files, read aloud, jump to latest
Reach the first-party mobile client's everyday features:

- sessions: a search button opens a field; typing asks the server with
  its search parameter (350 ms settle) and clearing restores the list
- composer: attach photos or files (up to five, 10 MB each) as data
  URLs with the prompt; attachments show as removable chips and are
  named under the sent message
- turn menu: read the answer aloud with the system voice, or stop it
- chat: a "latest" button appears after scrolling up and returns to the
  end of the conversation
- reset a live search when a connection ends

Bump version to 0.2.0 (build 14).
2026-11-17 21:52:06 +08:00
blumia 4c6fcf4cbe fix: skip a late tool event that has no name
A terminal tool event can arrive without its starting one; adding a
blank row for it is worse than waiting for the next page read.

Bump version to 0.1.12 (build 13).
2026-11-16 20:11:14 +08:00
blumia e67490e768 perf: open long sessions without re-reading every tool result
A chat page carried every finished tool result, and the app fetched it
twice when opening a chat, with a 20 second deadline. On a slow link a
long session (this one was ~530 KB per page) timed out.

- ask for shelled pages (x-openchamber-part-shells: v1), which drops
  finished tool results: ~180 KB for the same page
- fetch one message by id when its tool row is opened
- keep tool and step updates local from events instead of re-reading
  the page on every step, and only resync after a real disconnect
- 60 second deadline with a retry button

Bump version to 0.1.11 (build 12).
2026-11-16 20:04:42 +08:00
blumia 0e34d82a06 feat: actions under user messages, and a dependable footer icon
Every prompt now carries a row with its time, a copy button and a menu
(copy message, fork before this prompt), matching the first-party
client. The turn footer's sparkles became an inline SVG: the platform
symbol table left an empty square on some devices.

Bump version to 0.1.10 (build 11).
2026-11-16 19:55:05 +08:00
blumia d3e92f036a feat: open the turn actions in a bottom sheet
The footer's "more" button now opens a sheet with the completion time
above the actions, matching the first-party client; the platform action
sheet dropped the time. Copy answer and fork from here are listed, and
a back gesture dismisses it.

Bump version to 0.1.9 (build 10).
2026-11-16 18:34:32 +08:00
blumia a471c026f1 fix: measure a turn's duration when its prompt is not loaded
A long turn's prompt can fall before the loaded message page. Measure
from the first record of the run then, so historical turns still show a
duration in the footer.

Bump version to 0.1.8 (build 9).
2026-11-16 18:19:27 +08:00
blumia 8268bdecc2 feat: show a model, agent and duration footer after each turn
Match the first-party chat footer on touch screens: after a turn ends,
its last assistant message gets a row with the model name (resolved
from /api/model with the id as fallback), the agent and how long the
turn took, plus a "more" menu. The menu shows the completion timestamp
and offers copy answer and fork from here; forking copies history
before the next prompt (or the whole history at the end) and opens the
new session.

Bump version to 0.1.7 (build 8).
2026-11-16 18:05:15 +08:00
blumia 56cf889ee9 fix: no dead title bar on the server list
While disconnected the screen is the bare list with its own heading;
the navigation stack (and its new-session and refresh actions) exists
only once connected. That removes the duplicate title and the buttons
that could do nothing without a session.

Bump version to 0.1.6 (build 7).
2026-11-16 13:58:01 +08:00
251 changed files with 41778 additions and 5575 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)
}
+812 -6
View File
@@ -1,13 +1,796 @@
# 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.7.4 已知项目只算 OpenChamber 的项目列表(分支 `flutter`)
**可行,且 asuka 的覆盖度比预期好。** 但真正的风险不在 UI,而在三处:
| 项 | 结果 |
| --- | --- |
| 列表 | 0.7.3 用 `app.projects` 做过滤,但这个列表同时包含 OpenCode 发现的所有目录(`~/.config/pitchfork`、`~/Downloads` 等),所以那些端口仍被当成「已知项目」显示。现在只把带 OpenChamber 设置记录的项目(`metaId` 非空)加上当前项目当作已知工作区,和网页端的项目列表一致;没有目录的 announced 端口(9090)仍显示。手机列表恢复为网页端看到的 8080、9090 |
| 版本 | **0.7.4(code 704)** |
---
## 0.7.3 开发服务器列表与网页端同一套过滤(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 列表 | 0.7.2 放开了项目目录过滤,结果把 `~/.config/pitchfork`、`~/Downloads` 等不在项目列表里的端口也列了出来(手机 7 个,网页只有 2 个)。现在按网页端的规则:只列出「返回了网页」且目录属于已知项目(含当前目录)或没有目录(announced)的端口;不在任何项目里的端口像网页端一样隐藏在「显示已隐藏端口」之后。Telegram 的 8080 属于已知项目、9090 没有目录,两者都会显示 |
| 版本 | **0.7.3(code 703)** |
---
## 0.7.2 开发服务器列表改为全机器范围(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 列表 | 网页端的「正在运行的开发服务器」是整台宿主机的列表,不按当前项目过滤;手机端之前多了一层「当前项目目录」过滤,导致 `telegram-antispam-bot` 的 8080 在手机上不显示。现在同样列出服务端发现的所有「返回了网页」的端口(无页面的 adb/模拟器端口仍隐藏),与网页端一致 |
| 版本 | **0.7.2(code 702)** |
---
## 0.7.1 浏览器通过服务端 dev tunnel 预览(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 网络 | 不再是手机本机网络:`localhost` / `127.0.0.1` 地址改为在手机本地绑定一个随机端口的 TCP 监听器,每条连接通过 Relay/直连的 WebSocket 连到服务端 `/api/dev-tunnel?port=…&oc_url_token=…`,由服务端连接它自己 loopback 上的 dev server;页面 origin 是本地监听器,绝对路径、Cookie、HMR WebSocket 都按这个 origin 工作 |
| dev server 列表 | 从 `/api/dev-servers` 读取服务端发现且返回了网页的项目 dev server(按当前项目目录过滤,过滤掉 adb/模拟器等没有页面的端口);空状态列出标题 / URL / 命令,点击即可预览;也可以手动输入 URL |
| 地址栏 | 显示原始 `http://localhost:端口/...`,内部加载本地隧道地址;页面里的同源链接会重写到隧道,跳到另一个 loopback 端口会为新端口开隧道;历史记录保存原始地址 |
| 鉴权 | Relay 由 `RelayTransport` 自动 mint `oc_url_token`;直连时客户端 `POST /auth/url-token` 取短期 token 并缓存,WebSocket 同时带 bearer;服务端仍只允许它发现列表里的端口 |
| 版本 | **0.7.1(code 701)** |
---
## 0.7.0 浏览器地址栏菜单与网络说明(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 地址栏 | 后退 / 前进 / 在系统浏览器中打开 / 历史记录收进右上角「三个点」菜单;历史记录是二级菜单(最近 20 条,空时显示「暂无历史记录」)。地址栏只保留网址输入、停止/刷新和菜单,手机宽度下输入区明显变宽 |
| 网络 | 嵌入式 WebView 运行在**手机本机**,`localhost` 是手机而不是 OpenChamber 服务端;OpenChamber 网页端的浏览器面板同样在客户端渲染,服务端没有通用 URL 代理。空状态明确提示:要预览 OpenChamber 主机上的开发服务器,请输入主机的局域网地址(或让服务监听 0.0.0.0) |
| 版本 | **0.7.0(code 700)** |
---
## 0.6.7 右侧栏浏览器与图标标签(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 浏览器 | 右侧栏新增【浏览器】页:地址栏(后退 / 前进 / 输入网址 / 前进按钮 / 停止或刷新)、历史记录、在系统浏览器中打开;空状态提供 `localhost:3000`、`5173`、`8080` 快捷入口;页面用嵌入式 WebView 打开(Android/iOS),桌面显示仅移动端可用的提示 |
| 地址栏 | 自动补 `http://`(localhost/回环地址)或 `https://`,加载错误时显示错误条和重试;地址字段把光标放在末尾,窄栏也能看到刚访问的部分 |
| 标签 | 右侧栏顶部由文字标签改为**图标 + tooltip**(文件、项目知识、终端、浏览器),项目多/栏窄时不再截断文字;四个页签用懒加载的 Offstage 栈保持各自状态(浏览器页面切走再切回不会重新加载) |
| 明文 | Android 允许 WebView 加载 HTTP(`usesCleartextTraffic`),本地开发服务器可直接预览 |
| 版本 | **0.6.7(code 607)** |
---
## 0.6.6 图片查看器:保存/分享与隐藏顶栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 保存/分享 | 查看器右上角新增保存到相册、分享(Android):保存通过 MediaStore 写入 `Pictures/Chamber Go`(Android 10+ 无需权限,旧版本按需申请存储权限),分享用 FileProvider 生成临时文件并打开系统分享面板;非 Android 平台不显示这两个按钮 |
| 顶栏 | dsh-Go 的查看器顶栏(返回、文件名)是**始终显示**的;按你的建议,我们改为单指点击图片切换顶栏和底部页码的显示/隐藏,再点一次恢复,避免标题和按钮挡住图片;双击仍用于 2.5 倍缩放,未放大时左右滑动翻页,放大后单指拖动平移 |
| 版本 | **0.6.6(code 606)** |
---
## 0.6.5 会话图片全屏查看(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 查看器 | 会话内图片(用户附件、工具生成/读取的图片、生成图片)从对话框改为全屏查看:黑底、返回 + 标题 + 页码;双指缩放最大 8 倍,双击在 2.5 倍与原始大小间切换,缩放后可单指拖动查看局部;多张图片可左右滑动 |
| 翻页与拖动 | 未缩放时单指左右滑动翻页;一旦放大,单指拖动用于平移图片,翻页被禁用,缩回原始大小后恢复翻页 |
| 参考 | dsh-Go 的图片查看器就是这种相册式行为(`ImageViewerPage` + `ImagePager` + `ZoomableImage`:双指 8 倍、双击 2.5 倍、缩放时禁用翻页),本次按同样的交互实现 |
| 版本 | **0.6.5(code 605)** |
---
## 0.6.4 Relay 错误横幅在后台恢复后不消失(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 原因 | 从后台恢复时,Relay 隧道第一次请求可能因 DNS/网络尚未就绪失败,`refreshSessions` 把「无法连接 Relay…」写进 `AppState.error`;后续会话列表或事件流成功后没有清除它(事件流只清除固定的「Connection lost, reconnecting…」文案)。侧栏的「重试」只调用 `refreshSessions`,成功也不清错误,所以看起来没有反应,尽管会话、文件和实时更新都已恢复 |
| 修复 | 区分传输错误与会话操作错误:会话列表、搜索、加载更多、归档、活动状态、权限、聊天设置、项目、文件主页、模型等任一成功请求,以及事件流恢复后的任意事件,都会清除传输错误;置顶/归档等动作错误不会被例行刷新清掉。侧栏「重试」改为 `retryConnection()`:没有客户端时重连已保存的连接,否则重新拉取会话列表并清掉过期的传输错误 |
| 版本 | **0.6.4(code 604)** |
---
## 0.6.3 文件侧栏的 gitignore 开关改用服务端值(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 服务端存储 | OpenChamber 的设置文档里有 `filesViewShowGitignored`(profile scope,网页端也用它),没有该键时默认不显示被 git 忽略的文件。客户端现在从 `/api/config/settings` 读取它,不再写死本地默认值 |
| 切换 | 文件侧栏的【显示被 git 忽略的文件】勾选/取消勾选后立即刷新列表,并通过 `PUT /api/config/settings` 写回服务端(`surface=mobile`);保存失败时恢复原值并显示错误 |
| 同步 | 侧栏打开期间如果服务端值变化(例如网页端改了同一设置),监听 `AppState` 后按新值重新加载列表 |
| 版本 | **0.6.3(code 603)** |
---
## 0.6.2 归档选择器只列有归档的项目(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 筛选范围 | 归档页打开的项目选择器只列出**实际有已归档会话**的项目(按名字排序),不再显示全部项目;同时隐藏「添加项目」按钮(归档页不会新增归档,添加项目在此无意义)。聊天归档仍通过「聊天」行进入 |
| 版本 | **0.6.2(code 602)** |
---
## 0.6.1 归档筛选改用共享项目选择器(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 项目筛选 | 归档页顶部原来的横向项目 chips 改为与新建会话 / 计划任务 / 统计一致的项目选择行:点击打开共享项目 bottomsheet(含「所有项目」「聊天」与全部项目、图标、路径、当前选中标记),选完立即筛选归档列表;项目很多时不会再横向挤在一起 |
| 选择器搜索 | 共享项目 bottomsheet 新增搜索框,按项目名或路径过滤,项目很多时也能快速定位;无匹配时显示「没有匹配的项目」 |
| 版本 | **0.6.1(code 601)** |
---
## 0.6.0 归档页面(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 归档页面 | 全部功能新增【归档】:标题下显示已归档会话数量,支持按标题 / 会话 ID / 项目名搜索,顶部按项目分组的 chips 可筛选(全部 + 各项目及数量),点击行打开会话,行尾可取消归档(恢复)或打开菜单(打开 / 取消归档 / 复制会话 ID / 删除)。页面参考 OpenChamber 手机端归档页 |
| 侧栏 | 去掉【显示已归档】按钮和侧栏里的归档列表;侧栏只保留活动会话,归档统一从【全部功能 → 归档】进入 |
| 列表 | 归档会话按归档时间(缺失时按更新时间)倒序;项目分组按最近归档时间排序;取消归档后该行从归档页移回侧栏的活动列表 |
| 版本 | **0.6.0(code 600)** |
---
## 0.5.7 添加项目与上下文环回退(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 添加项目 | 项目选择器右上角新增【添加项目】:从服务器用户主目录开始浏览文件夹(可输入路径、上一级、新建文件夹),选中后写入 OpenChamber 项目列表并立即作为当前目标;新建会话、计划任务、统计的项目列表共享同一入口 |
| 项目列表 | `/api/project` 只在项目里有会话后才返回该项;`refreshProjects` 现在合并设置文档里的项目(按 `addedAt` 新的在前),所以刚添加、还没有会话的项目也能在选择器里出现 |
| 上下文环 | 旧会话的模型可能已从服务器模型目录移除,`usageReading` 找不到上下文窗口时不再隐藏输入框底部的环:按 200K 窗口估算并显示 `~百分比`;用量弹层注明「该模型不在模型目录中,上下文窗口为估算值」 |
| 版本 | **0.5.7(code 507)** |
---
## 0.5.6 统计页面与 Chamber Go(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 统计 | 全部功能里新增【统计】:时间范围(今天 / 7 天 / 30 天 / 90 天 / 全部)、项目筛选(所有项目或某个检出)、会话 / 提示词 / 令牌 / 费用 / 活跃天数 / 连续天数、每日(超过 92 天按周)活动柱状图、令牌构成、效率指标、模型排行(按令牌 / 费用 / 步数)、按需加载的工具调用统计(调用次数、成功率、失败、中位耗时)。数据来自 `/api/experimental/session/stats`;时区取设备的 IANA 名称(Android 平台通道,桌面回退 UTC) |
| 命名 | 客户端显示名改为 **Chamber Go**(Android 启动器、iOS、Linux 窗口、关于页),包名不变。配对兑换上报的 `clientLabel` / `deviceName`、登录标签与请求 user-agent(`chamber-go/<版本>`)一并改名 |
| 名称来源 | 网页端「连接到此服务器」列表显示服务器保存的 client label:操作员建配对链接时填的名字优先;否则沿用同设备(dedupeKey)已有的名字;第一次配对且都没填时才用客户端自报的 `clientLabel` / `deviceName`。因此老设备改名后仍显示旧名,要在列表里重命名,或撤销后重新配对 |
| 版本 | **0.5.6(code 506)** |
---
## 0.5.5 项目选择与计划任务运行位置(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 空白选项 | 服务器会把根目录 `/` 也列成一个项目;`pathLeaf('/')` 取最后一段时得到空串,标签就成了空白。根路径现在用自己的路径作名称(`/`);同一个 checkout 被服务器列两次(项目记录 + sandbox)时也合并成一行 |
| 新建会话 | 点项目名不再先等项目接口:bottomsheet 立即弹出,列表为空时显示「正在加载项目…」,刷新完成(或已有缓存)后展示列表;确实没有项目时显示「没有可用的项目」 |
| 计划任务 | 运行位置改用与新建会话相同的项目 bottomsheet(含「聊天」scope、图标、路径与当前选中标记),不再用长列表下拉框 |
| 版本 | **0.5.5(code 505)** |
---
## 0.5.4 文件下载进度(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 进度 | 下载对话框的进度条改为确定进度:用 `fs/stat` 取到的文件大小当总量,服务器给出 `Content-Length` 时以服务器为准;显示「已下载 / 总大小 (百分比)」。Relay 把响应体按 chunked 转发、不带 `Content-Length` 时也能看到百分比 |
| 取消 | 取消仍然中断请求并丢弃已下载的数据;完全没有大小信息时保持不确定进度条,并显示已下载字节数 |
| 版本 | **0.5.4(code 504)** |
---
## 0.5.3 英文为源、按范围选择文本(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 语言 | 默认跟随系统(中文系统用中文,其它语言用英文),可在 设置 → 常规 → 语言 里固定「中文 / English」;选择保存在本机,启动时先读取再出第一帧,系统语言变化时「跟随系统」会立即重绘 |
| 文案 | 代码里直接写英文;`tr()` / `trArgs()` 查中文表 `lib/l10n/zh.dart`,`AppText` 同理。没有对应表的语言(西班牙语等)按英文显示,缺条目也回退英文,不会出现空文案。服务器与用户数据(会话标题、消息、任务名、文件内容等)用 `Text` 原样显示 |
| 系统组件 | 接入 `flutter_localizations`,日期/时间选择器、文本选择菜单等系统文案随语言切换 |
| 选择文本 | 只有会话内容可选中:消息气泡、回答正文、展开后的工具调用详情(命令/参数/输出)、一轮结束后的「模型 · 模式 · 耗时」行。未展开的工具调用行与「已完成 · X 次工具调用」等状态提示不可选中 |
| 会话同步 | 事件流断开期间开始的回合,其开始事件收不到:收到未知助手消息的事件时先拉取一次尾部,补齐用户消息与完整答复,而不是只拼出后续增量 |
| 测试 | `test/l10n_test.dart`:中文查表与回退、无表的系统语言读英文、`AppText` 跟随语言、代码里每处 `AppText`/`tr`/`trArgs` 字面量都有中文条目 |
| 验证 | 模拟器:系统英文 → 全英文;切中文后整页与系统时间选择器立即变中文,重启保持;切回「跟随系统」;中文与英文下逐页检查;长按消息文本出现选择菜单,长按未展开的工具行与状态提示不再触发选择;断网重连后从网页端继续会话,手机端自动补齐新回合 |
| 版本 | **0.5.3(code 503)** |
---
## 0.5.2 中英双语与长按选择文本(分支 `flutter`,已被 0.5.3 调整)
- 初版:界面文案以中文写在代码里、查英文表;会话消息区整体包进 `SelectionArea`,长按任意位置都能选文本;接入 `flutter_localizations`。
- 0.5.3 起改为英文为源、按范围选择文本,见上。
---
## 0.5.1 计划任务与「全部功能」入口(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 入口 | 侧栏底部、设置按钮左侧新增「全部功能」按钮,打开一个功能页;目前里面只有【计划任务】一张卡片(图标 + 一句说明) |
| 计划任务 | 对照网页端:顶部选择运行位置(已注册项目 + 「聊天」scope,默认取当前会话所在项目),下面列出该项目的任务。每张卡片显示名称、计划、上次运行/状态、下次运行、模型行与错误;开关直接暂停/启用,菜单里可立即运行、编辑、删除;下拉刷新 |
| 编辑器 | 底部弹层:任务名称(≤80)、提示词(≤20000)、计划类型(每天 / 每周 / 一次性 / Cron)、时间点(可加多个)、星期、日期与时间(中文的日期/时间选择器)、Cron 示例、是否启用;默认「使用默认模型与智能体」,关闭后可选模型(复用模型选择器)与智能体 |
| 接口 | `GET/PUT /api/projects/:id/scheduled-tasks`、`DELETE …/:taskId`、`POST …/:taskId/run`,与网页端同一份数据;`openchamber:chats` 作为聊天 scope;服务器没有该接口(404)时页面写明「服务器不支持计划任务」。时间按服务器时区 |
| 中文化 | 应用整体指定中文(`flutter_localizations`),系统自带的日期/时间选择器、文本选择菜单随之是中文 |
| 测试 | 新增 `test/scheduled_tasks_test.dart`:四种计划的解析与展示文案、保存时只带该类型用到的字段、默认模型判断、状态与相对时间、功能页入口、编辑器的必填校验与草稿;`sidebar_footer_test` 覆盖新按钮;95 项全过 |
| 验证 | 模拟器(真实服务端):侧栏「全部功能」→ 计划任务;默认运行位置取当前会话所在项目(聊天目录与 chats 根不出现在项目列表里,统一归到末尾的「聊天」scope)。新建「Daily time report」(每天 09:00)后列表显示「下次:8 小时 45 分钟后」;「立即运行」→ 服务端 `lastStatus: sent` 并新建一个 scheduled 会话,卡片显示「上次运行 00:16 · 成功」;编辑弹层带出原值;关掉开关变「已暂停」;删除 → 确认 → 列表为空、服务端任务为空(运行产生的会话也已删除);切到「聊天」scope 正常加载 |
| 版本 | **0.5.1(code 501)** |
---
## 0.5.0 设置「常规」分组与「通用」页(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 分组 | 原来的【通用】分组改名【常规】,其下第一项新增【通用】页(智能体工具与记忆),第二项仍是【聊天】 |
| 通用页 | 对照网页端的「通用」页补齐:**在聊天中** —— 图表和原型、图像(开启时可选图像模型)、密钥、通知;**智能体知道的内容** —— 记忆(服务端支持时才出现;开启时带「整理记忆」勾选、模型与思考级别)、项目知识、用量限额。每项都有与网页端一致的一句说明 |
| 数据 | 全部走 `/api/config/settings?surface=mobile`,与网页端读写同一份设置;服务器未返回的键用网页端的默认值(图表/密钥/项目知识默认开,图像/通知/记忆/用量/整理记忆默认关),保存后以服务器返回的设置回填 |
| 模型选择 | 图像模型取 `/api/model?types=image`,整理记忆模型取会话的模型列表,都在底部弹层里选;可以清空回「不指定 / 默认模型」;换模型会清空思考级别 |
| 版本 | 版本号改为 **0.5.0(code 500)**,之后按 0.5.x 递增 |
| 测试 | `test/settings_screen_test.dart` 增加「通用」页:分组标题、六个开关与网页端一致的默认值(记忆需要服务端能力才显示);88 项全过 |
| 验证 | 模拟器(真实服务端):常规 → 通用;开关显示服务端当前值(图表关、图像开 + 图像模型 SenseNova U1.5 Lite、密钥开、通知关、记忆开、项目知识开、用量限额关)。开「图表和原型」后服务端 `agentRenderToolEnabled` 变 true;勾「整理记忆」出现模型行(AxonHub::deepseek-flash / 默认);图像模型弹层列出 Grok Imagine 与 SenseNova 并可清空回「不指定」;整理记忆弹层列出会话模型与「默认模型」。验证后把这两项改回原值 |
| 版本 | **0.5.0(code 500)** |
---
## 0.4.17 设置按分组拆页,新增「关于」(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 分组 | 设置页改成索引,对齐 dsh-Go 的组织方式:【通用】聊天;【外观】主题、宠物;【帮助与关于】关于。每行带图标、一句说明与右箭头,点开是独立子页;原来的全部控件搬进各自子页,索引里只留入口 |
| 版本 | 应用版本改为运行时从平台读取(`package_info_plus` 的 `version`;不含 Android build 号,因为 ABI 拆分会给它加一位、四个 APK 各不相同),`pubspec.yaml` 成为唯一出处;配对/relay 握手里的 `appVersion` 也用它,不再有写死的常量(之前还停在 0.4.14) |
| 关于 | 新增「关于」子页:应用图标与名称、版本号、开源许可入口、服务端 OpenCode 版本(`/api/info`)与 OpenChamber 版本(`/api/version`),右上角可重新获取;开源许可按包列出,点开看完整许可证文本(自绘中文页,不用英文的 `LicensePage`);未连接或取不到时明确写「未连接」「未获取到」 |
| 测试 | `test/settings_screen_test.dart` 重写:索引分组、聊天/主题/宠物/关于四个子页、版本与许可入口;87 项全过 |
| 验证 | 模拟器:设置索引三个分组四行;主题页模式/主题色可用;宠物页显示已导入的「Deepy 小鲸鱼」、启用开关与大小;关于页版本「0.4.17」、OpenCode「2.4.0」、OpenChamber「2.8.0」(取自当前服务器),许可页按包列出、点开显示完整许可证文本 |
| 版本 | **0.4.17(code 417)** |
---
## 0.4.16 回到前台后重新对账运行状态(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 会话进行到一半把应用切到后台,期间这一轮结束了:回到前台时对话区会刷新出新内容,但输入框上方的运行状态条还停在切走时的样子(该消失却没消失)。侧栏的运行标记同样只看事件流,漏掉结束事件后也会一直转 |
| 会话状态条 | 回前台时不再只重载转录,还会读一次 `GET /api/session/active`,再按服务器答复重新算「这一轮是否在跑」:在跑就显示、结束就收起。服务器没答上来时退回转录尾部(最新一条 assistant 消息还没有 `completed` 时间就是在跑),不会把一次失败的请求当成「全部空闲」 |
| 侧栏 | 回前台时刷新活动会话集合(`refreshActive`),侧栏的运行标记与后台会话的嵌套标记随之更新;服务器明确答复后才覆盖本地集合,请求失败保留原状态 |
| 事件流重连 | 同一套对账也挂在事件流恢复后的第一个事件上:socket 静默断过(不一定切过后台)而漏掉「这一轮结束」时,状态条和侧栏同样会自愈 |
| 打开会话 | 打开一个已经在中途的会话时也问一次服务器,状态条从第一帧就是对的(以前要等下一批事件才知道在跑) |
| 测试 | 新增 `test/running_state_test.dart`:服务器说空闲/在跑、服务器无答复时按转录尾部判断(有未完成的 assistant 消息算在跑,全部完成则不算);83 项全过 |
| 验证 | 模拟器:另一个会话里跑一轮长命令 → 切到后台 → 等这一轮结束 → 回到前台:状态条不再出现,侧栏该会话的运行标记消失;再验回前台时仍在进行的一轮保持显示 |
| 版本 | **0.4.16(code 416)** |
---
## 0.4.15 后台任务条细节:外观一致、停止移到弹层、宠物站位(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 外观一致 | 后台任务条改为与运行状态胶囊同一套形状:8 边距、14 水平内边距、36 最小高度、Stadium 圆角、相同的文字大小与基线,两条叠在一起时读作一组;多条任务在同一条胶囊里逐行排列 |
| 停止 | 按反馈去掉任务条上的「停止」按钮:它会把右侧对齐从计时挤开,与上方运行条的右端对不齐。现在点任意一行打开弹层,停止与复制都在弹层里(确认框「停止这个任务?」不变) |
| 弹层状态行 | 不再写「运行中」(弹层开着就是在跑,计时已经说明),也没有会让人误以为「点我刷新」的 `sync` 图标:左边只有计时;「停止」改成带方块停止图标的按钮;命令结束后才显示「已结束」 |
| 弹层关闭 | 去掉右侧的 x:拖动把手下滑和点遮罩都能关,x 是多余的 |
| 宠物 | 宠物站在最上方那条胶囊的边沿:有运行条或后台任务条时按它的 4px 上边距收脚,都不在时按输入框的 6px;之前会陷进胶囊顶边 2px |
| 测试 | `test/shell_jobs_test.dart`:任务条不再有「停止」、点行回调打开弹层、计时仍在;80 项全过 |
| 验证 | 模拟器:运行中 + 一条后台任务,两条胶囊等高同圆角;点任务行打开弹层:计时、带图标的「停止」与「复制」、实时输出与跟随,没有「运行中」字样与 x;首次读取时显示「读取输出…」转圈,不会误报「等待输出」;弹层内停止 → 确认 → shell 消失,弹层转为「已结束」并保留最后输出;从弹层头部下滑确实能关闭(x 去掉的前提);宠物在只有运行条、只有任务条、两者都有时都踩在胶囊上沿 |
| 版本 | **0.4.15(code 415)** |
---
## 0.4.14 后台任务:状态条、实时输出与停止(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 状态条 | 输入框上方新增后台任务条(在运行状态胶囊之下):1 条时直接显示命令、计时、`停止`;多条折叠成「正在执行 N 条命令」,默认 N ≤ 3 展开;子代理会话的任务标「子代理」 |
| 输出 | 点状态条任意一行打开底部弹层:完整命令、运行状态与计时、实时输出(1 秒轮询 `GET /api/shell/:id/output`,cursor 续读、尾部 256KB 封顶)、自动跟随与「回到最新」、复制、停止 |
| 工具行 | 起后台命令的 `bash` 行带「后台」标签;展开后显示「后台输出」预览(最后 8 行,仅展开时轮询)+「查看全部」+「停止」 |
| 数据来源 | 首选 `GET /api/experimental/job?sessionID=…&descendants=true&status=running` 里的 `kind=shell`(opencode 自己的后台记录:`shellID`、`command`、`sessionID`、`time.started`,覆盖子会话,不会混入前台命令);老服务端 404 时退回 `GET /api/shell` + 转录里 `{status:running, shellID}` 的标记 |
| 停止 | 确认框「停止这个任务?」→ `DELETE /api/shell/:id` → 向启动它的会话写一条 synthetic 说明(“用户停止了这条后台命令,随后的 Shell.NotFoundError 不是失败,不要因此重跑”,与上游口径一致),然后刷新列表 |
| 结束后 | 命令结束后,工具行与弹层不再轮询,改用会话里 synthetic `<background-result kind="shell" …>` 的最终输出(shell 被删除后仍能看);如果是用户在 App 里停的,显示「用户停止了这条命令。」而不是 Shell.NotFoundError |
| 刷新 | 打开会话立即刷新,之后 3 秒一次;会话消息变化时也刷新(新任务立刻出现);服务端无该接口时停止轮询 |
| 测试 | 新增 `test/shell_jobs_test.dart`:后台标记识别(前台命令不算)、转录/任务/外壳列表解析、输出页、完成说明与停止标记、计时格式、停止说明,以及状态条 1 条/2 条/多条折叠的布局;80 项全过 |
| 验证 | 模拟器(真实任务):`sleep 900` 单条任务条 → 第二条命令变为「正在执行 2 条命令」+ 两条行;弹层实时输出(每秒 tick);弹层内「停止」→ 确认 → 任务与 shell 消失、模型收到 synthetic 停止说明;工具行「后台」标签 + 展开后的最终输出/「用户停止了这条命令。」。后台进程可用前台命令超时后「移到后台」的方式启动(`timeout` 5 秒、不加 background),这样不会像 `background: true` 那样在超时点被 SIGKILL,任务会一直跑到手动停止 |
| 版本 | **0.4.14(code 414)** |
---
## 0.4.13 相对路径与生成图片的行内展示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 路径显示 | 折叠状态下 `read` / `write` / `edit` 等文件工具只显示相对于会话目录的路径(如 `lib/screens/chat_screen.dart`),不再被 `/home/...` 前缀挤掉文件名;会话目录之外的路径(如 `/tmp/...`)仍显示完整路径。diff 展开后的多文件标题同样去前缀 |
| 生成图片 | 对照上游确认:`openchamber_image`(`action=image.generate`,结果 JSON 里 `data.images[].path`)在 `isShownInPlace` 为真时会从 Activity 折叠里**提升**出来,由 `ShownToolCard → GeneratedImages` 在对话中直接显示图片(懒加载、点开画廊、上方有下载)。现在我们也把它从工具运行段里提出来:运行段在它之前结束,图片以卡片形式出现在原位置,最大高度 380,点击打开既有的全屏预览;运行中仍是「正在生成图片」的普通步骤,失败则留在运行段显示错误 |
| 图片缓存 | 卡片与全屏预览共用一份内存缓存(最多 8 张),列表重建不重复请求 `/api/fs/raw` |
| 测试 | 新增 `test/generated_images_test.dart`:结果 JSON 解析多图、未完成/失败/其它工具/非 JSON 不显示,`relativePath` 去前缀、目录外保留、尾斜杠与相似前缀;65 项全过 |
| 版本 | **0.4.13(code 413)** |
---
## 0.4.12 编辑工具的 diff 显示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 展开为 diff | `edit` / `write` / `patch` 等文件修改工具展开后不再显示一整段 old/new 纯文本,而是逐行 diff:新增行绿色底、删除行红色底、`@@` hunk 头浅色标记、`---/+++` 等元信息变灰;长行软换行,整块可选中复制(对齐 dsh-Go / 上游 `ToolPartDiffPreview`) |
| 数据来源 | 优先用服务端 `state.metadata.files[].patch`(可能多文件,按文件显示标题),其次 `metadata.patch` / `metadata.diff`;老服务端没有 patch 时用输入的 `oldString`/`newString` 做行级 LCS,`write` 只有 `content` 时显示为全新增行 |
| 行尾统计 | 工具行右侧显示 `+N −M`(与 dsh-Go 一致),失败/运行中不显示 |
| 大 diff | 最多渲染 600 行,超出显示「仅显示前 600 行,共 N 行」,避免聊天列表一次构建过多行 |
| 结果行 | diff 下方保留一行工具自身结果(如「Edited PLAN.md (1 replacement)」),错误仍用错误色 |
| 测试 | 新增 `test/diff_view_test.dart`:metadata patch 解析与增删计数、无 patch 的 old/new 回退、`write` 内容回退、失败/非文件工具不显示、DiffView 渲染增删行;57 项全过 |
| 验证 | 桌面快速验证:`PATH=$HOME/SDK/flutter/bin:$HOME/SDK/localbin:$PATH CC=clang CXX=clang++ PKG_CONFIG_PATH=$HOME/SDK/linuxdev/usr/lib/x86_64-linux-gnu/pkgconfig:$HOME/SDK/linuxdev/usr/share/pkgconfig flutter build linux --release`,然后 `DISPLAY=:99 build/linux/x64/release/bundle/openchamber` + `ffmpeg -f x11grab` 截图。跑之前先 `pkill -f build/linux`:残留的旧 debug 实例会占着窗口,点到的其实是旧代码(界面看着"不是最新版"就是这个原因)。最终效果仍在模拟器上用触摸验证 |
| 版本 | **0.4.12(code 412)** |
---
## 0.4.11 侧栏对齐调整(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 折叠箭头对齐 | 项目分组带内部 contentPadding 归零(外层仍为 8):分组折叠箭头与有子代理会话行的箭头在同一条竖线上 |
| 左右边距 | 会话行左右均为 8;项目带的 + 与会话行的 ⋮ 也都在右侧 8 的同一竖线上,标题可用宽度更大 |
| 标题起点 | 所有顶层会话行都保留固定 18px 的箭头列(无子代理时留空),标题横向起点一致;子代理行缩进 32 并保留竖线 |
| 测试 | 新增「分组箭头/子代理箭头同列、有无子代理的标题同起点」用例;52 项全过 |
| 版本 | **0.4.11(code 411)** |
---
## 0.4.10 子代理树折叠、Agent Task 行与只读输入(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏树 | 子代理行默认折叠:有子代理的父行左侧出现展开/收起箭头(tooltip「展开子代理/收起子代理」),展开后子行缩进并带一条竖线;父行副标题仍显示「N 个子代理」。当前打开的子代理会自动展开它的父行,手动收起后不会被重新展开 |
| Agent Task | 父会话的工具步骤识别 `subagent` / `task`(上游 Agent Task),显示子代理图标和描述;点击整行直接打开对应子会话(`state.metadata.sessionID`,旧结果从 `sessionID: ses_…` 文本解析)。会话不在当前分页时用 `GET /api/session/{id}` 取回 |
| 只读输入 | 普通子代理会话默认只读,底部显示「无法向子智能体会话发送提示。」;服务端 `allowPromptingSubagentSessions` 为 true 时才显示输入框。Lead 的 operator-child(`metadata.openchamber.kind = 'operator-child'`)始终只读,显示「此会话由 Lead 管理,接管后才能继续。」,直到后续实现接管 |
| 返回父会话 | 0.4.9 的父会话返回保留 |
| 测试 | `test/subagent_readonly_test.dart`(默认只读、设置放开、operator-child 即使放开也只读);侧栏测试改为默认折叠→点箭头展开→打开子行;51 项全过 |
| 版本 | **0.4.10(code 410)** |
---
## 0.4.9 浏览子代理会话(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏嵌套 | 子代理会话(`parentID` 指向父会话)不再被过滤掉:父行下面缩进显示一个子代理行(robot 图标,副标题以「子代理 ·」开头),父行的副标题显示「N 个子代理」;父会话在置顶区也带出它的子代理。子代理行可以点开查看完整会话内容,⋮ 菜单与普通会话一致 |
| 按需加载 | 打开父会话时并行请求 `GET /api/session?parentID=<id>`(每个父会话一次),把不在当前分页里的旧子代理补进列表;断开连接时清空缓存 |
| 父会话返回 | 子代理会话的 AppBar 左侧改为返回箭头(tooltip「返回父会话」),标题前有 robot 标记;点击回到父会话。侧栏点父行也能回去 |
| 测试 | `test/sidebar_rows_test.dart` 新增:父子会话同时显示、缩进/robot 图标、「1 个子代理」副标题、点击子行打开该会话;46 项全过 |
| 版本 | **0.4.9(code 409)** |
---
## 0.4.8 项目图标与聊天图标(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 元数据 | `refreshProjects` 同时读 `/api/config/settings?surface=mobile` 的 `projects`,把 label / icon / color / iconBackground / iconImage 按路径合并到 `/api/project` 的条目上(自定义 data dir、Windows 大小写/分隔符都按路径匹配) |
| 项目图标 | 聊天组改用聊天气泡图标;项目组、项目选择器、草稿的项目 chip 统一用 `ProjectIcon`:OpenChamber 的 46 个 icon key 映射到 Material 图标,`color` 支持 hex 与旧主题 key(primary/error/comment/keyword/string/…),无自定义图标时显示对应颜色的图标/文件夹 |
| 自定义图标 | `iconImage` 存在时经 `GET /api/projects/<settingsId>/icon?theme=…&iconColor=…` 取图(带认证,走 Transport/Relay);SVG 用 `flutter_svg` 渲染,PNG/favicon 用 `Image.memory`;有 `iconBackground` 时加圆角底色;加载失败回退字形,按 theme+updatedAt 缓存 |
| 测试 | 现有 46 项全过;模拟器上确认聊天组是气泡、项目组带各自的颜色/图标、选择器与草稿 chip 一致 |
| 版本 | **0.4.8(code 408)** |
---
## 0.4.7 聊天分组与「聊天」新建目标(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 聊天分组 | 连接后读 `GET /api/fs/home` 的 `chatsRoot` / `canonicalChatsRoot` / 旧版 `.config/openchamber/chats`,所有位于这些根下的会话(`chats/<日期>/session-…`)合并成一个「聊天」组;修复此前按目录 leaf 分组、每个聊天各显示成 `session-xxxxx` 的问题。自定义 data dir、Windows 分隔符/盘符大小写都按路径边界匹配 |
| 新建目标 | 新会话的项目选择器新增「聊天」:选择后草稿 chip 显示聊天图标和「聊天」;首次发送时先在 `chatsRoot/YYYY-MM-DD/session-<id>` 建目录(`POST /api/fs/mkdir`),再在该目录创建会话。已有聊天里点新会话会得到一个新的聊天目录,不会复用旧的 |
| 侧栏 | 聊天组的「+」提示「新建聊天」,直接打开以聊天为目标的草稿;项目选择器不再把聊天目录当作项目列出 |
| 测试 | `test/paths_test.dart` 增加聊天根边界(POSIX/Windows、`chats-other` 不误判);`test/sidebar_rows_test.dart` 增加多个聊天目录合并为唯一「聊天」组、不出现 `session-xxxxx` 的断言;本地服务器上用 curl 验证了在 chatsRoot 下 mkdir + 建会话 + 删除 |
| 版本 | **0.4.7(code 407)** |
---
## 0.4.6 扫码无反应的修复与诊断(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 原因候选 | 0.4.5 以 480p 取流,配对二维码很密(网页端 1024px、L 级纠错、只有 2 个模块的静区),模块在画面里可能小于 zxing 能识别的尺寸;另外部分设备的 Y 平面最后一帧不含行尾 padding(长度为 `rowStride*(h-1)+w`),旧代码会直接丢弃所有帧 |
| 取流 | 先请求 720p(`ResolutionPreset.high`),失败才退回 480p;取流失败不再静默显示预览,而是显示错误;4 秒没有帧时提示「没有收到相机画面」 |
| 解码 | zxing 加 `tryHarder`;正常解码失败后再用 `InvertedLuminanceSource` 试一次反色(深色卡片上的浅色二维码);Y 平面允许最后一帧缺少 padding |
| 诊断 | 扫描页底部显示「1280×720 yuv420 · 已扫描 N 帧 / 解码 M 次」;首帧通过 `debugPrint` 记录分辨率/planes/rowStride/像素步长/字节数,解码异常也会记录一次 |
| 测试 | `test/qr_scan_test.dart` 增加最后一帧无 padding、反色二维码两项;全部通过 |
| 版本 | **0.4.6(code 406)** |
---
## 0.4.5 扫码配对(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 扫码入口 | 「配对链接」对话框新增「扫码」:全屏相机 + 取景框 + 手电筒;扫到配对链接直接开始配对,不再要求按第二个按钮 |
| 解码 | 用 `camera` 0.12 + `zxing2` 0.2(纯 Dart,不依赖 ML Kit / Google Play 服务)。Android 取 YUV420 的 Y 平面直接作为亮度;BGRA(iOS/部分相机)按绿加权转亮度。解码放在 `compute` isolate,每帧不阻塞 UI,同一时间只解一帧 |
| 取景 | 后置相机优先、480p 预览、覆盖率/圆角遮罩 + 四角标记;非配对二维码提示「这不是 OpenChamber 配对二维码」并继续扫;无相机/权限被拒给出说明与重试 |
| 权限 | AndroidManifest 增加 CAMERA 权限;camera 硬件声明为非必需,没相机的设备仍可安装 |
| 测试 | `test/qr_scan_test.dart`:用 `qr` 生成配对链接二维码,渲染成 Y 平面(含 rowStride 内边距)后由 `decodeQrLuminance` 解出原文;空白帧、过短/非法尺寸返回 null |
| 版本 | **0.4.5(code 405)** |
---
## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 配对链接 | 服务器列表新增「配对链接」:粘贴 `openchamber://connect?v=2&p=…`,解析一次性密钥与候选地址(lan / tunnel / relay,按 priority 先直连后 Relay),用第一个能连上的候选兑换设备 token 并保存 |
| 端到端加密 | 新增 `relay_crypto.dart`:P-256 ECDH + HKDF-SHA256(salt = 握手 nonce,info = `openchamber-relay-v1`)派生两条 AES-256-GCM 方向密钥;帧 = 版本 + 12 字节 IV(4 随机前缀 + 8 字节计数器)+ 密文 + GCM tag,计数器严格递增,失败即关闭。与官方 `packages/ui/src/lib/relay/crypto.ts` 字节兼容 |
| 隧道 | 新增 `relay_tunnel.dart`:连 `wss://…/ws?v=1&role=client&serverId=…`,明文 hello/ready 握手,之后是加密的 mux 帧(HttpRequest/Body/Response/StreamEnd/Abort、WsOpen/Opened/Text/Binary/Close、Ping/Pong)。大消息按 64 KiB 分片与重组,断线不自动重拉(下一次请求重连,SSE 自己的重试循环会恢复) |
| Transport | `Transport.webSocket` 改为返回 `TransportSocket`(直连包装 WebSocket,Relay 用子流);新增 `RelayTransport` 实现同一接口,所有 HTTP/SSE 走隧道。Relay 下的终端 WebSocket 先经隧道 `POST /auth/url-token` 换取短时 token,附到 `oc_url_token` 查询参数 |
| 连接模型 | `Connection` 增加 `relayUrl/serverId/hostKey/grant` 与 `isRelay`;直连字段不变。配对成功的连接与设备 token 一起保存,之后启动/重连直接用 token,不再需要配对链接 |
| 未协商 | 不声明 batch、下行 flow control 与响应 gzip,走宿主端的 legacy 路径(一帧一条消息、明文响应体),先保证正确性 |
| 切换 | 已连接时配对会先断开旧服务器(关闭旧 shell、事件流),再切到新连接;`ChatScreen` 现在持有自己的 `ChatState`,不再在 dispose/计时器里读已清空的 `app.chat!`(修掉切换服务器时的一个空指针崩溃) |
| 测试 | `test/relay_crypto_test.dart`(JWK 往返、双方派生一致、方向密钥、重放/篡改失败、base64url)、`test/pairing_test.dart`(直连优先、relay-only、grant、过期/非法/裸 payload);`tool/relay_probe.dart` 对真实 relay 做了握手、兑换、/api/version、会话列表、SSE 与终端快照的端到端验证;模拟器上从「配对链接」粘贴 relay-only 链接、重启后自动重连、终端命令输入输出都通过 |
| 版本 | **0.4.4(code 404)** |
---
## 0.4.3 终端多标签:下拉切换、新建、按标签恢复(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 多标签 | 每个目录一个 `TerminalWorkspace`,持有多个 `TerminalTab`(各自的 xterm 模型与 socket)。切换标签时旧标签 detach、新标签 attach,不同时占用多条 WebSocket;后台输出由服务端 snapshot 在切回时重放 |
| 下拉 | 状态条左侧变成标签下拉:显示「终端 N · 运行中」,菜单列出所有标签(当前项打勾)与「新建终端」。新建的标签自动用最小的空闲编号(终端 1、终端 2…) |
| 关闭/重启 | ⋮ 菜单改为「关闭此终端」,关掉当前标签并 DELETE;关掉最后一个会自动留一个新标签。重启只作用于当前标签,死会话在原标签内换成新会话 |
| 恢复 | 本机按连接 + 目录保存标签列表(id + 名称 + 活动标签)。启动后首次打开:`GET /api/terminal/sessions?cwd=` 与服务端对账,仍存在的会话按保存的顺序和名称还原,服务端新出现的会话(网页端开的)按创建时间追加成标签,服务端已没有的标签丢弃;一个都没有才新建。兼容 0.4.2 的单会话存档 |
| 过滤 | 只把 interactive 会话算作标签,project-action 的命令运行器不显示 |
| 测试 | `test/terminal_restore_test.dart`:标签对账(顺序、名称、丢弃、列表失败的兜底、过滤 action)、编号复用、按连接+目录保存标签与活动项、0.4.2 存档迁移 |
| 版本 | **0.4.3(code 403)** |
---
## 0.4.2 终端恢复:重启后接回原来的 shell(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 之前 `sessionId` 只在内存里:每次启动 App 后第一次打开终端都走 `POST /api/terminal/create`,旧 shell 还留在服务器上(无连接时 30 分钟空闲回收),只是再也接不回去 |
| 恢复 | 按连接 + 目录记住最后一次的终端 id(`openchamber.terminalSessions.<connId>`)。首次打开终端先 `GET /api/terminal/sessions?cwd=`:记得的 id 还在就直接 attach(服务端 snapshot 重放历史);不在了就采用该目录最新的运行中会话;一个都没有才新建 |
| 关闭 | 「关闭终端」先 DELETE 并忘掉记录,再用 `fresh` 新建,避免又接回刚关掉的会话;断开连接/切换服务器时照旧关闭 shell |
| 失效 | attach 收到 fatal `SESSION_NOT_FOUND`(例如服务端在中间重启过)时清掉记录并自动新建,不留死面板 |
| 单终端 | 仍是每个目录一个终端视图,不是多标签;同目录的其它会话保留给网页端,不会被删除 |
| 测试 | `test/terminal_restore_test.dart`:恢复优先级(记得的 > 最新运行中 > 最新)、按连接+目录保存与清除 |
| 版本 | **0.4.2(code 402)** |
---
## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 不再占位 | `PetSlot` 换成 `PetLayer`:宠物画在消息列表的 Stack 上层,列表恢复完整高度,字会从宠物四周透出来,不再有一条空白带把最后一行截掉 |
| 透明 | 只有精灵本身作画;画布其余部分不填充。命中测试只认 `contentBox`(外扩 4px),点空白处仍然滚动/点消息 |
| 拖动 | 按住身体左右拖,脚沿输入框上沿移动;松手保存在本机(`pet.x.v1`,0–1 的比例),重启后回到同一位置,窄屏/旋转按比例换算并夹在两端内 |
| 拖动反馈 | 拖动时抬升 6px,并播放包里的 `drag`(`react-drag`)动画;没有该动画就保持当前状态,松手回到聊天状态 |
| 点击 | 从 `onTapDown` 改为 `onTapUp`,拖动不再误触发左右半区的 `tapLeft/tapRight` |
| 测试 | `test/pet_layer_test.dart`:空白处点击穿透、身体吃掉点击、拖动改位置并写入 prefs、无宠物时不画 |
| 版本 | **0.4.1(code 401)** |
---
## 0.4.0 输入框宠物:导入宠物包、精灵动画与状态(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 默认无宠物 | 不内置任何宠物;设置 → 宠物 显示「尚未导入宠物」和导入按钮,导入后才启用 |
| 宠物包 | 兼容 dsh-Go 的 PNG 精灵包:zip 内 `pack.json` + 各动画的 sprite sheet。解析 canvas / anchor / contentBox / animations(frames, cols, box) / states / reactions;导入时校验 `pack.json` 与每张精灵图,解压到应用文档目录 `pets/<id>/`,支持更换、启用/关闭、大小(40 / 52 / 64)与移除 |
| 渲染 | 新增 `PetSlot` / `PetSprite`:按 `anchor` 让宠物站在输入框上方(运行时有活动条则站在活动条顶边);按状态播放 `idle / thinking / working / error`;点击左右半区播放 `react-left / react-right`。图片一次只解码当前动画,切换时释放上一张 |
| 状态 | 活动条是「思考中」→ thinking,其余运行状态(回复中、调用工具)→ working,最后一轮失败 → error,空闲 → idle;草稿页显示 idle |
| 示例包 | `dist/deepy-whale-pet.zip`(dsh-Go 的 Deepy 小鲸鱼,保留包内 name/author/license) |
| 测试 | `test/pet_pack_test.dart`(真实 deepy pack 解析、帧与状态映射)、`test/pet_import_test.dart`(zip 解包、嵌套目录、缺少 pack.json 拒绝) |
| 版本 | **0.4.0(code 400)** |
---
## 0.3.21 侧栏行更紧凑(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 行高 | 项目条和会话行都改为 `dense: true` + `minTileHeight: 56`,实测都是 54(此前是 72);标题 14 / 项目名 14.5,路径与副标题保持较小字号 |
| 对齐 | 仍然等高等宽;`+` 与会话 `⋮` 的 x 中心保持对齐(测试断言) |
| 版本 | **0.3.21(code 321)** |
---
## 0.3.20 侧栏项目/会话行等高与右对齐、活动条改为 dsh-Go 胶囊(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏等高 | 项目分组头改用与会话行相同的 `ListTile`(标题 + 副标题),两者高度都是 72;分组的 8px 外边距由 ListTile 的内边距补偿,`+` 与会话的 `⋮` 落在同一竖线上 |
| 活动条 | 改为 dsh-Go 风格的全宽胶囊:左侧「标题 + 步骤摘要」,右侧等宽数字计时 `m:ss`(不足一分钟也显示 `0:03`),半透明 surface 背景,最小高度 36;去掉条内的转圈。胶囊顶边就是之后输入框宠物的栖息位置 |
| 版本 | **0.3.20(code 320)** |
---
## 0.3.19 输入框环居中、运行状态条、侧栏项目层级与 Windows 路径(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 上下文环 | 单行输入框用 `CrossAxisAlignment.end`,16px 的环贴着底部而按键是 36px;给环加 10px 底边距,与按键同一中轴(有焦点时的两行布局本来就是居中,未改) |
| 运行中的尾部 | 运行中不再显示上一轮的 footer(模型 · 模式 · 用时,以及“复制回答 / 从这里分叉”菜单):`_turnRows` 在 `chat.running` 为真时不加 footer。改为在输入框上方显示 dsh-Go 风格的活动条:「思考中 / 正在回复 / 正在读取 · …」加当前步骤摘要和秒表,每秒刷新 |
| 侧栏项目 | 项目分组头改成带底色的圆角条,最小高度 56,加文件夹图标;标题 13.5 粗体、路径作副标题,与会话行的层级更清楚 |
| Windows 路径 | 项目名只取路径最后一段,`/` 与 `\` 都识别;同一项目的比较统一分隔符(盘符路径忽略大小写),分组键也统一分隔符,避免一个项目被拆成两组 |
| 版本 | **0.3.19(code 319)** |
---
## 0.3.18 需要密码的服务器无法输入密码(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 问题 | 「添加服务器」表单的密码框只在编辑已保存服务器时显示(`!_editNew`)。新服务器首次连接被 401 拒绝后只提示「需要密码或已保存的凭据」,却没有输入密码的地方 |
| 修复 | 密码框始终显示,文案为「密码(如果需要)」,提示服务器未设置可留空;连接失败且错误提示需要密码时自动聚焦密码框;服务端返回 `Invalid credentials` 时显示为「密码错误,请重试」。新增 `test/servers_form_test.dart` 覆盖新服务器表单含密码框 |
| 版本 | **0.3.18(code 318)** |
---
## 0.3.17 设置页、侧栏底部服务器栏与追问处理行为(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 设置页 | 新增 `lib/screens/settings_screen.dart`,分「外观 / 聊天 / 宠物」三组 |
| 侧栏 | 服务器切换从顶部移到底部:左侧是当前服务器名(点击打开服务器面板),右侧齿轮进入设置页,和原版手机端侧栏一致 |
| 外观 | 主题模式(跟随系统 / 浅色 / 深色)与主题色(8 个种子色);`lib/appearance_prefs.dart` 存本机 `shared_preferences`,明确不同步服务端;`main.dart` 的 `ThemeData` 读取它 |
| 聊天 | 「追问处理行为」:转向 / 排队。读写服务端 `GET/PUT /api/config/settings?surface=mobile` 的 `followUpBehavior`(profile 级、跨 surface 共享,默认 queue)。运行中短按发送按该设置执行,长按「发送方式」可临时选另一种并标出默认项。连接成功、设置页打开、应用回到前台时重新读取 |
| 宠物 | 仅占位,显示「暂未提供设置」 |
| 版本 | **0.3.17(code 317)** |
---
## 0.3.16 输入法收起、模式面板与排队消息(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框收起 | 手机返回手势关闭输入法(焦点仍在)时,输入框也收回单行:dsh-Go 用键盘高度判断;`Scaffold` 会从 body 去掉底部 viewInsets,所以由 `HomeScreen`(Scaffold 之上)读取键盘高度,经 `ChatScreen` / `NewSessionScreen` 传给 `ComposerBox`。键盘升到过的峰值一半以下即视为收起,再次唤起时展开。新增 `test/composer_box_test.dart` 覆盖 |
| 模式面板 | 「模式」(Build / Plan)chip 由下拉框改为底部面板:标题、图标、说明、当前项打勾;仍与模型/思考强度分开 |
| 排队消息 | 运行中短按发送默认「转向」(`delivery: steer`),长按发送键弹出「转向当前回合 / 排队」,只用服务端支持的 steer/queue。排队或转向的消息不乐观写入对话,而是显示为末尾的待发气泡(半透明 + 状态:正在转入 / 已排队 / 未发送),可「改为排队 / 转为转向」与「撤回」(`DELETE /api/session/:id/inbox/:id`,文本放回输入框)。打开会话与前台恢复时 `GET /api/session/:id/inbox`;订阅 `session.inbox.enqueued / delivered / cancelled / delivery.changed`,送达时刷新尾部。运行且输入框有文字时发送键显示为发送(dsh-Go 行为),空输入时才显示停止 |
| 版本 | **0.3.16(code 316)** |
---
## 0.3.15 输入框两行折叠、模型与思考成组、模式独立(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框折叠动画 | 新增 `lib/widgets/composer_box.dart`:未获焦点时是单行(附件键在左、输入框、上下文环、发送键在右),获得焦点时平滑展开为两行(上为输入框,下为附件键/模型/模式/环/发送键),失焦后收回单行;输入框用 `GlobalKey` 在两种布局间搬移,保留焦点与输入连接。参照 dsh-Go `Composer` 的 `footer` + `_ComposerRows` + `AnimationController` 做法 |
| 模型与思考强度成组 | 模型 chip 直接显示 `模型 · 思考档位`(如 `deepseek-flash · 高`),点开同一个面板:选模型后若该模型有 variants,底部出现思考强度选择,选完一次提交;最近使用的档位记在本机。草稿页与聊天页共用 `ModelPill` |
| 模式独立 | 原「智能体」chip 改为独立的 `ModeChip`(Build / Plan),与模型 chip 并列,不再把智能体与模型放在同一行组里;仍通过 `switchAgent` / 草稿的 `agent` 提交 |
| 草稿页 | 同样使用两行折叠 `ComposerBox`;项目 chip 单独在输入框上方始终可见(草稿页没有会话,模型/模式放在折叠的第二行);斜杠面板、快捷键保持不变 |
| 版本 | **0.3.15(code 315)** |
---
## 0.3.14 模型切换修复、输入框模型行、思考强度与模型面板(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 切换模型报错 | `POST /api/session/:id/model` 的 body 应为 `{model: {id, providerID, variant?}}`,之前把模型对象直接放在顶层,服务端报 `Missing key at ["model"]`;已修正并实测切换成功 |
| 输入框模型行 | 参照 dsh-Go:聊天页把模型/智能体从顶栏移到输入框上方,输入框获得焦点、有草稿文字或正在生成时显示;草稿页始终显示同一行(左侧多一个项目 chip)。聊天顶栏只留文件按钮 |
| 思考强度 | `/api/model` 的每个模型带 `variants`(v2 的 `{id, settings.reasoningEffort}`)。输入框行在模型有档位时显示「思考·默认/低/中/高/极高」,点开选档;选择以 `ModelRef.variant` 随 `POST /session/:id/model` 或建会话时提交,实测会话的 `model.variant` 变为 `high`。每个模型上次的档位记在本机 |
| 模型面板 | 重做 `lib/widgets/model_picker.dart`:按 provider 分组(可折叠)、「收藏」「最近」分组(本机 `shared_preferences`,收藏用星标切换)、每个模型标注上下文大小(如 `200K 上下文`)、推理能力标记、搜索、当前项打勾;智能体分段保留 |
| 草稿斜杠 | 斜杠面板抽成共享的 `lib/widgets/slash_palette.dart`(匹配、排序、面板、快捷键),草稿页与聊天页共用;草稿只列 `/api/command` 与 `/api/skill` 的结果,不含需要已有会话的客户端内置 `/compact`;无参命令选中即发送(先建会话再执行命令),带参命令补全名称 |
| 版本 | **0.3.14(code 314)** |
---
## 0.3.13 草稿会话与分组侧栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 新会话 = 草稿 | 左侧栏 `+` 不再弹「标题」底部框,而是进入 `NewSessionScreen`:大标题「我们今天要做什么?」、项目 chip(`GET /api/project`,按 canonical 去重)、模型/智能体 chip(与聊天共用新的 `lib/widgets/model_picker.dart`)、附件与输入框。**发送前不创建会话**:第一次发送才 `POST /api/session`(带 `location.directory`、`model`、`agent`),随后 `openChat` 并发出这条消息 |
| 草稿生命周期 | 草稿只存内存(`AppState.draft` + `draftOpen`):未发送就离开时保留,侧栏顶部出现「草稿 · 项目名」一行(笔图标、首行、× 丢弃),点它回到草稿;发送成功即清空,创建失败留在草稿并显示错误。第二期接服务端 `/api/session-drafts`(已记入项目待办) |
| 侧栏分组 | 会话按 `location.directory` 分组(`.openchamber/chats` 归为「聊天」),组头是项目名 + 路径 + 折叠 + 「在此项目新会话」;组内按 `updated` 倒序并插「今天 / 昨天 / 本周早些时候 / 更早」小标题;默认过滤子会话(`parentID`),父会话的运行点会带上子会话的活动 |
| 置顶 | 写进 `session.metadata.openchamber.pinned`(`PATCH /api/session/:id {metadata}`,合并原有 metadata),跨客户端可见;置顶的会话收进顶部「已置顶」区,不再重复出现在项目组里 |
| 归档 | 主列表请求 `archived=false`;底部「显示已归档」按需拉 `archived=true`,展开后可取消归档(事件 `session.archived/unarchived` 同步) |
| 行操作 | 左滑(`flutter_slidable`,DrawerMotion)露出置顶 / 归档 / 删除;`⋮` 菜单有重命名、置顶、归档、删除、复制会话 ID;选中行有底色与加粗 |
| 其它 | 会话列表支持「载入更多」(cursor 分页);聊天页标题改为跟随 `AppState.sessions`,服务端根据首条消息生成的标题会即时显示;附件选择与缩略图抽到 `lib/widgets/composer_attachment.dart`,与草稿页共用 |
| 版本 | **0.3.13(code 313)** |
---
## 0.3.12 侧栏头部、Termux 按键栏、键盘避让与记忆(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 侧栏头部 | 顶部一行改成「标签组 + 关闭按钮」,标题/目录副标题去掉(目录本来就在面包屑里);文件/项目知识/终端各自的功能按钮下沉到标签自己的头部行——文件页是面包屑右侧的「+ / ⋯」(预览时是「编辑 / 下载」),项目知识页是搜索框 + 刷新,终端页是状态 + 键盘/重启/菜单 |
| 按键栏 | 按 Termux 改成两行七列等宽:`ESC / — HOME ↑ END PGUP`、`TAB CTRL ALT ← ↓ → PGDN`(左下角是 **TAB**,不是收起按钮);CTRL/ALT 修饰对手机输入法的字符仍然生效 |
| 键盘避让 | 侧栏是对话框,不会自己随输入法缩小;现在给底部加上 `MediaQuery.viewInsets.bottom` 的内边距,终端连同按键栏一起抬到键盘上方,`TerminalView` 随之减少行数并把新尺寸回传给 PTY |
| 记忆 | 项目知识新增「记忆」标签:`GET /api/agent-memory/all` 一次取全局与项目两份,服务端把功能关掉时(404)整个标签不出现;卡片显示标题、类型(事实/偏好/参考)、内容,可编辑(标题/类型/正文)与删除,搜索也覆盖记忆 |
| 顺带修复 | 文件预览的编辑框 `expands: true` 缺 `minLines: null`,进编辑会触发断言 |
| 版本 | **0.3.12(code 312)** |
---
## 0.3.11 终端、项目知识与下载进度(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 终端 | 右侧栏「终端」页:`POST /api/terminal/create` 建 PTY(cwd = 会话目录),`/api/terminal/ws` 走二进制控制帧(`0x01` + JSON:hello/attach/write/ping,snapshot/output/restart/exit/error)。渲染用 **xterm 4.0.0**(`Terminal` 模型 + `TerminalView`),断线按 500ms 起指数退避重连、重连后按服务端快照重放(先 `resize` 到快照尺寸再写历史);`/api/terminal/:id/resize` 做 250ms 去抖;App 回前台时自动重连 |
| 底栏 | 仿 Termux 的按键条(横向滚动):CTRL / ALT / SHIFT 修饰键,ESC、TAB、方向键、HOME/END/PGUP/PGDN/DEL,以及 `/ - \| ~ * $ # _ = + : ; " ' ( ) [ ] { } < > ? ! & \ ^ % @`;修饰键对**手机输入法**输入的字符同样生效(在 `onOutput` 里把下一个可打印字符映射成控制字符/ESC 前缀),按一次即清除 |
| 状态 | 状态条显示「运行中 / 正在连接 / 已退出(退出码)/ 连接失败」,并提供键盘、重启、清屏、关闭终端;终端会话按目录保存在 `AppState.terminals`,关面板不断 shell,切换服务器时显式关闭 |
| 项目知识 | 右侧栏「项目知识」页:`/api/project-context/:projectId`(projectId = `path_` + 目录 base64url);笔记(新建/编辑/置顶/删除)、待办(勾选、新建、删除,完成项沉底)、计划(新建、置顶、删除、打开全文);搜索框跨三种记录即时过滤;计划详情是全屏页(Markdown 渲染 + 编辑原文 + 保存) |
| 下载进度 | `/api/fs/raw` 改为流式:`downloadFile` 带 `onProgress` 与 `CancelToken`,请求头 `accept-encoding: identity` 以拿到 `Content-Length`(gzip 会让响应变成 chunked,进度只能是不确定态);下载中弹「正在下载」对话框显示已下载/总量/百分比,取消即中止连接并丢弃结果;完成后才弹保存对话框 |
| 修复 | `MarkdownView` 里的任务列表不再用 `material_ui` 的 Checkbox(它会找 `material_ui` 的 Material 祖先,应用里没有),改为 `✅`/`⬜` 文本;对话框里的 `TextEditingController` 改由对话框自身持有,避免关闭动画期间 dispose 触发框架断言 |
| 版本 | **0.3.11(code 311)** |
---
## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| Transport | 新增 `lib/api/transport.dart`:`TransportRequest`(method/path/query/rawQuery/headers/body)、`TransportResponse`(状态码/头/`Stream<List<int>>`,SSE 与文件下载仍可流式读)、`abstract Transport`;`DirectTransport` 就是原来的直连实现(HTTP CONNECT、SOCKS5/socks5h、自签与指纹固定、SHA-256 内置实现),`Client` 只保留业务方法,构造时可注入别的 Transport。行为与之前逐字节一致,后续 Private Relay 只需再加一个 `RelayTransport` |
| 历史图片 | 用户消息里的 `files` 现在从服务端读 `data`(base64)并缓存解码结果;气泡内显示缩略图,点按打开图片预览(与工具行读图共用同一个对话框)。无内联图片时仍回退到刚发送时的本地路径 |
| 原生表单 | `FormInfo`/`AgentFormField`/`FormOption`/`FormWhen` 按 `@opencode/client` 2.2.7 的 schema 建模;`GET /api/session/:id/form` 拉取待答问题,`POST …/form/:fid/reply` 提交、`DELETE …/form/:fid` 取消;订阅 `form.created/replied/cancelled`。输入框上方是表单卡片:string(带 options 时用 chip + 「其他…」)、multiselect、boolean(开关)、number/integer、external(链接确认);`when` 控制字段显隐,必填项(含「必须打开」的开关)不满足时提示并阻止发送,最多 360 px 内部滚动 |
| 左右分栏 | 新增 `lib/screens/home_screen.dart`:手机(< 840 px)把会话列表放进左侧 Drawer、聊天占满屏幕、顶栏是菜单键;宽屏(平板/桌面)左侧常驻 320 px 会话列 + 聊天。两者共用同一个 `SessionListPane`(会话选中高亮、搜索、新建、服务器、重命名/归档/删除)。启动时若还没有打开的会话,自动打开最新一条(与官方手机端一致) |
| 版本 | **0.3.10(code 310)** |
---
## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
**背景**: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 +802,8 @@
---
## 0.1 进展(2026-11-15)
### 0.1 进展(2026-11-15)
M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行的 OpenChamber 2.7.0(无密码):
@@ -42,10 +826,32 @@ M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行
| 多实例 | 保存多个服务器,按最近使用排序;首屏选择连接,连接后可切换;添加/编辑/删除;从旧的单连接记录自动迁移 |
| 连接界面(对齐官方) | 首连引导 →「手动输入地址」;有保存时列表:最近使用的置顶卡片(连接/已连接)、其他服务器、添加按钮;每行「…」菜单(连接/编辑/删除,删除二次确认);密码按需弹层、失败保留并可从表单重试;连接失败时回到表单并保留输入 |
| 顶栏服务器入口 | 会话页只保留一个「服务器」图标按钮,打开实例列表;点选实例即断开当前连接并连到所选实例;「断开当前连接」移入实例列表 |
| 首屏无导航栏 | 未连接时直接显示服务器列表(自带标题),不再套用带「新建/刷新」的应用栏;连接后才建立导航栈与动作栏 |
| 轮次页脚 | 每个回合结束后显示「模型 · Agent · 耗时」,右侧「…」打开操作面板(时间戳、复制回答、从这里分叉);模型名由 `/api/model` 解析,耗时按 prompt→完成计算;模型图标改用内置 SVG(不依赖平台符号表) |
| 用户消息操作 | 每条用户消息下有「时间 · 复制 · …」一排;「…」面板含时间戳、复制消息、从此消息前分叉 |
| 长会话加载 | 首屏只取最新 30 条(倒序);请求 `x-openchamber-part-shells: v1` 让服务端省略已完成工具结果(本会话 530KB→180KB);展开工具时再按消息 id 取全文;流式期间用事件本地更新工具/步骤,不再反复拉整页;60s 超时 + 重试;连接建立不重复同步 |
| 会话搜索 | 顶栏搜索按钮展开输入框,350ms 去抖后走服务端 `search` 参数,可清除恢复全量 |
| 附件 | 输入区可添加照片/文件(最多 5 个,单个 ≤10MB),以 data URL 随 prompt 发送;发送前显示可移除的附件条 |
| 回到最新 | 上滑离开底部后出现「最新」悬浮按钮,回到末尾并重新贴底 |
| 朗读回答 | 回合菜单可用系统 TTS 朗读回答,或停止朗读 |
| 图片内联预览 | 发送的图片附件保留本地副本,消息气泡内直接显示缩略图(200×150 圆角),不受后续重载影响 |
| 撤回 | 用户消息菜单「撤回此消息及之后」:二次确认后 stage+commit 服务端 revert,删除该消息及之后内容 |
| 应用图标 | 使用 OpenChamber 官方图标(`assets/icon.png`,取自 `packages/mobile/assets/icon-only.png`) |
| 上下文占用 | 输入区右侧环形进度 + 百分比(绿/橙/红阈值 75%/90%,与官方一致);点击打开详情 Sheet:模型、已用 tokens、上下文上限、输出预留、占用百分比、本轮费用;阈值按 `上限 - min(输出, 32K)` 计算 |
| 工具图片预览 | 工具调用涉及图片时(read 的 `state.attachments` data URL、输入 `filePath/path`、输出文本中的绝对图片路径),在工具行下显示图片链接;点击后从 data URL 解码或经 `/api/fs/raw`(带 `allowOutsideWorkspace=true`,工作区外的 /tmp 截图也能看)取回,全屏 Sheet 预览并缓存 |
| 目录请求头 | `x-opencode-directory` 附带 `x-opencode-directory-encoding: uri`,修复 scoped 请求(如 `/api/fs/raw`)被当成未解码路径的问题 |
| Agent 选择 | 只列 `mode=primary` 的 Agent,子智能体(General/Explore)不再出现 |
| 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 |
| 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 |
| 下一步 | 打磨:图标/splash、中英 i18n、空态与错误页;可选 fork asuka 支持更低 minSdk |
| 下一步 | 打磨:splash、中英 i18n、空态与错误页;归档会话查看/恢复;可选 fork asuka 支持更低 minSdk |
### 终端功能评估(未实现)
- **官方实现**:`/api/terminal/ws` WebSocket(v3 二进制 JSON 控制帧),携带 URL-token 鉴权与 relay 路由;客户端需做 ANSI/终端仿真渲染、行列 resize、输入回传、触摸滚动/选择。
- **方案 A:原生终端视图(Kotlin 包)**——把 Termux 系的 `terminal-view`(Android TerminalView)作为 asuka native view 集成;体验最好(复制/选择/IME),但要把输入流、resize、主题、生命周期接到 Go 侧,工作量约 2–4 天并要维护。
- **方案 B:Go 端 ANSI 渲染到 `ui.Canvas`/原生 TextView**——有现成 Go VT 解析器(charmbracelet/x/ansi、vt10x),但按网格逐格绘制性能与文本选择是难点;适合只读日志场景。
- **方案 C:`ui.WebView` + 本地 xterm.js**——最快(1–2 天),交互完整,但回到 WebView 渲染,偏离 asuka 原生初衷,且需处理 WebView 的 WS 与凭证注入。
- **建议**:先做方案 A 的 PoC(纯查看 + 输入),若 asuka native view 集成顺利再做完整版;否则退而求其次用 C 快速交付。
### 与官方移动端连接界面的差异(有意保留)
+111 -56
View File
@@ -1,74 +1,129 @@
# OpenChamber Native
# Chamber Go
A lightweight OpenChamber client for phones, written in Go with
[Asuka](https://asuka.egoist.dev/)'s native widgets. Android first.
Chamber Go is a lightweight OpenChamber client for phones, written in
**Flutter** (Dart).
Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity.
Status: M0–M4 done — multiple saved servers with a connect list (add, edit,
delete, switch; password prompt; HTTP or SOCKS5 proxy and self-signed
certificates per server), live session list, chat with streaming Markdown,
permissions, model/agent switching, new sessions, archive/delete/rename, and a
UI-independent API client.
Status: 0.7.4 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a
context usage ring with a detail sheet (an estimated window when the session's
model has left the server catalog), model/agent switching (Build/Plan only,
current one checked), copy / fork / revert, attachments (photos/files, kept
after a reload), the agent's native forms, permissions. The project picker can
add a folder from the server: it browses from the server user's home, renames
paths and creates folders, and keeps a project that exists only in OpenChamber's
settings (no session yet) in the list. The files sidebar also
carries the project knowledge (notes, todos, plans, and agent memory when the
server enables it) and a full terminal with a Termux-style key bar; downloads
show their progress and can be cancelled. The terminal holds several tabs per
project, switched from a dropdown next to the status (new tab included), and
remembers them per connection and directory: reopening after an app restart
attaches to the shells the server still holds instead of starting new ones. The panel is a tab row with its own
close button, and each tab has its own header row. Starting a session opens a
draft that only creates the session on the first send; the session list is
grouped by project with date captions, pins, archive and swipe actions;
subagent sessions nest under the session that started them (collapsed until
expanded) and open from the sidebar or the parent's Agent Task row; a subagent
chat is read-only unless the server allows prompting subagents; edit, write
and patch calls open as tinted line diffs with +N −M counts and show their
file path relative to the session directory; a finished image-generation call
shows the picture in the conversation instead of folding it away; commands
running in the background get a strip above the composer with their clock and
a stop, and their live output opens from there; the
server's managed chat folders are one 聊天 group, and a new session can target
聊天 instead of a project. Project rows use the icon and colour chosen in
OpenChamber (including an uploaded/auto icon image), and the chat group has a
chat icon. The
composer folds to one line when unfocused (or when the keyboard is dismissed)
and opens into two rows on focus, as in dsh-Go: the model and its thinking level
form one pill, the Build/Plan mode a separate chip (picked from a sheet). A
message sent while a turn runs can steer it or queue for its end, and waits as a
pending bubble that can be withdrawn; while a turn runs, an activity strip above
the input names the current step and its clock instead of the finished turn's
footer. Pets are opt-in: nothing is built in, and a dsh-Go sprite pack (a zip
with pack.json) is imported from Settings → 宠物 to stand above the input and
react to the turn's mood. The pet floats over the messages (only its body
takes touches) and can be dragged along the input's top edge; the spot is
remembered on the device. The picker groups providers, favourites,
recents and context size. The sidebar footer names the connected server (tap to
switch) beside a settings key; settings holds appearance (theme mode and seed
colour, device-local), the server's follow-up behavior (steer or queue on a send
while a turn runs) and a pet placeholder. A
phone opens the session list as the left drawer and a wide window (tablet,
desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop
target used for local testing.
## What is here
| 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
+57
View File
@@ -0,0 +1,57 @@
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")
}
}
}
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
}
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>
+68
View File
@@ -0,0 +1,68 @@
<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"/>
<!-- Saving to the gallery; Android 10+ uses MediaStore without this. -->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<!-- The camera plugin declares audio for video; the scanner only reads
frames, so the app must not end up asking for the microphone. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<application
android:label="Chamber Go"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<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>
<!-- Pictures the image viewer shares out of the app's cache. -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
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,227 @@
package net.blumia.openchamber.flutter
import android.Manifest
import android.content.ClipData
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
class MainActivity : FlutterActivity() {
private data class PendingSave(
val bytes: ByteArray,
val name: String,
val mime: String,
val result: MethodChannel.Result,
)
private var pendingSave: PendingSave? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// The app's private files directory, for imported pet packs. A small
// channel instead of path_provider, whose JNI binding does not load
// on this engine.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/appdir")
.setMethodCallHandler { call, result ->
when (call.method) {
"documents" -> result.success(filesDir.absolutePath)
else -> result.notImplemented()
}
}
// The statistics API buckets days by an IANA zone; Dart only knows the
// abbreviation, so the platform reports the real id.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/device")
.setMethodCallHandler { call, result ->
when (call.method) {
"ianaTimeZone" -> result.success(java.util.TimeZone.getDefault().id)
else -> result.notImplemented()
}
}
// The right sidebar's browser hands a page to the system browser.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/browser")
.setMethodCallHandler { call, result ->
when (call.method) {
"openUrl" -> {
val url = call.argument<String>("url")
if (url.isNullOrBlank()) {
result.error("bad_args", "Missing URL", null)
return@setMethodCallHandler
}
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
result.success(true)
} catch (e: Exception) {
result.error("open_failed", e.message ?: "Could not open the URL", null)
}
}
else -> result.notImplemented()
}
}
// Saving a conversation picture to the gallery and sharing it: both
// need Android APIs (MediaStore, FileProvider) that a Dart package
// would pull in another native dependency for.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/media")
.setMethodCallHandler { call, result ->
when (call.method) {
"saveImage" -> {
val bytes = call.argument<ByteArray>("bytes")
val name = call.argument<String>("name")
val mime = call.argument<String>("mime") ?: "image/png"
if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) {
result.error("bad_args", "Missing image data", null)
return@setMethodCallHandler
}
saveImage(bytes, name, mime, result)
}
"shareImage" -> {
val bytes = call.argument<ByteArray>("bytes")
val name = call.argument<String>("name")
val mime = call.argument<String>("mime") ?: "image/png"
if (bytes == null || bytes.isEmpty() || name.isNullOrBlank()) {
result.error("bad_args", "Missing image data", null)
return@setMethodCallHandler
}
shareImage(bytes, name, mime, result)
}
else -> result.notImplemented()
}
}
}
private fun saveImage(
bytes: ByteArray,
name: String,
mime: String,
result: MethodChannel.Result,
) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED
) {
if (pendingSave != null) {
result.error("busy", "Another picture is being saved", null)
return
}
pendingSave = PendingSave(bytes, name, mime, result)
requestPermissions(
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_SAVE,
)
return
}
writeImage(bytes, name, mime, result)
}
private fun writeImage(
bytes: ByteArray,
name: String,
mime: String,
result: MethodChannel.Result,
) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, name)
put(MediaStore.Images.Media.MIME_TYPE, mime)
put(
MediaStore.Images.Media.RELATIVE_PATH,
"${Environment.DIRECTORY_PICTURES}/Chamber Go",
)
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val collection = MediaStore.Images.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL_PRIMARY,
)
val uri = contentResolver.insert(collection, values)
?: throw IllegalStateException("Could not create the picture")
contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IllegalStateException("Could not open the picture")
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
contentResolver.update(uri, values, null, null)
} else {
@Suppress("DEPRECATION")
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
?: throw IllegalStateException("Could not decode the picture")
@Suppress("DEPRECATION")
val uri = MediaStore.Images.Media.insertImage(
contentResolver, bitmap, name, null,
) ?: throw IllegalStateException("Could not save the picture")
bitmap.recycle()
@Suppress("DEPRECATION")
MediaScannerConnection.scanFile(
this,
arrayOf(Uri.parse(uri).path ?: ""),
arrayOf(mime),
null,
)
}
result.success(true)
} catch (e: Exception) {
result.error("save_failed", e.message ?: "Could not save the picture", null)
}
}
private fun shareImage(
bytes: ByteArray,
name: String,
mime: String,
result: MethodChannel.Result,
) {
try {
val directory = File(cacheDir, "shared_images").apply { mkdirs() }
val file = File(directory, name)
file.writeBytes(bytes)
val uri = FileProvider.getUriForFile(
this, "$packageName.fileprovider", file,
)
val intent = Intent(Intent.ACTION_SEND).apply {
type = mime
putExtra(Intent.EXTRA_STREAM, uri)
clipData = ClipData.newRawUri("image", uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(intent, "Share image"))
result.success(true)
} catch (e: Exception) {
result.error("share_failed", e.message ?: "Could not share the picture", null)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != REQUEST_SAVE) return
val pending = pendingSave ?: return
pendingSave = null
if (grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
writeImage(pending.bytes, pending.name, pending.mime, pending.result)
} else {
pending.result.error(
"permission",
"Storage permission is required to save the picture",
null,
)
}
}
private companion object {
const val REQUEST_SAVE = 701
}
}
@@ -0,0 +1,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,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!-- Pictures the viewer writes before sharing them. -->
<cache-path name="shared_images" path="shared_images/" />
</paths>
@@ -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")
-7
View File
@@ -1,7 +0,0 @@
{
"name": "OpenChamber",
"id": "com.openchamber.native",
"version": "0.1.5",
"build": 6,
"orientations": ["portrait", "landscape"]
}
-207
View File
@@ -1,207 +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 "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
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=
-963
View File
@@ -1,963 +0,0 @@
package appui
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/egoist/asuka/colors"
"github.com/egoist/asuka/fonts"
"github.com/egoist/asuka/sdk/markdown"
"github.com/egoist/asuka/signal"
"github.com/egoist/asuka/ui"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
// chatItem is one row of the chat list: a whole message, or one part of an
// assistant message. Splitting parts into rows keeps every row's structure
// fixed, which the list's recycled cells require.
type chatItem struct {
Key string
Kind string // user | thinking | text | reasoning | tool | shell | note
MsgID string
Part int
}
// chat is one open session: its messages, its event projection and its
// composer.
type chat struct {
c *controller
id string
dir string
nav *ui.Navigator
open bool
title *signal.Signal[string]
msgs *signal.Signal[[]ocapi.Message]
byID *signal.Signal[map[string]ocapi.Message]
running *signal.Signal[bool]
loading *signal.Signal[bool]
draft *signal.Signal[string]
expanded *signal.Signal[map[string]bool]
errText *signal.Signal[string]
olderCursor string
hasMore bool
textSlots map[string]map[int]int
reasoningSlots map[string]map[int]int
reloadScheduled bool
listNode ui.Node
permList *signal.Signal[[]ocapi.PermissionRequest]
hasPerms *signal.Signal[bool]
pickerOpen *signal.Signal[bool]
pickerKind string
pickerItems *signal.Signal[[]pickerItem]
pickerFilter *signal.Signal[string]
pickerLoad *signal.Signal[bool]
}
// pickerItem is one row of the model/agent sheet.
type pickerItem struct {
Key string
Title string
Subtitle string
Model *ocapi.ModelRef
Agent string
}
func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat {
dir := ""
if s.Location != nil {
dir = s.Location.Directory
}
ch := &chat{
c: c,
id: s.ID,
dir: dir,
nav: nav,
open: true,
title: signal.New(s.Title),
msgs: signal.NewFunc([]ocapi.Message{}, nil),
byID: signal.NewFunc(map[string]ocapi.Message{}, nil),
running: signal.New(c.active.Peek()[s.ID]),
loading: signal.New(false),
draft: signal.New(""),
expanded: signal.NewFunc(map[string]bool{}, nil),
errText: signal.New(""),
textSlots: map[string]map[int]int{},
reasoningSlots: map[string]map[int]int{},
permList: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
hasPerms: signal.New(false),
pickerOpen: signal.New(false),
pickerItems: signal.NewFunc([]pickerItem{}, nil),
pickerFilter: signal.New(""),
pickerLoad: signal.New(false),
}
c.chat = ch
ch.syncPerms()
ch.load()
return ch
}
func (ch *chat) client() *ocapi.Client { return ch.c.client }
func (ch *chat) load() {
client := ch.client()
if client == nil {
return
}
ch.loading.Set(true)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
Directory: ch.dir, Limit: 30, Order: "desc",
})
ui.Post(func() {
ch.loading.Set(false)
if err != nil {
if ocapi.IsUnauthorized(err) {
ch.c.logout("登录已失效,请输入密码重新连接")
return
}
ch.errText.Set(friendlyError(err))
return
}
ch.olderCursor = page.Cursor.Next
ch.hasMore = page.Cursor.Next != ""
ch.setMessages(ascending(page.Data))
})
}()
}
func (ch *chat) loadOlder() {
if !ch.hasMore || ch.loading.Peek() || ch.olderCursor == "" {
return
}
client := ch.client()
if client == nil {
return
}
ch.loading.Set(true)
cursor := ch.olderCursor
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
Directory: ch.dir, Limit: 30, Cursor: cursor,
})
ui.Post(func() {
ch.loading.Set(false)
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
older := ascending(page.Data)
ch.olderCursor = page.Cursor.Next
ch.hasMore = page.Cursor.Next != ""
ch.setMessages(append(older, ch.msgs.Peek()...))
})
}()
}
// reloadTail refetches the newest messages and replaces the tail, which is
// how tool state and turn boundaries become authoritative.
func (ch *chat) reloadTail() {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
page, err := client.ListMessages(ctx, ch.id, ocapi.ListMessagesOptions{
Directory: ch.dir, Limit: 30, Order: "desc",
})
if err != nil {
return
}
tail := ascending(page.Data)
ui.Post(func() {
ch.reloadScheduled = false
if len(tail) == 0 {
return
}
cutoff := tail[0].Time.Created
keep := make([]ocapi.Message, 0, len(ch.msgs.Peek())+len(tail))
for _, m := range ch.msgs.Peek() {
if m.Time.Created < cutoff {
keep = append(keep, m)
}
}
ch.setMessages(append(keep, tail...))
})
}()
}
// scheduleReload coalesces the many events a tool call produces.
func (ch *chat) scheduleReload() {
if ch.reloadScheduled {
return
}
ch.reloadScheduled = true
time.AfterFunc(300*time.Millisecond, func() {
ui.Post(func() {
if ch.open {
ch.reloadTail()
}
})
})
}
func (ch *chat) send() {
text := strings.TrimSpace(ch.draft.Peek())
if text == "" || ch.client() == nil {
return
}
id := newMessageID()
ch.draft.Set("")
ch.errText.Set("")
ch.running.Set(true)
ch.addMessage(ocapi.Message{
ID: id,
Type: "user",
Text: text,
Time: ocapi.MessageTime{Created: time.Now().UnixMilli()},
})
client := ch.client()
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
err := client.Prompt(ctx, ch.id, ocapi.PromptOptions{Directory: ch.dir, Text: text, MessageID: id})
if err == nil {
return
}
ui.Post(func() {
ch.running.Set(false)
if ocapi.IsUnauthorized(err) {
ch.c.logout("登录已失效,请输入密码重新连接")
return
}
ch.errText.Set(friendlyError(err))
})
}()
ui.ScrollToEnd(ch.listNode, true)
}
func (ch *chat) stop() {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
_, err := client.Interrupt(ctx, ch.id, ch.dir)
ui.Post(func() {
if err != nil {
ch.errText.Set(friendlyError(err))
}
})
}()
}
// handleEvent runs on the main thread, routed by the controller's stream.
func (ch *chat) handleEvent(ev ocapi.Event) {
switch ev.Type {
case "session.execution.started":
ch.running.Set(true)
case "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted":
ch.running.Set(false)
ch.scheduleReload()
case "session.step.started":
var d struct {
AssistantMessageID string `json:"assistantMessageID"`
}
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.running.Set(true)
case "session.step.ended", "session.step.failed":
ch.scheduleReload()
case "session.text.started", "session.text.delta", "session.text.ended":
ch.applyDelta(ev, "text", ch.textSlots)
case "session.reasoning.started", "session.reasoning.delta", "session.reasoning.ended":
ch.applyDelta(ev, "reasoning", ch.reasoningSlots)
case "session.tool.input.started", "session.tool.input.ended", "session.tool.called",
"session.tool.success", "session.tool.failed", "session.tool.progress":
ch.scheduleReload()
}
}
type deltaData struct {
AssistantMessageID string `json:"assistantMessageID"`
Ordinal int `json:"ordinal"`
Delta string `json:"delta"`
Text string `json:"text"`
}
func (ch *chat) applyDelta(ev ocapi.Event, kind string, slots map[string]map[int]int) {
var d deltaData
if ev.UnmarshalData(&d) != nil || d.AssistantMessageID == "" {
return
}
ch.ensureAssistant(d.AssistantMessageID, ev.Created)
ch.updateMessage(d.AssistantMessageID, func(m *ocapi.Message) {
idx := slotFor(slots, m, d.Ordinal, kind)
if idx < 0 || idx >= len(m.Content) {
return
}
part := &m.Content[idx]
switch {
case strings.HasSuffix(ev.Type, ".started"):
part.Type = kind
case strings.HasSuffix(ev.Type, ".delta"):
part.Text += d.Delta
case strings.HasSuffix(ev.Type, ".ended"):
part.Text = d.Text
}
})
}
func slotFor(slots map[string]map[int]int, m *ocapi.Message, ordinal int, kind string) int {
byOrdinal := slots[m.ID]
if byOrdinal == nil {
byOrdinal = map[int]int{}
slots[m.ID] = byOrdinal
}
if idx, ok := byOrdinal[ordinal]; ok && idx < len(m.Content) {
return idx
}
m.Content = append(m.Content, ocapi.ContentPart{Type: kind})
idx := len(m.Content) - 1
byOrdinal[ordinal] = idx
return idx
}
func (ch *chat) ensureAssistant(id string, created int64) {
if _, ok := ch.byID.Peek()[id]; ok {
return
}
ch.addMessage(ocapi.Message{ID: id, Type: "assistant", Time: ocapi.MessageTime{Created: created}})
}
func (ch *chat) addMessage(m ocapi.Message) {
list := ch.msgs.Peek()
next := make([]ocapi.Message, len(list), len(list)+1)
copy(next, list)
next = append(next, m)
sort.SliceStable(next, func(i, j int) bool {
if next[i].Time.Created == next[j].Time.Created {
return next[i].ID < next[j].ID
}
return next[i].Time.Created < next[j].Time.Created
})
ch.setMessages(next)
}
func (ch *chat) updateMessage(id string, fn func(*ocapi.Message)) {
list := ch.msgs.Peek()
next := make([]ocapi.Message, len(list))
copy(next, list)
for i := range next {
if next[i].ID == id {
fn(&next[i])
break
}
}
ch.setMessages(next)
}
// setMessages publishes a new transcript: the rows read byID, the list reads
// the ordered slice. Duplicates (a page overlapping the loaded tail) are
// dropped by id, the later copy winning.
func (ch *chat) setMessages(list []ocapi.Message) {
sort.SliceStable(list, func(i, j int) bool {
if list[i].Time.Created == list[j].Time.Created {
return list[i].ID < list[j].ID
}
return list[i].Time.Created < list[j].Time.Created
})
index := make(map[string]ocapi.Message, len(list))
out := list[:0]
for _, m := range list {
if _, ok := index[m.ID]; ok {
continue
}
index[m.ID] = m
out = append(out, m)
}
ch.msgs.Set(out)
ch.byID.Set(index)
}
func (ch *chat) toggle(key string) {
cur := ch.expanded.Peek()
next := make(map[string]bool, len(cur)+1)
for k, v := range cur {
next[k] = v
}
next[key] = !cur[key]
ch.expanded.Set(next)
}
func (ch *chat) close() {
ch.open = false
if ch.c.chat == ch {
ch.c.chat = nil
}
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
func (ch *chat) screen() ui.Node {
signal.OnCleanup(ch.close)
ch.listNode = ui.List(ui.ListProps{
Appearance: ui.ListBare,
Anchor: ui.AnchorBottom,
OnStartReached: ch.loadOlder,
}, ch.items(), func(it chatItem) string { return it.Key }, ch.itemRow)
return ui.SafeArea(ui.Style{Grow: 1},
ui.Column(ui.Style{Grow: 1},
ui.Show(signal.Func(func() bool { return ch.errText.Get() != "" }), func() ui.Node {
return ui.Text(ch.errText, ui.Style{Color: colors.Red, Font: fonts.Footnote,
Padding: ui.Symmetric(4, 16)})
}),
ui.Show(ch.loading, func() ui.Node {
return ui.Progress(nil, ui.Style{Padding: ui.Symmetric(2, 16)})
}),
ch.listNode,
ch.permissionSection(),
ch.composer(),
),
ui.Sheet(ui.SheetProps{
Open: ch.pickerOpen,
Detents: ui.DetentLarge,
Grabber: true,
Content: ch.pickerSheet,
OnDismiss: func() { ch.pickerOpen.Set(false) },
}),
)
}
func (ch *chat) openModelPicker() {
ch.openPicker("model")
}
func (ch *chat) openAgentPicker() {
ch.openPicker("agent")
}
func (ch *chat) openPicker(kind string) {
client := ch.client()
if client == nil {
return
}
ch.pickerKind = kind
ch.pickerFilter.Set("")
ch.pickerItems.Set(nil)
ch.pickerLoad.Set(true)
ch.pickerOpen.Set(true)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var items []pickerItem
var err error
switch kind {
case "model":
var models []ocapi.ModelInfo
models, err = client.Models(ctx, ch.dir)
for _, m := range models {
name := m.Name
if name == "" {
name = m.ID
}
items = append(items, pickerItem{
Key: m.ProviderID + "/" + m.ID,
Title: name,
Subtitle: m.ProviderID + " · " + m.ID,
Model: &ocapi.ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant},
})
}
case "agent":
var agents []ocapi.AgentInfo
agents, err = client.Agents(ctx, ch.dir)
for _, a := range agents {
// A session runs a primary agent; subagents are what the
// primary one delegates to.
if a.Hidden || a.Mode == "subagent" {
continue
}
items = append(items, pickerItem{
Key: a.ID,
Title: a.Name,
Subtitle: a.Description,
Agent: a.ID,
})
}
}
ui.Post(func() {
ch.pickerLoad.Set(false)
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
ch.pickerItems.Set(items)
})
}()
}
func (ch *chat) filteredPicks() signal.Accessor[[]pickerItem] {
return signal.Func(func() []pickerItem {
q := strings.ToLower(strings.TrimSpace(ch.pickerFilter.Get()))
items := ch.pickerItems.Get()
if q == "" {
return items
}
out := make([]pickerItem, 0, len(items))
for _, it := range items {
if strings.Contains(strings.ToLower(it.Title), q) ||
strings.Contains(strings.ToLower(it.Subtitle), q) {
out = append(out, it)
}
}
return out
})
}
func (ch *chat) pickerSheet() ui.Node {
title := "选择模型"
if ch.pickerKind == "agent" {
title = "选择 Agent"
}
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 12, Grow: 1},
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
ui.TextField(ui.TextFieldProps{
Value: ch.pickerFilter,
Placeholder: ui.Val("搜索"),
Style: ui.Style{Grow: 0},
}),
ui.Show(ch.pickerLoad, func() ui.Node {
return ui.Activity()
}),
ui.List(ui.ListProps{Appearance: ui.ListPlain, Style: ui.Style{Grow: 1}},
ch.filteredPicks(), func(it pickerItem) string { return it.Key },
func(it signal.Accessor[pickerItem], _ signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{OnPress: func() { ch.applyPick(it.Get()) },
Style: ui.Style{Padding: ui.Symmetric(10, 4), Gap: 2}},
ui.Text(signal.Func(func() string { return it.Get().Title }), ui.Style{Font: fonts.Headline, Lines: 1}),
ui.Show(signal.Func(func() bool { return it.Get().Subtitle != "" }),
func() ui.Node {
return ui.Text(signal.Func(func() string { return it.Get().Subtitle }),
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2})
}),
)
}),
)
}
func (ch *chat) applyPick(it pickerItem) {
ch.pickerOpen.Set(false)
client := ch.client()
if client == nil {
return
}
kind := ch.pickerKind
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var err error
if kind == "model" && it.Model != nil {
err = client.SwitchModel(ctx, ch.id, ch.dir, *it.Model)
} else if it.Agent != "" {
err = client.SwitchAgent(ctx, ch.id, ch.dir, it.Agent)
}
ui.Post(func() {
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
if kind == "model" && it.Model != nil {
ch.c.patchSession(ch.id, func(s *ocapi.Session) { s.Model = it.Model })
} else if it.Agent != "" {
ch.c.patchSession(ch.id, func(s *ocapi.Session) { s.Agent = it.Agent })
}
})
}()
}
// perms are the pending permission requests for this session.
func (ch *chat) perms() []ocapi.PermissionRequest {
var out []ocapi.PermissionRequest
for _, p := range ch.c.perms.Get() {
if p.SessionID == ch.id {
out = append(out, p)
}
}
return out
}
// syncPerms publishes this session's pending permission requests. The list
// and the flag are plain signals so the section updates without a computed
// chain (which is timing-sensitive in the test host).
func (ch *chat) syncPerms() {
list := ch.perms()
ch.permList.Set(list)
ch.hasPerms.Set(len(list) > 0)
}
func (ch *chat) permissionSection() ui.Node {
return ui.Show(ch.hasPerms, func() ui.Node {
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
ui.For(ch.permList, func(p ocapi.PermissionRequest) string { return p.ID },
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
CornerRadius: 12, Background: colors.SecondaryBackground}},
ui.Text(signal.Func(func() string { return "需要权限:" + p.Get().Action }),
ui.Style{Font: fonts.Footnote.Weighted(fonts.Semibold)}),
ui.Show(signal.Func(func() bool { return strings.Join(p.Get().Resources, ", ") != "" }),
func() ui.Node {
return ui.Text(signal.Func(func() string {
return strings.Join(p.Get().Resources, ", ")
}), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
}),
ui.Row(ui.Style{Gap: 8, Wrap: true},
ui.Button(ui.ButtonProps{Title: ui.Val("允许一次"), Variant: ui.ButtonTinted,
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionOnce) }}),
ui.Button(ui.ButtonProps{Title: ui.Val("总是允许"), Variant: ui.ButtonTinted,
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionAlways) }}),
ui.Button(ui.ButtonProps{Title: ui.Val("拒绝"), Variant: ui.ButtonGray,
OnPress: func() { ch.reply(p.Get(), ocapi.PermissionReject) }}),
),
)
}),
)
})
}
func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDecision) {
client := ch.client()
if client == nil {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err := client.ReplyPermission(ctx, req.SessionID, req.ID, decision, "")
ui.Post(func() {
if err != nil {
ch.errText.Set(friendlyError(err))
return
}
list := ch.c.perms.Peek()
next := make([]ocapi.PermissionRequest, 0, len(list))
for _, p := range list {
if p.ID != req.ID {
next = append(next, p)
}
}
ch.c.perms.Set(next)
ch.syncPerms()
})
}()
}
func (ch *chat) composer() ui.Node {
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignEnd, Padding: ui.Symmetric(8, 12)},
ui.TextField(ui.TextFieldProps{
Value: ch.draft,
Placeholder: ui.Val("发消息…"),
Multiline: true,
Style: ui.Style{Grow: 1, Lines: 5},
}),
ui.Show(ch.running,
func() ui.Node {
return ui.Button(ui.ButtonProps{
Title: ui.Val("停止"),
Variant: ui.ButtonGray,
OnPress: ch.stop,
})
},
func() ui.Node {
return ui.Button(ui.ButtonProps{
Icon: ui.IconSend,
Label: ui.Val("发送"),
Variant: ui.ButtonFilled,
Disabled: signal.Func(func() bool { return strings.TrimSpace(ch.draft.Get()) == "" }),
OnPress: ch.send,
})
}),
)
}
// items derives the list's rows: one per message, or per assistant part.
func (ch *chat) items() signal.Accessor[[]chatItem] {
return signal.Func(func() []chatItem {
msgs := ch.msgs.Get()
out := make([]chatItem, 0, len(msgs))
for _, m := range msgs {
switch m.Type {
case "user":
out = append(out, chatItem{Key: "u/" + m.ID, Kind: "user", MsgID: m.ID})
case "assistant":
if len(m.Content) == 0 {
if m.Time.Completed == 0 {
out = append(out, chatItem{Key: "a/" + m.ID, Kind: "thinking", MsgID: m.ID})
}
continue
}
for i, p := range m.Content {
kind := p.Type
switch kind {
case "text", "reasoning":
case "tool":
default:
continue
}
out = append(out, chatItem{
Key: fmt.Sprintf("a/%s/%s/%d", m.ID, kind, i),
Kind: kind,
MsgID: m.ID,
Part: i,
})
}
case "shell":
out = append(out, chatItem{Key: "s/" + m.ID, Kind: "shell", MsgID: m.ID})
case "system", "synthetic", "skill", "compaction":
if strings.TrimSpace(m.Text) != "" {
out = append(out, chatItem{Key: "n/" + m.ID, Kind: "note", MsgID: m.ID})
}
}
}
return out
})
}
func (ch *chat) itemRow(it signal.Accessor[chatItem], _ signal.Accessor[int]) ui.Node {
// The row's structure follows the item's kind, which changes only when
// a recycled cell is bound to another item.
return ui.Dynamic(func() ui.Node {
cur := it.Get()
switch cur.Kind {
case "user":
return ui.Row(ui.Style{Justify: ui.JustifyEnd, Padding: ui.Symmetric(4, 12)},
ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 12), CornerRadius: 16,
MaxWidth: ui.Pct(80), Background: colors.Accent}},
ui.Text(ch.textOf(cur.MsgID), ui.Style{Color: colors.OnAccent}),
),
)
case "thinking":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
ui.StaticText("正在思考…", ui.Style{Color: colors.SecondaryLabel, Font: fonts.Footnote}),
)
case "text":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(6, 14)}},
markdown.View(markdown.Props{
Text: ch.partText(cur.MsgID, cur.Part),
Streaming: ch.streaming(cur.MsgID),
}),
)
case "reasoning":
return ch.reasoningRow(cur)
case "tool":
return ch.toolRow(cur)
case "shell":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
ui.Text(ch.shellText(cur.MsgID), ui.Style{Font: codeFont(), Color: colors.SecondaryLabel}),
)
case "note":
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(4, 14)}},
ui.Text(ch.textOf(cur.MsgID), ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
)
}
return ui.View(ui.ViewProps{})
})
}
func (ch *chat) reasoningRow(cur chatItem) ui.Node {
key := fmt.Sprintf("reason/%s/%d", cur.MsgID, cur.Part)
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
label := signal.Func(func() string {
n := len([]rune(ch.partTextValue(cur.MsgID, cur.Part)))
head := fmt.Sprintf("思考过程(%d 字)", n)
if open.Get() {
return "▾ " + head
}
return "▸ " + head
})
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
ui.Text(label, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
),
ui.Show(open, func() ui.Node {
return ui.Text(ch.partText(cur.MsgID, cur.Part),
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel})
}),
)
}
func (ch *chat) toolRow(cur chatItem) ui.Node {
key := fmt.Sprintf("tool/%s/%d", cur.MsgID, cur.Part)
open := signal.Func(func() bool { return ch.expanded.Get()[key] })
part := ch.partAccessor(cur.MsgID, cur.Part)
status := signal.Func(func() string {
p := part.Get()
if p.State == nil {
return ""
}
return p.State.Status
})
headline := signal.Func(func() string {
p := part.Get()
icon := "●"
switch status.Get() {
case "running", "streaming":
icon = "◌"
case "completed":
icon = "✓"
case "error":
icon = "✕"
}
mark := "▸"
if open.Get() {
mark = "▾"
}
return fmt.Sprintf("%s %s %s", icon, strings.TrimSpace(p.Name+" "+toolSummary(p)), mark)
})
return ui.Column(ui.Style{Gap: 4, Padding: ui.Symmetric(4, 14)},
ui.View(ui.ViewProps{OnPress: func() { ch.toggle(key) }},
ui.Text(headline, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}),
),
ui.Show(open, func() ui.Node {
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.Symmetric(8, 10), CornerRadius: 8,
Background: colors.SecondaryBackground, Gap: 8}},
ui.Text(signal.Func(func() string {
p := part.Get()
if p.State == nil {
return ""
}
buf, _ := json.MarshalIndent(p.State.Input, "", " ")
return string(buf)
}), ui.Style{Font: codeFont()}),
ui.Text(signal.Func(func() string { return toolOutput(part.Get()) }), ui.Style{Font: codeFont()}),
)
}),
)
}
// ---------------------------------------------------------------------------
// Value helpers
// ---------------------------------------------------------------------------
func (ch *chat) msg(id string) ocapi.Message { return ch.byID.Get()[id] }
func (ch *chat) textOf(id string) signal.Accessor[string] {
return signal.Func(func() string { return ch.byID.Get()[id].Text })
}
func (ch *chat) partAccessor(id string, index int) signal.Accessor[ocapi.ContentPart] {
return signal.Func(func() ocapi.ContentPart {
m := ch.byID.Get()[id]
if index < 0 || index >= len(m.Content) {
return ocapi.ContentPart{}
}
return m.Content[index]
})
}
func (ch *chat) partText(id string, index int) signal.Accessor[string] {
return signal.Func(func() string { return ch.partTextValue(id, index) })
}
func (ch *chat) partTextValue(id string, index int) string {
m := ch.byID.Get()[id]
if index < 0 || index >= len(m.Content) {
return ""
}
return m.Content[index].Text
}
func (ch *chat) streaming(id string) signal.Accessor[bool] {
return signal.Func(func() bool {
m := ch.byID.Get()[id]
return m.Time.Completed == 0
})
}
func (ch *chat) shellText(id string) signal.Accessor[string] {
return signal.Func(func() string {
m := ch.byID.Get()[id]
out := "$ " + m.Command
if strings.TrimSpace(m.Output) != "" {
out += "\n" + m.Output
}
return out
})
}
func toolSummary(p ocapi.ContentPart) string {
if p.State == nil {
return ""
}
for _, k := range []string{"command", "filePath", "pattern", "path", "description", "query"} {
if v, ok := p.State.Input[k].(string); ok && strings.TrimSpace(v) != "" {
return firstLine(v)
}
}
return ""
}
func toolOutput(p ocapi.ContentPart) string {
if p.State == nil {
return ""
}
var b strings.Builder
for _, c := range p.State.Content {
if c.Type == "text" && c.Text != "" {
if b.Len() > 0 {
b.WriteByte('\n')
}
b.WriteString(c.Text)
}
}
out := b.String()
if len(out) > 4000 {
out = out[:4000] + "\n…"
}
return out
}
func firstLine(s string) string {
if i := strings.IndexByte(s, '\n'); i >= 0 {
return s[:i]
}
return s
}
func codeFont() fonts.Font { return fonts.Custom("monospace", fonts.Footnote) }
func ascending(list []ocapi.Message) []ocapi.Message {
out := make([]ocapi.Message, len(list))
for i, m := range list {
out[len(list)-1-i] = m
}
return out
}
func newMessageID() string {
var b [8]byte
_, _ = rand.Read(b[:])
return "msg_" + fmt.Sprint(time.Now().UnixMilli()) + hex.EncodeToString(b[:])
}
-281
View File
@@ -1,281 +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
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),
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","time":{"created":11,"completed":12},
"content":[{"type":"text","text":"**Hello** from the agent"}]}
],"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"},
{"id":"claude","providerID":"anthropic","name":"Claude"}]}`)
})
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/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")
}
-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()
},
}),
),
)
},
})
}
-297
View File
@@ -1,297 +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
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:
ui.Post(func() {
if c.client != client {
return
}
c.status.Set("连接中断,正在重连…")
})
case ocapi.Subscribed:
// 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)
}
-26
View File
@@ -1,26 +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>`)
// 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)},
}))
}
-602
View File
@@ -1,602 +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)
node := ui.Stack(c.screen, ui.ScreenOptions{
Title: ui.Val("OpenChamber"),
Actions: []ui.Action{
{
Title: ui.Val("新建"),
Icon: ui.IconPlus,
Disabled: signal.Func(func() bool { return !c.connected.Get() }),
OnPress: c.openNewSession,
},
{
Title: ui.Val("刷新"),
Icon: ui.IconRefresh,
Disabled: signal.Func(func() bool { return !c.connected.Get() || c.busy.Get() }),
OnPress: c.refresh,
},
},
})
return c, node
}
type controller struct {
st storage.Store
connections *signal.Signal[[]storage.Connection]
url *signal.Signal[string]
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(""),
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
}
func (c *controller) screen() ui.Node {
return ui.SafeArea(ui.Style{Grow: 1},
ui.Show(c.connected, c.sessionsScreen, c.connectionsScreen),
c.formSheet(),
c.passwordSheet(),
c.instancesSheet(),
c.newSessionSheetNode(),
)
}
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
}
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"})
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.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))
}
}
-336
View File
@@ -1,336 +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
}
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":{}}`, sessionTitle)
})
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("取消")
}
-101
View File
@@ -1,101 +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/ocapi"
)
func (c *controller) sessionsScreen() ui.Node {
nav := ui.UseNavigator()
c.nav = nav
return 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})
}),
),
c.instancesButton(),
),
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)})
}
})
}()
}
-157
View File
@@ -1,157 +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)
}
}
-379
View File
@@ -1,379 +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))
}
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
}
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
}
-295
View File
@@ -1,295 +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.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"}); err != nil {
t.Fatal(err)
}
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
t.Errorf("prompt body: %v", promptBody)
}
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
}
-269
View File
@@ -1,269 +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"
}
// 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)
}
var page MessagePage
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
requestOptions{directory: o.Directory, query: q}, nil, &page)
return page, 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"`
}
// 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
}
// 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)
}
-49
View File
@@ -1,49 +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
}
// 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
}
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
}
// 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)
}
-219
View File
@@ -1,219 +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 {
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"`
}
// 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"`
Metadata map[string]any `json:"metadata,omitempty"`
Error json.RawMessage `json:"error,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>
@@ -0,0 +1,8 @@
<?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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,8 @@
<?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>PreviewsEnabled</key>
<false/>
</dict>
</plist>
@@ -0,0 +1,119 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1510"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<PreActions>
<ExecutionAction
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
<ActionContent
title = "Run Prepare Flutter Framework Script"
scriptText = "/bin/sh &quot;$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh&quot; prepare&#10;">
<EnvironmentBuildable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</EnvironmentBuildable>
</ActionContent>
</ExecutionAction>
</PreActions>
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331C8080294A63A400263BE5"
BuildableName = "RunnerTests.xctest"
BlueprintName = "RunnerTests"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
enableGPUValidationMode = "1"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,8 @@
<?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>PreviewsEnabled</key>
<false/>
</dict>
</plist>
Loaded 100 of 251 files, more files were not shown because too many files have changed in this diff. Show more