Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

Remote screen, a terminal UI and a redesigned Mac menu bar

leepokai076055e7ec64
diff --git a/CLAUDE.md b/CLAUDE.md
index 8db2eb42..8368f7e2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,7 +14,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
## Architecture
-- Clients: iOS app, native Mac window (menu bar app), native Linux app (`apps/linux/`, GTK 4 + libadwaita in Rust). All talk to the host API; no web UI.
+- Clients: iOS app, native Mac window (menu bar app), native Linux app (`apps/linux/`, GTK 4 + libadwaita in Rust), terminal UI (`codync-host tui`, `host/src/tui/`, ratatui; layout and state vocabulary modeled on herdr). All talk to the host API; no web UI.
- Shared Swift (`kit/`): `CodyncKit` (models, client, theme, avatars) + `CodyncUI` (`BotStore` + chat screens) used by iOS and macOS. Platform specifics go through `BotStore` hooks or `Platform.swift`.
- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).
- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`backends.rs`: login-shell PATH + known dirs) and the ACP registry (`registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.
@@ -22,6 +22,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- **Chat shows only**: user messages, the *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).
- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).
- API: `POST /api/<method>` + SSE, bearer token (`~/.codync/token`). Default port **19222**, binds 0.0.0.0 for Tailscale/LAN.
+- Remote screen (`host/src/screen.rs` is the reference): phones view/control the computer over WebRTC (hardware H.264, non-trickle SDP relayed by `screenOffer`, input on data channels `input` / `input-fast`); bots get the built-in `computer` MCP server (`codync-host mcp computer`, `host/src/mcp.rs`) when their `computer` flag is on. Capture/input live in a helper on `~/.codync/screen.sock`: `apps/screen` (macOS, launchd agent via `SMAppService`, owns the TCC grants) or `apps/screen-linux` (`codync-screen`: portals + GStreamer, started by the host). Off by default; `setScreenEnabled` is accepted only from loopback. An interactive phone takes over (bots may only look).
- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it to the host. Only two alert kinds: *needs you* and *done*, suppressed while the iOS app is connected.
- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.
- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`; menu bar shows status/pairing/usage and opens the native chat window (NavigationSplitView over `CodyncUI`). Not sandboxed, not Mac App Store (the host must spawn CLIs).
@@ -50,6 +51,8 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- `macOS` (`apps/macos/`) — menu bar app + embedded host
- `iOS` (`apps/ios/`) — iOS app
+- `Screen` (`apps/screen/`) — Codync Screen: capture, input and WebRTC for Remote screen, embedded in the Mac app (`Contents/Library/LoginItems`)
+- `apps/screen-linux/` — `codync-screen` (Rust, GStreamer + xdg portals), the Linux Remote screen helper; build/test in the same container as `apps/linux`
- `Widgets` (`apps/ios/Widgets/`) — usage widget + bot Live Activity (bundle id `com.pokai.Codync.ios.LiveActivity`)
- `CodyncKit` (`kit/`) — shared Swift package: `CodyncKit` + `CodyncUI` libraries
- `apps/linux/` — `codync` GTK app (build/test in a container with libgtk-4-dev + libadwaita-1-dev)
diff --git a/Codync.xcodeproj/project.pbxproj b/Codync.xcodeproj/project.pbxproj
index b57c0fa9..bec21107 100644
--- a/Codync.xcodeproj/project.pbxproj
+++ b/Codync.xcodeproj/project.pbxproj
@@ -8,16 +8,26 @@
/* Begin PBXBuildFile section */
03774684DC8344D81AFED53B /* ChatWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A59E3A7670EAF57F2F4C9B9 /* ChatWindow.swift */; };
+ 1C2F108FE28961E13EF9AF61 /* ViewingBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F16B11B2920E9D05621AFE7 /* ViewingBadge.swift */; };
24DF3CB466CC877FCB8BAED6 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = BEE30A9D5C73E5A151F34180 /* CodyncUI */; };
25667EBFCCC64B96FDCE95A9 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 59F5D19A417A7A50596902FA /* CodyncKit */; };
+ 25FCB36A2661833502357807 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A657FB98BBE0D73807B263 /* Session.swift */; };
2CC074683AE086D6C77CC1E8 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B274A0195CB3B2409EA4C194 /* WidgetKit.framework */; };
+ 2D724C1001CF872BAFCAE7EA /* IconButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3831394C093AF3A4E504BC5 /* IconButton.swift */; };
2F0A1C29DBBD1D700C10BE46 /* CodyncApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45CCA6BBDCF412897AEC105 /* CodyncApp.swift */; };
31A78A067C217F77FBDEDFD0 /* Push.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55AABA9596547D7459B1CC5B /* Push.swift */; };
+ 484455D97513F09142D21D0D /* Capture.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE4D28E8291EEB43E17B11FA /* Capture.swift */; };
48DAAA1384E5B8D0BA27C895 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1E47C60032C326157E0386B8 /* SwiftUI.framework */; };
+ 498C81B8C82557C85F912238 /* HostLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75CAC64DDC41D4A222A12DDE /* HostLink.swift */; };
513F59BF65DED5379AB950A1 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D2C705F063CD20F5B3036BD4 /* Assets.xcassets */; };
52CF04B855C6AAEC47B75B8F /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 06C9F37C6502131CAF0F145E /* CodyncUI */; };
+ 5F9AE9B8E7FF66F194162BDC /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */; };
826FEDA23997E436D632E579 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB70DD8757C90695CDA211 /* PrivacyInfo.xcprivacy */; };
8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */; };
+ AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };
+ ACCB28F3DB9C89108B7911E3 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 842DA106CA15E3810C3C9461 /* Input.swift */; };
+ AFC0CD8BD1FA61F810C96057 /* com.pokai.Codync.screen.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = 895BB6C2EB8986266EB4159A /* com.pokai.Codync.screen.plist */; };
+ B55C0D49B47C628C367BD92A /* AXTree.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97876A72710A37EB86A082C1 /* AXTree.swift */; };
B75DD137E6F645F797B60B09 /* PairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 739EC95223CC8F8717C33736 /* PairingView.swift */; };
C937F66F810AA238B73E8363 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4EDD440CC0624F03363AC1BA /* PrivacyInfo.xcprivacy */; };
CC9F6FB8055C38D5D625F738 /* BotListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5E57711E223A292872322C5 /* BotListView.swift */; };
@@ -25,6 +35,7 @@
DEF7478AB86DB605F52905F5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */; };
E430F9317B690366F62164DB /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1B79D48C1D6F90D53751B3F /* RootView.swift */; };
EBB0417A5FB2CE6D514D21BE /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };
+ EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 741B706007BA1B91CB853699 /* Screen.app */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
ED143C01BF7AD4953101D160 /* UsageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47BCE8E2AFA6CA829DBC489A /* UsageView.swift */; };
F0A26FABD15480810021C86A /* HostController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93A9881C76B67297BE26D8FD /* HostController.swift */; };
F191B13B972C72CB4253B449 /* CodyncWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00F135A0B168269BD6C2A199 /* CodyncWidgets.swift */; };
@@ -33,6 +44,13 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
+ 2E0B0CAFDFEF730B8269AE49 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 5B6351DD20AF4506794D6460 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = 907F1F4A709111FC7178EAE9;
+ remoteInfo = Screen;
+ };
D40A213F2C1B900F886F95EB /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5B6351DD20AF4506794D6460 /* Project object */;
@@ -54,11 +72,33 @@
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
+ A39B341E188CE8DB0A29ACC0 /* Embed Dependencies */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = Contents/Library/LoginItems;
+ dstSubfolderSpec = 1;
+ files = (
+ EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */,
+ );
+ name = "Embed Dependencies";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ F03A20C030394F9A65472B30 /* CopyFiles */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = Contents/Library/LaunchAgents;
+ dstSubfolderSpec = 1;
+ files = (
+ AFC0CD8BD1FA61F810C96057 /* com.pokai.Codync.screen.plist in CopyFiles */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
00F135A0B168269BD6C2A199 /* CodyncWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncWidgets.swift; sourceTree = "<group>"; };
1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
+ 1F16B11B2920E9D05621AFE7 /* ViewingBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewingBadge.swift; sourceTree = "<group>"; };
22F1B304BD18E48C91FC73E3 /* Widgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Widgets.entitlements; sourceTree = "<group>"; };
232B2C00B9575BFF7068BB62 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncMacApp.swift; sourceTree = "<group>"; };
@@ -69,14 +109,23 @@
60422D3CA8FEBCDC5AC465E0 /* iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
6D734BEE7CD3F84677B0218B /* Widgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = Widgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };
739EC95223CC8F8717C33736 /* PairingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingView.swift; sourceTree = "<group>"; };
+ 741B706007BA1B91CB853699 /* Screen.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Screen.app; sourceTree = BUILT_PRODUCTS_DIR; };
74BB0269490A0689868F05F7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 75CAC64DDC41D4A222A12DDE /* HostLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostLink.swift; sourceTree = "<group>"; };
7A2F5A7F5A648909D8CC5C19 /* kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = kit; path = kit; sourceTree = SOURCE_ROOT; };
+ 842DA106CA15E3810C3C9461 /* Input.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Input.swift; sourceTree = "<group>"; };
+ 895BB6C2EB8986266EB4159A /* com.pokai.Codync.screen.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = com.pokai.Codync.screen.plist; sourceTree = "<group>"; };
93A9881C76B67297BE26D8FD /* HostController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostController.swift; sourceTree = "<group>"; };
+ 97876A72710A37EB86A082C1 /* AXTree.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AXTree.swift; sourceTree = "<group>"; };
991A0FD3EAAD4B446F3BF14E /* macOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = macOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
9A59E3A7670EAF57F2F4C9B9 /* ChatWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatWindow.swift; sourceTree = "<group>"; };
+ AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenHelper.swift; sourceTree = "<group>"; };
B274A0195CB3B2409EA4C194 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };
C5E57711E223A292872322C5 /* BotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotListView.swift; sourceTree = "<group>"; };
+ CE4D28E8291EEB43E17B11FA /* Capture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Capture.swift; sourceTree = "<group>"; };
+ D0A657FB98BBE0D73807B263 /* Session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = "<group>"; };
D2C705F063CD20F5B3036BD4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ D3831394C093AF3A4E504BC5 /* IconButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IconButton.swift; sourceTree = "<group>"; };
DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
E1B79D48C1D6F90D53751B3F /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
E8B808BC2A9AA0ECD666A454 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -94,6 +143,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ 9BF4C7DD5C26BAD44BD453BF /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
9C830BBB73D8BC95B4167B13 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@@ -142,6 +199,7 @@
children = (
B297A6ACE16EAA751102BC05 /* ios */,
C0244F098744E616AB7FA840 /* macos */,
+ E6BF4F999DB656FB8CB90885 /* screen */,
);
path = apps;
sourceTree = "<group>";
@@ -160,6 +218,7 @@
children = (
60422D3CA8FEBCDC5AC465E0 /* iOS.app */,
991A0FD3EAAD4B446F3BF14E /* macOS.app */,
+ 741B706007BA1B91CB853699 /* Screen.app */,
6D734BEE7CD3F84677B0218B /* Widgets.appex */,
);
name = Products;
@@ -188,10 +247,19 @@
isa = PBXGroup;
children = (
9A59E3A7670EAF57F2F4C9B9 /* ChatWindow.swift */,
+ D3831394C093AF3A4E504BC5 /* IconButton.swift */,
);
path = Views;
sourceTree = "<group>";
};
+ 9D23811123D1C6A69D61B9CE /* LaunchAgents */ = {
+ isa = PBXGroup;
+ children = (
+ 895BB6C2EB8986266EB4159A /* com.pokai.Codync.screen.plist */,
+ );
+ path = LaunchAgents;
+ sourceTree = "<group>";
+ };
AD54741A2330C502CD3BB628 /* Packages */ = {
isa = PBXGroup;
children = (
@@ -224,6 +292,7 @@
isa = PBXGroup;
children = (
BDFF077DDD37FEC8B83F2AED /* App */,
+ 9D23811123D1C6A69D61B9CE /* LaunchAgents */,
FBD5ECB1F12422DB8CC87897 /* Resources */,
81605AFE04C3CF723841CD87 /* Views */,
);
@@ -251,6 +320,20 @@
path = Resources;
sourceTree = "<group>";
};
+ E6BF4F999DB656FB8CB90885 /* screen */ = {
+ isa = PBXGroup;
+ children = (
+ 97876A72710A37EB86A082C1 /* AXTree.swift */,
+ CE4D28E8291EEB43E17B11FA /* Capture.swift */,
+ 75CAC64DDC41D4A222A12DDE /* HostLink.swift */,
+ 842DA106CA15E3810C3C9461 /* Input.swift */,
+ AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */,
+ D0A657FB98BBE0D73807B263 /* Session.swift */,
+ 1F16B11B2920E9D05621AFE7 /* ViewingBadge.swift */,
+ );
+ path = screen;
+ sourceTree = "<group>";
+ };
FBD5ECB1F12422DB8CC87897 /* Resources */ = {
isa = PBXGroup;
children = (
@@ -268,12 +351,15 @@
buildPhases = (
FD97D0661DD7AA54EB7DE077 /* Sources */,
14FEC4FC6C72AC9A2596C04C /* Resources */,
+ F03A20C030394F9A65472B30 /* CopyFiles */,
1AC8A5FB72DF4C3DAEDBA56F /* Frameworks */,
+ A39B341E188CE8DB0A29ACC0 /* Embed Dependencies */,
C0A14ED49FC6A533FEABD5B2 /* Embed codync-host */,
);
buildRules = (
);
dependencies = (
+ 403D98EE1C95EF3BA01D41CB /* PBXTargetDependency */,
);
name = macOS;
packageProductDependencies = (
@@ -284,6 +370,25 @@
productReference = 991A0FD3EAAD4B446F3BF14E /* macOS.app */;
productType = "com.apple.product-type.application";
};
+ 907F1F4A709111FC7178EAE9 /* Screen */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = EC3A304F5821443C1DD50876 /* Build configuration list for PBXNativeTarget "Screen" */;
+ buildPhases = (
+ 34C567D8C7B2C02F5D48CA29 /* Sources */,
+ 9BF4C7DD5C26BAD44BD453BF /* Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = Screen;
+ packageProductDependencies = (
+ 2D9748E611692583AFC5A152 /* WebRTC */,
+ );
+ productName = Screen;
+ productReference = 741B706007BA1B91CB853699 /* Screen.app */;
+ productType = "com.apple.product-type.application";
+ };
913BDA9F79CE8C35A9E35830 /* iOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 3C74A86E026A9B24540EC0B2 /* Build configuration list for PBXNativeTarget "iOS" */;
@@ -340,6 +445,10 @@
DevelopmentTeam = 7FUM8A8H72;
ProvisioningStyle = Automatic;
};
+ 907F1F4A709111FC7178EAE9 = {
+ DevelopmentTeam = 7FUM8A8H72;
+ ProvisioningStyle = Automatic;
+ };
913BDA9F79CE8C35A9E35830 = {
DevelopmentTeam = 7FUM8A8H72;
ProvisioningStyle = Automatic;
@@ -361,12 +470,14 @@
mainGroup = C9B7D3953422AE726DDC6347;
minimizedProjectReferenceProxies = 1;
packageReferences = (
+ 979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */,
0E2B25AB265C8FA83E7E1560 /* XCLocalSwiftPackageReference "kit" */,
);
preferredProjectObjectVersion = 77;
projectDirPath = "";
projectRoot = "";
targets = (
+ 907F1F4A709111FC7178EAE9 /* Screen */,
A27E4E88D6A5B9850734B594 /* Widgets */,
913BDA9F79CE8C35A9E35830 /* iOS */,
72F29E7EBE9A88B16B4E608A /* macOS */,
@@ -434,6 +545,20 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ 34C567D8C7B2C02F5D48CA29 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ B55C0D49B47C628C367BD92A /* AXTree.swift in Sources */,
+ 484455D97513F09142D21D0D /* Capture.swift in Sources */,
+ 498C81B8C82557C85F912238 /* HostLink.swift in Sources */,
+ ACCB28F3DB9C89108B7911E3 /* Input.swift in Sources */,
+ 5F9AE9B8E7FF66F194162BDC /* ScreenHelper.swift in Sources */,
+ 25FCB36A2661833502357807 /* Session.swift in Sources */,
+ 1C2F108FE28961E13EF9AF61 /* ViewingBadge.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
B42F6957E97BFF5E6D8F504B /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -455,12 +580,18 @@
03774684DC8344D81AFED53B /* ChatWindow.swift in Sources */,
8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */,
F0A26FABD15480810021C86A /* HostController.swift in Sources */,
+ 2D724C1001CF872BAFCAE7EA /* IconButton.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
+ 403D98EE1C95EF3BA01D41CB /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = 907F1F4A709111FC7178EAE9 /* Screen */;
+ targetProxy = 2E0B0CAFDFEF730B8269AE49 /* PBXContainerItemProxy */;
+ };
40DF4BEA40A82C095F51AB76 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = A27E4E88D6A5B9850734B594 /* Widgets */;
@@ -521,7 +652,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.0.0;
+ MARKETING_VERSION = 2.1.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -554,6 +685,28 @@
};
name = Debug;
};
+ 6377E0B7DC2015DD92AB6550 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ COMBINE_HIDPI_IMAGES = YES;
+ ENABLE_APP_SANDBOX = NO;
+ ENABLE_HARDENED_RUNTIME = YES;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_CFBundleDisplayName = "Codync Screen";
+ INFOPLIST_KEY_LSUIElement = YES;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.screen;
+ PRODUCT_NAME = CodyncScreen;
+ SDKROOT = macosx;
+ SKIP_INSTALL = YES;
+ };
+ name = Debug;
+ };
6A5CD5AB98E7B897A9E57C49 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -574,6 +727,28 @@
};
name = Debug;
};
+ 8BF1ED628DCBF23F16CFD028 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ COMBINE_HIDPI_IMAGES = YES;
+ ENABLE_APP_SANDBOX = NO;
+ ENABLE_HARDENED_RUNTIME = YES;
+ GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_CFBundleDisplayName = "Codync Screen";
+ INFOPLIST_KEY_LSUIElement = YES;
+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync.screen;
+ PRODUCT_NAME = CodyncScreen;
+ SDKROOT = macosx;
+ SKIP_INSTALL = YES;
+ };
+ name = Release;
+ };
A8BF4A3388AA1B9ECD65A197 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -632,7 +807,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.0.0;
+ MARKETING_VERSION = 2.1.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -662,7 +837,7 @@
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -692,7 +867,7 @@
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -776,6 +951,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
+ EC3A304F5821443C1DD50876 /* Build configuration list for PBXNativeTarget "Screen" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 6377E0B7DC2015DD92AB6550 /* Debug */,
+ 8BF1ED628DCBF23F16CFD028 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Debug;
+ };
F977CF173B7D60769B393751 /* Build configuration list for PBXProject "Codync" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@@ -794,6 +978,17 @@
};
/* End XCLocalSwiftPackageReference section */
+/* Begin XCRemoteSwiftPackageReference section */
+ 979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */ = {
+ isa = XCRemoteSwiftPackageReference;
+ repositoryURL = "https://github.com/stasel/WebRTC";
+ requirement = {
+ kind = exactVersion;
+ version = 153.0.0;
+ };
+ };
+/* End XCRemoteSwiftPackageReference section */
+
/* Begin XCSwiftPackageProductDependency section */
06C9F37C6502131CAF0F145E /* CodyncUI */ = {
isa = XCSwiftPackageProductDependency;
@@ -803,6 +998,11 @@
isa = XCSwiftPackageProductDependency;
productName = CodyncKit;
};
+ 2D9748E611692583AFC5A152 /* WebRTC */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = 979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */;
+ productName = WebRTC;
+ };
59F5D19A417A7A50596902FA /* CodyncKit */ = {
isa = XCSwiftPackageProductDependency;
productName = CodyncKit;
diff --git a/README.md b/README.md
index e37b6c59..9ad36426 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
**Your coding agents, as teammates you can message.**
-Codync turns the coding agents on your computer — Claude Code, Codex, Cursor, Pi, OpenCode, Grok Build, Gemini, Copilot and ~40 more — into persistent *bots* you delegate to from your iPhone, Mac or Linux desktop, the way you'd message a colleague. Pick who, say what, put the phone away. You get a notification when a bot finishes or needs your approval.
+Codync turns the coding agents on your computer — Claude Code, Codex, Cursor, Pi, OpenCode, Grok Build, Gemini, Copilot and ~40 more — into persistent *bots* you delegate to from your iPhone, Mac, Linux desktop or any terminal, the way you'd message a colleague. Pick who, say what, put the phone away. You get a notification when a bot finishes or needs your approval.
> Why bots? On a phone, "find the right working session, then pick an environment" is too slow. With bots you already know who to hand the intent to: open the chat, type, done.
@@ -58,6 +58,7 @@ Install [Tailscale](https://tailscale.com) on the computer and the phone to reac
| Command | |
|---|---|
| `codync-host install` / `uninstall` | background service (launchd on macOS, systemd `--user` on Linux) |
+| `codync-host tui [--url … --token …]` | message your bots from a terminal (this computer by default; SSH-friendly) |
| `codync-host pair [--json]` | pairing QR code / link |
| `codync-host status` | installed? running? |
| `codync-host serve [--port 19222]` | run in the foreground |
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index cc272760..2d9eab2f 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -31,6 +31,8 @@ struct CodyncApp: App {
model.selection = nil
tab = .bots
model.showProfile = true
+ } else if url.host() == "screen" {
+ model.screenRequest = ScreenRequest()
}
}
.onChange(of: scenePhase, initial: true) { _, phase in
@@ -43,6 +45,10 @@ struct CodyncApp: App {
model.pair(p)
}
if ProcessInfo.processInfo.environment["CODYNC_OPEN_USAGE"] != nil { tab = .usage }
+ if ProcessInfo.processInfo.environment["CODYNC_OPEN_SCREEN"] != nil {
+ try? await Task.sleep(for: .seconds(2))
+ model.screenRequest = ScreenRequest()
+ }
}
#endif
}
@@ -74,6 +80,11 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent
return true
}
+ /// Portrait, except while the screen viewer is open.
+ func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
+ OrientationLock.mask
+ }
+
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Task { @MainActor in PushRegistrar.shared.didRegister(token: deviceToken) }
}
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index a5cf75d6..a7d625eb 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -66,6 +66,12 @@ struct BotListView: View {
}
// Grok-style bare top bar: no visible title, just the two buttons.
ToolbarItem(placement: .principal) { Color.clear.frame(width: 1, height: 1) }
+ if model.screen != nil {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button("Screen", systemImage: "display") { model.screenRequest = ScreenRequest() }
+ .disabled(model.connection != .online)
+ }
+ }
ToolbarItem(placement: .topBarTrailing) {
Button("New bot", systemImage: "plus") {
editing = EditorRequest(BotDraft())
diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swift
index 27e31c19..e4ea871b 100644
--- a/apps/ios/Views/PairingView.swift
+++ b/apps/ios/Views/PairingView.swift
@@ -11,6 +11,8 @@ struct PairingView: View {
@State private var scanning = false
@State private var pasted = ""
@State private var error: String?
+ @State private var tailscaleOn = Tailscale.isConnected
+ @Environment(\.scenePhase) private var scenePhase
var body: some View {
ScrollView {
@@ -37,6 +39,7 @@ struct PairingView: View {
Step(n: nil, title: "", detail: "Linux:", code: "brew install leepokai/codync/codync-host\ncodync-host install")
Step(n: 2, title: "Show the pairing code", detail: "On a Mac, click Codync in the menu bar → Pair iPhone. Or run:", code: "codync-host pair")
Step(n: 3, title: "Scan it", detail: "Use the button below, or point the Camera app at the code.", code: nil)
+ TailscaleStep(connected: tailscaleOn)
}
VStack(spacing: 12) {
@@ -89,6 +92,8 @@ struct PairingView: View {
.padding(16)
}
}
+ // Coming back from the Tailscale app: show whether it's connected now.
+ .onChange(of: scenePhase) { _, phase in if phase == .active { tailscaleOn = Tailscale.isConnected } }
.sheet(isPresented: $scanning) {
QRScanner { code in
scanning = false
@@ -142,6 +147,37 @@ private struct Step: View {
}
}
+/// Optional step: Tailscale is what lets the phone reach the computer off the home Wi-Fi.
+private struct TailscaleStep: View {
+ let connected: Bool
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ Text("04")
+ .font(.system(size: 12, weight: .medium, design: .monospaced))
+ .frame(width: 24, alignment: .leading)
+ .padding(.top, 2)
+ .foregroundStyle(Palette.tertiary)
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Away from home (optional)").font(.headline).foregroundStyle(Palette.text)
+ Text("Without it, Codync works on the same Wi-Fi as your computer. Install Tailscale on this iPhone and on the computer, and sign in to both with the same account.")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ if connected {
+ Label("Tailscale is on", systemImage: "checkmark.circle.fill")
+ .font(.subheadline.weight(.medium))
+ .foregroundStyle(Palette.added)
+ } else {
+ Link(destination: Tailscale.downloadURL) {
+ Label("Get Tailscale", systemImage: "arrow.down.circle")
+ .font(.subheadline.weight(.medium))
+ }
+ }
+ }
+ }
+ }
+}
+
/// VisionKit live QR scanner.
struct QRScanner: UIViewControllerRepresentable {
let onCode: (String) -> Void
diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swift
index d295b843..80f1ea9a 100644
--- a/apps/ios/Views/RootView.swift
+++ b/apps/ios/Views/RootView.swift
@@ -38,5 +38,9 @@ struct RootView: View {
}
.background(Palette.background)
.storeErrorAlert(model)
+ .fullScreenCover(item: Bindable(model).screenRequest) { request in
+ ScreenView(watching: request.watching)
+ .environment(model)
+ }
}
}
diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swift
index bf39843d..530228ed 100644
--- a/apps/ios/Views/SettingsView.swift
+++ b/apps/ios/Views/SettingsView.swift
@@ -146,6 +146,12 @@ private struct ComputerRow: View {
Text(status).font(.subheadline).foregroundStyle(Palette.secondary).lineLimit(1)
}
Spacer()
+ if !active || model.screen != nil {
+ Button("Screen", systemImage: "display") { openScreen() }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.borderless)
+ .foregroundStyle(Palette.text)
+ }
if active {
Image(systemName: "checkmark").font(.body.weight(.semibold)).foregroundStyle(Palette.text)
}
@@ -153,6 +159,17 @@ private struct ComputerRow: View {
.padding(.vertical, 2)
}
+ /// Only the active computer is connected: switch to this one first, then open its screen.
+ private func openScreen() {
+ if !active { model.pair(computer) }
+ model.showProfile = false
+ Task {
+ // Let the sheet finish closing before covering the screen.
+ try? await Task.sleep(for: .milliseconds(450))
+ model.screenRequest = ScreenRequest()
+ }
+ }
+
private var status: String {
guard active else { return "\(computer.urls.count) address\(computer.urls.count == 1 ? "" : "es")" }
return switch model.connection {
diff --git a/apps/linux/Cargo.lock b/apps/linux/Cargo.lock
index e04ec59e..4b81d333 100644
--- a/apps/linux/Cargo.lock
+++ b/apps/linux/Cargo.lock
@@ -152,7 +152,7 @@ dependencies = [
[[package]]
name = "codync-gtk"
-version = "2.0.0"
+version = "2.1.0"
dependencies = [
"async-channel",
"dirs",
diff --git a/apps/linux/Cargo.toml b/apps/linux/Cargo.toml
index 2eb7e8d1..fd0744a2 100644
--- a/apps/linux/Cargo.toml
+++ b/apps/linux/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "codync-gtk"
-version = "2.0.0"
+version = "2.1.0"
edition = "2024"
description = "Codync for Linux: message your coding-agent bots (GTK 4 + libadwaita)"
license = "MIT"
diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rs
index 4d802648..71e5e3ba 100644
--- a/apps/linux/src/dialogs.rs
+++ b/apps/linux/src/dialogs.rs
@@ -301,6 +301,12 @@ pub fn editor(ui: &App, bot: Option<Value>) {
.active(d.borrow()["notify"].as_bool().unwrap_or(true))
.build();
perms.add(&notify);
+ let computer = adw::SwitchRow::builder()
+ .title("Use the computer")
+ .subtitle("Let this bot see the screen and use the mouse and keyboard (needs Remote screen in Settings).")
+ .active(d.borrow()["computer"].as_bool().unwrap_or(false))
+ .build();
+ perms.add(&computer);
page.add(&perms);
view.set_content(Some(&page));
@@ -316,6 +322,7 @@ pub fn editor(ui: &App, bot: Option<Value>) {
.into();
body["permission"] = if auto.is_active() { "auto" } else { "ask" }.into();
body["notify"] = notify.is_active().into();
+ body["computer"] = computer.is_active().into();
let m = model.text().trim().to_owned();
body["model"] = if m.is_empty() { Value::Null } else { m.into() };
body["command"] = if body["backend"] == "custom" {
@@ -609,6 +616,58 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {
// MARK: settings & pairing
+/// Remote screen: see and control this computer from the iPhone, and let bots use it.
+/// Only this computer can turn it on (the host checks the request comes from itself).
+fn remote_screen_group() -> adw::PreferencesGroup {
+ let group = adw::PreferencesGroup::builder()
+ .title("Remote screen")
+ .description("See and control this computer from your iPhone, and let bots use it. The first time, your desktop asks you to allow screen sharing.")
+ .build();
+ let row = adw::SwitchRow::builder().title("Allow remote screen").build();
+ let status = adw::ActionRow::builder().title("Status").build();
+ status.set_visible(false);
+ group.add(&row);
+ group.add(&status);
+ let show = {
+ let status = status.clone();
+ move |v: &Value| {
+ let text = if v["enabled"] != true {
+ None
+ } else if v["connected"] != true {
+ Some("Waiting for screen sharing approval…")
+ } else if v["input"] != true {
+ Some("Viewing only: control wasn't allowed")
+ } else {
+ Some("Ready")
+ };
+ status.set_visible(text.is_some());
+ status.set_subtitle(text.unwrap_or_default());
+ }
+ };
+ {
+ let row = row.clone();
+ let show = show.clone();
+ client::call("screenStatus", client::empty(), move |r| {
+ if let Ok(v) = r {
+ row.set_active(v["enabled"] == true);
+ show(&v);
+ } else {
+ // A host from before Remote screen.
+ row.set_sensitive(false);
+ }
+ });
+ }
+ row.connect_active_notify(move |row| {
+ let show = show.clone();
+ client::call("setScreenEnabled", json!({"enabled": row.is_active()}), move |r| {
+ if let Ok(v) = r {
+ show(&v);
+ }
+ });
+ });
+ group
+}
+
pub fn settings(ui: &App) {
let (dialog, view, _) = header_dialog("Settings", 520, 720);
let page = adw::PreferencesPage::new();
@@ -666,6 +725,8 @@ pub fn settings(ui: &App) {
}
});
+ page.add(&remote_screen_group());
+
let st = ui.state.borrow();
let agents = adw::PreferencesGroup::builder()
.title("Coding agents on this computer")
diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swift
index 47af8c45..0c674d79 100644
--- a/apps/macos/App/CodyncMacApp.swift
+++ b/apps/macos/App/CodyncMacApp.swift
@@ -35,71 +35,86 @@ struct MenuView: View {
var body: some View {
VStack(alignment: .leading, spacing: 0) {
header
- if showPairing {
- PairingPanel { showPairing = false }
- } else {
- content
+ VStack(spacing: 8) {
+ if showPairing {
+ PairingPanel()
+ .tile()
+ // Grows out of the QR button that opened it, and goes back into it.
+ .transition(.scale(0.97, anchor: .topTrailing).combined(with: .opacity))
+ } else {
+ content
+ }
}
+ .padding(.horizontal, 10)
footer
}
.background(Palette.background)
+ .animation(Motion.layout, value: showPairing)
}
+ // MARK: header
+
private var header: some View {
HStack(spacing: 10) {
CodyncMark()
- .frame(width: 30, height: 30)
+ .frame(width: 28, height: 28)
.foregroundStyle(Palette.text)
.accessibilityHidden(true)
- VStack(alignment: .leading, spacing: 1) {
+ VStack(alignment: .leading, spacing: 2) {
Text("Codync").font(.headline).foregroundStyle(Palette.text)
- Text(statusLine).font(.caption).foregroundStyle(Palette.secondary)
+ HStack(spacing: 5) {
+ if let color = status.color {
+ Circle().fill(color).frame(width: 6, height: 6)
+ }
+ Text(status.text).font(.caption).foregroundStyle(Palette.secondary)
+ }
+ .accessibilityElement(children: .combine)
}
Spacer()
if host.state == .running {
- Button {
+ IconButton("Open Codync", systemImage: "bubble.left.and.bubble.right") {
openWindow(id: "chat")
NSApp.activate()
- } label: {
- Image(systemName: "bubble.left.and.bubble.right")
}
- .help("Open Codync")
- .accessibilityLabel("Open Codync")
- .controlSize(.small)
- Button {
+ IconButton("Pair iPhone", systemImage: "qrcode", selected: showPairing) {
showPairing.toggle()
if showPairing { host.loadPairing() }
- } label: {
- Image(systemName: "qrcode")
}
- .help("Pair iPhone")
- .accessibilityLabel("Pair iPhone")
- .buttonStyle(.borderedProminent)
- .tint(Palette.accentFill)
- .foregroundStyle(Palette.onAccent)
- .controlSize(.small)
}
}
- .padding(12)
+ .padding(.horizontal, 14)
+ .padding(.top, 14)
+ .padding(.bottom, 12)
}
- private var statusLine: String {
+ /// The header's state line. A dot only when something is going on: blue working, amber needs you, red trouble.
+ private var status: (text: String, color: Color?) {
switch host.state {
- case .missingBinary: "Host not found"
- case .notInstalled: "Host not installed"
- case .starting: "Starting host…"
- case .running: host.working > 0 ? "\(host.working) bot\(host.working == 1 ? "" : "s") working" : "Ready · v\(host.version ?? "")"
- case .failed: "Host problem"
+ case .missingBinary: ("Host not found", Palette.danger)
+ case .notInstalled: ("Host not installed", nil)
+ case .starting: ("Connecting…", nil)
+ case .failed: ("Host problem", Palette.danger)
+ case .running:
+ if host.needsAttention {
+ ("A bot needs you", Palette.warning)
+ } else if host.working > 0 {
+ ("\(host.working) bot\(host.working == 1 ? "" : "s") working", Palette.switchOn)
+ } else {
+ ("Connected", nil)
+ }
}
}
+ // MARK: content
+
@ViewBuilder private var content: some View {
switch host.state {
case .missingBinary:
Notice(text: "This build of Codync doesn't include codync-host. Reinstall the app, or install the host with Homebrew:", code: "brew install leepokai/codync/codync-host")
+ .tile()
case .notInstalled:
VStack(alignment: .leading, spacing: 10) {
- Text("Run your bots on this Mac").font(.subheadline.bold()).foregroundStyle(Palette.text)
+ Text("Run your bots on this Mac").font(.callout.weight(.semibold)).foregroundStyle(Palette.text)
Text("Codync installs a small background service that runs Claude Code, Codex and other agents for your bots — even when this menu is closed.")
.font(.caption)
.foregroundStyle(Palette.secondary)
@@ -109,75 +124,82 @@ struct MenuView: View {
.tint(Palette.accentFill)
.foregroundStyle(Palette.onAccent)
}
- .padding(12)
+ .tile()
case .starting:
- HStack { ProgressView().controlSize(.small); Text("Connecting…").font(.caption) }.padding(12)
+ HStack(spacing: 8) {
+ ProgressView().controlSize(.small)
+ Text("Connecting…").font(.caption).foregroundStyle(Palette.secondary)
+ }
+ .frame(maxWidth: .infinity)
+ .tile()
case let .failed(message):
- VStack(alignment: .leading, spacing: 8) {
+ VStack(alignment: .leading, spacing: 10) {
Text(message).font(.caption).foregroundStyle(Palette.danger).textSelection(.enabled)
HStack {
Button("Restart host") { host.restart() }
Button("Open log") { NSWorkspace.shared.open(host.logURL) }
}
+ .controlSize(.small)
}
- .padding(12)
+ .tile()
case .running:
- running
+ bots
+ if host.screen != nil {
+ RemoteScreenSection().tile()
+ }
+ if !host.usage.providers.isEmpty {
+ VStack(spacing: 12) {
+ ForEach(host.usage.providers) { UsageBlock(provider: $0) }
+ }
+ .tile()
+ }
}
}
- private var running: some View {
- VStack(alignment: .leading, spacing: 0) {
- if host.bots.isEmpty {
- Text("No bots yet. Create one from the Codync app on your iPhone.")
- .fixedSize(horizontal: false, vertical: true)
- .font(.caption)
- .foregroundStyle(Palette.secondary)
- .padding(12)
- } else {
- ScrollView {
- VStack(spacing: 2) {
- ForEach(host.bots) { bot in
- BotLine(bot: bot) { host.stop(bot) }
- .contentShape(Rectangle())
- .onTapGesture {
- host.store?.selection = bot.id
- openWindow(id: "chat")
- NSApp.activate()
- }
- }
- }
- .padding(6)
+ @ViewBuilder private var bots: some View {
+ if host.bots.isEmpty {
+ HStack(spacing: 12) {
+ CharacterAvatar(shape: "cloud", color: "gray", size: 32)
+ VStack(alignment: .leading, spacing: 2) {
+ Text("No bots yet").font(.callout.weight(.medium)).foregroundStyle(Palette.text)
+ Text("Create one from Codync on your iPhone.").font(.caption).foregroundStyle(Palette.secondary)
}
- // ScrollView has no intrinsic height inside a MenuBarExtra window.
- .frame(height: min(CGFloat(host.bots.count) * 46 + 12, 320))
+ Spacer(minLength: 0)
}
- if !host.usage.providers.isEmpty {
- VStack(alignment: .leading, spacing: 8) {
- ForEach(host.usage.providers) { p in
- ForEach(p.windows) { w in
- HStack(spacing: 8) {
- Text("\(p.name) \(w.label)").font(.caption).foregroundStyle(Palette.secondary).frame(width: 130, alignment: .leading)
- ProgressView(value: min(w.percent, 100), total: 100)
- .tint(Palette.usageTint(w.percent))
- Text("\(Int(w.percent.rounded()))%").font(.caption.monospacedDigit()).frame(width: 36, alignment: .trailing)
+ .tile()
+ } else {
+ ScrollView {
+ VStack(spacing: 0) {
+ ForEach(host.bots) { bot in
+ BotLine(bot: bot) { host.stop(bot) }
+ .contentShape(Rectangle())
+ .onTapGesture {
+ host.store?.selection = bot.id
+ openWindow(id: "chat")
+ NSApp.activate()
}
- }
}
}
- .padding(12)
+ .padding(4)
}
+ // ScrollView has no intrinsic height inside a MenuBarExtra window.
+ .frame(height: min(CGFloat(host.bots.count) * 46 + 8, 320))
+ .tile(padding: 0)
}
}
+ // MARK: footer
+
+ /// Rarely used, so quiet: settings (with Open at login) and Quit.
private var footer: some View {
- @Bindable var host = host
- return HStack {
- Toggle("Open at login", isOn: Binding(get: { host.launchAtLogin }, set: { host.setLaunchAtLogin($0) }))
- .toggleStyle(.checkbox)
- .font(.caption)
+ HStack(spacing: 2) {
+ if let version = host.version {
+ Text("v\(version)").font(.caption2.monospacedDigit()).foregroundStyle(Palette.tertiary).padding(.leading, 6)
+ }
Spacer()
Menu {
+ Toggle("Open at login", isOn: Binding(get: { host.launchAtLogin }, set: { host.setLaunchAtLogin($0) }))
+ Divider()
Button("Restart host") { host.restart() }
Button("Open log") { NSWorkspace.shared.open(host.logURL) }
Divider()
@@ -185,14 +207,169 @@ struct MenuView: View {
} label: {
Image(systemName: "gearshape")
}
- .menuStyle(.borderlessButton)
+ .menuStyle(.button)
+ .buttonStyle(IconButtonStyle())
+ .menuIndicator(.hidden)
.fixedSize()
- Button("Quit Codync", systemImage: "power") { NSApp.terminate(nil) }
- .labelStyle(.iconOnly)
- .help("Quit Codync")
- .font(.caption)
+ .help("Settings")
+ IconButton("Quit Codync", systemImage: "power") { NSApp.terminate(nil) }
}
- .padding(10)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ }
+}
+
+private extension View {
+ /// A Control Center–style module: one group of related things on a raised surface.
+ func tile(padding: CGFloat = 12) -> some View {
+ self.padding(padding)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.border, lineWidth: 0.5))
+ }
+}
+
+/// Remote screen: see and control this Mac from the iPhone, and let bots use it.
+/// One line when all is well; it only grows to say what's missing.
+private struct RemoteScreenSection: View {
+ @Environment(HostController.self) private var host
+
+ var body: some View {
+ let screen = host.screen ?? ScreenState()
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 10) {
+ Image(systemName: "display")
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(screen.enabled ? .white : Palette.text)
+ .frame(width: 30, height: 30)
+ .background(screen.enabled ? Palette.switchOn : Palette.bubbleUser, in: Circle())
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Remote screen").font(.callout.weight(.medium)).foregroundStyle(Palette.text)
+ Text(subtitle(screen))
+ .font(.caption)
+ .foregroundStyle(screen.enabled && screen.viewers > 0 ? Palette.switchOn : Palette.secondary)
+ .lineLimit(2)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 8)
+ Toggle("Remote screen", isOn: Binding(get: { screen.enabled }, set: { host.setRemoteScreen($0) }))
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.mini)
+ }
+ if screen.enabled {
+ if host.screenAgentNeedsApproval {
+ PermissionLine(title: "Codync Screen in Login Items") { host.openLoginItemsSettings() }
+ } else if screen.connected {
+ if !screen.capture {
+ PermissionLine(title: "Screen recording") {
+ open("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
+ }
+ }
+ if !screen.input {
+ PermissionLine(title: "Accessibility (mouse and keyboard)") {
+ open("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
+ }
+ }
+ }
+ }
+ if let error = host.screenError {
+ Text(error).font(.caption).foregroundStyle(Palette.danger).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .animation(Motion.layout, value: screen)
+ }
+
+ private func subtitle(_ screen: ScreenState) -> String {
+ guard screen.enabled else { return "Control this Mac from your iPhone" }
+ if host.screenAgentNeedsApproval { return "Needs one more step" }
+ if !screen.connected { return "Starting Codync Screen…" }
+ if !screen.capture || !screen.input { return "Needs permission" }
+ if screen.viewers > 0 { return screen.viewers == 1 ? "Your iPhone is viewing" : "\(screen.viewers) viewers" }
+ if let bot = screen.agentBot, let name = host.bots.first(where: { $0.id == bot })?.name { return "\(name) is using it" }
+ let display = screen.displays.first(where: \.main)?.name ?? screen.displays.first?.name
+ return display.map { "Ready · \($0)" } ?? "Ready"
+ }
+
+ private func open(_ url: String) {
+ if let url = URL(string: url) { NSWorkspace.shared.open(url) }
+ }
+}
+
+/// A permission that's still missing, with the way to fix it.
+private struct PermissionLine: View {
+ let title: String
+ let fix: () -> Void
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "exclamationmark.circle.fill")
+ .foregroundStyle(Palette.warning)
+ .accessibilityHidden(true)
+ Text(title).font(.caption).foregroundStyle(Palette.text)
+ Spacer()
+ IconButton("Open System Settings", systemImage: "gearshape", action: fix)
+ }
+ .padding(.leading, 8)
+ .padding(.vertical, 2)
+ .background(Palette.warning.opacity(0.1), in: RoundedRectangle(cornerRadius: 9, style: .continuous))
+ .accessibilityElement(children: .combine)
+ .accessibilityValue("Not allowed")
+ }
+}
+
+/// One provider's limits: its character and name, then a thin bar per limit in its color.
+private struct UsageBlock: View {
+ let provider: UsageProvider
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 7) {
+ HStack(spacing: 6) {
+ AgentIcon(registry: provider.registry, size: 15)
+ Text(provider.name).font(.caption.weight(.semibold)).foregroundStyle(Palette.text)
+ Spacer()
+ Text("updated \(RelativeTime.short(Date(milliseconds: provider.updatedAt)))")
+ .font(.caption2)
+ .foregroundStyle(Palette.tertiary)
+ }
+ ForEach(provider.windows) { w in
+ HStack(spacing: 8) {
+ Text(w.title).font(.caption).foregroundStyle(Palette.secondary).lineLimit(1)
+ .frame(width: 58, alignment: .leading)
+ ThinBar(percent: w.percent, tint: provider.tint)
+ Text("\(Int(w.percent.rounded()))%")
+ .font(.caption.monospacedDigit().weight(.medium))
+ .foregroundStyle(Palette.text)
+ .frame(width: 34, alignment: .trailing)
+ Text(w.resetDate.map { RelativeTime.until($0) } ?? "")
+ .font(.caption2.monospacedDigit())
+ .foregroundStyle(Palette.tertiary)
+ .frame(width: 48, alignment: .trailing)
+ }
+ .help(w.resetsShort() ?? w.label)
+ .accessibilityElement(children: .combine)
+ }
+ }
+ }
+}
+
+/// 4pt track in the provider's color; amber from 70%, red from 90%. Empty stays empty.
+private struct ThinBar: View {
+ let percent: Double
+ let tint: Color
+
+ var body: some View {
+ let color = percent >= 90 ? Palette.danger : percent >= 70 ? Palette.warning : tint
+ GeometryReader { geo in
+ ZStack(alignment: .leading) {
+ Capsule().fill(Palette.text.opacity(0.08))
+ if percent > 0 {
+ Capsule().fill(color).frame(width: max(4, geo.size.width * min(1, percent / 100)))
+ }
+ }
+ }
+ .frame(height: 4)
}
}
@@ -213,24 +390,21 @@ private struct BotLine: View {
}
Spacer()
if bot.isWorking && hovering {
- Button("Stop", systemImage: "stop.fill", action: stop)
- .labelStyle(.iconOnly)
- .help("Stop")
- .controlSize(.small)
+ IconButton("Stop", systemImage: "stop.fill", action: stop)
} else {
Text(RelativeTime.short(Date(milliseconds: bot.lastAt))).font(.caption2).foregroundStyle(Palette.tertiary)
}
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
- .background(hovering ? Palette.bubbleAgent : .clear, in: RoundedRectangle(cornerRadius: 8))
+ .background(hovering ? Palette.text.opacity(0.06) : .clear, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ .animation(Motion.hover, value: hovering)
.onHover { hovering = $0 }
}
}
private struct PairingPanel: View {
@Environment(HostController.self) private var host
- let close: () -> Void
var body: some View {
VStack(spacing: 12) {
@@ -250,26 +424,16 @@ private struct PairingPanel: View {
Text("No network address found. Connect this Mac to Wi-Fi or Tailscale.")
.font(.caption)
.foregroundStyle(Palette.warning)
- } else if !info.urls.contains(where: { $0.contains("://100.") || $0.contains(".ts.net") }) {
- Text("Tip: install Tailscale on this Mac and your iPhone to reach your bots from anywhere.")
- .font(.caption)
- .foregroundStyle(Palette.tertiary)
- .multilineTextAlignment(.center)
+ } else if !info.urls.contains(where: Tailscale.isAddress) {
+ TailscaleTip()
}
- Button("Copy pairing link", systemImage: "doc.on.doc") {
+ IconButton("Copy pairing link", systemImage: "doc.on.doc") {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(info.pairingUrl, forType: .string)
}
- .labelStyle(.iconOnly)
- .help("Copy pairing link")
- .controlSize(.small)
} else {
ProgressView()
}
- Button("Close", systemImage: "xmark", action: close)
- .labelStyle(.iconOnly)
- .help("Close")
- .controlSize(.small)
}
.frame(maxWidth: .infinity)
.padding(16)
@@ -287,6 +451,28 @@ private struct PairingPanel: View {
}
}
+/// Without Tailscale the iPhone only reaches this Mac on the same Wi-Fi.
+private struct TailscaleTip: View {
+ private static let app = URL(fileURLWithPath: "/Applications/Tailscale.app")
+ private let installed = FileManager.default.fileExists(atPath: app.path)
+
+ var body: some View {
+ VStack(spacing: 6) {
+ Text(installed
+ ? "Tailscale isn't connected. Open it and sign in to reach your bots away from home."
+ : "Install Tailscale on this Mac and your iPhone to reach your bots away from home.")
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ if installed {
+ Button("Open Tailscale") { NSWorkspace.shared.open(Self.app) }.controlSize(.small)
+ } else {
+ Link("Get Tailscale", destination: Tailscale.downloadURL).font(.caption)
+ }
+ }
+ }
+}
+
private struct Notice: View {
let text: String
let code: String
diff --git a/apps/macos/App/HostController.swift b/apps/macos/App/HostController.swift
index 46a54d90..a7f3070f 100644
--- a/apps/macos/App/HostController.swift
+++ b/apps/macos/App/HostController.swift
@@ -29,11 +29,16 @@ final class HostController {
private(set) var pairInfo: PairingInfo?
private(set) var version: String?
var launchAtLogin: Bool = SMAppService.mainApp.status == .enabled
+ /// Codync Screen (capture + input for Remote screen), a launchd agent inside this app.
+ private let screenAgent = SMAppService.agent(plistName: "com.pokai.Codync.screen.plist")
+ private(set) var screenAgentNeedsApproval = false
+ private(set) var screenError: String?
private var streamTask: Task<Void, Never>?
var bots: [Bot] { store?.roster ?? [] }
var usage: Usage { store?.usage ?? Usage() }
+ var screen: ScreenState? { store?.screen }
var needsAttention: Bool { bots.contains(where: \.needsInput) }
var working: Int { bots.filter(\.isWorking).count }
@@ -118,6 +123,34 @@ final class HostController {
launchAtLogin = SMAppService.mainApp.status == .enabled
}
+ /// Remote screen: starts/stops Codync Screen and tells the host (which only accepts this from the Mac itself).
+ func setRemoteScreen(_ on: Bool) {
+ Task {
+ do {
+ if on { try screenAgent.register() } else { try await screenAgent.unregister() }
+ try await store?.setScreenEnabled(on)
+ screenError = nil
+ } catch {
+ screenError = error.localizedDescription
+ }
+ screenAgentNeedsApproval = screenAgent.status == .requiresApproval
+ }
+ }
+
+ func openLoginItemsSettings() {
+ SMAppService.openSystemSettingsLoginItems()
+ }
+
+ /// Keeps Codync Screen registered while the host has Remote screen on (e.g. after the app moved).
+ private func syncScreenAgent() {
+ guard screen?.enabled == true, screenAgent.status != .enabled else {
+ screenAgentNeedsApproval = false
+ return
+ }
+ try? screenAgent.register()
+ screenAgentNeedsApproval = screenAgent.status == .requiresApproval
+ }
+
func stop(_ bot: Bot) {
Task { try? await client()?.stop(bot.id) }
}
@@ -147,6 +180,7 @@ final class HostController {
self.store = store
}
self.state = .running
+ self.syncScreenAgent()
} else {
failures += 1
if failures > 5 { self.state = .failed("The host isn't responding. See the log for details.") }
diff --git a/apps/macos/LaunchAgents/com.pokai.Codync.screen.plist b/apps/macos/LaunchAgents/com.pokai.Codync.screen.plist
new file mode 100644
index 00000000..6cd06846
--- /dev/null
+++ b/apps/macos/LaunchAgents/com.pokai.Codync.screen.plist
@@ -0,0 +1,22 @@
+<?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>Label</key>
+ <string>com.pokai.Codync.screen</string>
+ <key>BundleProgram</key>
+ <string>Contents/Library/LoginItems/CodyncScreen.app/Contents/MacOS/CodyncScreen</string>
+ <key>AssociatedBundleIdentifiers</key>
+ <array>
+ <string>com.pokai.Codync</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>ProcessType</key>
+ <string>Interactive</string>
+ <key>LimitLoadToSessionType</key>
+ <string>Aqua</string>
+</dict>
+</plist>
diff --git a/apps/macos/Views/ChatWindow.swift b/apps/macos/Views/ChatWindow.swift
index b2f9054b..a0253571 100644
--- a/apps/macos/Views/ChatWindow.swift
+++ b/apps/macos/Views/ChatWindow.swift
@@ -32,6 +32,8 @@ private struct ChatSplitView: View {
@State private var composing = false
@State private var columns: NavigationSplitViewVisibility = .all
@State private var showPlugins = false
+ @AppStorage("sidebarCompact") private var compact = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
/// Sheets hang from the window's title bar; sized from it so they never run past its bottom edge.
@State private var windowSize = CGSize(width: 1100, height: 760)
@@ -41,40 +43,50 @@ private struct ChatSplitView: View {
@Bindable var model = model
NavigationSplitView(columnVisibility: $columns) {
List(selection: $model.selection) {
- ConnectionBanner()
- if !model.usage.providers.isEmpty {
- UsageStrip(usage: model.usage)
- .listRowSeparator(.hidden)
- }
- ForEach(model.roster) { bot in
- BotRow(bot: bot)
- .tag(bot.id)
- .contextMenu {
- Button(bot.pinned ? "Unpin" : "Pin") { model.setPinned(bot, !bot.pinned) }
- Button("Edit Profile…") { editing = EditorRequest(BotDraft(bot)) }
- Button("Mark as Read") { model.markRead(bot.id) }
- Button("Hide from List") { model.setHidden(bot, true) }
- Divider()
- Button("Delete…", role: .destructive) { confirmDelete = bot }
- }
+ if compact {
+ ForEach(model.roster) { bot in
+ AvatarWithStatus(bot: bot, size: 40)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 4)
+ .help(bot.name)
+ .accessibilityLabel(bot.name)
+ .tag(bot.id)
+ .contextMenu { botMenu(bot) }
+ }
+ } else {
+ ConnectionBanner()
+ if !model.usage.providers.isEmpty {
+ UsageStrip(usage: model.usage)
+ .listRowSeparator(.hidden)
+ }
+ ForEach(model.roster) { bot in
+ BotRow(bot: bot)
+ .tag(bot.id)
+ .contextMenu { botMenu(bot) }
+ }
}
}
+ .safeAreaInset(edge: .bottom) {
+ if compact { railActions }
+ }
.navigationSplitViewColumnWidth(min: 260, ideal: 300, max: 420)
+ .background(SidebarWidth(compact: compact, animated: !reduceMotion))
.navigationTitle(model.hostName)
.toolbar {
- ToolbarItem {
- Button("Marketplace", systemImage: "square.grid.2x2") { showPlugins = true }
- .help("Marketplace: agents, connectors and skills")
- }
- ToolbarItem {
- Button("New Message", systemImage: "square.and.pencil") {
- model.selection = nil
- composing = true
+ if !compact {
+ ToolbarItem {
+ Button("Marketplace", systemImage: "square.grid.2x2") { showPlugins = true }
+ .help("Marketplace: agents, connectors and skills")
}
- .keyboardShortcut("n")
- .disabled(model.connection != .online)
+ ToolbarItem {
+ Button("New Message", systemImage: "square.and.pencil", action: compose)
+ .keyboardShortcut("n")
+ .disabled(model.connection != .online)
+ }
+ ToolbarItem { collapseButton }
}
}
+ .toolbar(removing: .sidebarToggle)
} detail: {
if composing {
// The To: row takes the title bar's place instead of sitting under an empty one.
@@ -84,6 +96,7 @@ private struct ChatSplitView: View {
} else if let id = model.selection, model.bots[id] != nil {
NavigationStack { ThreadView(botId: id) }
.id(id)
+ .transition(.asymmetric(insertion: .opacity, removal: .identity))
} else {
VStack(spacing: 14) {
HStack(spacing: -10) {
@@ -119,7 +132,16 @@ private struct ChatSplitView: View {
.hiddenWindowTitle()
.deleteBotConfirmation($confirmDelete)
.storeErrorAlert(model)
+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: model.selection)
+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: composing)
.onChange(of: model.selection) { _, id in if id != nil { composing = false } }
+ // Dragging the divider shut lands on the rail, not on nothing.
+ .onChange(of: columns) { _, visibility in
+ if visibility == .detailOnly {
+ compact = true
+ columns = .all
+ }
+ }
#if DEBUG
.onAppear {
// Screenshot/UI checks: CODYNC_DEBUG_OPEN=compose | plugins | <bot name>
@@ -136,6 +158,102 @@ private struct ChatSplitView: View {
}
}
+private extension ChatSplitView {
+ func compose() {
+ model.selection = nil
+ composing = true
+ }
+
+ var collapseButton: some View {
+ Button(compact ? "Expand Sidebar" : "Collapse Sidebar", systemImage: "sidebar.left") {
+ withAnimation(Motion.reduced(Motion.morph, reduceMotion)) { compact.toggle() }
+ }
+ .keyboardShortcut("s", modifiers: [.control, .command])
+ .help(compact ? "Expand sidebar" : "Collapse sidebar")
+ }
+
+ /// Rail footer: what the toolbar holds when the sidebar is wide.
+ var railActions: some View {
+ VStack(spacing: 6) {
+ Button("New Message", systemImage: "plus", action: compose)
+ .disabled(model.connection != .online)
+ .help("New message")
+ Button("Marketplace", systemImage: "square.grid.2x2") { showPlugins = true }
+ .help("Marketplace: agents, connectors and skills")
+ collapseButton
+ }
+ .labelStyle(.iconOnly)
+ .buttonStyle(IconButtonStyle(size: 34))
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 12)
+ }
+
+ @ViewBuilder func botMenu(_ bot: Bot) -> some View {
+ Button(bot.pinned ? "Unpin" : "Pin") { model.setPinned(bot, !bot.pinned) }
+ Button("Edit Profile…") { editing = EditorRequest(BotDraft(bot)) }
+ Button("Mark as Read") { model.markRead(bot.id) }
+ Button("Hide from List") { model.setHidden(bot, true) }
+ Divider()
+ Button("Delete…", role: .destructive) { confirmDelete = bot }
+ }
+}
+
+/// Collapsed = an avatar rail (Grok Bot), never a hidden sidebar. SwiftUI applies
+/// `navigationSplitViewColumnWidth` only once, so the rail resizes the AppKit split item directly.
+private struct SidebarWidth: NSViewRepresentable {
+ let compact: Bool
+ let animated: Bool
+
+ final class Coordinator {
+ var applied = false
+ var glide: Task<Void, Never>?
+ }
+
+ func makeCoordinator() -> Coordinator { Coordinator() }
+
+ func makeNSView(context: Context) -> NSView { NSView() }
+
+ func updateNSView(_ view: NSView, context: Context) {
+ let compact = compact
+ // Only on a toggle, so a width the user dragged to stays put.
+ guard compact != context.coordinator.applied else { return }
+ context.coordinator.applied = compact
+ // The view joins the window's split view only after the first layout pass.
+ DispatchQueue.main.async {
+ var ancestor = view.superview
+ while let current = ancestor, !(current is NSSplitView) { ancestor = current.superview }
+ guard let split = ancestor as? NSSplitView,
+ let controller = split.delegate as? NSSplitViewController,
+ let item = controller.splitViewItems.first else { return }
+ let width: CGFloat = compact ? 76 : 300
+ item.canCollapse = false
+ let from = item.viewController.view.frame.width
+ // Let the divider travel the whole way; the final limits apply once it lands.
+ item.minimumThickness = min(from, width, compact ? 76 : 260)
+ item.maximumThickness = max(from, width, compact ? 76 : 420)
+ let land = {
+ item.minimumThickness = compact ? 76 : 260
+ item.maximumThickness = compact ? 76 : 420
+ split.setPosition(width, ofDividerAt: 0)
+ }
+ context.coordinator.glide?.cancel()
+ guard animated, abs(from - width) > 1 else { return land() }
+ context.coordinator.glide = Task { @MainActor in
+ let start = ContinuousClock.now
+ let duration = Duration.milliseconds(260) // Grok's rail cluster: width .26s cubic-bezier(.22,1,.36,1)
+ var t = 0.0
+ while t < 1 {
+ try? await Task.sleep(for: .milliseconds(8))
+ if Task.isCancelled { return }
+ t = min(1, (ContinuousClock.now - start) / duration)
+ split.setPosition(from + (width - from) * Motion.morphCurve.value(at: t), ofDividerAt: 0)
+ }
+ land()
+ }
+ }
+ }
+}
+
private extension View {
/// The toolbar shows icons only, no "Codync" title next to them.
@ViewBuilder func hiddenWindowTitle() -> some View {
diff --git a/apps/macos/Views/IconButton.swift b/apps/macos/Views/IconButton.swift
new file mode 100644
index 00000000..71b1bce6
--- /dev/null
+++ b/apps/macos/Views/IconButton.swift
@@ -0,0 +1,47 @@
+import CodyncKit
+import SwiftUI
+
+/// Plain icon button that lights up on hover and on press, like toolbar buttons.
+struct IconButton: View {
+ let title: String
+ let systemImage: String
+ var selected = false
+ let action: () -> Void
+
+ init(_ title: String, systemImage: String, selected: Bool = false, action: @escaping () -> Void) {
+ self.title = title
+ self.systemImage = systemImage
+ self.selected = selected
+ self.action = action
+ }
+
+ var body: some View {
+ Button(title, systemImage: systemImage, action: action)
+ .labelStyle(.iconOnly)
+ .buttonStyle(IconButtonStyle(selected: selected))
+ .help(title)
+ }
+}
+
+struct IconButtonStyle: ButtonStyle {
+ var selected = false
+ var size: CGFloat = 28
+ @State private var hovering = false
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(.system(size: size / 2, weight: .medium))
+ .foregroundStyle(selected ? Palette.onAccent : hovering ? Palette.text : Palette.secondary)
+ .frame(width: size, height: size)
+ .background(
+ selected ? Palette.accentFill : Palette.text.opacity(configuration.isPressed ? 0.14 : hovering ? 0.08 : 0),
+ in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)
+ )
+ .scaleEffect(configuration.isPressed ? Motion.pressScale : 1)
+ .animation(Motion.press, value: configuration.isPressed)
+ .animation(Motion.hover, value: hovering)
+ .animation(Motion.hover, value: selected)
+ .contentShape(Rectangle())
+ .onHover { hovering = $0 }
+ }
+}
diff --git a/apps/screen-linux/Cargo.lock b/apps/screen-linux/Cargo.lock
new file mode 100644
index 00000000..ca31fddf
--- /dev/null
+++ b/apps/screen-linux/Cargo.lock
@@ -0,0 +1,1661 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "ashpd"
+version = "0.13.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111"
+dependencies = [
+ "enumflags2",
+ "futures-util",
+ "getrandom",
+ "serde",
+ "serde_repr",
+ "tokio",
+ "zbus",
+]
+
+[[package]]
+name = "async-broadcast"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-executor"
+version = "1.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
+dependencies = [
+ "async-task",
+ "concurrent-queue",
+ "fastrand",
+ "futures-lite",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "async-io"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix",
+ "slab",
+ "windows-sys",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock",
+ "async-signal",
+ "async-task",
+ "blocking",
+ "cfg-if",
+ "event-listener",
+ "futures-lite",
+ "rustix",
+]
+
+[[package]]
+name = "async-recursion"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
+dependencies = [
+ "async-io",
+ "async-lock",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+[[package]]
+name = "async-trait"
+version = "0.1.92"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "atomic_refcell"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4"
+
+[[package]]
+name = "atspi"
+version = "0.30.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6bf601cccedfffec598ec2db1f9d6745885458bccc0e8916d7023f017c94b3d0"
+dependencies = [
+ "atspi-common",
+ "atspi-connection",
+ "atspi-proxies",
+ "zbus",
+]
+
+[[package]]
+name = "atspi-common"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8a79bed3f5b408ce3152f36e07327a845e6ed5d7e2821a89264037dbcc11daf"
+dependencies = [
+ "enumflags2",
+ "serde",
+ "static_assertions",
+ "zbus",
+ "zbus-lockstep",
+ "zbus-lockstep-macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "atspi-connection"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fab8e4f574f5a7d3af280b38eff25fb6f47a537dac9ae39ce152f52b19fb10b"
+dependencies = [
+ "atspi-common",
+ "atspi-proxies",
+ "futures-lite",
+ "zbus",
+]
+
+[[package]]
+name = "atspi-proxies"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53403acd3ab2fdb5914f6558da22e540fc07656fce5510f8c02be0e6ef68413e"
+dependencies = [
+ "atspi-common",
+ "serde",
+ "zbus",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "blocking"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
+dependencies = [
+ "async-channel",
+ "async-task",
+ "futures-io",
+ "futures-lite",
+ "piper",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "cfg-expr"
+version = "0.20.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917"
+dependencies = [
+ "smallvec",
+ "target-lexicon",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "codync-screen"
+version = "2.1.0"
+dependencies = [
+ "anyhow",
+ "ashpd",
+ "atspi",
+ "base64",
+ "dirs",
+ "gstreamer",
+ "gstreamer-app",
+ "gstreamer-sdp",
+ "gstreamer-webrtc",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+ "zbus",
+]
+
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "dirs"
+version = "7.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
+dependencies = [
+ "libc",
+ "option-ext",
+ "redox_users",
+ "windows-sys",
+]
+
+[[package]]
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+
+[[package]]
+name = "endi"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+
+[[package]]
+name = "enumflags2"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
+dependencies = [
+ "enumflags2_derive",
+ "serde",
+]
+
+[[package]]
+name = "enumflags2_derive"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "event-listener"
+version = "5.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
+dependencies = [
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-lite"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-macro",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "gio-sys"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+ "windows-sys",
+]
+
+[[package]]
+name = "glib"
+version = "0.22.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
+dependencies = [
+ "bitflags",
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-task",
+ "futures-util",
+ "gio-sys",
+ "glib-macros",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "memchr",
+ "smallvec",
+]
+
+[[package]]
+name = "glib-macros"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "glib-sys"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
+dependencies = [
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gobject-sys"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
+dependencies = [
+ "glib-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gstreamer"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6"
+dependencies = [
+ "cfg-if",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "glib",
+ "gstreamer-sys",
+ "itertools",
+ "kstring",
+ "libc",
+ "muldiv",
+ "num-integer",
+ "num-rational",
+ "option-operations",
+ "pastey",
+ "pin-project-lite",
+ "smallvec",
+ "thiserror",
+]
+
+[[package]]
+name = "gstreamer-app"
+version = "0.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "glib",
+ "gstreamer",
+ "gstreamer-app-sys",
+ "gstreamer-base",
+ "libc",
+]
+
+[[package]]
+name = "gstreamer-app-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743"
+dependencies = [
+ "glib-sys",
+ "gstreamer-base-sys",
+ "gstreamer-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gstreamer-base"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e"
+dependencies = [
+ "atomic_refcell",
+ "cfg-if",
+ "glib",
+ "gstreamer",
+ "gstreamer-base-sys",
+ "libc",
+]
+
+[[package]]
+name = "gstreamer-base-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "gstreamer-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gstreamer-sdp"
+version = "0.25.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a7859290ba340f1bd45d4bc0ada958700e9d3b1a522b456fd7ee88da468cd13"
+dependencies = [
+ "glib",
+ "gstreamer",
+ "gstreamer-sdp-sys",
+]
+
+[[package]]
+name = "gstreamer-sdp-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e5afafebe4a135392ec2455144cec78821681e007cb9b19c071a4c86b218f64"
+dependencies = [
+ "glib-sys",
+ "gstreamer-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gstreamer-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9"
+dependencies = [
+ "cfg-if",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gstreamer-webrtc"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de524e63b32f3f478b9f718ef6895bd50a1bb1d1d4d7c2134f0a30f36d046157"
+dependencies = [
+ "glib",
+ "gstreamer",
+ "gstreamer-sdp",
+ "gstreamer-webrtc-sys",
+ "libc",
+]
+
+[[package]]
+name = "gstreamer-webrtc-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf77b07fd279bf060d938c7024c8a152a566b4b5e9ff401c7ba890d278a47d1b"
+dependencies = [
+ "glib-sys",
+ "gstreamer-sdp-sys",
+ "gstreamer-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "itertools"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "js-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "kstring"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "558bf9508a558512042d3095138b1f7b8fe90c5467d94f9f1da28b3731c5dbd1"
+dependencies = [
+ "static_assertions",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys",
+]
+
+[[package]]
+name = "muldiv"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0"
+
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "option-operations"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754"
+dependencies = [
+ "pastey",
+]
+
+[[package]]
+name = "ordered-stream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
+[[package]]
+name = "pastey"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "piper"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "redox_users"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
+dependencies = [
+ "libredox",
+ "thiserror",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_repr"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "system-deps"
+version = "9.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a0dae2cbca1f0ff93795713cfe0a4c02f760e3c0b8ae2ab4ec4045808ff429f"
+dependencies = [
+ "cfg-expr",
+ "heck",
+ "pkg-config",
+ "toml",
+ "version-compare",
+]
+
+[[package]]
+name = "target-lexicon"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "tokio"
+version = "1.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "tracing",
+ "windows-sys",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "toml"
+version = "1.1.6+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.15+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"
+dependencies = [
+ "indexmap",
+ "toml_datetime",
+ "toml_parser",
+ "winnow",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
+dependencies = [
+ "winnow",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+]
+
+[[package]]
+name = "uds_windows"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
+dependencies = [
+ "memoffset",
+ "tempfile",
+ "windows-sys",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "uuid"
+version = "1.26.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
+dependencies = [
+ "getrandom",
+ "js-sys",
+ "serde_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
+[[package]]
+name = "version-compare"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "zbus"
+version = "5.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
+dependencies = [
+ "async-broadcast",
+ "async-executor",
+ "async-io",
+ "async-lock",
+ "async-process",
+ "async-recursion",
+ "async-task",
+ "async-trait",
+ "blocking",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-lite",
+ "hex",
+ "libc",
+ "ordered-stream",
+ "rustix",
+ "serde",
+ "serde_repr",
+ "tokio",
+ "tracing",
+ "uds_windows",
+ "uuid",
+ "windows-sys",
+ "winnow",
+ "zbus_macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus-lockstep"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863"
+dependencies = [
+ "zbus_xml",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus-lockstep-macros"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "zbus-lockstep",
+ "zbus_xml",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "5.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "zbus_names",
+ "zvariant",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zbus_names"
+version = "4.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
+dependencies = [
+ "serde",
+ "winnow",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_xml"
+version = "5.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a"
+dependencies = [
+ "serde",
+ "winnow",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zcheapstr"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zvariant"
+version = "5.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "winnow",
+ "zcheapstr",
+ "zvariant_derive",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "5.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn 3.0.6",
+ "winnow",
+]
diff --git a/apps/screen-linux/Cargo.toml b/apps/screen-linux/Cargo.toml
new file mode 100644
index 00000000..c9b076e0
--- /dev/null
+++ b/apps/screen-linux/Cargo.toml
@@ -0,0 +1,41 @@
+[package]
+name = "codync-screen"
+version = "2.1.0"
+edition = "2024"
+description = "Codync Remote screen helper for Linux: xdg portals + PipeWire + GStreamer WebRTC"
+license = "MIT"
+
+[dependencies]
+anyhow = "1"
+ashpd = { version = "0.13", default-features = false, features = ["tokio", "remote_desktop", "screencast"] }
+atspi = { version = "0.30", default-features = false, features = ["proxies", "connection", "tokio"] }
+base64 = "0.22"
+dirs = "7"
+gst = { package = "gstreamer", version = "0.25" }
+gst-app = { package = "gstreamer-app", version = "0.25" }
+gst-sdp = { package = "gstreamer-sdp", version = "0.25" }
+gst-webrtc = { package = "gstreamer-webrtc", version = "0.25", features = ["v1_22"] }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "process"] }
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+zbus = { version = "5", default-features = false, features = ["tokio"] }
+
+[lints.rust]
+unsafe_code = "forbid"
+
+[lints.clippy]
+correctness = { level = "deny", priority = -1 }
+suspicious = { level = "warn", priority = -1 }
+style = { level = "warn", priority = -1 }
+complexity = { level = "warn", priority = -1 }
+perf = { level = "warn", priority = -1 }
+pedantic = { level = "warn", priority = -1 }
+missing_errors_doc = "allow"
+missing_panics_doc = "allow"
+too_many_lines = "allow"
+# Portal calls take `Default::default()` options everywhere; product names in docs read fine.
+default_trait_access = "allow"
+doc_markdown = "allow"
+unwrap_used = "warn"
diff --git a/apps/screen-linux/src/a11y.rs b/apps/screen-linux/src/a11y.rs
new file mode 100644
index 00000000..ec0bc172
--- /dev/null
+++ b/apps/screen-linux/src/a11y.rs
@@ -0,0 +1,92 @@
+//! The active window's accessibility tree over AT-SPI, in the same shape as the
+//! macOS helper: `{role, title?, description?, value?, frame: [x, y, w, h], children?}`
+//! with frames relative to the display.
+
+use crate::portal::Display;
+use anyhow::{Context, Result, anyhow};
+use atspi::connection::AccessibilityConnection;
+use atspi::proxy::accessible::{AccessibleProxy, ObjectRefExt};
+use atspi::proxy::proxy_ext::ProxyExt;
+use atspi::{CoordType, State};
+use serde_json::{Map, Value, json};
+
+const MAX_NODES: usize = 600;
+const MAX_DEPTH: usize = 30;
+
+pub async fn frontmost(d: &Display) -> Result<Value> {
+ let a11y = AccessibilityConnection::new()
+ .await
+ .context("AT-SPI (accessibility) isn't running")?;
+ let conn = a11y.connection();
+ let root = a11y.root_accessible_on_registry().await?;
+ for app in root.get_children().await? {
+ let Ok(app) = app.as_accessible_proxy(conn).await else {
+ continue;
+ };
+ for win in app.get_children().await.unwrap_or_default() {
+ let Ok(win) = win.as_accessible_proxy(conn).await else {
+ continue;
+ };
+ if win
+ .get_state()
+ .await
+ .is_ok_and(|s| s.contains(State::Active))
+ {
+ let mut budget = MAX_NODES;
+ let tree = Box::pin(node(conn, &win, 0, &mut budget, d))
+ .await
+ .unwrap_or(Value::Null);
+ return Ok(
+ json!({"app": app.name().await.unwrap_or_default(), "tree": tree, "truncated": budget == 0}),
+ );
+ }
+ }
+ }
+ Err(anyhow!(
+ "No window is active, or its app doesn't expose accessibility."
+ ))
+}
+
+async fn node(
+ conn: &zbus::Connection,
+ el: &AccessibleProxy<'_>,
+ depth: usize,
+ budget: &mut usize,
+ d: &Display,
+) -> Option<Value> {
+ if *budget == 0 || depth >= MAX_DEPTH {
+ return None;
+ }
+ *budget -= 1;
+ let mut n = Map::new();
+ n.insert(
+ "role".into(),
+ el.get_role_name().await.unwrap_or_default().into(),
+ );
+ for (key, value) in [
+ ("title", el.name().await),
+ ("description", el.description().await),
+ ] {
+ if let Some(v) = value.ok().filter(|v| !v.is_empty()) {
+ n.insert(key.into(), v.chars().take(200).collect::<String>().into());
+ }
+ }
+ if let Ok(proxies) = el.proxies().await
+ && let Ok(component) = proxies.component().await
+ && let Ok((x, y, w, h)) = component.get_extents(CoordType::Screen).await
+ {
+ n.insert("frame".into(), json!([x - d.x, y - d.y, w, h]));
+ }
+ let mut children = vec![];
+ for child in el.get_children().await.unwrap_or_default() {
+ if let Ok(c) = child.as_accessible_proxy(conn).await
+ && let Some(v) = Box::pin(node(conn, &c, depth + 1, budget, d)).await
+ {
+ children.push(v);
+ }
+ }
+ if !children.is_empty() {
+ n.insert("children".into(), children.into());
+ }
+ Some(Value::Object(n))
+}
diff --git a/apps/screen-linux/src/input.rs b/apps/screen-linux/src/input.rs
new file mode 100644
index 00000000..e03ffe5c
--- /dev/null
+++ b/apps/screen-linux/src/input.rs
@@ -0,0 +1,247 @@
+//! Input events (see `host/src/screen.rs`) through the `RemoteDesktop` portal.
+
+use crate::portal::{Display, Portal};
+use anyhow::{Result, anyhow};
+use ashpd::desktop::remote_desktop::{Axis, KeyState};
+use serde_json::Value;
+use std::time::Duration;
+
+/// Linux input event codes (`linux/input-event-codes.h`).
+const BTN_LEFT: i32 = 0x110;
+const BTN_RIGHT: i32 = 0x111;
+const BTN_MIDDLE: i32 = 0x112;
+
+pub async fn perform(portal: &Portal, display: &Display, event: &Value) -> Result<()> {
+ let (d, e) = (display, event);
+ let rd = portal.remote();
+ let session = portal.session();
+ let num = |k: &str| e[k].as_f64();
+ let point = || -> Result<(f64, f64)> {
+ Ok((
+ num("x").ok_or_else(|| anyhow!("x is required"))?,
+ num("y").ok_or_else(|| anyhow!("y is required"))?,
+ ))
+ };
+ let button = match e["button"].as_str() {
+ Some("right") => BTN_RIGHT,
+ Some("middle") => BTN_MIDDLE,
+ _ => BTN_LEFT,
+ };
+ let modifiers: Vec<i32> = e["modifiers"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|m| modifier(m.as_str()?))
+ .collect();
+ let move_to = |x: f64, y: f64| {
+ rd.notify_pointer_motion_absolute(session, d.node, x, y, Default::default())
+ };
+ let hold = |down: bool| {
+ let modifiers = modifiers.clone();
+ async move {
+ let state = if down {
+ KeyState::Pressed
+ } else {
+ KeyState::Released
+ };
+ for m in modifiers {
+ rd.notify_keyboard_keysym(session, m, state, Default::default())
+ .await?;
+ }
+ anyhow::Ok(())
+ }
+ };
+ match e["type"].as_str().unwrap_or_default() {
+ "move" => {
+ let (px, py) = point()?;
+ move_to(px, py).await?;
+ }
+ "down" | "up" => {
+ let (px, py) = point()?;
+ move_to(px, py).await?;
+ let state = if e["type"] == "down" {
+ KeyState::Pressed
+ } else {
+ KeyState::Released
+ };
+ rd.notify_pointer_button(session, button, state, Default::default())
+ .await?;
+ }
+ "click" => {
+ let (px, py) = point()?;
+ move_to(px, py).await?;
+ hold(true).await?;
+ let count = e["count"].as_u64().unwrap_or(1).clamp(1, 3);
+ for _ in 0..count {
+ rd.notify_pointer_button(session, button, KeyState::Pressed, Default::default())
+ .await?;
+ rd.notify_pointer_button(session, button, KeyState::Released, Default::default())
+ .await?;
+ }
+ hold(false).await?;
+ }
+ "drag" => {
+ let (px, py) = point()?;
+ let (tx, ty) = (
+ num("toX").ok_or_else(|| anyhow!("toX is required"))?,
+ num("toY").ok_or_else(|| anyhow!("toY is required"))?,
+ );
+ move_to(px, py).await?;
+ rd.notify_pointer_button(session, BTN_LEFT, KeyState::Pressed, Default::default())
+ .await?;
+ for i in 1..=20 {
+ tokio::time::sleep(Duration::from_millis(15)).await;
+ let t = f64::from(i) / 20.0;
+ move_to(px + (tx - px) * t, py + (ty - py) * t).await?;
+ }
+ rd.notify_pointer_button(session, BTN_LEFT, KeyState::Released, Default::default())
+ .await?;
+ }
+ "scroll" => {
+ let (px, py) = point()?;
+ move_to(px, py).await?;
+ let (dx, dy) = (num("dx").unwrap_or(0.0), num("dy").unwrap_or(0.0));
+ if e["units"] == "pixel" {
+ rd.notify_pointer_axis(
+ session,
+ dx,
+ dy,
+ ashpd::desktop::remote_desktop::NotifyPointerAxisOptions::default()
+ .set_finish(true),
+ )
+ .await?;
+ } else {
+ #[expect(clippy::cast_possible_truncation, reason = "a few scroll lines")]
+ for (axis, steps) in [
+ (Axis::Vertical, dy.round() as i32),
+ (Axis::Horizontal, dx.round() as i32),
+ ] {
+ if steps != 0 {
+ rd.notify_pointer_axis_discrete(session, axis, steps, Default::default())
+ .await?;
+ }
+ }
+ }
+ }
+ "text" => {
+ for c in e["text"].as_str().unwrap_or_default().chars() {
+ let sym = char_keysym(c);
+ rd.notify_keyboard_keysym(session, sym, KeyState::Pressed, Default::default())
+ .await?;
+ rd.notify_keyboard_keysym(session, sym, KeyState::Released, Default::default())
+ .await?;
+ }
+ }
+ "key" => {
+ let name = e["key"].as_str().unwrap_or_default();
+ let sym = keysym(name).ok_or_else(|| anyhow!("unknown key {name}"))?;
+ hold(true).await?;
+ rd.notify_keyboard_keysym(session, sym, KeyState::Pressed, Default::default())
+ .await?;
+ rd.notify_keyboard_keysym(session, sym, KeyState::Released, Default::default())
+ .await?;
+ hold(false).await?;
+ }
+ other => return Err(anyhow!("unknown input {other}")),
+ }
+ Ok(())
+}
+
+fn modifier(name: &str) -> Option<i32> {
+ Some(match name {
+ "cmd" => 0xffeb, // Super_L
+ "option" => 0xffe9, // Alt_L
+ "ctrl" => 0xffe3, // Control_L
+ "shift" => 0xffe1, // Shift_L
+ _ => return None,
+ })
+}
+
+/// X keysym for a key name from the shared protocol, or a single character.
+pub fn keysym(name: &str) -> Option<i32> {
+ let named = match name {
+ "return" => 0xff0d,
+ "tab" => 0xff09,
+ "space" => 0x20,
+ "escape" => 0xff1b,
+ "delete" => 0xff08, // BackSpace: the protocol names keys like a Mac keyboard
+ "forwardDelete" => 0xffff,
+ "left" => 0xff51,
+ "up" => 0xff52,
+ "right" => 0xff53,
+ "down" => 0xff54,
+ "home" => 0xff50,
+ "end" => 0xff57,
+ "pageUp" => 0xff55,
+ "pageDown" => 0xff56,
+ _ => {
+ if let Some(n) = name
+ .strip_prefix('f')
+ .and_then(|n| n.parse::<i32>().ok())
+ .filter(|n| (1..=12).contains(n))
+ {
+ return Some(0xffbe + n - 1);
+ }
+ let mut chars = name.chars();
+ return match (chars.next(), chars.next()) {
+ (Some(c), None) => Some(char_keysym(c)),
+ _ => None,
+ };
+ }
+ };
+ Some(named)
+}
+
+/// Latin-1 keysyms are the code point; everything else is the Unicode keysym range.
+pub fn char_keysym(c: char) -> i32 {
+ let cp = u32::from(c);
+ let sym = match cp {
+ 0x0a | 0x0d => 0xff0d,
+ 0x09 => 0xff09,
+ 0x20..=0x7e | 0xa0..=0xff => cp,
+ _ => 0x0100_0000 + cp,
+ };
+ i32::try_from(sym).unwrap_or(0)
+}
+
+/// Opens an app by desktop-file id or name, else runs it as a command.
+pub async fn open_app(name: &str) -> Result<()> {
+ let id = name.trim().trim_end_matches(".desktop");
+ let candidates = [
+ id.to_owned(),
+ id.to_lowercase(),
+ id.to_lowercase().replace(' ', "-"),
+ ];
+ for c in &candidates {
+ let ok = tokio::process::Command::new("gtk-launch")
+ .arg(c)
+ .status()
+ .await
+ .is_ok_and(|s| s.success());
+ if ok {
+ return Ok(());
+ }
+ }
+ tokio::process::Command::new(id.to_lowercase())
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map_err(|_| anyhow!("Couldn't find an app named {name}."))?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn keysyms() {
+ assert_eq!(keysym("return"), Some(0xff0d));
+ assert_eq!(keysym("f5"), Some(0xffc2));
+ assert_eq!(keysym("a"), Some(0x61));
+ assert_eq!(keysym("banana"), None);
+ assert_eq!(char_keysym('é'), 0xe9);
+ assert_eq!(char_keysym('中'), 0x0100_4e2d);
+ }
+}
diff --git a/apps/screen-linux/src/main.rs b/apps/screen-linux/src/main.rs
new file mode 100644
index 00000000..cbcbbbe7
--- /dev/null
+++ b/apps/screen-linux/src/main.rs
@@ -0,0 +1,190 @@
+//! `codync-screen`: Remote screen for Linux. The host (`codync-host`) starts it
+//! while Remote screen is on; it connects to `~/.codync/screen.sock` and serves
+//! the same JSON-RPC as the macOS helper (see `host/src/screen.rs`):
+//! capture and input through the xdg `RemoteDesktop` + `ScreenCast` portals
+//! (approved once, then restored from a saved token), video as H.264 over
+//! GStreamer `webrtcbin`, and the accessibility tree over AT-SPI.
+
+mod a11y;
+mod input;
+mod portal;
+mod stream;
+
+use anyhow::{Context, Result, anyhow};
+use serde_json::{Value, json};
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::net::UnixStream;
+use tokio::sync::{Mutex, mpsc};
+
+fn data_dir() -> PathBuf {
+ std::env::var_os("CODYNC_HOME").map_or_else(
+ || dirs::home_dir().expect("HOME must be set").join(".codync"),
+ PathBuf::from,
+ )
+}
+
+/// Messages to the host, one JSON line each.
+pub type Outbox = mpsc::UnboundedSender<Value>;
+
+pub struct Helper {
+ portal: portal::Portal,
+ sessions: Mutex<HashMap<String, stream::Session>>,
+ out: Outbox,
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| "codync_screen=info".into()),
+ )
+ .init();
+ gst::init().context("starting GStreamer")?;
+ // One portal session for the life of the process: the approval dialog appears once,
+ // and later runs restore it silently from the saved token.
+ let portal = portal::Portal::start(&data_dir()).await?;
+ loop {
+ match UnixStream::connect(data_dir().join("screen.sock")).await {
+ Ok(sock) => {
+ tracing::info!("connected to codync-host");
+ if let Err(error) = serve(sock, &portal).await {
+ tracing::warn!(error = format!("{error:#}"), "host link ended");
+ }
+ }
+ Err(error) => tracing::debug!(%error, "codync-host isn't listening yet"),
+ }
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+}
+
+async fn serve(sock: UnixStream, portal: &portal::Portal) -> Result<()> {
+ let (rd, mut wr) = sock.into_split();
+ let (out, mut outbox) = mpsc::unbounded_channel::<Value>();
+ let writer = tokio::spawn(async move {
+ while let Some(msg) = outbox.recv().await {
+ let mut line = msg.to_string();
+ line.push('\n');
+ if wr.write_all(line.as_bytes()).await.is_err() {
+ break;
+ }
+ }
+ });
+ let helper = Arc::new(Helper {
+ portal: portal.clone(),
+ sessions: Mutex::default(),
+ out: out.clone(),
+ });
+ let _ =
+ out.send(json!({"jsonrpc": "2.0", "method": "status", "params": helper.portal.status()}));
+ let mut lines = BufReader::new(rd).lines();
+ while let Some(line) = lines.next_line().await? {
+ let Ok(msg) = serde_json::from_str::<Value>(&line) else {
+ continue;
+ };
+ let (Some(method), Some(id)) = (
+ msg["method"].as_str().map(str::to_owned),
+ msg.get("id").cloned(),
+ ) else {
+ continue;
+ };
+ let helper = helper.clone();
+ tokio::spawn(async move {
+ let reply = match handle(&helper, &method, &msg["params"]).await {
+ Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
+ Err(error) => {
+ json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": format!("{error:#}")}})
+ }
+ };
+ let _ = helper.out.send(reply);
+ });
+ }
+ writer.abort();
+ for (_, s) in helper.sessions.lock().await.drain() {
+ s.close();
+ }
+ Ok(())
+}
+
+async fn handle(h: &Arc<Helper>, method: &str, p: &Value) -> Result<Value> {
+ let display = || h.portal.display(p["display"].as_u64());
+ Ok(match method {
+ "answer" => {
+ let id = p["session"]
+ .as_str()
+ .ok_or_else(|| anyhow!("session is required"))?
+ .to_owned();
+ let sdp = p["sdp"]
+ .as_str()
+ .ok_or_else(|| anyhow!("sdp is required"))?;
+ if let Some(s) = h.sessions.lock().await.get(&id) {
+ return Ok(json!({"sdp": s.answer(sdp).await?}));
+ }
+ let d = display()?;
+ let fd = h.portal.pipewire_fd().await?;
+ let session = stream::Session::new(id.clone(), &d, fd, h.clone())?;
+ let answer = session.answer(sdp).await?;
+ h.sessions.lock().await.insert(id, session);
+ json!({"sdp": answer})
+ }
+ "close" => {
+ if let Some(s) = p["session"]
+ .as_str()
+ .and_then(|id| h.sessions.try_lock().ok()?.remove(id))
+ {
+ s.close();
+ }
+ json!({})
+ }
+ "closeAll" => {
+ for (_, s) in h.sessions.lock().await.drain() {
+ s.close();
+ }
+ json!({})
+ }
+ "screenshot" => {
+ let (w, h2) = (
+ p["width"].as_u64().unwrap_or(1280),
+ p["height"].as_u64().unwrap_or(800),
+ );
+ let d = display()?;
+ let fd = h.portal.pipewire_fd().await?;
+ let jpeg = stream::screenshot(fd, &d, u32::try_from(w)?, u32::try_from(h2)?).await?;
+ json!({"data": jpeg})
+ }
+ "input" => {
+ let d = display()?;
+ input::perform(&h.portal, &d, &p["event"]).await?;
+ json!({})
+ }
+ "uiTree" => a11y::frontmost(&display()?).await?,
+ "openApp" => {
+ input::open_app(
+ p["name"]
+ .as_str()
+ .ok_or_else(|| anyhow!("name is required"))?,
+ )
+ .await?;
+ json!({})
+ }
+ other => return Err(anyhow!("unknown method {other}")),
+ })
+}
+
+impl Helper {
+ /// A session's WebRTC connection ended on its own.
+ pub fn ended(self: &Arc<Self>, id: &str) {
+ let this = self.clone();
+ let id = id.to_owned();
+ tokio::spawn(async move {
+ if let Some(s) = this.sessions.lock().await.remove(&id) {
+ s.close();
+ }
+ let _ = this.out.send(json!({"jsonrpc": "2.0", "method": "session", "params": {"session": id, "state": "closed"}}));
+ });
+ }
+}
diff --git a/apps/screen-linux/src/portal.rs b/apps/screen-linux/src/portal.rs
new file mode 100644
index 00000000..e81135c8
--- /dev/null
+++ b/apps/screen-linux/src/portal.rs
@@ -0,0 +1,156 @@
+//! One xdg `RemoteDesktop` session with screen cast sources: input injection and
+//! PipeWire streams for every monitor. Persisted with a restore token so the user
+//! approves once.
+
+use anyhow::{Context, Result, anyhow};
+use ashpd::desktop::PersistMode;
+use ashpd::desktop::Session;
+use ashpd::desktop::remote_desktop::{DeviceType, RemoteDesktop, SelectDevicesOptions};
+use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};
+use serde_json::{Value, json};
+use std::os::fd::OwnedFd;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+/// A monitor as the portal streams it. `width`/`height` are logical pixels: the
+/// coordinate space of input events and of the host's `Display` points.
+#[derive(Clone, Debug)]
+pub struct Display {
+ pub id: u32,
+ pub node: u32,
+ pub x: i32,
+ pub y: i32,
+ pub width: f64,
+ pub height: f64,
+}
+
+#[derive(Clone)]
+pub struct Portal(Arc<Inner>);
+
+struct Inner {
+ remote: RemoteDesktop,
+ screencast: Screencast,
+ session: Session<RemoteDesktop>,
+ displays: Vec<Display>,
+ input: bool,
+}
+
+impl Portal {
+ pub async fn start(data: &Path) -> Result<Self> {
+ let token_file = data.join("screen-restore-token");
+ let token = std::fs::read_to_string(&token_file).ok();
+ let remote = RemoteDesktop::new()
+ .await
+ .context("the RemoteDesktop portal isn't available")?;
+ let screencast = Screencast::new()
+ .await
+ .context("the ScreenCast portal isn't available")?;
+ let session = remote.create_session(Default::default()).await?;
+ remote
+ .select_devices(
+ &session,
+ SelectDevicesOptions::default()
+ .set_devices(DeviceType::Keyboard | DeviceType::Pointer)
+ .set_persist_mode(PersistMode::ExplicitlyRevoked)
+ .set_restore_token(token.as_deref().map(str::trim)),
+ )
+ .await?;
+ screencast
+ .select_sources(
+ &session,
+ SelectSourcesOptions::default()
+ .set_cursor_mode(CursorMode::Embedded)
+ .set_sources(ashpd::enumflags2::BitFlags::from(SourceType::Monitor))
+ .set_multiple(true),
+ )
+ .await?;
+ let started = remote
+ .start(&session, None, Default::default())
+ .await?
+ .response()
+ .context("remote access to this screen was not allowed")?;
+ if let Some(t) = started.restore_token() {
+ save_token(&token_file, t);
+ }
+ let displays = started
+ .streams()
+ .iter()
+ .enumerate()
+ .map(|(i, s)| {
+ let (x, y) = s.position().unwrap_or((0, 0));
+ let (w, h) = s.size().unwrap_or((1920, 1080));
+ Display {
+ id: u32::try_from(i).unwrap_or(0),
+ node: s.pipe_wire_node_id(),
+ x,
+ y,
+ width: f64::from(w),
+ height: f64::from(h),
+ }
+ })
+ .collect::<Vec<_>>();
+ if displays.is_empty() {
+ return Err(anyhow!("the portal shared no screen"));
+ }
+ let input = started.devices().contains(DeviceType::Pointer);
+ Ok(Self(Arc::new(Inner {
+ remote,
+ screencast,
+ session,
+ displays,
+ input,
+ })))
+ }
+
+ pub fn status(&self) -> Value {
+ json!({
+ "platform": "linux",
+ "version": env!("CARGO_PKG_VERSION"),
+ "capture": true,
+ "input": self.0.input,
+ "displays": self.0.displays.iter().map(|d| json!({
+ "id": d.id,
+ "name": format!("Display {}", d.id + 1),
+ "width": d.width,
+ "height": d.height,
+ "main": d.id == 0,
+ })).collect::<Vec<_>>(),
+ })
+ }
+
+ pub fn display(&self, id: Option<u64>) -> Result<Display> {
+ let id = id.map_or(0, |i| u32::try_from(i).unwrap_or(u32::MAX));
+ self.0
+ .displays
+ .iter()
+ .find(|d| d.id == id)
+ .cloned()
+ .ok_or_else(|| anyhow!("no such display"))
+ }
+
+ /// A fresh PipeWire remote for one consumer (each pipeline owns its fd).
+ pub async fn pipewire_fd(&self) -> Result<OwnedFd> {
+ Ok(self
+ .0
+ .screencast
+ .open_pipe_wire_remote(&self.0.session, Default::default())
+ .await?)
+ }
+
+ pub fn remote(&self) -> &RemoteDesktop {
+ &self.0.remote
+ }
+
+ pub fn session(&self) -> &Session<RemoteDesktop> {
+ &self.0.session
+ }
+}
+
+fn save_token(path: &PathBuf, token: &str) {
+ use std::os::unix::fs::PermissionsExt;
+ if let Err(error) = std::fs::write(path, token) {
+ tracing::warn!(%error, "couldn't save the portal restore token");
+ return;
+ }
+ let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
+}
diff --git a/apps/screen-linux/src/stream.rs b/apps/screen-linux/src/stream.rs
new file mode 100644
index 00000000..6f2ac651
--- /dev/null
+++ b/apps/screen-linux/src/stream.rs
@@ -0,0 +1,367 @@
+//! Video: a PipeWire monitor stream encoded as H.264 and sent over GStreamer
+//! `webrtcbin` (non-trickle, like the macOS helper), plus one-off JPEG stills.
+
+use crate::portal::Display;
+use crate::{Helper, input};
+use anyhow::{Context, Result, anyhow};
+use base64::Engine as _;
+use gst::prelude::*;
+use serde_json::{Value, json};
+use std::os::fd::{IntoRawFd, OwnedFd};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tokio::sync::{mpsc, oneshot};
+
+/// Hardware encoders first; x264 is the always-there fallback.
+const ENCODERS: &[&str] = &[
+ "vah264lpenc",
+ "vah264enc",
+ "nvh264enc",
+ "vaapih264enc",
+ "x264enc",
+ "openh264enc",
+];
+const BITRATE_KBPS: u32 = 8000;
+
+pub struct Session {
+ pipeline: gst::Pipeline,
+ webrtc: gst::Element,
+}
+
+impl Session {
+ pub fn new(id: String, display: &Display, fd: OwnedFd, helper: Arc<Helper>) -> Result<Self> {
+ let pipeline = gst::Pipeline::new();
+ let src = gst::ElementFactory::make("pipewiresrc")
+ .property("fd", fd.into_raw_fd())
+ .property("path", display.node.to_string())
+ .property("do-timestamp", true)
+ .build()
+ .context("GStreamer's PipeWire plugin (gstreamer1.0-pipewire) is missing")?;
+ if src.has_property("keepalive-time") {
+ // A still screen keeps sending frames now and then, so keyframe requests get answered.
+ src.set_property("keepalive-time", 1000i32);
+ }
+ let convert = make("videoconvert")?;
+ let crop = make("videocrop")?;
+ let scale = make("videoscale")?;
+ let size = make("capsfilter")?;
+ let rate = make("videorate")?;
+ rate.set_property("max-rate", 60i32);
+ rate.set_property("drop-only", true);
+ let convert2 = make("videoconvert")?;
+ let queue = make("queue")?;
+ queue.set_property_from_str("leaky", "downstream");
+ queue.set_property("max-size-buffers", 2u32);
+ let encoder = encoder()?;
+ let parse = make("h264parse")?;
+ let pay = make("rtph264pay")?;
+ pay.set_property("config-interval", -1i32);
+ pay.set_property_from_str("aggregate-mode", "zero-latency");
+ pay.set_property("pt", 96u32);
+ let rtp_caps = make("capsfilter")?;
+ rtp_caps.set_property(
+ "caps",
+ gst::Caps::builder("application/x-rtp")
+ .field("media", "video")
+ .field("encoding-name", "H264")
+ .field("payload", 96i32)
+ .field("clock-rate", 90000i32)
+ .build(),
+ );
+ let webrtc = make("webrtcbin")?;
+ webrtc.set_property_from_str("bundle-policy", "max-bundle");
+ let chain = [
+ &src, &convert, &crop, &scale, &size, &rate, &convert2, &queue, &encoder, &parse, &pay,
+ &rtp_caps, &webrtc,
+ ];
+ pipeline.add_many(chain)?;
+ gst::Element::link_many(chain)?;
+
+ // Input from the phone, applied in order.
+ let (tx, mut rx) = mpsc::unbounded_channel::<Value>();
+ let view = View {
+ crop: crop.clone(),
+ size: size.clone(),
+ display: display.clone(),
+ };
+ let channels: Arc<Mutex<Vec<gst_webrtc::WebRTCDataChannel>>> = Arc::default();
+ {
+ let helper = helper.clone();
+ let channels = channels.clone();
+ let display = display.clone();
+ tokio::spawn(async move {
+ while let Some(msg) = rx.recv().await {
+ let reply = match msg["type"].as_str() {
+ Some("view") => Some(view.apply(&msg)),
+ Some("clipboard") => {
+ set_clipboard(msg["text"].as_str().unwrap_or_default())
+ .await
+ .err()
+ .as_ref()
+ .map(error_msg)
+ }
+ _ => input::perform(&helper.portal, &display, &msg)
+ .await
+ .err()
+ .as_ref()
+ .map(error_msg),
+ };
+ if let Some(reply) = reply {
+ send(&channels, &reply);
+ }
+ }
+ });
+ }
+ webrtc.connect("on-data-channel", false, {
+ let channels = channels.clone();
+ move |values| {
+ let channel = values[1].get::<gst_webrtc::WebRTCDataChannel>().ok()?;
+ let tx = tx.clone();
+ channel.connect("on-message-string", false, move |v| {
+ if let Some(msg) = v[1]
+ .get::<Option<String>>()
+ .ok()
+ .flatten()
+ .and_then(|s| serde_json::from_str::<Value>(&s).ok())
+ {
+ let _ = tx.send(msg);
+ }
+ None
+ });
+ if let Ok(mut list) = channels.lock() {
+ list.push(channel);
+ }
+ None
+ }
+ });
+ webrtc.connect_notify(Some("ice-connection-state"), move |w, _| {
+ let state = w.property::<gst_webrtc::WebRTCICEConnectionState>("ice-connection-state");
+ if matches!(
+ state,
+ gst_webrtc::WebRTCICEConnectionState::Failed
+ | gst_webrtc::WebRTCICEConnectionState::Closed
+ ) {
+ helper.ended(&id);
+ }
+ });
+ pipeline
+ .set_state(gst::State::Playing)
+ .context("starting the video pipeline")?;
+ Ok(Self { pipeline, webrtc })
+ }
+
+ /// Answers an offer (first connect or ICE restart) once every local candidate is in.
+ pub async fn answer(&self, offer: &str) -> Result<String> {
+ let sdp = gst_sdp::SDPMessage::parse_buffer(offer.as_bytes())
+ .map_err(|_| anyhow!("bad offer"))?;
+ let offer =
+ gst_webrtc::WebRTCSessionDescription::new(gst_webrtc::WebRTCSDPType::Offer, sdp);
+ let (p, done) = promise();
+ self.webrtc
+ .emit_by_name::<()>("set-remote-description", &[&offer, &p]);
+ done.await?;
+ let (p, done) = promise();
+ self.webrtc
+ .emit_by_name::<()>("create-answer", &[&None::<gst::Structure>, &p]);
+ let reply = done.await?.ok_or_else(|| anyhow!("no answer"))?;
+ let answer = reply
+ .get::<gst_webrtc::WebRTCSessionDescription>("answer")
+ .map_err(|_| anyhow!("no answer"))?;
+ let (p, done) = promise();
+ self.webrtc
+ .emit_by_name::<()>("set-local-description", &[&answer, &p]);
+ done.await?;
+ for _ in 0..60 {
+ if self
+ .webrtc
+ .property::<gst_webrtc::WebRTCICEGatheringState>("ice-gathering-state")
+ == gst_webrtc::WebRTCICEGatheringState::Complete
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let local = self
+ .webrtc
+ .property::<Option<gst_webrtc::WebRTCSessionDescription>>("local-description");
+ let local = local.unwrap_or(answer);
+ local
+ .sdp()
+ .as_text()
+ .map_err(|_| anyhow!("couldn't write the answer"))
+ }
+
+ pub fn close(self) {
+ let _ = self.pipeline.set_state(gst::State::Null);
+ }
+}
+
+/// Crop and output size for what the phone shows (see the iOS `ScreenViewport`).
+struct View {
+ crop: gst::Element,
+ size: gst::Element,
+ display: Display,
+}
+
+impl View {
+ fn apply(&self, msg: &Value) -> Value {
+ // Source frames can be larger than the logical size (HiDPI).
+ let (fw, fh) = self
+ .crop
+ .static_pad("sink")
+ .and_then(|p| p.current_caps())
+ .and_then(|c| {
+ let s = c.structure(0)?;
+ Some((
+ f64::from(s.get::<i32>("width").ok()?),
+ f64::from(s.get::<i32>("height").ok()?),
+ ))
+ })
+ .unwrap_or((self.display.width, self.display.height));
+ let factor = fw / self.display.width;
+ let crop = msg["crop"].as_array().and_then(|c| {
+ let v: Vec<f64> = c.iter().filter_map(Value::as_f64).collect();
+ (v.len() == 4 && v[2] >= 16.0 && v[3] >= 16.0)
+ .then(|| (v[0].max(0.0), v[1].max(0.0), v[2], v[3]))
+ });
+ let (x, y, w, h) = crop.unwrap_or((0.0, 0.0, self.display.width, self.display.height));
+ let px = |v: f64| to_i32(v * factor);
+ self.crop.set_property("left", px(x));
+ self.crop.set_property("top", px(y));
+ self.crop
+ .set_property("right", (to_i32(fw) - px(x + w)).max(0));
+ self.crop
+ .set_property("bottom", (to_i32(fh) - px(y + h)).max(0));
+ if let (Some(long), Some(short)) = (msg["long"].as_f64(), msg["short"].as_f64()) {
+ let (cw, ch) = (w * factor, h * factor);
+ let fit = (long.min(3840.0) / cw.max(ch))
+ .min(short.min(2160.0) / cw.min(ch))
+ .min(1.0);
+ let even = |v: f64| (to_i32(v * fit) / 2 * 2).max(2);
+ self.size.set_property(
+ "caps",
+ gst::Caps::builder("video/x-raw")
+ .field("width", even(cw))
+ .field("height", even(ch))
+ .build(),
+ );
+ }
+ json!({"type": "view", "display": self.display.id, "crop": crop.map(|(x, y, w, h)| json!([x, y, w, h]))})
+ }
+}
+
+#[expect(
+ clippy::cast_possible_truncation,
+ reason = "screen sizes are a few thousand pixels"
+)]
+fn to_i32(v: f64) -> i32 {
+ v.round() as i32
+}
+
+fn error_msg(e: &anyhow::Error) -> Value {
+ json!({"type": "error", "message": format!("{e:#}")})
+}
+
+fn send(channels: &Mutex<Vec<gst_webrtc::WebRTCDataChannel>>, msg: &Value) {
+ let Ok(list) = channels.lock() else { return };
+ if let Some(ch) = list.iter().find(|c| c.label().as_deref() == Some("input"))
+ && let Err(error) = ch.send_string_full(Some(&msg.to_string()))
+ {
+ tracing::debug!(%error, "couldn't reply on the data channel");
+ }
+}
+
+/// Wayland first, then X11.
+async fn set_clipboard(text: &str) -> Result<()> {
+ use tokio::io::AsyncWriteExt;
+ for (cmd, args) in [
+ ("wl-copy", &[][..]),
+ ("xclip", &["-selection", "clipboard"][..]),
+ ] {
+ let Ok(mut child) = tokio::process::Command::new(cmd)
+ .args(args)
+ .stdin(std::process::Stdio::piped())
+ .spawn()
+ else {
+ continue;
+ };
+ if let Some(mut stdin) = child.stdin.take() {
+ stdin.write_all(text.as_bytes()).await?;
+ }
+ if child.wait().await?.success() {
+ return Ok(());
+ }
+ }
+ Err(anyhow!(
+ "Install wl-clipboard (or xclip) on this computer to paste from your phone."
+ ))
+}
+
+fn make(name: &str) -> Result<gst::Element> {
+ gst::ElementFactory::make(name)
+ .build()
+ .with_context(|| format!("GStreamer element {name} is missing"))
+}
+
+fn encoder() -> Result<gst::Element> {
+ let name = ENCODERS
+ .iter()
+ .find(|n| gst::ElementFactory::find(n).is_some())
+ .ok_or_else(|| {
+ anyhow!("no H.264 encoder: install gstreamer1.0-plugins-ugly (x264) or a VA-API driver")
+ })?;
+ let e = make(name)?;
+ match *name {
+ "x264enc" => {
+ e.set_property_from_str("tune", "zerolatency");
+ e.set_property_from_str("speed-preset", "veryfast");
+ e.set_property("bitrate", BITRATE_KBPS);
+ e.set_property("key-int-max", 120u32);
+ }
+ "openh264enc" => e.set_property("bitrate", BITRATE_KBPS * 1000),
+ _ => {
+ if e.has_property("bitrate") {
+ e.set_property_from_str("bitrate", &BITRATE_KBPS.to_string());
+ }
+ }
+ }
+ tracing::info!(encoder = name, "video encoder");
+ Ok(e)
+}
+
+fn promise() -> (gst::Promise, oneshot::Receiver<Option<gst::Structure>>) {
+ let (tx, rx) = oneshot::channel();
+ let p = gst::Promise::with_change_func(move |reply| {
+ let _ = tx.send(reply.ok().flatten().map(ToOwned::to_owned));
+ });
+ (p, rx)
+}
+
+/// One still for agents: `width`×`height` JPEG, base64.
+pub async fn screenshot(fd: OwnedFd, d: &Display, width: u32, height: u32) -> Result<String> {
+ let desc = format!(
+ "pipewiresrc name=src path={} do-timestamp=true ! videoconvert ! videoscale ! video/x-raw,width={width},height={height} ! jpegenc quality=80 ! appsink name=sink max-buffers=1",
+ d.node
+ );
+ let pipeline = gst::parse::launch(&desc)?
+ .downcast::<gst::Pipeline>()
+ .map_err(|_| anyhow!("bad pipeline"))?;
+ let src = pipeline
+ .by_name("src")
+ .ok_or_else(|| anyhow!("no source"))?;
+ src.set_property("fd", fd.into_raw_fd());
+ let sink = pipeline
+ .by_name("sink")
+ .ok_or_else(|| anyhow!("no sink"))?
+ .downcast::<gst_app::AppSink>()
+ .map_err(|_| anyhow!("no sink"))?;
+ pipeline.set_state(gst::State::Playing)?;
+ let sample =
+ tokio::task::spawn_blocking(move || sink.try_pull_sample(gst::ClockTime::from_seconds(3)))
+ .await?;
+ let _ = pipeline.set_state(gst::State::Null);
+ let sample = sample.ok_or_else(|| anyhow!("the screen sent no frame"))?;
+ let buffer = sample.buffer().ok_or_else(|| anyhow!("empty frame"))?;
+ let map = buffer.map_readable()?;
+ Ok(base64::engine::general_purpose::STANDARD.encode(map.as_slice()))
+}
diff --git a/apps/screen/AXTree.swift b/apps/screen/AXTree.swift
new file mode 100644
index 00000000..8bd58b8c
--- /dev/null
+++ b/apps/screen/AXTree.swift
@@ -0,0 +1,69 @@
+import AppKit
+import ApplicationServices
+
+/// The frontmost app's accessibility tree, compact enough to hand to an agent.
+/// Frames are `[x, y, w, h]` in points relative to the display's top-left corner.
+@MainActor
+enum AXTree {
+ private static let maxNodes = 600
+ private static let maxDepth = 30
+ /// Wrappers with nothing to say and a single child are skipped.
+ private static let passThrough: Set<String> = ["AXGroup", "AXSplitGroup", "AXScrollArea", "AXLayoutArea", "AXUnknown"]
+
+ static func frontmost(display: CGDirectDisplayID) throws -> [String: Any] {
+ guard AXIsProcessTrusted() else {
+ throw HelperError("Codync Screen isn't allowed to read the screen's controls yet. Allow it under Privacy & Security → Accessibility.")
+ }
+ guard let app = NSWorkspace.shared.frontmostApplication else { throw HelperError("No app is in front.") }
+ let root = AXUIElementCreateApplication(app.processIdentifier)
+ AXUIElementSetMessagingTimeout(root, 1)
+ var budget = maxNodes
+ let origin = CGDisplayBounds(display).origin
+ let windows: [AXUIElement] = attribute(root, kAXWindowsAttribute) ?? []
+ let tree: [String: Any] = [
+ "role": "AXApplication",
+ "title": app.localizedName ?? "",
+ "children": windows.compactMap { node($0, depth: 0, budget: &budget, origin: origin) },
+ ]
+ return ["app": app.localizedName ?? "", "tree": tree, "truncated": budget <= 0]
+ }
+
+ private static func node(_ el: AXUIElement, depth: Int, budget: inout Int, origin: CGPoint) -> [String: Any]? {
+ guard budget > 0, depth < maxDepth else { return nil }
+ budget -= 1
+ var n: [String: Any] = [:]
+ let role: String = attribute(el, kAXRoleAttribute) ?? "AXUnknown"
+ n["role"] = role
+ for (key, attr) in [("title", kAXTitleAttribute), ("description", kAXDescriptionAttribute), ("help", kAXHelpAttribute), ("id", kAXIdentifierAttribute)] {
+ if let s: String = attribute(el, attr), !s.isEmpty { n[key] = String(s.prefix(200)) }
+ }
+ if let v: Any = attribute(el, kAXValueAttribute) {
+ if let s = v as? String, !s.isEmpty { n["value"] = String(s.prefix(200)) } else if let num = v as? NSNumber { n["value"] = num }
+ }
+ if let enabled: Bool = attribute(el, kAXEnabledAttribute), !enabled { n["enabled"] = false }
+ if let focused: Bool = attribute(el, kAXFocusedAttribute), focused { n["focused"] = true }
+ if let frame = frame(el) {
+ n["frame"] = [frame.minX - origin.x, frame.minY - origin.y, frame.width, frame.height].map { ($0 * 10).rounded() / 10 }
+ }
+ let kids: [AXUIElement] = attribute(el, kAXChildrenAttribute) ?? []
+ let children = kids.compactMap { node($0, depth: depth + 1, budget: &budget, origin: origin) }
+ if passThrough.contains(role), children.count == 1, n["title"] == nil, n["description"] == nil, n["value"] == nil {
+ return children[0]
+ }
+ if !children.isEmpty { n["children"] = children }
+ return n
+ }
+
+ private static func frame(_ el: AXUIElement) -> CGRect? {
+ guard let pos: AXValue = attribute(el, kAXPositionAttribute), let size: AXValue = attribute(el, kAXSizeAttribute) else { return nil }
+ var p = CGPoint.zero, s = CGSize.zero
+ guard AXValueGetValue(pos, .cgPoint, &p), AXValueGetValue(size, .cgSize, &s) else { return nil }
+ return CGRect(origin: p, size: s)
+ }
+
+ private static func attribute<T>(_ el: AXUIElement, _ name: String) -> T? {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(el, name as CFString, &value) == .success else { return nil }
+ return value as? T
+ }
+}
diff --git a/apps/screen/Capture.swift b/apps/screen/Capture.swift
new file mode 100644
index 00000000..a17cbbe9
--- /dev/null
+++ b/apps/screen/Capture.swift
@@ -0,0 +1,154 @@
+import CoreMedia
+import Foundation
+import ImageIO
+@preconcurrency import ScreenCaptureKit
+import UniformTypeIdentifiers
+@preconcurrency import WebRTC
+
+/// Hands ScreenCaptureKit frames to WebRTC. Lives on its own queue: frames never touch the main thread.
+final class FrameSink: NSObject, SCStreamOutput, @unchecked Sendable {
+ // @unchecked: every field is only touched on `queue` (SCStream's sample queue and the idle
+ // timer both run there), and WebRTC's ObjC types carry no Sendable annotations.
+ let queue = DispatchQueue(label: "com.pokai.Codync.screen.frames", qos: .userInteractive)
+ private let source: RTCVideoSource
+ private let capturer: RTCVideoCapturer
+ private var last: RTCVideoFrame?
+ private var lastAt: UInt64 = 0
+ private var timer: DispatchSourceTimer?
+
+ init(source: RTCVideoSource) {
+ self.source = source
+ capturer = RTCVideoCapturer(delegate: source)
+ super.init()
+ let t = DispatchSource.makeTimerSource(queue: queue)
+ t.schedule(deadline: .now() + 1, repeating: .milliseconds(500))
+ t.setEventHandler { [weak self] in self?.repeatIfIdle() }
+ t.resume()
+ timer = t
+ }
+
+ func stop() {
+ timer?.cancel()
+ }
+
+ func stream(_ stream: SCStream, didOutputSampleBuffer sample: CMSampleBuffer, of type: SCStreamOutputType) {
+ guard type == .screen,
+ let info = (CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[SCStreamFrameInfo: Any]])?.first,
+ let raw = info[.status] as? Int, SCFrameStatus(rawValue: raw) == .complete,
+ let pixels = CMSampleBufferGetImageBuffer(sample)
+ else { return }
+ deliver(RTCCVPixelBuffer(pixelBuffer: pixels))
+ }
+
+ /// ScreenCaptureKit only sends frames when something changes. A still screen still needs
+ /// frames now and then so the encoder can answer keyframe requests after packet loss.
+ private func repeatIfIdle() {
+ guard let last, DispatchTime.now().uptimeNanoseconds - lastAt > 900_000_000 else { return }
+ deliver(last.buffer)
+ }
+
+ private func deliver(_ buffer: RTCVideoFrameBuffer) {
+ let now = DispatchTime.now().uptimeNanoseconds
+ let frame = RTCVideoFrame(buffer: buffer, rotation: ._0, timeStampNs: Int64(now))
+ last = frame
+ lastAt = now
+ source.capturer(capturer, didCapture: frame)
+ }
+}
+
+/// Streams one display (or a region of it) into WebRTC at the size the phone can show.
+@MainActor
+final class Capture {
+ let sink: FrameSink
+ private var stream: SCStream?
+ private(set) var display: CGDirectDisplayID
+ /// Region to stream, in display points; `nil` = the whole display.
+ private var crop: CGRect?
+ /// Largest frame the viewer can use, in pixels (long edge, short edge).
+ private var limit = (long: 2560.0, short: 1600.0)
+
+ init(display: CGDirectDisplayID, source: RTCVideoSource) {
+ self.display = display
+ sink = FrameSink(source: source)
+ }
+
+ func start() async throws {
+ let s = SCStream(filter: try await Self.filter(display), configuration: configuration(), delegate: nil)
+ try s.addStreamOutput(sink, type: .screen, sampleHandlerQueue: sink.queue)
+ try await s.startCapture()
+ stream = s
+ }
+
+ func stop() async {
+ sink.stop()
+ try? await stream?.stopCapture()
+ stream = nil
+ }
+
+ /// What the phone wants to see: display, region and its viewport size.
+ /// Returns what's streamed from now on.
+ @discardableResult
+ func view(display: CGDirectDisplayID?, crop: CGRect?, long: Double?, short: Double?) async throws -> (display: CGDirectDisplayID, crop: CGRect?) {
+ if let long, let short, long > 0, short > 0 {
+ limit = (min(long, 3840), min(short, 2160))
+ }
+ self.crop = crop.map { $0.intersection(CGRect(origin: .zero, size: CGDisplayBounds(display ?? self.display).size)) }
+ .flatMap { $0.width >= 16 && $0.height >= 16 ? $0 : nil }
+ if let display, display != self.display {
+ self.display = display
+ try await stream?.updateContentFilter(try await Self.filter(display))
+ }
+ try await stream?.updateConfiguration(configuration())
+ return (self.display, self.crop)
+ }
+
+ private func configuration() -> SCStreamConfiguration {
+ let c = SCStreamConfiguration()
+ let region = crop ?? CGRect(origin: .zero, size: CGDisplayBounds(display).size)
+ let scale = Self.backingScale(display)
+ let w = region.width * scale, h = region.height * scale
+ let fit = min(1, limit.long / max(w, h), limit.short / min(w, h))
+ // 4:2:0 needs even sizes.
+ c.width = max(2, Int(w * fit / 2) * 2)
+ c.height = max(2, Int(h * fit / 2) * 2)
+ if crop != nil { c.sourceRect = region }
+ c.minimumFrameInterval = CMTime(value: 1, timescale: 60)
+ c.pixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
+ c.colorMatrix = CGDisplayStream.yCbCrMatrix_ITU_R_709_2
+ c.showsCursor = true
+ c.queueDepth = 6
+ return c
+ }
+
+ static func backingScale(_ display: CGDirectDisplayID) -> Double {
+ let points = CGDisplayBounds(display).width
+ guard points > 0, let mode = CGDisplayCopyDisplayMode(display) else { return 2 }
+ return Double(mode.pixelWidth) / points
+ }
+
+ /// The display without our own windows (the "viewing" badge).
+ static func filter(_ display: CGDirectDisplayID) async throws -> SCContentFilter {
+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
+ guard let d = content.displays.first(where: { $0.displayID == display }) else {
+ throw HelperError("That display isn't connected anymore.")
+ }
+ let own = content.applications.filter { $0.processID == getpid() }
+ return SCContentFilter(display: d, excludingApplications: own, exceptingWindows: [])
+ }
+
+ /// A still for agents: exactly `width`×`height`, JPEG, base64.
+ static func screenshot(display: CGDirectDisplayID, width: Int, height: Int) async throws -> String {
+ let cfg = SCStreamConfiguration()
+ cfg.width = width
+ cfg.height = height
+ cfg.showsCursor = true
+ let image = try await SCScreenshotManager.captureImage(contentFilter: try await filter(display), configuration: cfg)
+ let data = NSMutableData()
+ guard let dest = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil) else {
+ throw HelperError("Couldn't encode the screenshot.")
+ }
+ CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: 0.8] as CFDictionary)
+ guard CGImageDestinationFinalize(dest) else { throw HelperError("Couldn't encode the screenshot.") }
+ return (data as Data).base64EncodedString()
+ }
+}
diff --git a/apps/screen/HostLink.swift b/apps/screen/HostLink.swift
new file mode 100644
index 00000000..e499ac6f
--- /dev/null
+++ b/apps/screen/HostLink.swift
@@ -0,0 +1,116 @@
+import Foundation
+import Network
+
+struct HelperError: LocalizedError {
+ let errorDescription: String?
+ init(_ message: String) { errorDescription = message }
+}
+
+/// JSON-RPC 2.0, one message per line, over the host's `~/.codync/screen.sock`.
+/// The host sends requests; we answer them and send notifications. Reconnects forever.
+@MainActor
+final class HostLink {
+ typealias Handler = @MainActor (_ method: String, _ params: [String: Any]) async throws -> Any
+
+ /// Answers the host's requests.
+ var handler: Handler?
+ private var connection: NWConnection?
+ private var buffer = Data()
+ private(set) var isConnected = false
+ /// Runs on every (re)connect: the host forgets us when we drop.
+ var onConnect: (@MainActor () -> Void)?
+
+ static var socketPath: String {
+ let base = ProcessInfo.processInfo.environment["CODYNC_HOME"] ?? NSHomeDirectory() + "/.codync"
+ return base + "/screen.sock"
+ }
+
+ func start() {
+ let c = NWConnection(to: .unix(path: Self.socketPath), using: .tcp)
+ connection = c
+ c.stateUpdateHandler = { [weak self] state in
+ MainActor.assumeIsolated { self?.changed(state, of: c) }
+ }
+ c.start(queue: .main)
+ }
+
+ private func changed(_ state: NWConnection.State, of c: NWConnection) {
+ guard c === connection else { return }
+ switch state {
+ case .ready:
+ isConnected = true
+ buffer = Data()
+ receive(on: c)
+ onConnect?()
+ case .waiting, .failed:
+ // The host isn't running (yet): try again shortly.
+ drop(c)
+ default:
+ break
+ }
+ }
+
+ private func drop(_ c: NWConnection) {
+ guard c === connection else { return }
+ isConnected = false
+ connection = nil
+ c.stateUpdateHandler = nil
+ c.cancel()
+ Task { [weak self] in
+ try? await Task.sleep(for: .seconds(2))
+ self?.start()
+ }
+ }
+
+ private func receive(on c: NWConnection) {
+ c.receive(minimumIncompleteLength: 1, maximumLength: 1 << 20) { [weak self] data, _, done, error in
+ MainActor.assumeIsolated {
+ guard let self, c === self.connection else { return }
+ if let data {
+ self.buffer.append(data)
+ self.drain()
+ }
+ if done || error != nil {
+ self.drop(c)
+ } else {
+ self.receive(on: c)
+ }
+ }
+ }
+ }
+
+ private func drain() {
+ while let nl = buffer.firstIndex(of: 0x0A) {
+ let line = buffer[buffer.startIndex..<nl]
+ buffer.removeSubrange(buffer.startIndex...nl)
+ guard let msg = (try? JSONSerialization.jsonObject(with: line)) as? [String: Any],
+ let method = msg["method"] as? String
+ else { continue }
+ let id = msg["id"].map { "\($0)" }
+ let params = msg["params"] as? [String: Any] ?? [:]
+ Task { await self.run(method, params, id: id) }
+ }
+ }
+
+ private func run(_ method: String, _ params: [String: Any], id: String?) async {
+ do {
+ guard let handler else { throw HelperError("not ready") }
+ let result = try await handler(method, params)
+ if let id { send(["jsonrpc": "2.0", "id": Int(id) ?? 0, "result": result]) }
+ } catch {
+ if let id {
+ send(["jsonrpc": "2.0", "id": Int(id) ?? 0, "error": ["code": -32000, "message": error.localizedDescription]])
+ }
+ }
+ }
+
+ func notify(_ method: String, _ params: [String: Any]) {
+ send(["jsonrpc": "2.0", "method": method, "params": params])
+ }
+
+ private func send(_ msg: [String: Any]) {
+ guard let connection, isConnected, var data = try? JSONSerialization.data(withJSONObject: msg) else { return }
+ data.append(0x0A)
+ connection.send(content: data, completion: .contentProcessed { _ in })
+ }
+}
diff --git a/apps/screen/Input.swift b/apps/screen/Input.swift
new file mode 100644
index 00000000..0b37eb56
--- /dev/null
+++ b/apps/screen/Input.swift
@@ -0,0 +1,199 @@
+import AppKit
+import Carbon.HIToolbox
+import CoreGraphics
+
+/// Posts mouse and keyboard events. Coordinates are display-local points.
+/// Event JSON is shared by the host (bots) and the phone's data channels:
+/// `move`, `down`/`up`, `click`, `drag`, `scroll`, `text`, `key` (see `host/src/screen.rs`).
+@MainActor
+final class InputInjector {
+ private let source = CGEventSource(stateID: .hidSystemState)
+ /// Button held by a phone drag (`down` … `up`).
+ private var held: CGMouseButton?
+ private var heldFlags: CGEventFlags = []
+
+ func perform(_ e: [String: Any], display: CGDirectDisplayID) async throws {
+ guard AXIsProcessTrusted() else {
+ throw HelperError("Codync Screen isn't allowed to control this computer yet. Allow it under Privacy & Security → Accessibility.")
+ }
+ let origin = CGDisplayBounds(display).origin
+ func point() throws -> CGPoint {
+ guard let x = Self.number(e["x"]), let y = Self.number(e["y"]) else { throw HelperError("x and y are required") }
+ return CGPoint(x: origin.x + x, y: origin.y + y)
+ }
+ let button = Self.button(e["button"])
+ let flags = Self.flags(e["modifiers"])
+ switch e["type"] as? String {
+ case "move":
+ let p = try point()
+ if let held {
+ post(mouse: Self.dragType(held), at: p, button: held, flags: heldFlags)
+ } else {
+ post(mouse: .mouseMoved, at: p, button: .left, flags: [])
+ }
+ case "down":
+ let p = try point()
+ held = button
+ heldFlags = flags
+ post(mouse: Self.downType(button), at: p, button: button, flags: flags, clicks: Int64(Self.number(e["count"]) ?? 1))
+ case "up":
+ let p = try point()
+ post(mouse: Self.upType(held ?? button), at: p, button: held ?? button, flags: heldFlags, clicks: Int64(Self.number(e["count"]) ?? 1))
+ held = nil
+ heldFlags = []
+ case "click":
+ let p = try point()
+ post(mouse: .mouseMoved, at: p, button: .left, flags: [])
+ let count = max(1, min(3, Int(Self.number(e["count"]) ?? 1)))
+ for i in 1...count {
+ post(mouse: Self.downType(button), at: p, button: button, flags: flags, clicks: Int64(i))
+ post(mouse: Self.upType(button), at: p, button: button, flags: flags, clicks: Int64(i))
+ }
+ case "drag":
+ let from = try point()
+ guard let tx = Self.number(e["toX"]), let ty = Self.number(e["toY"]) else { throw HelperError("toX and toY are required") }
+ let to = CGPoint(x: origin.x + tx, y: origin.y + ty)
+ post(mouse: .mouseMoved, at: from, button: .left, flags: [])
+ post(mouse: .leftMouseDown, at: from, button: .left, flags: [])
+ // Apps need intermediate moves (and a little time) to recognize a drag.
+ let steps = 20
+ for i in 1...steps {
+ try await Task.sleep(for: .milliseconds(15))
+ let t = Double(i) / Double(steps)
+ post(mouse: .leftMouseDragged, at: CGPoint(x: from.x + (to.x - from.x) * t, y: from.y + (to.y - from.y) * t), button: .left, flags: [])
+ }
+ post(mouse: .leftMouseUp, at: to, button: .left, flags: [])
+ case "scroll":
+ let p = try point()
+ post(mouse: .mouseMoved, at: p, button: .left, flags: [])
+ let pixels = (e["units"] as? String) == "pixel"
+ let dy = Int32((Self.number(e["dy"]) ?? 0).rounded()), dx = Int32((Self.number(e["dx"]) ?? 0).rounded())
+ // Positive dy scrolls content down, which is a negative wheel delta.
+ CGEvent(scrollWheelEvent2Source: source, units: pixels ? .pixel : .line, wheelCount: 2, wheel1: -dy, wheel2: -dx, wheel3: 0)?
+ .post(tap: .cghidEventTap)
+ case "text":
+ type(e["text"] as? String ?? "")
+ case "key":
+ guard let name = e["key"] as? String, let code = Self.keyCode(name) else {
+ throw HelperError("unknown key \(e["key"] ?? "")")
+ }
+ for down in [true, false] {
+ let ev = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down)
+ ev?.flags = flags
+ ev?.post(tap: .cghidEventTap)
+ }
+ default:
+ throw HelperError("unknown input \(e["type"] ?? "")")
+ }
+ }
+
+ private func post(mouse type: CGEventType, at p: CGPoint, button: CGMouseButton, flags: CGEventFlags, clicks: Int64 = 1) {
+ guard let ev = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: p, mouseButton: button) else { return }
+ ev.flags = flags
+ if type != .mouseMoved { ev.setIntegerValueField(.mouseEventClickState, value: clicks) }
+ ev.post(tap: .cghidEventTap)
+ }
+
+ /// Any Unicode, independent of the keyboard layout.
+ private func type(_ text: String) {
+ let units = Array(text.utf16)
+ // The unicode payload of one key event is capped at 20 UTF-16 units.
+ for start in stride(from: 0, to: units.count, by: 16) {
+ let chunk = Array(units[start..<min(start + 16, units.count)])
+ for down in [true, false] {
+ let ev = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: down)
+ chunk.withUnsafeBufferPointer { ev?.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: $0.baseAddress) }
+ ev?.post(tap: .cghidEventTap)
+ }
+ }
+ }
+
+ // MARK: mapping
+
+ static func number(_ v: Any?) -> Double? { (v as? NSNumber)?.doubleValue }
+
+ static func button(_ v: Any?) -> CGMouseButton {
+ switch v as? String {
+ case "right": .right
+ case "middle": .center
+ default: .left
+ }
+ }
+
+ static func flags(_ v: Any?) -> CGEventFlags {
+ var f: CGEventFlags = []
+ for m in v as? [String] ?? [] {
+ switch m {
+ case "cmd": f.insert(.maskCommand)
+ case "option": f.insert(.maskAlternate)
+ case "ctrl": f.insert(.maskControl)
+ case "shift": f.insert(.maskShift)
+ default: break
+ }
+ }
+ return f
+ }
+
+ static func downType(_ b: CGMouseButton) -> CGEventType {
+ switch b {
+ case .left: .leftMouseDown
+ case .right: .rightMouseDown
+ default: .otherMouseDown
+ }
+ }
+
+ static func upType(_ b: CGMouseButton) -> CGEventType {
+ switch b {
+ case .left: .leftMouseUp
+ case .right: .rightMouseUp
+ default: .otherMouseUp
+ }
+ }
+
+ static func dragType(_ b: CGMouseButton) -> CGEventType {
+ switch b {
+ case .left: .leftMouseDragged
+ case .right: .rightMouseDragged
+ default: .otherMouseDragged
+ }
+ }
+
+ private static let named: [String: Int] = [
+ "return": kVK_Return, "tab": kVK_Tab, "space": kVK_Space, "escape": kVK_Escape,
+ "delete": kVK_Delete, "forwardDelete": kVK_ForwardDelete,
+ "left": kVK_LeftArrow, "right": kVK_RightArrow, "up": kVK_UpArrow, "down": kVK_DownArrow,
+ "home": kVK_Home, "end": kVK_End, "pageUp": kVK_PageUp, "pageDown": kVK_PageDown,
+ "f1": kVK_F1, "f2": kVK_F2, "f3": kVK_F3, "f4": kVK_F4, "f5": kVK_F5, "f6": kVK_F6,
+ "f7": kVK_F7, "f8": kVK_F8, "f9": kVK_F9, "f10": kVK_F10, "f11": kVK_F11, "f12": kVK_F12,
+ ]
+
+ /// Named keys, else the key that types `name` on the current keyboard layout
+ /// (so ⌘Z is ⌘Z on AZERTY too).
+ static func keyCode(_ name: String) -> CGKeyCode? {
+ if let code = named[name] { return CGKeyCode(code) }
+ guard name.count == 1 else { return nil }
+ return layoutCodes()[name.lowercased()]
+ }
+
+ private static func layoutCodes() -> [String: CGKeyCode] {
+ var map: [String: CGKeyCode] = [:]
+ guard let source = TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(),
+ let raw = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData)
+ else { return map }
+ let data = Unmanaged<CFData>.fromOpaque(raw).takeUnretainedValue() as Data
+ data.withUnsafeBytes { bytes in
+ guard let layout = bytes.baseAddress?.assumingMemoryBound(to: UCKeyboardLayout.self) else { return }
+ for code in 0..<128 {
+ var dead: UInt32 = 0
+ var chars = [UniChar](repeating: 0, count: 4)
+ var length = 0
+ let status = UCKeyTranslate(layout, UInt16(code), UInt16(kUCKeyActionDown), 0, UInt32(LMGetKbdType()),
+ OptionBits(kUCKeyTranslateNoDeadKeysMask), &dead, chars.count, &length, &chars)
+ guard status == noErr, length > 0 else { continue }
+ let s = String(utf16CodeUnits: chars, count: length).lowercased()
+ if map[s] == nil { map[s] = CGKeyCode(code) }
+ }
+ }
+ return map
+ }
+}
diff --git a/apps/screen/ScreenHelper.swift b/apps/screen/ScreenHelper.swift
new file mode 100644
index 00000000..c8b9e05f
--- /dev/null
+++ b/apps/screen/ScreenHelper.swift
@@ -0,0 +1,175 @@
+import AppKit
+import ApplicationServices
+import CoreGraphics
+
+/// Serves the host's screen requests (see `host/src/screen.rs` for the protocol).
+@MainActor
+final class ScreenHelper {
+ private let link = HostLink()
+ let input = InputInjector()
+ private var sessions: [String: Session] = [:]
+ private let badge = ViewingBadge()
+ private var lastStatus: [String: AnyHashable] = [:]
+
+ init() {
+ link.handler = { [unowned self] method, params in try await self.handle(method, params) }
+ link.onConnect = { [unowned self] in
+ // The host lost every session when we dropped.
+ closeAll()
+ lastStatus = [:]
+ sendStatus()
+ }
+ badge.onDisconnect = { [unowned self] in closeAll() }
+ }
+
+ func start() {
+ let captureAtLaunch = CGPreflightScreenCaptureAccess()
+ if !captureAtLaunch { CGRequestScreenCaptureAccess() }
+ // `kAXTrustedCheckOptionPrompt` is a C global Swift 6 won't read; its value is this string.
+ _ = AXIsProcessTrustedWithOptions(["AXTrustedCheckOptionPrompt": true] as CFDictionary)
+ link.start()
+ NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated { self?.sendStatus() }
+ }
+ // Permission grants don't notify: poll, cheaply, and report changes.
+ Task { [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(3))
+ self?.sendStatus()
+ // A process keeps the screen-recording answer it saw at launch, so a grant made
+ // while we run never shows up here. Ask a fresh process; once it's granted, quit
+ // and let launchd (KeepAlive) start us again with capture working.
+ if !captureAtLaunch, await Self.captureGrantedNow() {
+ self?.closeAll()
+ exit(0)
+ }
+ }
+ }
+ }
+
+ private func handle(_ method: String, _ p: [String: Any]) async throws -> Any {
+ switch method {
+ case "answer":
+ guard let id = p["session"] as? String, let sdp = p["sdp"] as? String else { throw HelperError("session and sdp are required") }
+ if let s = sessions[id] { return ["sdp": try await s.answer(offer: sdp)] }
+ let s = Session(id: id, display: display(p["display"]), helper: self)
+ sessions[id] = s
+ do {
+ let answer = try await s.answer(offer: sdp)
+ badge.update(viewers: sessions.count)
+ return ["sdp": answer]
+ } catch {
+ sessions[id] = nil
+ s.close()
+ throw error
+ }
+ case "close":
+ if let id = p["session"] as? String, let s = sessions.removeValue(forKey: id) {
+ s.close()
+ badge.update(viewers: sessions.count)
+ }
+ return [String: Any]()
+ case "closeAll":
+ closeAll()
+ return [String: Any]()
+ case "screenshot":
+ guard let w = InputInjector.number(p["width"]), let h = InputInjector.number(p["height"]) else { throw HelperError("width and height are required") }
+ return ["data": try await Capture.screenshot(display: display(p["display"]), width: Int(w), height: Int(h))]
+ case "input":
+ guard let event = p["event"] as? [String: Any] else { throw HelperError("event is required") }
+ try await input.perform(event, display: display(p["display"]))
+ return [String: Any]()
+ case "uiTree":
+ return try AXTree.frontmost(display: display(p["display"]))
+ case "openApp":
+ guard let name = p["name"] as? String, !name.isEmpty else { throw HelperError("name is required") }
+ try await openApp(name)
+ return [String: Any]()
+ default:
+ throw HelperError("unknown method \(method)")
+ }
+ }
+
+ func sessionEnded(_ id: String) {
+ guard let s = sessions.removeValue(forKey: id) else { return }
+ s.close()
+ badge.update(viewers: sessions.count)
+ link.notify("session", ["session": id, "state": "closed"])
+ }
+
+ private func closeAll() {
+ for (id, s) in sessions {
+ s.close()
+ link.notify("session", ["session": id, "state": "closed"])
+ }
+ sessions = [:]
+ badge.update(viewers: 0)
+ }
+
+ /// Runs this binary with `--probe-capture`: a new process reads the current grant.
+ private static func captureGrantedNow() async -> Bool {
+ guard let exe = Bundle.main.executableURL else { return false }
+ let p = Process()
+ p.executableURL = exe
+ p.arguments = ["--probe-capture"]
+ return await withCheckedContinuation { c in
+ p.terminationHandler = { c.resume(returning: $0.terminationStatus == 0) }
+ do { try p.run() } catch { c.resume(returning: false) }
+ }
+ }
+
+ private func display(_ v: Any?) -> CGDirectDisplayID {
+ (v as? NSNumber)?.uint32Value ?? CGMainDisplayID()
+ }
+
+ private func openApp(_ name: String) async throws {
+ let p = Process()
+ p.executableURL = URL(filePath: "/usr/bin/open")
+ p.arguments = ["-a", name]
+ let err = Pipe()
+ p.standardError = err
+ try p.run()
+ await withCheckedContinuation { c in p.terminationHandler = { _ in c.resume() } }
+ guard p.terminationStatus == 0 else { throw HelperError("Couldn't find an app named \(name).") }
+ }
+
+ // MARK: status
+
+ private func sendStatus() {
+ var ids = [CGDirectDisplayID](repeating: 0, count: 16)
+ var count: UInt32 = 0
+ CGGetActiveDisplayList(UInt32(ids.count), &ids, &count)
+ let main = CGMainDisplayID()
+ let displays: [[String: AnyHashable]] = ids.prefix(Int(count)).map { id in
+ let b = CGDisplayBounds(id)
+ let name = NSScreen.screens.first { ($0.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value == id }?.localizedName
+ return ["id": Int(id), "name": name ?? "Display", "width": b.width, "height": b.height, "main": id == main]
+ }
+ let status: [String: AnyHashable] = [
+ "platform": "macos",
+ "version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "",
+ "displays": displays,
+ "capture": CGPreflightScreenCaptureAccess(),
+ "input": AXIsProcessTrusted(),
+ ]
+ guard status != lastStatus, link.isConnected else { return }
+ lastStatus = status
+ link.notify("status", status)
+ }
+}
+
+@main
+enum ScreenHelperMain {
+ @MainActor static var helper: ScreenHelper?
+
+ @MainActor
+ static func main() {
+ if CommandLine.arguments.contains("--probe-capture") { exit(CGPreflightScreenCaptureAccess() ? 0 : 1) }
+ let app = NSApplication.shared
+ app.setActivationPolicy(.accessory)
+ let helper = ScreenHelper()
+ Self.helper = helper
+ helper.start()
+ app.run()
+ }
+}
diff --git a/apps/screen/Session.swift b/apps/screen/Session.swift
new file mode 100644
index 00000000..7ff3b72f
--- /dev/null
+++ b/apps/screen/Session.swift
@@ -0,0 +1,254 @@
+import AppKit
+import IOKit.pwr_mgt
+@preconcurrency import WebRTC
+
+/// One phone watching: answers its WebRTC offer, streams a display as H.264,
+/// and applies input from its data channels (`input` reliable, `input-fast` for moves).
+@MainActor
+final class Session: NSObject {
+ static let factory: RTCPeerConnectionFactory = {
+ RTCInitializeSSL()
+ return RTCPeerConnectionFactory(encoderFactory: ScreenEncoderFactory(), decoderFactory: RTCDefaultVideoDecoderFactory())
+ }()
+
+ let id: String
+ private weak var helper: ScreenHelper?
+ private var pc: RTCPeerConnection?
+ private let track: RTCVideoTrack
+ private let capture: Capture
+ private var channels: [RTCDataChannel] = []
+ private var gathered: CheckedContinuation<Void, Never>?
+ private var capturing = false
+ private var awake: IOPMAssertionID = 0
+ private var clipboardCount = NSPasteboard.general.changeCount
+ private var clipboardTask: Task<Void, Never>?
+
+ var display: CGDirectDisplayID { capture.display }
+
+ init(id: String, display: CGDirectDisplayID, helper: ScreenHelper) {
+ self.id = id
+ self.helper = helper
+ let source = Self.factory.videoSource(forScreenCast: true)
+ track = Self.factory.videoTrack(with: source, trackId: "screen")
+ capture = Capture(display: display, source: source)
+ super.init()
+ let config = RTCConfiguration()
+ config.sdpSemantics = .unifiedPlan
+ // No STUN/TURN: the phone already reaches this computer (LAN / Tailscale), so host
+ // candidates connect; TCP candidates cover networks that drop UDP.
+ config.iceServers = []
+ config.tcpCandidatePolicy = .enabled
+ config.continualGatheringPolicy = .gatherOnce
+ config.bundlePolicy = .maxBundle
+ pc = Self.factory.peerConnection(with: config, constraints: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil), delegate: self)
+ }
+
+ /// Answers the phone's offer (first connect or an ICE restart). Non-trickle: waits
+ /// for local candidates so the answer carries them all.
+ func answer(offer: String) async throws -> String {
+ guard let pc else { throw HelperError("session closed") }
+ try await pc.setRemoteDescription(RTCSessionDescription(type: .offer, sdp: offer))
+ if !capturing, let video = pc.transceivers.first(where: { $0.mediaType == .video }) {
+ video.sender.track = track
+ video.sender.streamIds = ["screen"]
+ var error: NSError?
+ video.setDirection(.sendOnly, error: &error)
+ if let error { throw error }
+ }
+ let answer = try await pc.answer(for: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil))
+ try await pc.setLocalDescription(answer)
+ await waitForCandidates()
+ if !capturing {
+ tune()
+ try await capture.start()
+ capturing = true
+ keepAwake(true)
+ watchClipboard()
+ }
+ return pc.localDescription?.sdp ?? answer.sdp
+ }
+
+ /// Screen content: keep text sharp (drop frames before resolution), allow a high bitrate on fast links.
+ private func tune() {
+ guard let sender = pc?.transceivers.first(where: { $0.mediaType == .video })?.sender else { return }
+ let p = sender.parameters
+ p.degradationPreference = NSNumber(value: RTCDegradationPreference.maintainResolution.rawValue)
+ for e in p.encodings {
+ e.maxBitrateBps = 16_000_000
+ e.maxFramerate = 60
+ e.networkPriority = .high
+ }
+ sender.parameters = p
+ }
+
+ private func waitForCandidates() async {
+ guard pc?.iceGatheringState != .complete else { return }
+ Task {
+ try? await Task.sleep(for: .seconds(3))
+ self.finishGathering()
+ }
+ await withCheckedContinuation { gathered = $0 }
+ }
+
+ private func finishGathering() {
+ gathered?.resume()
+ gathered = nil
+ }
+
+ func close() {
+ finishGathering()
+ clipboardTask?.cancel()
+ keepAwake(false)
+ channels.forEach { $0.close() }
+ channels = []
+ pc?.close()
+ pc = nil
+ let capture = capture
+ Task { await capture.stop() }
+ }
+
+ // MARK: display wake
+
+ private func keepAwake(_ on: Bool) {
+ if on {
+ // Wake a sleeping display, then keep it on while someone watches.
+ var activity: IOPMAssertionID = 0
+ IOPMAssertionDeclareUserActivity("Codync remote screen" as CFString, kIOPMUserActiveLocal, &activity)
+ IOPMAssertionCreateWithName(kIOPMAssertionTypePreventUserIdleDisplaySleep as CFString,
+ IOPMAssertionLevel(kIOPMAssertionLevelOn), "Codync remote screen" as CFString, &awake)
+ } else if awake != 0 {
+ IOPMAssertionRelease(awake)
+ awake = 0
+ }
+ }
+
+ // MARK: clipboard
+
+ private func watchClipboard() {
+ clipboardTask = Task { [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(1))
+ self?.checkClipboard()
+ }
+ }
+ }
+
+ private func checkClipboard() {
+ let pb = NSPasteboard.general
+ guard pb.changeCount != clipboardCount else { return }
+ clipboardCount = pb.changeCount
+ if let text = pb.string(forType: .string), text.utf8.count <= 256 * 1024 {
+ send(["type": "clipboard", "text": text])
+ }
+ }
+
+ private func send(_ msg: [String: Any]) {
+ guard let data = try? JSONSerialization.data(withJSONObject: msg),
+ let channel = channels.first(where: { $0.label == "input" && $0.readyState == .open })
+ else { return }
+ channel.sendData(RTCDataBuffer(data: data, isBinary: false))
+ }
+
+ // MARK: messages from the phone
+
+ private func received(_ data: Data) {
+ guard let msg = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return }
+ switch msg["type"] as? String {
+ case "clipboard":
+ guard let text = msg["text"] as? String else { return }
+ let pb = NSPasteboard.general
+ pb.clearContents()
+ pb.setString(text, forType: .string)
+ clipboardCount = pb.changeCount
+ case "view":
+ let display = (msg["display"] as? NSNumber)?.uint32Value
+ let crop = (msg["crop"] as? [NSNumber]).flatMap { c in
+ c.count == 4 ? CGRect(x: c[0].doubleValue, y: c[1].doubleValue, width: c[2].doubleValue, height: c[3].doubleValue) : nil
+ }
+ let capture = capture
+ Task {
+ do {
+ let applied = try await capture.view(display: display, crop: crop, long: InputInjector.number(msg["long"]), short: InputInjector.number(msg["short"]))
+ // Frames from here on show this region: the phone re-aligns its view on this.
+ let region: Any = applied.crop.map { [$0.minX, $0.minY, $0.width, $0.height] } ?? NSNull()
+ self.send(["type": "view", "display": applied.display, "crop": region])
+ } catch {
+ self.send(["type": "error", "message": error.localizedDescription])
+ }
+ }
+ default:
+ guard let helper else { return }
+ let display = self.display
+ Task {
+ do {
+ try await helper.input.perform(msg, display: display)
+ } catch {
+ self.send(["type": "error", "message": error.localizedDescription])
+ }
+ }
+ }
+ }
+
+ private func connectionChanged(_ state: RTCIceConnectionState) {
+ switch state {
+ case .failed, .closed:
+ // `disconnected` can recover (or the phone restarts ICE); `failed` can't.
+ helper?.sessionEnded(id)
+ default:
+ break
+ }
+ }
+
+ private func opened(_ channel: RTCDataChannel) {
+ channel.delegate = self
+ channels.append(channel)
+ }
+}
+
+extension Session: RTCPeerConnectionDelegate, RTCDataChannelDelegate {
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {}
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {}
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {}
+ nonisolated func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {}
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {}
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {}
+
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
+ Task { @MainActor in self.connectionChanged(newState) }
+ }
+
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
+ guard newState == .complete else { return }
+ Task { @MainActor in self.finishGathering() }
+ }
+
+ nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {
+ Task { @MainActor in self.opened(dataChannel) }
+ }
+
+ nonisolated func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {}
+
+ nonisolated func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
+ let data = buffer.data
+ Task { @MainActor in self.received(data) }
+ }
+}
+
+/// The default encoders, except H.264 always runs at level 5.2. WebRTC advertises level 3.1,
+/// which VideoToolbox enforces: anything over 1280×720 fails to encode and WebRTC falls back
+/// to software VP8. Phones decode any level, so only the encoder needs lifting.
+final class ScreenEncoderFactory: NSObject, RTCVideoEncoderFactory {
+ private let base = RTCDefaultVideoEncoderFactory()
+
+ func createEncoder(_ info: RTCVideoCodecInfo) -> (any RTCVideoEncoder)? {
+ guard info.name == kRTCVideoCodecH264Name else { return base.createEncoder(info) }
+ var params = info.parameters
+ let profile = RTCH264ProfileLevelId(hexString: params["profile-level-id"] ?? kRTCLevel31ConstrainedBaseline)?.profile ?? .constrainedBaseline
+ params["profile-level-id"] = RTCH264ProfileLevelId(profile: profile, level: .level5_2).hexString
+ return RTCVideoEncoderH264(codecInfo: RTCVideoCodecInfo(name: info.name, parameters: params))
+ }
+
+ func supportedCodecs() -> [RTCVideoCodecInfo] {
+ base.supportedCodecs()
+ }
+}
diff --git a/apps/screen/ViewingBadge.swift b/apps/screen/ViewingBadge.swift
new file mode 100644
index 00000000..ceb70e8e
--- /dev/null
+++ b/apps/screen/ViewingBadge.swift
@@ -0,0 +1,90 @@
+import AppKit
+import SwiftUI
+
+/// A small always-on-top pill while a phone is watching, so it's never a secret;
+/// its button disconnects every viewer. Black and white like the rest of Codync.
+@MainActor
+final class ViewingBadge {
+ var onDisconnect: (() -> Void)?
+ private var panel: NSPanel?
+ private let model = BadgeModel()
+
+ func update(viewers: Int) {
+ guard viewers > 0 else {
+ panel?.orderOut(nil)
+ return
+ }
+ model.viewers = viewers
+ let panel = panel ?? makePanel()
+ self.panel = panel
+ // Measure after SwiftUI has laid out the new text, or the pill gets clipped.
+ panel.contentView?.layoutSubtreeIfNeeded()
+ let size = panel.contentView?.fittingSize ?? NSSize(width: 220, height: 34)
+ if let screen = NSScreen.main {
+ let f = screen.visibleFrame
+ panel.setFrame(NSRect(x: f.midX - size.width / 2, y: f.maxY - size.height - 10, width: size.width, height: size.height), display: true)
+ }
+ panel.orderFrontRegardless()
+ }
+
+ private func makePanel() -> NSPanel {
+ let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 220, height: 30), styleMask: [.nonactivatingPanel, .borderless], backing: .buffered, defer: false)
+ panel.level = .statusBar
+ panel.collectionBehavior = [.canJoinAllSpaces, .stationary, .fullScreenAuxiliary]
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = false
+ let host = NSHostingView(rootView: BadgeView(model: model) { [weak self] in self?.onDisconnect?() })
+ host.sizingOptions = [.intrinsicContentSize]
+ host.wantsLayer = true
+ host.layer?.backgroundColor = .clear
+ panel.contentView = host
+ return panel
+ }
+}
+
+@MainActor
+@Observable
+private final class BadgeModel {
+ var viewers = 1
+}
+
+private struct BadgeView: View {
+ let model: BadgeModel
+ let disconnect: () -> Void
+ @State private var pulse = false
+ @State private var hovering = false
+
+ var body: some View {
+ HStack(spacing: 8) {
+ // A live dot, like the system's recording indicator.
+ Circle()
+ .fill(Color.white)
+ .frame(width: 7, height: 7)
+ .opacity(pulse ? 0.35 : 1)
+ .animation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true), value: pulse)
+ .onAppear { pulse = true }
+ Text(model.viewers == 1 ? "iPhone is viewing" : "\(model.viewers) viewers")
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(.white)
+ Button(action: disconnect) {
+ Image(systemName: "xmark")
+ .font(.system(size: 9, weight: .bold))
+ .foregroundStyle(.white.opacity(hovering ? 1 : 0.7))
+ .frame(width: 18, height: 18)
+ .background(Circle().fill(.white.opacity(hovering ? 0.22 : 0.12)))
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering = $0 }
+ .help("Disconnect")
+ .accessibilityLabel("Disconnect")
+ }
+ .padding(.leading, 12)
+ .padding(.trailing, 5)
+ .padding(.vertical, 5)
+ .background(Capsule().fill(Color.black.opacity(0.88)))
+ .overlay(Capsule().strokeBorder(.white.opacity(0.14), lineWidth: 0.5))
+ .fixedSize()
+ .padding(2)
+ }
+}
diff --git a/host/Cargo.lock b/host/Cargo.lock
index 394f01bd..4e46f00a 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -11,6 +11,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
[[package]]
name = "anstream"
version = "1.0.0"
@@ -67,12 +73,27 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
[[package]]
name = "aws-lc-rs"
version = "1.18.1"
@@ -175,12 +196,27 @@ version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+[[package]]
+name = "by_address"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
+
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+[[package]]
+name = "castaway"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
+dependencies = [
+ "rustversion",
+]
+
[[package]]
name = "cc"
version = "1.4.7"
@@ -267,16 +303,18 @@ dependencies = [
[[package]]
name = "codync-host"
-version = "2.0.0"
+version = "2.1.0"
dependencies = [
"anyhow",
"axum",
"clap",
+ "crossterm",
"dirs",
"futures",
"gethostname",
"if-addrs",
"qrcode",
+ "ratatui",
"reqwest",
"rusqlite",
"serde",
@@ -286,6 +324,7 @@ dependencies = [
"tokio-stream",
"tracing",
"tracing-subscriber",
+ "unicode-width",
"uuid",
]
@@ -305,12 +344,35 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "compact_str"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"
+dependencies = [
+ "castaway",
+ "cfg-if",
+ "itoa",
+ "rustversion",
+ "ryu",
+ "static_assertions",
+]
+
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+[[package]]
+name = "convert_case"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
+dependencies = [
+ "unicode-segmentation",
+]
+
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -336,6 +398,34 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crossterm"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
+dependencies = [
+ "bitflags",
+ "crossterm_winapi",
+ "derive_more",
+ "document-features",
+ "futures-core",
+ "mio",
+ "parking_lot",
+ "rustix",
+ "signal-hook",
+ "signal-hook-mio",
+ "winapi",
+]
+
+[[package]]
+name = "crossterm_winapi"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "crypto-common"
version = "0.2.2"
@@ -345,6 +435,68 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "darling"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
+dependencies = [
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+
+[[package]]
+name = "derive_more"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
+dependencies = [
+ "convert_case",
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn 2.0.119",
+]
+
[[package]]
name = "digest"
version = "0.11.3"
@@ -388,12 +540,27 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
[[package]]
name = "dunce"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+[[package]]
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -580,6 +747,8 @@ version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
+ "allocator-api2",
+ "equivalent",
"foldhash",
]
@@ -589,6 +758,8 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
+ "allocator-api2",
+ "equivalent",
"foldhash",
]
@@ -804,6 +975,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
[[package]]
name = "idna"
version = "1.1.0"
@@ -845,6 +1022,28 @@ dependencies = [
"hashbrown 0.17.1",
]
+[[package]]
+name = "indoc"
+version = "2.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
+dependencies = [
+ "rustversion",
+]
+
+[[package]]
+name = "instability"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20"
+dependencies = [
+ "darling",
+ "indoc",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -857,6 +1056,15 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.18"
@@ -933,6 +1141,17 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "kasuari"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899"
+dependencies = [
+ "hashbrown 0.16.1",
+ "portable-atomic",
+ "thiserror",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -945,6 +1164,12 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
[[package]]
name = "libredox"
version = "0.1.25"
@@ -965,6 +1190,15 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "line-clipping"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e"
+dependencies = [
+ "bitflags",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -977,6 +1211,12 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+[[package]]
+name = "litrs"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
+
[[package]]
name = "lock_api"
version = "0.4.14"
@@ -992,6 +1232,15 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+[[package]]
+name = "lru"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5"
+dependencies = [
+ "hashbrown 0.17.1",
+]
+
[[package]]
name = "lru-slab"
version = "0.1.3"
@@ -1032,6 +1281,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
+ "log",
"wasi",
"windows-sys 0.61.2",
]
@@ -1045,6 +1295,30 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num_threads"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -1069,6 +1343,39 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "palette"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64"
+dependencies = [
+ "approx",
+ "libm",
+ "palette_derive",
+ "palette_math",
+]
+
+[[package]]
+name = "palette_derive"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be"
+dependencies = [
+ "by_address",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "palette_math"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12"
+dependencies = [
+ "libm",
+]
+
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -1110,6 +1417,12 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -1119,6 +1432,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "powerfmt"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1232,6 +1551,72 @@ dependencies = [
"rand_core",
]
+[[package]]
+name = "ratatui"
+version = "0.30.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d"
+dependencies = [
+ "instability",
+ "ratatui-core",
+ "ratatui-crossterm",
+ "ratatui-widgets",
+ "serde",
+]
+
+[[package]]
+name = "ratatui-core"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c"
+dependencies = [
+ "bitflags",
+ "compact_str",
+ "hashbrown 0.17.1",
+ "itertools",
+ "kasuari",
+ "lru",
+ "palette",
+ "serde",
+ "strum",
+ "thiserror",
+ "unicode-segmentation",
+ "unicode-truncate",
+ "unicode-width",
+]
+
+[[package]]
+name = "ratatui-crossterm"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0"
+dependencies = [
+ "cfg-if",
+ "crossterm",
+ "instability",
+ "ratatui-core",
+]
+
+[[package]]
+name = "ratatui-widgets"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.17.1",
+ "indoc",
+ "instability",
+ "itertools",
+ "line-clipping",
+ "ratatui-core",
+ "serde",
+ "strum",
+ "time",
+ "unicode-segmentation",
+ "unicode-width",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -1277,6 +1662,7 @@ dependencies = [
"base64",
"bytes",
"futures-core",
+ "futures-util",
"http",
"http-body",
"http-body-util",
@@ -1296,12 +1682,14 @@ dependencies = [
"sync_wrapper",
"tokio",
"tokio-rustls",
+ "tokio-util",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
+ "wasm-streams",
"web-sys",
]
@@ -1605,6 +1993,27 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+[[package]]
+name = "signal-hook"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
+dependencies = [
+ "libc",
+ "signal-hook-registry",
+]
+
+[[package]]
+name = "signal-hook-mio"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
+dependencies = [
+ "libc",
+ "mio",
+ "signal-hook",
+]
+
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -1671,12 +2080,39 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "strum"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -1754,6 +2190,27 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "time"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
+dependencies = [
+ "deranged",
+ "libc",
+ "num-conv",
+ "num_threads",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
[[package]]
name = "tinystr"
version = "0.8.4"
@@ -1959,6 +2416,29 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "unicode-truncate"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"
+dependencies = [
+ "itertools",
+ "unicode-segmentation",
+ "unicode-width",
+]
+
+[[package]]
+name = "unicode-width"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -2092,6 +2572,19 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "wasm-streams"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
[[package]]
name = "web-sys"
version = "0.3.105"
@@ -2121,6 +2614,22 @@ dependencies = [
"rustls-pki-types",
]
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -2130,6 +2639,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
[[package]]
name = "windows-link"
version = "0.2.1"
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 4c050a5c..c14f716e 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "codync-host"
-version = "2.0.0"
+version = "2.1.0"
edition = "2024"
# let-chains (`if let … && let …`) need 1.88.
rust-version = "1.88"
@@ -11,13 +11,15 @@ repository = "https://github.com/leepokai/Codync"
[dependencies]
anyhow = "1.0.104"
axum = "0.8.9"
-clap = { version = "4.6.7", features = ["derive"] }
+clap = { version = "4.6.7", features = ["derive", "env"] }
+crossterm = { version = "0.29", features = ["event-stream"] }
dirs = "7.0.0"
futures = "0.3.34"
gethostname = "1.1.0"
if-addrs = "0.15.0"
qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }
-reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json"] }
+ratatui = { version = "0.30", default-features = false, features = ["crossterm"] }
+reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "stream"] }
rusqlite = { version = "0.40.2", features = ["bundled"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["preserve_order"] }
@@ -26,6 +28,7 @@ tokio = { version = "1.53.1", features = ["full"] }
tokio-stream = { version = "0.1.19", features = ["sync"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
+unicode-width = "0.2"
uuid = { version = "1.26.1", features = ["v4"] }
# rust-skills lint-* rules: all default groups plus pedantic, with the
diff --git a/host/src/api.rs b/host/src/api.rs
index b01294af..f21a028f 100644
--- a/host/src/api.rs
+++ b/host/src/api.rs
@@ -7,7 +7,7 @@ use crate::hub::Hub;
use crate::store::{BotConfig, EntryKind};
use crate::{backends, market, usage};
use anyhow::{Context, Result, anyhow, bail};
-use axum::extract::{Path, Query, State};
+use axum::extract::{ConnectInfo, Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
@@ -17,6 +17,7 @@ use futures::{Stream, StreamExt, stream};
use serde::Deserialize;
use serde_json::{Value, json};
use std::convert::Infallible;
+use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
@@ -76,6 +77,7 @@ async fn statusline(State(hub): State<Arc<Hub>>, headers: HeaderMap, Json(body):
async fn command(
State(hub): State<Arc<Hub>>,
Path(method): Path<String>,
+ ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
body: Option<Json<Value>>,
) -> Result<Json<Value>, ApiError> {
@@ -83,6 +85,13 @@ async fn command(
return Err(ApiError(StatusCode::UNAUTHORIZED, "invalid token".into()));
}
let body = body.map_or(Value::Null, |b| b.0);
+ // Letting phones see and control the screen is decided at the computer, never remotely.
+ if method == "setScreenEnabled" && !peer.ip().is_loopback() {
+ return Err(ApiError(
+ StatusCode::FORBIDDEN,
+ "Remote screen can only be turned on at the computer itself.".into(),
+ ));
+ }
match dispatch(&hub, &method, body).await {
Ok(v) => Ok(Json(v)),
Err(e) if e.is::<UnknownMethod>() => Err(ApiError(StatusCode::NOT_FOUND, e.to_string())),
@@ -97,16 +106,22 @@ fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {
pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
Ok(match method {
- "hello" => json!({
- "hostId": hub.host_id,
- "name": crate::service::host_name(),
- "version": env!("CARGO_PKG_VERSION"),
- "os": std::env::consts::OS,
- "device": tokio::task::spawn_blocking(crate::service::device).await?,
- "home": dirs::home_dir().map(|p| p.to_string_lossy().into_owned()),
- "backends": backends::list(),
- "rev": hub.store.current_rev(),
- }),
+ "hello" => {
+ let port = hub.port;
+ json!({
+ "hostId": hub.host_id,
+ "name": crate::service::host_name(),
+ "version": env!("CARGO_PKG_VERSION"),
+ "os": std::env::consts::OS,
+ "device": tokio::task::spawn_blocking(crate::service::device).await?,
+ "home": dirs::home_dir().map(|p| p.to_string_lossy().into_owned()),
+ "backends": backends::list(),
+ "rev": hub.store.current_rev(),
+ "screen": hub.screen.state(),
+ // Shells out to `tailscale`: keep it off the async workers.
+ "urls": tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?,
+ })
+ }
"sync" => {
let since = b["since"].as_i64().unwrap_or(0);
json!({
@@ -254,6 +269,28 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
market::remove_skill(&hub.store, str_arg(&b, "id")?)?;
json!({})
}
+ "screenStatus" => hub.screen.state(),
+ "screenOffer" => {
+ let display = b["display"].as_u64().and_then(|d| u32::try_from(d).ok());
+ hub.screen.offer(str_arg(&b, "sdp")?, b["session"].as_str(), display).await?
+ }
+ "screenClose" => {
+ hub.screen.close(str_arg(&b, "session")?).await?;
+ json!({})
+ }
+ "screenTakeover" => {
+ hub.screen.takeover(b["on"].as_bool().unwrap_or(false));
+ hub.screen.state()
+ }
+ "setScreenEnabled" => {
+ hub.screen.set_enabled(&hub.store, b["enabled"].as_bool().unwrap_or(false)).await?;
+ hub.screen.state()
+ }
+ "computerCall" => {
+ let tool: crate::screen::ComputerTool =
+ serde_json::from_value(b.clone()).context("invalid computer tool call")?;
+ json!({"content": crate::screen::computer(hub, str_arg(&b, "botId")?, tool).await?})
+ }
_ => return Err(UnknownMethod.into()),
})
}
@@ -333,7 +370,13 @@ async fn events(
catch_up.push(json!({"type": "entry", "rev": e.rev, "entry": e}));
}
catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));
- let hello = json!({"type": "hello", "hostId": hub.host_id, "rev": hub.store.current_rev(), "usage": hub.usage.locked().clone()});
+ let hello = json!({
+ "type": "hello",
+ "hostId": hub.host_id,
+ "rev": hub.store.current_rev(),
+ "usage": hub.usage.locked().clone(),
+ "screen": hub.screen.state(),
+ });
catch_up.insert(0, hello);
let guard = Arc::new((q.client.as_deref() == Some("ios")).then(|| IosClientGuard::new(hub.clone())));
diff --git a/host/src/bot.rs b/host/src/bot.rs
index a15c0ac6..3727d26f 100644
--- a/host/src/bot.rs
+++ b/host/src/bot.rs
@@ -166,7 +166,7 @@ impl Actor {
let cfg = *cfg;
let restart =
cfg.backend != self.cfg.backend || cfg.command != self.cfg.command || cfg.cwd != self.cfg.cwd;
- self.tools_changed |= cfg.connectors != self.cfg.connectors;
+ self.tools_changed |= cfg.connectors != self.cfg.connectors || cfg.computer != self.cfg.computer;
// New skills are announced with the next prompt.
if cfg.skills != self.cfg.skills && self.session_id.is_some() {
self.session_fresh = true;
@@ -293,12 +293,23 @@ impl Actor {
Ok(())
}
- /// ACP `mcpServers` for this bot's connectors.
+ /// ACP `mcpServers` for this bot's connectors, plus the built-in `computer` server.
fn mcp_servers(&self, http_ok: bool) -> Value {
let all = crate::market::connectors(&self.hub.store);
- Value::Array(
- all.iter().filter(|c| self.cfg.connectors.contains(&c.id)).filter_map(|c| c.acp(http_ok)).collect(),
- )
+ let mut servers: Vec<Value> =
+ all.iter().filter(|c| self.cfg.connectors.contains(&c.id)).filter_map(|c| c.acp(http_ok)).collect();
+ if self.cfg.computer {
+ match std::env::current_exe() {
+ Ok(exe) => servers.push(json!({
+ "name": "computer",
+ "command": exe,
+ "args": ["mcp", "computer", "--bot", self.cfg.id, "--port", self.hub.port.to_string()],
+ "env": [],
+ })),
+ Err(error) => tracing::warn!(%error, "can't locate codync-host for the computer MCP server"),
+ }
+ }
+ Value::Array(servers)
}
async fn ensure_session(&mut self) -> Result<()> {
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 391ea85b..75289417 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -2,6 +2,7 @@
use crate::LockExt;
use crate::bot::{self, BotHandle, Cmd};
+use crate::screen::Screen;
use crate::store::{BotConfig, BotRow, Entry, EntryKind, Store};
use crate::usage::Usage;
use crate::{push, service};
@@ -47,11 +48,13 @@ pub struct Hub {
keep_awake: Mutex<service::KeepAwake>,
/// botId -> Live Activity push tickets.
pub activities: Mutex<HashMap<String, Vec<String>>>,
+ pub screen: Arc<Screen>,
}
impl Hub {
pub fn new(store: Store, host_id: String, token: String, port: u16) -> Arc<Self> {
let (events, _) = broadcast::channel(1024);
+ let screen = Arc::new(Screen::new(Screen::load_enabled(&store), events.clone()));
Arc::new(Self {
store,
host_id,
@@ -65,6 +68,7 @@ impl Hub {
usage: Mutex::default(),
keep_awake: Mutex::default(),
activities: Mutex::default(),
+ screen,
})
}
diff --git a/host/src/main.rs b/host/src/main.rs
index 00c3f70f..3ebae065 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -6,10 +6,13 @@ mod backends;
mod bot;
mod hub;
mod market;
+mod mcp;
mod push;
mod registry;
+mod screen;
mod service;
mod store;
+mod tui;
mod usage;
use anyhow::{Context, Result};
@@ -90,6 +93,34 @@ enum Sub {
},
/// Rotate the pairing token (unpairs every phone).
ResetToken,
+ /// Message your bots from this terminal.
+ Tui {
+ /// Host to connect to (default: this computer).
+ #[arg(long)]
+ url: Option<String>,
+ /// Token for `--url` (default: this computer's `~/.codync/token`).
+ #[arg(long, env = "CODYNC_TOKEN", hide_env_values = true)]
+ token: Option<String>,
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ },
+ /// Built-in MCP servers that bots are started with (stdio).
+ #[command(hide = true)]
+ Mcp {
+ #[command(subcommand)]
+ server: McpServer,
+ },
+}
+
+#[derive(Subcommand)]
+enum McpServer {
+ /// See and operate this computer's desktop.
+ Computer {
+ #[arg(long)]
+ bot: String,
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ },
}
/// Host identity + auth token live in the database; the token is mirrored to
@@ -208,6 +239,10 @@ async fn main() -> Result<()> {
println!("Token rotated. Restart the host and pair your phone again.");
Ok(())
}
+ Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port).await,
+ Sub::Tui { url, token, port } => {
+ tui::run(url.unwrap_or_else(|| format!("http://127.0.0.1:{port}")), token).await
+ }
}
}
@@ -236,10 +271,15 @@ async fn serve(bind: &str, port: u16) -> Result<()> {
hub.start()?;
tokio::spawn(registry::refresh_loop());
tokio::spawn(usage::poll(hub.clone()));
+ tokio::spawn(screen::serve_helpers(hub.screen.clone()));
+ #[cfg(target_os = "linux")]
+ tokio::spawn(screen::supervise_linux_helper(hub.screen.clone()));
let listener =
tokio::net::TcpListener::bind((bind, port)).await.with_context(|| format!("binding {bind}:{port}"))?;
tracing::info!(version = env!("CARGO_PKG_VERSION"), bind, port, "codync-host listening");
- axum::serve(listener, api::router(hub.clone())).with_graceful_shutdown(shutdown_signal()).await?;
+ // Peer addresses: some settings may only be changed from this computer.
+ let app = api::router(hub.clone()).into_make_service_with_connect_info::<std::net::SocketAddr>();
+ axum::serve(listener, app).with_graceful_shutdown(shutdown_signal()).await?;
// launchd/systemd stop us with SIGTERM: stop every agent instead of orphaning it.
hub.shutdown().await;
tracing::info!("codync-host stopped");
diff --git a/host/src/mcp.rs b/host/src/mcp.rs
new file mode 100644
index 00000000..b04dccdf
--- /dev/null
+++ b/host/src/mcp.rs
@@ -0,0 +1,178 @@
+//! `codync-host mcp computer --bot <id>`: the built-in `computer` MCP server
+//! (stdio) handed to bots that have computer use turned on. Each tool call is
+//! forwarded to the running host (`POST /api/computerCall`), which checks the
+//! bot's permission and who's in control, then drives the screen helper.
+
+use anyhow::Result;
+use serde_json::{Value, json};
+use std::time::Duration;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+const PROTOCOL_VERSION: &str = "2025-06-18";
+
+const INSTRUCTIONS: &str = "Operate this computer's desktop like a person would. Start with `screenshot` \
+(or `ui_tree` to find controls precisely), then act; every action returns a fresh screenshot. \
+Coordinates are pixels in the latest screenshot. Prefer keyboard shortcuts and `open_app` over hunting with the mouse. \
+Don't type passwords or approve payments: ask the user to do that from their phone.";
+
+fn tools() -> Value {
+ let display = json!({"type": "integer", "description": "Display id; defaults to the main display."});
+ let xy = |what: &str| json!({"type": "number", "description": format!("{what} in screenshot pixels.")});
+ json!([
+ {
+ "name": "screenshot",
+ "description": "Capture the screen. Returns a JPEG whose pixels are the coordinate space for every other tool.",
+ "inputSchema": {"type": "object", "properties": {"display": display}},
+ "annotations": {"readOnlyHint": true},
+ },
+ {
+ "name": "ui_tree",
+ "description": "Accessibility tree of the frontmost app: roles, titles, values and frames in screenshot pixels. Cheaper and more precise than reading pixels when you need to find a control.",
+ "inputSchema": {"type": "object", "properties": {"display": display}},
+ "annotations": {"readOnlyHint": true},
+ },
+ {
+ "name": "click",
+ "description": "Click at a point. Returns a screenshot afterwards.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "x": xy("X"), "y": xy("Y"),
+ "button": {"type": "string", "enum": ["left", "right", "middle"], "default": "left"},
+ "count": {"type": "integer", "minimum": 1, "maximum": 3, "default": 1, "description": "2 = double-click, 3 = triple-click."},
+ "modifiers": {"type": "array", "items": {"type": "string", "enum": ["cmd", "option", "ctrl", "shift"]}, "description": "Keys held during the click."},
+ "display": display,
+ },
+ "required": ["x", "y"],
+ },
+ },
+ {
+ "name": "move",
+ "description": "Move the pointer (for hover menus and tooltips). Returns a screenshot afterwards.",
+ "inputSchema": {"type": "object", "properties": {"x": xy("X"), "y": xy("Y"), "display": display}, "required": ["x", "y"]},
+ },
+ {
+ "name": "drag",
+ "description": "Press at (x, y), drag to (to_x, to_y), release. Returns a screenshot afterwards.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"x": xy("Start x"), "y": xy("Start y"), "to_x": xy("End x"), "to_y": xy("End y"), "display": display},
+ "required": ["x", "y", "to_x", "to_y"],
+ },
+ },
+ {
+ "name": "scroll",
+ "description": "Scroll with the pointer over (x, y). Returns a screenshot afterwards.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "x": xy("X"), "y": xy("Y"),
+ "dx": {"type": "number", "description": "Lines to scroll right (negative = left)."},
+ "dy": {"type": "number", "description": "Lines to scroll down (negative = up)."},
+ "display": display,
+ },
+ "required": ["x", "y"],
+ },
+ },
+ {
+ "name": "type",
+ "description": "Type text into the focused field (any Unicode). Returns a screenshot afterwards.",
+ "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]},
+ },
+ {
+ "name": "key",
+ "description": "Press a key or shortcut, e.g. `return`, `escape`, `tab`, `cmd+t`, `cmd+shift+4`, `ctrl+c`. On Linux `cmd` is Super. Returns a screenshot afterwards.",
+ "inputSchema": {"type": "object", "properties": {"keys": {"type": "string"}}, "required": ["keys"]},
+ },
+ {
+ "name": "open_app",
+ "description": "Open or bring an application to the front by name (e.g. `Safari`, `Simulator`, `firefox`). Returns a screenshot afterwards.",
+ "inputSchema": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]},
+ },
+ ])
+}
+
+/// Serves MCP on stdio until the agent closes it.
+pub async fn serve(bot: String, port: u16) -> Result<()> {
+ let token = std::fs::read_to_string(crate::service::data_dir().join("token")).unwrap_or_default();
+ let token = token.trim().to_owned();
+ let mut lines = BufReader::new(tokio::io::stdin()).lines();
+ let mut out = tokio::io::stdout();
+ while let Some(line) = lines.next_line().await? {
+ let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
+ let Some(id) = msg.get("id").filter(|id| !id.is_null()).cloned() else {
+ continue; // notifications (`notifications/initialized`, cancellations)
+ };
+ let params = &msg["params"];
+ let reply = match msg["method"].as_str().unwrap_or_default() {
+ "initialize" => Ok(json!({
+ "protocolVersion": params["protocolVersion"].as_str().unwrap_or(PROTOCOL_VERSION),
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "codync-computer", "version": env!("CARGO_PKG_VERSION")},
+ "instructions": INSTRUCTIONS,
+ })),
+ "ping" => Ok(json!({})),
+ "tools/list" => Ok(json!({"tools": tools()})),
+ "tools/call" => Ok(call(port, &token, &bot, params).await),
+ method => Err(json!({"code": -32601, "message": format!("unknown method {method}")})),
+ };
+ let msg = match reply {
+ Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
+ Err(error) => json!({"jsonrpc": "2.0", "id": id, "error": error}),
+ };
+ let mut line = serde_json::to_vec(&msg)?;
+ line.push(b'\n');
+ out.write_all(&line).await?;
+ out.flush().await?;
+ }
+ Ok(())
+}
+
+/// One tool call through the host. Failures are tool errors the agent can read, not protocol errors.
+async fn call(port: u16, token: &str, bot: &str, params: &Value) -> Value {
+ let body = json!({
+ "botId": bot,
+ "name": params["name"],
+ "arguments": params.get("arguments").filter(|a| a.is_object()).cloned().unwrap_or_else(|| json!({})),
+ });
+ let res = crate::http()
+ .post(format!("http://127.0.0.1:{port}/api/computerCall"))
+ .bearer_auth(token)
+ .json(&body)
+ .timeout(Duration::from_secs(60))
+ .send()
+ .await;
+ let error = match res {
+ Ok(r) => {
+ let ok = r.status().is_success();
+ match r.json::<Value>().await {
+ Ok(v) if ok => return json!({"content": v["content"]}),
+ Ok(v) => v["error"].as_str().unwrap_or("the Codync host refused the call").to_owned(),
+ Err(e) => format!("bad response from the Codync host: {e}"),
+ }
+ }
+ Err(e) => format!("can't reach the Codync host: {e}"),
+ };
+ json!({"content": [{"type": "text", "text": error}], "isError": true})
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_tool_parses_as_a_computer_tool() {
+ for t in tools().as_array().unwrap() {
+ let name = t["name"].as_str().unwrap();
+ let required = t["inputSchema"]["required"].as_array().cloned().unwrap_or_default();
+ let mut args = json!({});
+ for r in required {
+ let k = r.as_str().unwrap();
+ args[k] = if t["inputSchema"]["properties"][k]["type"] == "string" { json!("x") } else { json!(1) };
+ }
+ let parsed =
+ serde_json::from_value::<crate::screen::ComputerTool>(json!({"name": name, "arguments": args}));
+ assert!(parsed.is_ok(), "{name}: {parsed:?}");
+ }
+ }
+}
diff --git a/host/src/screen.rs b/host/src/screen.rs
new file mode 100644
index 00000000..22a492f4
--- /dev/null
+++ b/host/src/screen.rs
@@ -0,0 +1,844 @@
+//! Remote screen: the phone views and controls this computer over WebRTC, and
+//! bots operate it through the built-in `computer` MCP server (`mcp.rs`).
+//!
+//! Capture, encoding and input injection live in a separate *screen helper*
+//! that connects to `~/.codync/screen.sock` — on macOS `CodyncScreen.app`
+//! (a signed bundle, so Screen Recording / Accessibility grants stick), on
+//! Linux `codync-screen` (xdg portals + `GStreamer`). The host stays the only
+//! network-facing process: it relays WebRTC signaling, gates access (off by
+//! default, enabled only from this computer) and arbitrates control between
+//! the user and bots.
+//!
+//! Helper protocol: newline-delimited JSON-RPC 2.0 over the socket.
+//! - helper → host notifications
+//! - `status` [`HelperStatus`]
+//! - `session {session, state: "connected" | "closed"}`
+//! - host → helper requests
+//! - `answer {session, sdp, display?}` → `{sdp}`: non-trickle; the offer and
+//! the answer carry every ICE candidate (host + TCP, no STUN/TURN: any
+//! network that reaches this API reaches the helper).
+//! - `close {session}`, `closeAll {}`
+//! - `screenshot {display, width, height}` → `{data}` (base64 JPEG, exactly
+//! that size)
+//! - `input {display, event}` → `{}`; `event` is an [`InputEvent`] in display points
+//! - `uiTree {display}` → `{app, tree}`: accessibility tree of the frontmost
+//! app; nodes are `{role, title?, value?, frame: [x, y, w, h], children?}`
+//! with frames in display points
+//! - `openApp {name}` → `{}`
+//!
+//! The phone's input travels straight to the helper over WebRTC data channels
+//! (`input-fast` unordered for moves, `input` reliable) using the same
+//! [`InputEvent`] JSON plus `down`/`up` for touch drags and `clipboard {text}`.
+
+use crate::LockExt;
+use crate::hub::Hub;
+use anyhow::{Result, anyhow, bail};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
+use std::time::{Duration, Instant};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::net::{UnixListener, UnixStream};
+use tokio::sync::{broadcast, mpsc, oneshot};
+
+/// Long edge of screenshots handed to agents: sharp enough to read UI text,
+/// small enough to keep every turn cheap.
+pub const SHOT_MAX_EDGE: f64 = 1280.0;
+/// How long after its last computer call a bot still counts as "using the computer".
+const AGENT_HOLD: Duration = Duration::from_secs(20);
+/// Lets the UI react to an action before the follow-up screenshot.
+const SETTLE: Duration = Duration::from_millis(400);
+const HELPER_TIMEOUT: Duration = Duration::from_secs(15);
+const KV_ENABLED: &str = "screen_enabled";
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Display {
+ pub id: u32,
+ #[serde(default)]
+ pub name: String,
+ /// Size in points (the coordinate space of [`InputEvent`]).
+ pub width: f64,
+ pub height: f64,
+ #[serde(default)]
+ pub main: bool,
+}
+
+impl Display {
+ /// Screenshot scale: points → agent image pixels.
+ fn shot_scale(&self) -> f64 {
+ (SHOT_MAX_EDGE / self.width.max(self.height)).min(1.0)
+ }
+
+ /// Agent image size for this display.
+ fn shot_size(&self) -> (u32, u32) {
+ let s = self.shot_scale();
+ // Display sizes are a few thousand points: always in range.
+ #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
+ ((self.width * s).round() as u32, (self.height * s).round() as u32)
+ }
+
+ /// Agent image pixels → display points, rejecting points off the image.
+ fn to_points(&self, x: f64, y: f64) -> Result<(f64, f64)> {
+ let (width, height) = self.shot_size();
+ if !(0.0..=f64::from(width)).contains(&x) || !(0.0..=f64::from(height)).contains(&y) {
+ bail!("({x}, {y}) is outside the {width}×{height} screenshot");
+ }
+ // Per axis: the image size is rounded, so its aspect differs slightly from the display's.
+ Ok((x * self.width / f64::from(width), y * self.height / f64::from(height)))
+ }
+}
+
+/// What the helper reports about itself.
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct HelperStatus {
+ #[serde(default)]
+ pub platform: String,
+ #[serde(default)]
+ pub version: String,
+ #[serde(default)]
+ pub displays: Vec<Display>,
+ /// Screen capture is permitted.
+ #[serde(default)]
+ pub capture: bool,
+ /// Input injection (and the accessibility tree) is permitted.
+ #[serde(default)]
+ pub input: bool,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Button {
+ #[default]
+ Left,
+ Right,
+ Middle,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Modifier {
+ /// ⌘ on macOS, Super on Linux.
+ Cmd,
+ Option,
+ Ctrl,
+ Shift,
+}
+
+/// One input action for the helper, in display points.
+#[derive(Clone, Debug, PartialEq, Serialize)]
+#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
+pub enum InputEvent {
+ Move {
+ x: f64,
+ y: f64,
+ },
+ Click {
+ x: f64,
+ y: f64,
+ button: Button,
+ count: u8,
+ modifiers: Vec<Modifier>,
+ },
+ Drag {
+ x: f64,
+ y: f64,
+ to_x: f64,
+ to_y: f64,
+ },
+ /// Scroll by `dx`/`dy` lines (positive = right/down) with the pointer at `x`,`y`.
+ Scroll {
+ x: f64,
+ y: f64,
+ dx: f64,
+ dy: f64,
+ },
+ Text {
+ text: String,
+ },
+ Key {
+ key: String,
+ modifiers: Vec<Modifier>,
+ },
+}
+
+/// Named keys the helpers understand; any other key is a single character.
+const NAMED_KEYS: &[&str] = &[
+ "return",
+ "tab",
+ "space",
+ "escape",
+ "delete",
+ "forwardDelete",
+ "left",
+ "right",
+ "up",
+ "down",
+ "home",
+ "end",
+ "pageUp",
+ "pageDown",
+ "f1",
+ "f2",
+ "f3",
+ "f4",
+ "f5",
+ "f6",
+ "f7",
+ "f8",
+ "f9",
+ "f10",
+ "f11",
+ "f12",
+];
+
+/// Modifier names with common aliases, deduplicated.
+fn parse_modifiers(names: &[impl AsRef<str>]) -> Result<Vec<Modifier>> {
+ let mut out = vec![];
+ for m in names {
+ let m = match m.as_ref().to_lowercase().as_str() {
+ "cmd" | "command" | "meta" | "super" | "win" => Modifier::Cmd,
+ "option" | "opt" | "alt" => Modifier::Option,
+ "ctrl" | "control" => Modifier::Ctrl,
+ "shift" => Modifier::Shift,
+ other => bail!("unknown modifier `{other}` (use cmd, option, ctrl, shift)"),
+ };
+ if !out.contains(&m) {
+ out.push(m);
+ }
+ }
+ Ok(out)
+}
+
+/// `"cmd+shift+t"` → key `t` with ⌘⇧. Accepts common aliases (`ctrl`, `alt`, `enter`, `esc`, …).
+pub fn parse_keys(combo: &str) -> Result<(String, Vec<Modifier>)> {
+ let parts: Vec<&str> = combo.split('+').map(str::trim).collect();
+ let (key, mods) =
+ parts.split_last().filter(|(k, _)| !k.is_empty()).ok_or_else(|| anyhow!("no key in `{combo}`"))?;
+ let modifiers = parse_modifiers(mods)?;
+ let lower = key.to_lowercase();
+ let key = match lower.as_str() {
+ "enter" => "return".to_owned(),
+ "esc" => "escape".to_owned(),
+ "backspace" => "delete".to_owned(),
+ "del" | "forwarddelete" => "forwardDelete".to_owned(),
+ "pageup" | "pgup" => "pageUp".to_owned(),
+ "pagedown" | "pgdn" => "pageDown".to_owned(),
+ "arrowleft" => "left".to_owned(),
+ "arrowright" => "right".to_owned(),
+ "arrowup" => "up".to_owned(),
+ "arrowdown" => "down".to_owned(),
+ _ if NAMED_KEYS.contains(&lower.as_str()) => lower,
+ _ if key.chars().count() == 1 => lower,
+ _ => bail!("unknown key `{key}`"),
+ };
+ Ok((key, modifiers))
+}
+
+/// A `computer` MCP tool call, as the MCP server forwards it (`{name, arguments}`).
+#[derive(Debug, Deserialize)]
+#[serde(tag = "name", content = "arguments", rename_all = "snake_case")]
+pub enum ComputerTool {
+ Screenshot {
+ display: Option<u32>,
+ },
+ Click {
+ x: f64,
+ y: f64,
+ #[serde(default)]
+ button: Button,
+ count: Option<u8>,
+ #[serde(default)]
+ modifiers: Vec<String>,
+ display: Option<u32>,
+ },
+ Move {
+ x: f64,
+ y: f64,
+ display: Option<u32>,
+ },
+ Drag {
+ x: f64,
+ y: f64,
+ to_x: f64,
+ to_y: f64,
+ display: Option<u32>,
+ },
+ Scroll {
+ x: f64,
+ y: f64,
+ #[serde(default)]
+ dx: f64,
+ #[serde(default)]
+ dy: f64,
+ display: Option<u32>,
+ },
+ Type {
+ text: String,
+ },
+ Key {
+ keys: String,
+ },
+ UiTree {
+ display: Option<u32>,
+ },
+ OpenApp {
+ name: String,
+ },
+}
+
+impl ComputerTool {
+ /// Tools that only look: allowed while the user has control.
+ fn read_only(&self) -> bool {
+ matches!(self, Self::Screenshot { .. } | Self::UiTree { .. })
+ }
+}
+
+type Pending = Mutex<HashMap<i64, oneshot::Sender<Result<Value, String>>>>;
+
+/// One connected screen helper.
+struct Link {
+ id: u64,
+ tx: mpsc::UnboundedSender<String>,
+ pending: Pending,
+ next_id: AtomicI64,
+}
+
+impl Link {
+ async fn request(&self, method: &str, params: Value) -> Result<Value> {
+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);
+ let (tx, rx) = oneshot::channel();
+ self.pending.locked().insert(id, tx);
+ let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string();
+ if self.tx.send(line).is_err() {
+ self.pending.locked().remove(&id);
+ bail!("the screen helper disconnected");
+ }
+ match tokio::time::timeout(HELPER_TIMEOUT, rx).await {
+ Ok(Ok(Ok(v))) => Ok(v),
+ Ok(Ok(Err(message))) => Err(anyhow!(message)),
+ Ok(Err(_)) => bail!("the screen helper disconnected"),
+ Err(_) => {
+ self.pending.locked().remove(&id);
+ bail!("the screen helper didn't answer `{method}` in time")
+ }
+ }
+ }
+}
+
+#[derive(Default)]
+struct Control {
+ /// The phone took over: bots may only look.
+ user: bool,
+ /// The bot using the computer, and when it last did.
+ agent: Option<(String, Instant)>,
+}
+
+impl Control {
+ fn active_agent(&self) -> Option<&str> {
+ self.agent.as_ref().filter(|(_, t)| t.elapsed() < AGENT_HOLD).map(|(b, _)| b.as_str())
+ }
+}
+
+pub struct Screen {
+ enabled: AtomicBool,
+ events: broadcast::Sender<Value>,
+ link: Mutex<Option<Arc<Link>>>,
+ status: Mutex<HelperStatus>,
+ control: Mutex<Control>,
+ sessions: Mutex<HashSet<String>>,
+ next_link: AtomicU64,
+}
+
+impl Screen {
+ pub fn new(enabled: bool, events: broadcast::Sender<Value>) -> Self {
+ Self {
+ enabled: AtomicBool::new(enabled),
+ events,
+ link: Mutex::default(),
+ status: Mutex::default(),
+ control: Mutex::default(),
+ sessions: Mutex::default(),
+ next_link: AtomicU64::new(1),
+ }
+ }
+
+ pub fn load_enabled(store: &crate::store::Store) -> bool {
+ store.kv_get(KV_ENABLED).as_deref() == Some("1")
+ }
+
+ pub fn enabled(&self) -> bool {
+ self.enabled.load(Ordering::Relaxed)
+ }
+
+ /// What clients show: availability, permissions, displays, who's in control.
+ pub fn state(&self) -> Value {
+ let st = self.status.locked().clone();
+ let connected = self.link.locked().is_some();
+ let c = self.control.locked();
+ json!({
+ "enabled": self.enabled(),
+ "connected": connected,
+ "platform": st.platform,
+ "capture": st.capture,
+ "input": st.input,
+ "displays": st.displays,
+ "userControl": c.user,
+ "agentBot": c.active_agent(),
+ "viewers": self.sessions.locked().len(),
+ })
+ }
+
+ fn emit(&self) {
+ let _ = self.events.send(json!({"type": "screen", "screen": self.state()}));
+ }
+
+ fn link(&self) -> Result<Arc<Link>> {
+ if !self.enabled() {
+ bail!("Remote screen is turned off on this computer. Turn it on in Codync's menu there.");
+ }
+ self.link.locked().clone().ok_or_else(|| anyhow!("The screen helper isn't running on this computer."))
+ }
+
+ fn display(&self, id: Option<u32>) -> Result<Display> {
+ let st = self.status.locked();
+ let found = match id {
+ Some(id) => st.displays.iter().find(|d| d.id == id),
+ None => st.displays.iter().find(|d| d.main).or_else(|| st.displays.first()),
+ };
+ found.cloned().ok_or_else(|| anyhow!("no such display"))
+ }
+
+ // MARK: phone
+
+ /// Answers a WebRTC offer from the phone (a new session, or an ICE restart of `session`).
+ pub async fn offer(&self, sdp: &str, session: Option<&str>, display: Option<u32>) -> Result<Value> {
+ let link = self.link()?;
+ if !self.status.locked().capture {
+ bail!("Codync isn't allowed to record this computer's screen yet. Allow it in System Settings there.");
+ }
+ let session = session.map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_owned);
+ let res = link.request("answer", json!({"session": session, "sdp": sdp, "display": display})).await?;
+ let answer = res["sdp"].as_str().ok_or_else(|| anyhow!("the screen helper sent no answer"))?;
+ if self.sessions.locked().insert(session.clone()) {
+ self.emit();
+ }
+ Ok(json!({"session": session, "sdp": answer}))
+ }
+
+ pub async fn close(&self, session: &str) -> Result<()> {
+ let link = self.link.locked().clone();
+ if let Some(link) = link {
+ link.request("close", json!({"session": session})).await?;
+ }
+ self.session_closed(session);
+ Ok(())
+ }
+
+ fn session_closed(&self, session: &str) {
+ let removed = {
+ let mut sessions = self.sessions.locked();
+ let removed = sessions.remove(session);
+ if sessions.is_empty() {
+ // Nobody is watching: hand control back to the bots.
+ self.control.locked().user = false;
+ }
+ removed
+ };
+ if removed {
+ self.emit();
+ }
+ }
+
+ pub fn takeover(&self, on: bool) {
+ self.control.locked().user = on;
+ self.emit();
+ }
+
+ /// Only callable from this computer (see `api.rs`).
+ pub async fn set_enabled(&self, store: &crate::store::Store, on: bool) -> Result<()> {
+ store.kv_set(KV_ENABLED, if on { "1" } else { "0" })?;
+ self.enabled.store(on, Ordering::Relaxed);
+ if !on {
+ let link = self.link.locked().clone();
+ if let Some(link) = link
+ && let Err(error) = link.request("closeAll", json!({})).await
+ {
+ tracing::warn!(error = format!("{error:#}"), "couldn't close screen sessions");
+ }
+ self.sessions.locked().clear();
+ *self.control.locked() = Control::default();
+ }
+ self.emit();
+ Ok(())
+ }
+
+ // MARK: bots
+
+ /// Marks `bot` as the one using the computer. Returns whether that's news.
+ fn claim(&self, bot: &str, read_only: bool) -> Result<bool> {
+ let mut c = self.control.locked();
+ if c.user && !read_only {
+ bail!(
+ "The user has taken over the screen from their phone. Wait until they hand it back, or ask them what to do."
+ );
+ }
+ if let Some(other) = c.active_agent()
+ && other != bot
+ {
+ bail!("Another bot is using the computer right now. Try again in a minute.");
+ }
+ let fresh = c.active_agent().is_none();
+ c.agent = Some((bot.to_owned(), Instant::now()));
+ Ok(fresh)
+ }
+}
+
+/// Runs one `computer` tool for `bot`: MCP `CallToolResult` content.
+pub async fn computer(hub: &Arc<Hub>, bot: &str, tool: ComputerTool) -> Result<Value> {
+ let row = hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ if !row.config.computer {
+ bail!("Computer use is turned off for this bot.");
+ }
+ let screen = &hub.screen;
+ let link = screen.link()?;
+ if screen.claim(bot, tool.read_only())? {
+ screen.emit();
+ let screen = screen.clone();
+ tokio::spawn(async move {
+ // Say when the bot stops, so phones drop the live chip.
+ loop {
+ tokio::time::sleep(AGENT_HOLD).await;
+ if screen.control.locked().active_agent().is_none() {
+ screen.emit();
+ return;
+ }
+ }
+ });
+ }
+ let display = |id| screen.display(id);
+ let act = |id: Option<u32>, event: InputEvent| {
+ let link = link.clone();
+ async move {
+ let d = display(id)?;
+ link.request("input", json!({"display": d.id, "event": event})).await?;
+ tokio::time::sleep(SETTLE).await;
+ shot(&link, &d).await
+ }
+ };
+ match tool {
+ ComputerTool::Screenshot { display: id } => shot(&link, &display(id)?).await,
+ ComputerTool::Click { x, y, button, count, modifiers, display: id } => {
+ let d = display(id)?;
+ let (x, y) = d.to_points(x, y)?;
+ let modifiers = parse_modifiers(&modifiers)?;
+ let count = count.unwrap_or(1).clamp(1, 3);
+ act(Some(d.id), InputEvent::Click { x, y, button, count, modifiers }).await
+ }
+ ComputerTool::Move { x, y, display: id } => {
+ let d = display(id)?;
+ let (x, y) = d.to_points(x, y)?;
+ act(Some(d.id), InputEvent::Move { x, y }).await
+ }
+ ComputerTool::Drag { x, y, to_x, to_y, display: id } => {
+ let d = display(id)?;
+ let (x, y) = d.to_points(x, y)?;
+ let (to_x, to_y) = d.to_points(to_x, to_y)?;
+ act(Some(d.id), InputEvent::Drag { x, y, to_x, to_y }).await
+ }
+ ComputerTool::Scroll { x, y, dx, dy, display: id } => {
+ let d = display(id)?;
+ let (x, y) = d.to_points(x, y)?;
+ act(Some(d.id), InputEvent::Scroll { x, y, dx, dy }).await
+ }
+ ComputerTool::Type { text } => act(None, InputEvent::Text { text }).await,
+ ComputerTool::Key { keys } => {
+ let (key, modifiers) = parse_keys(&keys)?;
+ act(None, InputEvent::Key { key, modifiers }).await
+ }
+ ComputerTool::UiTree { display: id } => {
+ let d = display(id)?;
+ let mut res = link.request("uiTree", json!({"display": d.id})).await?;
+ scale_frames(&mut res["tree"], d.shot_scale());
+ let text = format!(
+ "Accessibility tree of {} (frames are [x, y, width, height] in screenshot pixels):\n{}",
+ res["app"].as_str().unwrap_or("the frontmost app"),
+ res["tree"]
+ );
+ Ok(json!([{"type": "text", "text": text}]))
+ }
+ ComputerTool::OpenApp { name } => {
+ link.request("openApp", json!({"name": name})).await?;
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ shot(&link, &display(None)?).await
+ }
+ }
+}
+
+async fn shot(link: &Link, d: &Display) -> Result<Value> {
+ let (width, height) = d.shot_size();
+ let res = link.request("screenshot", json!({"display": d.id, "width": width, "height": height})).await?;
+ let data = res["data"].as_str().ok_or_else(|| anyhow!("the screen helper sent no image"))?;
+ Ok(json!([
+ {"type": "image", "data": data, "mimeType": "image/jpeg"},
+ {"type": "text", "text": format!(
+ "Display {} \"{}\", {width}×{height}. Coordinates for click/move/drag/scroll are pixels in this image.",
+ d.id, d.name
+ )},
+ ]))
+}
+
+/// Display points → screenshot pixels, for every `frame` in an accessibility tree.
+fn scale_frames(node: &mut Value, s: f64) {
+ if let Some(frame) = node.get_mut("frame").and_then(Value::as_array_mut) {
+ for v in frame.iter_mut() {
+ if let Some(f) = v.as_f64() {
+ *v = json!((f * s).round());
+ }
+ }
+ }
+ if let Some(children) = node.get_mut("children").and_then(Value::as_array_mut) {
+ for c in children {
+ scale_frames(c, s);
+ }
+ }
+}
+
+// MARK: helper socket
+
+/// Accepts screen helpers on `~/.codync/screen.sock`. The newest connection wins.
+pub async fn serve_helpers(screen: Arc<Screen>) {
+ let path = crate::service::data_dir().join("screen.sock");
+ let _ = std::fs::remove_file(&path);
+ let listener = match UnixListener::bind(&path) {
+ Ok(l) => l,
+ Err(error) => {
+ tracing::error!(%error, path = %path.display(), "can't listen for the screen helper");
+ return;
+ }
+ };
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if let Err(error) = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) {
+ tracing::warn!(%error, "couldn't restrict the screen helper socket");
+ }
+ }
+ loop {
+ match listener.accept().await {
+ Ok((stream, _)) => {
+ tokio::spawn(run_link(screen.clone(), stream));
+ }
+ Err(error) => {
+ tracing::warn!(%error, "screen helper accept failed");
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ }
+ }
+}
+
+/// Linux: the host runs `codync-screen` itself while Remote screen is on (on macOS
+/// launchd runs Codync Screen for the app). Restarts it if it exits; stops it when turned off.
+#[cfg(target_os = "linux")]
+pub async fn supervise_linux_helper(screen: Arc<Screen>) {
+ let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join("codync-screen")));
+ let program = exe.filter(|p| p.is_file()).unwrap_or_else(|| "codync-screen".into());
+ let mut child: Option<tokio::process::Child> = None;
+ let mut backoff = Duration::from_secs(1);
+ loop {
+ let running = child.as_mut().is_some_and(|c| matches!(c.try_wait(), Ok(None)));
+ if screen.enabled() && !running {
+ match tokio::process::Command::new(&program).kill_on_drop(true).spawn() {
+ Ok(c) => child = Some(c),
+ Err(error) => tracing::warn!(%error, program = %program.display(), "can't start codync-screen"),
+ }
+ tokio::time::sleep(backoff).await;
+ backoff = (backoff * 2).min(Duration::from_secs(30));
+ continue;
+ }
+ if !screen.enabled()
+ && let Some(mut c) = child.take()
+ {
+ let _ = c.kill().await;
+ }
+ if running && screen.link.locked().is_some() {
+ backoff = Duration::from_secs(1);
+ }
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+}
+
+async fn run_link(screen: Arc<Screen>, stream: UnixStream) {
+ let (rd, mut wr) = stream.into_split();
+ let (tx, mut rx) = mpsc::unbounded_channel::<String>();
+ let link = Arc::new(Link {
+ id: screen.next_link.fetch_add(1, Ordering::Relaxed),
+ tx,
+ pending: Mutex::default(),
+ next_id: AtomicI64::new(1),
+ });
+ *screen.link.locked() = Some(link.clone());
+ tracing::info!("screen helper connected");
+ let writer = tokio::spawn(async move {
+ while let Some(mut line) = rx.recv().await {
+ line.push('\n');
+ if wr.write_all(line.as_bytes()).await.is_err() {
+ break;
+ }
+ }
+ });
+ let mut lines = BufReader::new(rd).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let Ok(msg) = serde_json::from_str::<Value>(&line) else {
+ tracing::debug!(line, "ignoring non-JSON from the screen helper");
+ continue;
+ };
+ match (msg["method"].as_str(), msg["id"].as_i64()) {
+ (None, Some(id)) => {
+ if let Some(waiter) = link.pending.locked().remove(&id) {
+ let res = match msg.get("error") {
+ Some(e) => Err(e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned)),
+ None => Ok(msg["result"].clone()),
+ };
+ let _ = waiter.send(res);
+ }
+ }
+ (Some("status"), _) => match serde_json::from_value::<HelperStatus>(msg["params"].clone()) {
+ Ok(st) => {
+ *screen.status.locked() = st;
+ screen.emit();
+ }
+ Err(error) => tracing::warn!(%error, "bad status from the screen helper"),
+ },
+ (Some("session"), _) => {
+ if msg["params"]["state"] == "closed"
+ && let Some(s) = msg["params"]["session"].as_str()
+ {
+ screen.session_closed(s);
+ }
+ }
+ (Some(method), _) => tracing::debug!(method, "unknown screen helper notification"),
+ _ => {}
+ }
+ }
+ writer.abort();
+ link.pending.locked().clear();
+ let current = {
+ let mut slot = screen.link.locked();
+ let current = slot.as_ref().is_some_and(|l| l.id == link.id);
+ if current {
+ *slot = None;
+ }
+ current
+ };
+ if current {
+ *screen.status.locked() = HelperStatus::default();
+ screen.sessions.locked().clear();
+ screen.control.locked().user = false;
+ screen.emit();
+ }
+ tracing::info!("screen helper disconnected");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn retina() -> Display {
+ Display { id: 1, name: "Built-in".into(), width: 1512.0, height: 982.0, main: true }
+ }
+
+ #[test]
+ fn screenshot_coordinates_map_to_points() {
+ let d = retina();
+ assert_eq!(d.shot_size(), (1280, 831));
+ assert_eq!(d.to_points(1280.0, 831.0).unwrap(), (1512.0, 982.0));
+ let (x, y) = d.to_points(640.0, 415.5).unwrap();
+ assert!((x - 756.0).abs() < 0.01 && (y - 491.0).abs() < 0.01);
+ assert!(d.to_points(1281.0, 10.0).is_err());
+ // Small displays aren't upscaled.
+ let small = Display { width: 800.0, height: 600.0, ..retina() };
+ assert_eq!(small.shot_size(), (800, 600));
+ }
+
+ #[test]
+ fn key_combos_parse() {
+ assert_eq!(parse_keys("cmd+shift+T").unwrap(), ("t".into(), vec![Modifier::Cmd, Modifier::Shift]));
+ assert_eq!(parse_keys("Enter").unwrap(), ("return".into(), vec![]));
+ assert_eq!(parse_keys("ctrl+alt+Delete").unwrap(), ("delete".into(), vec![Modifier::Ctrl, Modifier::Option]));
+ assert_eq!(parse_keys("cmd++").unwrap_err().to_string(), "no key in `cmd++`");
+ assert!(parse_keys("hyper+x").is_err());
+ assert!(parse_keys("cmd+banana").is_err());
+ }
+
+ #[test]
+ fn tools_parse_from_mcp_calls() {
+ let t: ComputerTool =
+ serde_json::from_value(json!({"name": "click", "arguments": {"x": 1, "y": 2, "button": "right"}})).unwrap();
+ assert!(matches!(t, ComputerTool::Click { button: Button::Right, count: None, .. }));
+ let t: ComputerTool = serde_json::from_value(json!({"name": "screenshot", "arguments": {}})).unwrap();
+ assert!(t.read_only());
+ }
+
+ #[test]
+ fn input_events_serialize_for_helpers() {
+ let e = InputEvent::Drag { x: 1.0, y: 2.0, to_x: 3.0, to_y: 4.0 };
+ assert_eq!(
+ serde_json::to_value(e).unwrap(),
+ json!({"type": "drag", "x": 1.0, "y": 2.0, "toX": 3.0, "toY": 4.0})
+ );
+ }
+
+ #[test]
+ fn user_takeover_blocks_bot_actions_but_not_looking() {
+ let (tx, _) = broadcast::channel(8);
+ let s = Screen::new(true, tx);
+ assert!(s.claim("a", false).unwrap());
+ assert!(!s.claim("a", false).unwrap());
+ assert!(s.claim("b", true).is_err(), "one bot at a time");
+ s.takeover(true);
+ assert!(s.claim("a", false).is_err());
+ assert!(s.claim("a", true).is_ok());
+ }
+
+ #[test]
+ fn frames_scale_recursively() {
+ let mut t = json!({"frame": [100, 50, 200, 20], "children": [{"frame": [10.0, 10.0, 5.0, 5.0]}]});
+ scale_frames(&mut t, 0.5);
+ assert_eq!(t["frame"], json!([50.0, 25.0, 100.0, 10.0]));
+ assert_eq!(t["children"][0]["frame"], json!([5.0, 5.0, 3.0, 3.0]));
+ }
+
+ #[tokio::test]
+ async fn helper_roundtrip_over_the_socket() {
+ let (tx, _) = broadcast::channel(8);
+ let screen = Arc::new(Screen::new(true, tx));
+ let (a, b) = UnixStream::pair().unwrap();
+ // Fake helper: reports a display, then answers every request with its method name.
+ tokio::spawn(async move {
+ let (rd, mut wr) = b.into_split();
+ let status = json!({"jsonrpc": "2.0", "method": "status", "params": {"platform": "test", "capture": true, "displays": [retina()]}});
+ wr.write_all(format!("{status}\n").as_bytes()).await.unwrap();
+ let mut lines = BufReader::new(rd).lines();
+ while let Ok(Some(l)) = lines.next_line().await {
+ let m: Value = serde_json::from_str(&l).unwrap();
+ let res = json!({"jsonrpc": "2.0", "id": m["id"], "result": {"sdp": format!("answer to {}", m["params"]["sdp"].as_str().unwrap_or_default())}});
+ wr.write_all(format!("{res}\n").as_bytes()).await.unwrap();
+ }
+ });
+ tokio::spawn(run_link(screen.clone(), a));
+ for _ in 0..50 {
+ if screen.status.locked().capture {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ let res = screen.offer("offer", None, None).await.unwrap();
+ assert_eq!(res["sdp"], "answer to offer");
+ assert_eq!(screen.state()["viewers"], 1);
+ assert_eq!(screen.state()["displays"][0]["name"], "Built-in");
+ }
+}
diff --git a/host/src/store.rs b/host/src/store.rs
index f20f54a6..080d9cc5 100644
--- a/host/src/store.rs
+++ b/host/src/store.rs
@@ -82,6 +82,9 @@ pub struct BotConfig {
/// Skill ids the bot is told about; see `market`.
#[serde(default)]
pub skills: Vec<String>,
+ /// The bot gets the built-in `computer` MCP server (see `screen`).
+ #[serde(default)]
+ pub computer: bool,
#[serde(default)]
pub created_at: i64,
}
@@ -463,6 +466,7 @@ mod tests {
notify: None,
connectors: vec![],
skills: vec![],
+ computer: false,
created_at: 0,
};
s.save_bot(&cfg).unwrap();
diff --git a/host/src/tui/app.rs b/host/src/tui/app.rs
new file mode 100644
index 00000000..dc7cce42
--- /dev/null
+++ b/host/src/tui/app.rs
@@ -0,0 +1,1953 @@
+//! TUI state and everything that changes it: host events, keys, mouse, replies.
+
+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
+use ratatui::layout::{Position, Rect};
+use serde_json::{Value, json};
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::io::Write as _;
+use std::time::{Duration, Instant};
+use tokio::sync::mpsc::UnboundedSender;
+
+use super::net::Client;
+
+pub enum Msg {
+ Online(bool),
+ Event(Value),
+ Reply(After, Result<Value, String>),
+ /// The stream is starting over from rev 0: drop what we have.
+ Rewind,
+}
+
+/// What to do with a command's reply.
+#[derive(Clone)]
+pub enum After {
+ Nothing,
+ Hello,
+ History(String),
+ Dirs,
+ Pairing,
+ Backends,
+ Saved,
+ Connectors,
+ Skills,
+ Installed,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Status {
+ Idle,
+ Working,
+ NeedsInput,
+ Error,
+}
+
+/// What a bot's row shows, highest priority first.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Mark {
+ Need,
+ Error,
+ Unread,
+ Work,
+ Idle,
+}
+
+impl Mark {
+ pub fn priority(self) -> u8 {
+ match self {
+ Self::Need => 4,
+ Self::Error => 3,
+ Self::Unread => 2,
+ Self::Work => 1,
+ Self::Idle => 0,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+#[allow(clippy::struct_excessive_bools, reason = "mirrors the host's bot JSON")]
+pub struct Bot {
+ pub id: String,
+ pub name: String,
+ pub description: String,
+ pub color: String,
+ pub shape: String,
+ pub backend: String,
+ pub cwd: String,
+ pub auto: bool,
+ pub model: Option<String>,
+ pub pinned: bool,
+ pub hidden: bool,
+ pub notify: bool,
+ pub connectors: Vec<String>,
+ pub skills: Vec<String>,
+ pub status: Status,
+ pub activity: String,
+ pub started_at: Option<i64>,
+ pub unread: i64,
+ pub last_message: String,
+ pub last_at: i64,
+}
+
+fn strs(v: &Value) -> Vec<String> {
+ v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
+}
+
+impl Bot {
+ fn parse(v: &Value) -> Option<Self> {
+ let s = |k: &str| v[k].as_str().unwrap_or_default().to_owned();
+ Some(Self {
+ id: v["id"].as_str()?.to_owned(),
+ name: s("name"),
+ description: s("description"),
+ color: v["avatarColor"].as_str().unwrap_or("blue").to_owned(),
+ shape: v["avatarShape"].as_str().unwrap_or("blob").to_owned(),
+ backend: s("backend"),
+ cwd: s("cwd"),
+ auto: v["permission"] == "auto",
+ model: v["model"].as_str().filter(|m| !m.is_empty()).map(str::to_owned),
+ pinned: v["pinned"].as_bool().unwrap_or(false),
+ hidden: v["hidden"].as_bool().unwrap_or(false),
+ notify: v["notify"].as_bool().unwrap_or(true),
+ connectors: strs(&v["connectors"]),
+ skills: strs(&v["skills"]),
+ status: match v["status"].as_str() {
+ Some("working") => Status::Working,
+ Some("needsInput") => Status::NeedsInput,
+ Some("error") => Status::Error,
+ _ => Status::Idle,
+ },
+ activity: s("activity"),
+ started_at: v["startedAt"].as_i64(),
+ unread: v["unread"].as_i64().unwrap_or(0),
+ last_message: s("lastMessage"),
+ last_at: v["lastAt"].as_i64().unwrap_or(0),
+ })
+ }
+
+ pub fn mark(&self) -> Mark {
+ match self.status {
+ Status::NeedsInput => Mark::Need,
+ Status::Error => Mark::Error,
+ Status::Working => Mark::Work,
+ Status::Idle if self.unread > 0 => Mark::Unread,
+ Status::Idle => Mark::Idle,
+ }
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Kind {
+ User,
+ Agent,
+ Thought,
+ Tool,
+ Plan,
+ Permission,
+ Notice,
+ Other,
+}
+
+#[derive(Clone, Debug)]
+pub struct Entry {
+ pub id: String,
+ pub seq: i64,
+ pub turn: i64,
+ pub kind: Kind,
+ pub data: Value,
+ pub created_at: i64,
+}
+
+impl Entry {
+ fn parse(v: &Value) -> Option<(String, Self)> {
+ let kind = match v["kind"].as_str()? {
+ "user" => Kind::User,
+ "agent" => Kind::Agent,
+ "thought" => Kind::Thought,
+ "tool" => Kind::Tool,
+ "plan" => Kind::Plan,
+ "permission" => Kind::Permission,
+ "notice" => Kind::Notice,
+ _ => Kind::Other,
+ };
+ Some((
+ v["botId"].as_str()?.to_owned(),
+ Self {
+ id: v["id"].as_str()?.to_owned(),
+ seq: v["seq"].as_i64()?,
+ turn: v["turn"].as_i64().unwrap_or(0),
+ kind,
+ data: v["data"].clone(),
+ created_at: v["createdAt"].as_i64().unwrap_or(0),
+ },
+ ))
+ }
+
+ pub fn text(&self) -> &str {
+ self.data["text"].as_str().unwrap_or_default()
+ }
+
+ pub fn is_final(&self) -> bool {
+ self.kind == Kind::Agent && self.data["final"].as_bool().unwrap_or(false)
+ }
+
+ pub fn pending(&self) -> bool {
+ self.kind == Kind::Permission && self.data["status"] == "pending"
+ }
+
+ /// Approval options in the apps' order: allow once, allow always, reject once, reject always.
+ pub fn options(&self) -> Vec<(String, String, String)> {
+ let rank = |k: &str| match k {
+ "allow_once" => 0,
+ "allow_always" => 1,
+ "reject_once" => 2,
+ "reject_always" => 3,
+ _ => 9,
+ };
+ let mut o: Vec<(String, String, String)> = self.data["options"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|o| {
+ let s = |k: &str| o[k].as_str().unwrap_or_default().to_owned();
+ (s("optionId"), s("name"), s("kind"))
+ })
+ .collect();
+ o.sort_by_key(|(_, _, k)| rank(k));
+ o
+ }
+}
+
+/// A one-line-or-more text field with readline-style editing.
+#[derive(Clone, Default, Debug)]
+pub struct Editor {
+ pub text: String,
+ /// Byte offset, always on a char boundary.
+ pub cursor: usize,
+}
+
+impl Editor {
+ pub fn with(text: &str) -> Self {
+ Self { text: text.to_owned(), cursor: text.len() }
+ }
+
+ pub fn clear(&mut self) {
+ self.text.clear();
+ self.cursor = 0;
+ }
+
+ pub fn insert(&mut self, s: &str) {
+ self.text.insert_str(self.cursor, s);
+ self.cursor += s.len();
+ }
+
+ fn prev(&self, i: usize) -> usize {
+ self.text[..i].char_indices().next_back().map_or(0, |(j, _)| j)
+ }
+
+ fn next(&self, i: usize) -> usize {
+ self.text[i..].chars().next().map_or(i, |c| i + c.len_utf8())
+ }
+
+ fn word_left(&self) -> usize {
+ let mut i = self.cursor;
+ while i > 0 && self.text[..i].ends_with(char::is_whitespace) {
+ i = self.prev(i);
+ }
+ while i > 0 && !self.text[..i].ends_with(char::is_whitespace) {
+ i = self.prev(i);
+ }
+ i
+ }
+
+ fn word_right(&self) -> usize {
+ let mut i = self.cursor;
+ while i < self.text.len() && self.text[i..].starts_with(char::is_whitespace) {
+ i = self.next(i);
+ }
+ while i < self.text.len() && !self.text[i..].starts_with(char::is_whitespace) {
+ i = self.next(i);
+ }
+ i
+ }
+
+ fn line_start(&self) -> usize {
+ self.text[..self.cursor].rfind('\n').map_or(0, |i| i + 1)
+ }
+
+ fn line_end(&self) -> usize {
+ self.text[self.cursor..].find('\n').map_or(self.text.len(), |i| self.cursor + i)
+ }
+
+ /// Editing keys shared by every text field. Returns whether the key was used.
+ pub fn key(&mut self, k: KeyEvent) -> bool {
+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
+ let alt = k.modifiers.contains(KeyModifiers::ALT);
+ match k.code {
+ KeyCode::Char('a') if ctrl => self.cursor = self.line_start(),
+ KeyCode::Char('e') if ctrl => self.cursor = self.line_end(),
+ KeyCode::Char('b') if ctrl => self.cursor = self.prev(self.cursor),
+ KeyCode::Char('f') if ctrl => self.cursor = self.next(self.cursor),
+ KeyCode::Char('b') if alt => self.cursor = self.word_left(),
+ KeyCode::Char('f') if alt => self.cursor = self.word_right(),
+ KeyCode::Char('w') if ctrl => self.cut(self.word_left(), self.cursor),
+ KeyCode::Backspace if alt || ctrl => self.cut(self.word_left(), self.cursor),
+ KeyCode::Char('d') if alt => self.cut(self.cursor, self.word_right()),
+ KeyCode::Char('u') if ctrl => self.cut(self.line_start(), self.cursor),
+ KeyCode::Char('h') if ctrl => self.cut(self.prev(self.cursor), self.cursor),
+ KeyCode::Char('d') if ctrl => self.cut(self.cursor, self.next(self.cursor)),
+ KeyCode::Left if alt || ctrl => self.cursor = self.word_left(),
+ KeyCode::Right if alt || ctrl => self.cursor = self.word_right(),
+ KeyCode::Left => self.cursor = self.prev(self.cursor),
+ KeyCode::Right => self.cursor = self.next(self.cursor),
+ KeyCode::Home => self.cursor = self.line_start(),
+ KeyCode::End => self.cursor = self.line_end(),
+ KeyCode::Backspace => self.cut(self.prev(self.cursor), self.cursor),
+ KeyCode::Delete => self.cut(self.cursor, self.next(self.cursor)),
+ KeyCode::Char(c) if !ctrl && !alt => self.insert(c.encode_utf8(&mut [0; 4])),
+ KeyCode::Char(c) if alt && !ctrl && !c.is_ascii_alphabetic() => self.insert(c.encode_utf8(&mut [0; 4])),
+ _ => return false,
+ }
+ true
+ }
+
+ fn cut(&mut self, from: usize, to: usize) {
+ if from < to {
+ self.text.replace_range(from..to, "");
+ self.cursor = from;
+ }
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Focus {
+ Roster,
+ Chat,
+ Trace,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum TraceMode {
+ Off,
+ Pane,
+ Full,
+}
+
+/// Width class, set by the last draw.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Width {
+ /// < 80 columns: roster and chat are separate pages.
+ Narrow,
+ /// 80–99: compact roster.
+ Mid,
+ /// 100–149.
+ Wide,
+ /// ≥ 150.
+ Huge,
+}
+
+pub const FILTERS: [(&str, Option<Mark>); 5] = [
+ ("all", None),
+ ("needs you", Some(Mark::Need)),
+ ("working", Some(Mark::Work)),
+ ("unread", Some(Mark::Unread)),
+ ("error", Some(Mark::Error)),
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Action {
+ NewBot,
+ RefreshAgents,
+ Pair,
+ Usage,
+ Keys,
+}
+
+pub const ACTIONS: [(&str, &str, Action); 5] = [
+ ("New bot…", "n", Action::NewBot),
+ ("Refresh agents", "", Action::RefreshAgents),
+ ("Pair a phone…", "P", Action::Pair),
+ ("Usage", "U", Action::Usage),
+ ("Keys", "?", Action::Keys),
+];
+
+pub enum GotoItem {
+ Bot(String),
+ Action(Action),
+}
+
+pub struct Goto {
+ pub query: Editor,
+ pub filter: usize,
+ pub cursor: usize,
+}
+
+pub enum ConfirmAct {
+ Delete(String),
+ NewSession(String),
+}
+
+pub struct Confirm {
+ pub title: String,
+ pub detail: String,
+ pub note: String,
+ pub button: &'static str,
+ pub act: ConfirmAct,
+}
+
+pub struct AgentPicker {
+ pub query: Editor,
+ pub cursor: usize,
+}
+
+#[derive(Clone)]
+pub struct Dir {
+ pub name: String,
+ pub path: String,
+ pub git: bool,
+}
+
+pub struct FolderPicker {
+ pub path: String,
+ pub parent: Option<String>,
+ pub dirs: Vec<Dir>,
+ pub query: Editor,
+ pub cursor: usize,
+ pub error: Option<String>,
+ /// `Some(backend)`: step 2 of a new bot. `None`: picking for the open form.
+ pub new_bot: Option<String>,
+}
+
+pub const COLORS: [&str; 11] =
+ ["black", "brown", "red", "orange", "yellow", "green", "cyan", "blue", "violet", "magenta", "gray"];
+pub const SHAPES: [&str; 8] = ["blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop"];
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Field {
+ Name,
+ Instructions,
+ Agent,
+ Model,
+ Folder,
+ Approvals,
+ Notify,
+ Color,
+ Shape,
+ Connectors,
+ Skills,
+}
+
+pub const FIELDS: [Field; 11] = [
+ Field::Name,
+ Field::Instructions,
+ Field::Agent,
+ Field::Model,
+ Field::Folder,
+ Field::Approvals,
+ Field::Notify,
+ Field::Color,
+ Field::Shape,
+ Field::Connectors,
+ Field::Skills,
+];
+
+pub struct Toggle {
+ pub id: String,
+ pub name: String,
+ pub on: bool,
+}
+
+pub struct Form {
+ pub bot_id: Option<String>,
+ pub name: Editor,
+ pub instructions: Editor,
+ pub backend: String,
+ pub model: Editor,
+ pub cwd: String,
+ pub auto: bool,
+ pub notify: bool,
+ pub color: usize,
+ pub shape: usize,
+ pub connectors: Vec<Toggle>,
+ pub skills: Vec<Toggle>,
+ pub field: usize,
+ /// Cursor inside the connector / skill toggles.
+ pub sub: usize,
+ pub error: Option<String>,
+ pub saving: bool,
+}
+
+impl Form {
+ pub fn current(&self) -> Field {
+ FIELDS[self.field]
+ }
+}
+
+pub enum Overlay {
+ Goto(Goto),
+ Help(Editor),
+ Confirm(Confirm),
+ Agents(AgentPicker),
+ Folder(FolderPicker),
+ Form(Box<Form>),
+ Usage,
+ Pair(Option<String>),
+}
+
+pub struct Toast {
+ pub text: String,
+ pub need: bool,
+ pub until: Instant,
+}
+
+#[derive(Clone)]
+pub enum Click {
+ Bot(String),
+ Option { entry: String, option: String },
+ Filter(usize),
+ Composer,
+}
+
+#[derive(Default)]
+pub struct Hits {
+ pub roster: Rect,
+ pub chat: Rect,
+ pub trace: Rect,
+ pub clicks: Vec<(Rect, Click)>,
+}
+
+#[allow(clippy::struct_excessive_bools, reason = "independent UI flags, not a state machine")]
+pub struct App {
+ pub client: Client,
+ tx: UnboundedSender<Msg>,
+ pub url: String,
+ pub host: String,
+ pub home: String,
+ pub online: bool,
+ pub error: Option<String>,
+ pub bots: HashMap<String, Bot>,
+ pub entries: HashMap<String, BTreeMap<i64, Entry>>,
+ pub usage: Value,
+ pub backends: Vec<Value>,
+ pub selected: Option<String>,
+ pub focus: Focus,
+ pub typing: bool,
+ /// Narrow layout: showing the chat page (else the roster page).
+ pub chat_page: bool,
+ pub drafts: HashMap<String, Editor>,
+ /// Lines scrolled up from the bottom of the chat (0 = follow new messages).
+ pub chat_scroll: usize,
+ pub trace_scroll: usize,
+ pub trace: TraceMode,
+ /// Turn shown in the trace; `None` follows the latest.
+ pub trace_turn: Option<i64>,
+ pub compact: bool,
+ pub overlays: Vec<Overlay>,
+ pub toasts: Vec<Toast>,
+ pub frame: u64,
+ pub term_focused: bool,
+ pub quit: bool,
+ pub hits: Hits,
+ pub width: Width,
+ /// Chat/trace viewport heights from the last draw, for page scrolling.
+ pub chat_height: usize,
+ pub chat_top: bool,
+ pub market: (Vec<Toggle>, Vec<Toggle>),
+ reading: HashSet<String>,
+ history_busy: HashSet<String>,
+ history_done: HashSet<String>,
+ pub hint: Option<(String, Instant)>,
+}
+
+impl App {
+ pub fn new(client: Client, tx: UnboundedSender<Msg>, url: String) -> Self {
+ Self {
+ client,
+ tx,
+ url,
+ host: String::new(),
+ home: String::new(),
+ online: false,
+ error: None,
+ bots: HashMap::new(),
+ entries: HashMap::new(),
+ usage: Value::Null,
+ backends: vec![],
+ selected: None,
+ focus: Focus::Roster,
+ typing: false,
+ chat_page: false,
+ drafts: HashMap::new(),
+ chat_scroll: 0,
+ trace_scroll: 0,
+ trace: TraceMode::Off,
+ trace_turn: None,
+ compact: false,
+ overlays: vec![],
+ toasts: vec![],
+ frame: 0,
+ term_focused: true,
+ quit: false,
+ hits: Hits::default(),
+ width: Width::Wide,
+ chat_height: 20,
+ chat_top: false,
+ market: (vec![], vec![]),
+ reading: HashSet::new(),
+ history_busy: HashSet::new(),
+ history_done: HashSet::new(),
+ hint: None,
+ }
+ }
+
+ pub fn call(&self, method: &'static str, body: Value, after: After) {
+ self.client.spawn_call(method, body, after, self.tx.clone());
+ }
+
+ // ---------- derived ----------
+
+ /// Roster order: pinned first, then most recent (same as the phone).
+ pub fn roster(&self) -> Vec<&Bot> {
+ let mut v: Vec<&Bot> = self.bots.values().filter(|b| !b.hidden).collect();
+ v.sort_by(|a, b| b.pinned.cmp(&a.pinned).then(b.last_at.cmp(&a.last_at)).then(a.name.cmp(&b.name)));
+ v
+ }
+
+ pub fn bot(&self) -> Option<&Bot> {
+ self.selected.as_ref().and_then(|id| self.bots.get(id))
+ }
+
+ pub fn counts(&self) -> [usize; 4] {
+ let mut c = [0; 4];
+ for b in self.bots.values().filter(|b| !b.hidden) {
+ match b.mark() {
+ Mark::Need => c[0] += 1,
+ Mark::Work => c[1] += 1,
+ Mark::Unread => c[2] += 1,
+ Mark::Error => c[3] += 1,
+ Mark::Idle => {}
+ }
+ }
+ c
+ }
+
+ pub fn pending(&self) -> Option<&Entry> {
+ let id = self.selected.as_ref()?;
+ self.entries.get(id)?.values().rev().find(|e| e.pending())
+ }
+
+ pub fn latest_turn(&self, bot: &str) -> Option<i64> {
+ self.entries.get(bot)?.values().map(|e| e.turn).max()
+ }
+
+ /// Whether every older entry of this bot is loaded.
+ pub fn history_complete(&self, id: &str) -> bool {
+ self.history_done.contains(id) || self.entries.get(id).and_then(|m| m.keys().next()).is_none_or(|&s| s <= 1)
+ }
+
+ pub fn chat_visible(&self) -> bool {
+ self.selected.is_some() && (self.width != Width::Narrow || self.chat_page) && self.trace != TraceMode::Full
+ }
+
+ pub fn animating(&self) -> bool {
+ !self.toasts.is_empty() || self.hint.is_some() || self.bots.values().any(|b| b.status == Status::Working)
+ }
+
+ fn select(&mut self, id: &str) {
+ if self.selected.as_deref() != Some(id) {
+ self.selected = Some(id.to_owned());
+ self.chat_scroll = 0;
+ self.trace_scroll = 0;
+ self.trace_turn = None;
+ }
+ }
+
+ fn move_bot(&mut self, delta: isize) {
+ let ids: Vec<String> = self.roster().iter().map(|b| b.id.clone()).collect();
+ if ids.is_empty() {
+ return;
+ }
+ let i = self.selected.as_ref().and_then(|s| ids.iter().position(|x| x == s));
+ let n = isize::try_from(ids.len()).unwrap_or(isize::MAX);
+ let next = match i {
+ Some(i) => (isize::try_from(i).unwrap_or(0) + delta).clamp(0, n - 1),
+ None => 0,
+ };
+ let id = ids[usize::try_from(next).unwrap_or(0)].clone();
+ self.select(&id);
+ }
+
+ /// Next bot (after the selected one, wrapping) whose mark matches.
+ fn jump(&mut self, want: Mark) {
+ let ids: Vec<(String, Mark)> = self.roster().iter().map(|b| (b.id.clone(), b.mark())).collect();
+ let start = self.selected.as_ref().and_then(|s| ids.iter().position(|(x, _)| x == s)).map_or(0, |i| i + 1);
+ let found = (0..ids.len()).map(|k| &ids[(start + k) % ids.len()]).find(|(_, m)| *m == want).cloned();
+ match found {
+ Some((id, _)) => {
+ self.select(&id);
+ self.chat_page = true;
+ self.focus = Focus::Chat;
+ }
+ None => self.flash(match want {
+ Mark::Need => "No bot needs you",
+ Mark::Unread => "Nothing unread",
+ _ => "No match",
+ }),
+ }
+ }
+
+ pub fn flash(&mut self, s: &str) {
+ self.hint = Some((s.to_owned(), Instant::now() + Duration::from_secs(3)));
+ }
+
+ fn toast(&mut self, text: String, need: bool) {
+ if !self.term_focused {
+ // OSC 9 desktop notification (iTerm2, Ghostty, kitty, WezTerm…) plus a bell.
+ let mut out = std::io::stdout();
+ let _ = write!(out, "\x1b]9;{}\x07\x07", text.replace(['\x07', '\x1b'], ""));
+ let _ = out.flush();
+ }
+ self.toasts.retain(|t| t.text != text);
+ self.toasts.push(Toast { text, need, until: Instant::now() + Duration::from_secs(4) });
+ if self.toasts.len() > 2 {
+ self.toasts.remove(0);
+ }
+ }
+
+ /// Drops expired toasts and keeps the viewed bot marked read.
+ pub fn tick(&mut self) {
+ if self.selected.is_none()
+ && let Some(id) = self.roster().first().map(|b| b.id.clone())
+ {
+ self.selected = Some(id);
+ }
+ let now = Instant::now();
+ self.toasts.retain(|t| t.until > now);
+ if self.hint.as_ref().is_some_and(|(_, until)| *until <= now) {
+ self.hint = None;
+ }
+ if self.chat_visible()
+ && self.term_focused
+ && let Some(b) = self.bot()
+ && b.unread > 0
+ && !self.reading.contains(&b.id)
+ {
+ let id = b.id.clone();
+ self.reading.insert(id.clone());
+ self.call("markRead", json!({"botId": id}), After::Nothing);
+ }
+ if self.chat_top && self.chat_visible() {
+ self.load_history();
+ }
+ }
+
+ fn load_history(&mut self) {
+ let Some(id) = self.selected.clone() else { return };
+ if self.history_busy.contains(&id) || self.history_done.contains(&id) {
+ return;
+ }
+ let Some(oldest) = self.entries.get(&id).and_then(|m| m.keys().next().copied()) else { return };
+ if oldest <= 1 {
+ self.history_done.insert(id);
+ return;
+ }
+ self.history_busy.insert(id.clone());
+ self.call("history", json!({"botId": id, "beforeSeq": oldest, "limit": 200}), After::History(id));
+ }
+
+ // ---------- host messages ----------
+
+ pub fn on_msg(&mut self, m: Msg) {
+ match m {
+ Msg::Online(on) => {
+ self.online = on;
+ if !on && self.error.is_none() && self.bots.is_empty() {
+ // Say why instead of spinning on "Connecting…".
+ self.call("hello", json!({}), After::Hello);
+ }
+ if on {
+ self.error = None;
+ if self.host.is_empty() {
+ self.call("hello", json!({}), After::Hello);
+ }
+ }
+ }
+ Msg::Rewind => {
+ self.bots.clear();
+ self.entries.clear();
+ self.history_done.clear();
+ }
+ Msg::Event(v) => self.on_event(&v),
+ Msg::Reply(after, r) => self.on_reply(after, r),
+ }
+ }
+
+ fn on_event(&mut self, v: &Value) {
+ match v["type"].as_str() {
+ Some("hello") if !v["usage"].is_null() => self.usage = v["usage"].clone(),
+ Some("usage") => self.usage = v["usage"].clone(),
+ Some("bot") => self.upsert_bot(&v["bot"]),
+ Some("entry") => {
+ if let Some((bot, e)) = Entry::parse(&v["entry"]) {
+ self.entries.entry(bot).or_default().insert(e.seq, e);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn upsert_bot(&mut self, v: &Value) {
+ let Some(id) = v["id"].as_str() else { return };
+ if v["deleted"].as_bool().unwrap_or(false) {
+ self.bots.remove(id);
+ self.entries.remove(id);
+ if self.selected.as_deref() == Some(id) {
+ self.selected = None;
+ self.chat_page = false;
+ self.typing = false;
+ }
+ return;
+ }
+ let Some(new) = Bot::parse(v) else { return };
+ if new.unread == 0 {
+ self.reading.remove(&new.id);
+ }
+ let old = self.bots.insert(new.id.clone(), new.clone());
+ let Some(old) = old else { return };
+ let watching = self.selected.as_deref() == Some(new.id.as_str()) && self.chat_visible() && self.term_focused;
+ if !new.notify || watching {
+ return;
+ }
+ if new.status == Status::NeedsInput && old.status != Status::NeedsInput {
+ self.toast(format!("{} needs you", new.name), true);
+ } else if old.status == Status::Working && new.status == Status::Idle {
+ self.toast(format!("{} is done", new.name), false);
+ } else if old.status != Status::Error && new.status == Status::Error {
+ self.toast(format!("{} hit an error", new.name), true);
+ }
+ }
+
+ fn on_reply(&mut self, after: After, r: Result<Value, String>) {
+ let v = match r {
+ Ok(v) => v,
+ Err(e) => {
+ match after {
+ After::Hello => self.error = Some(e),
+ After::History(id) => {
+ self.history_busy.remove(&id);
+ }
+ After::Saved => {
+ if let Some(Overlay::Form(f)) = self.overlays.last_mut() {
+ f.saving = false;
+ f.error = Some(e);
+ }
+ }
+ After::Dirs => {
+ if let Some(Overlay::Folder(p)) = self.overlays.last_mut() {
+ p.error = Some(e);
+ }
+ }
+ _ => self.flash(&e),
+ }
+ return;
+ }
+ };
+ match after {
+ After::Nothing => {}
+ After::Installed => {
+ self.error = None;
+ self.flash("Host installed; connecting…");
+ self.call("hello", json!({}), After::Hello);
+ }
+ After::Hello => {
+ v["name"].as_str().unwrap_or("computer").clone_into(&mut self.host);
+ v["home"].as_str().unwrap_or_default().clone_into(&mut self.home);
+ self.backends = v["backends"].as_array().cloned().unwrap_or_default();
+ }
+ After::Backends => {
+ self.backends = v["backends"].as_array().cloned().unwrap_or_default();
+ self.flash("Agents refreshed");
+ }
+ After::History(id) => {
+ self.history_busy.remove(&id);
+ let list = v["entries"].as_array().cloned().unwrap_or_default();
+ if list.is_empty() {
+ self.history_done.insert(id);
+ }
+ for e in &list {
+ if let Some((bot, e)) = Entry::parse(e) {
+ self.entries.entry(bot).or_default().entry(e.seq).or_insert(e);
+ }
+ }
+ }
+ After::Dirs => {
+ if let Some(Overlay::Folder(p)) = self.overlays.last_mut() {
+ v["path"].as_str().unwrap_or_default().clone_into(&mut p.path);
+ p.parent = v["parent"].as_str().map(str::to_owned);
+ p.dirs = v["dirs"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|d| Dir {
+ name: d["name"].as_str().unwrap_or_default().to_owned(),
+ path: d["path"].as_str().unwrap_or_default().to_owned(),
+ git: d["isGit"].as_bool().unwrap_or(false),
+ })
+ .collect();
+ p.query.clear();
+ p.cursor = 0;
+ p.error = None;
+ }
+ }
+ After::Pairing => {
+ if let Some(Overlay::Pair(url)) = self.overlays.last_mut() {
+ *url = v["pairingUrl"].as_str().map(str::to_owned);
+ }
+ }
+ After::Saved => {
+ let saved = self.overlays.iter().rposition(|o| matches!(o, Overlay::Form(_)));
+ if let Some(i) = saved {
+ self.overlays.truncate(i);
+ }
+ if let Some(id) = v["bot"]["id"].as_str() {
+ let id = id.to_owned();
+ self.upsert_bot(&v["bot"]);
+ self.select(&id);
+ self.chat_page = true;
+ self.focus = Focus::Chat;
+ self.typing = true;
+ }
+ }
+ After::Connectors | After::Skills => {
+ let list: Vec<Toggle> = v["items"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|c| {
+ let id = c["id"].as_str()?.to_owned();
+ let name = c["name"].as_str().unwrap_or(&id).to_owned();
+ Some(Toggle { id, name, on: false })
+ })
+ .collect();
+ let connectors = matches!(after, After::Connectors);
+ if connectors {
+ self.market.0 = list;
+ } else {
+ self.market.1 = list;
+ }
+ for o in &mut self.overlays {
+ if let Overlay::Form(f) = o {
+ if connectors {
+ merge_toggles(&mut f.connectors, &self.market.0);
+ } else {
+ merge_toggles(&mut f.skills, &self.market.1);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // ---------- input ----------
+
+ pub fn on_paste(&mut self, s: &str) {
+ let s = s.replace("\r\n", "\n").replace('\r', "\n");
+ if let Some(ed) = self.top_editor() {
+ ed.insert(&s);
+ } else if let Some(id) = self.selected.clone() {
+ self.typing = true;
+ self.focus = Focus::Chat;
+ self.drafts.entry(id).or_default().insert(&s);
+ }
+ }
+
+ fn top_editor(&mut self) -> Option<&mut Editor> {
+ match self.overlays.last_mut()? {
+ Overlay::Goto(g) => Some(&mut g.query),
+ Overlay::Help(e) => Some(e),
+ Overlay::Agents(a) => Some(&mut a.query),
+ Overlay::Folder(p) => Some(&mut p.query),
+ Overlay::Form(f) => match f.current() {
+ Field::Name => Some(&mut f.name),
+ Field::Instructions => Some(&mut f.instructions),
+ Field::Model => Some(&mut f.model),
+ _ => None,
+ },
+ _ => None,
+ }
+ }
+
+ pub fn on_key(&mut self, k: KeyEvent) {
+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
+ if ctrl && k.code == KeyCode::Char('k') {
+ if matches!(self.overlays.last(), Some(Overlay::Goto(_))) {
+ self.overlays.pop();
+ } else {
+ self.overlays.push(Overlay::Goto(Goto { query: Editor::default(), filter: 0, cursor: 0 }));
+ }
+ return;
+ }
+ if !self.overlays.is_empty() {
+ self.overlay_key(k);
+ return;
+ }
+ if self.typing {
+ self.composer_key(k);
+ return;
+ }
+ self.nav_key(k);
+ }
+
+ fn composer_key(&mut self, k: KeyEvent) {
+ let Some(id) = self.selected.clone() else {
+ self.typing = false;
+ return;
+ };
+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
+ let newline = k.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT);
+ let draft = self.drafts.entry(id.clone()).or_default();
+ match k.code {
+ KeyCode::Esc => self.typing = false,
+ KeyCode::Enter if newline => draft.insert("\n"),
+ KeyCode::Char('j') if ctrl => draft.insert("\n"),
+ KeyCode::Enter => {
+ let text = draft.text.trim().to_owned();
+ if text.is_empty() {
+ return;
+ }
+ draft.clear();
+ self.chat_scroll = 0;
+ let nonce = uuid::Uuid::new_v4().to_string();
+ self.call("send", json!({"botId": id, "text": text, "clientNonce": nonce}), After::Nothing);
+ }
+ KeyCode::Char('c') if ctrl => {
+ if draft.text.is_empty() {
+ self.flash("esc then s stops the bot");
+ } else {
+ draft.clear();
+ }
+ }
+ KeyCode::Up if draft.text.is_empty() => self.scroll_chat(1),
+ KeyCode::Down if draft.text.is_empty() => self.scroll_chat(-1),
+ KeyCode::PageUp => self.scroll_chat(page(self.chat_height)),
+ KeyCode::PageDown => self.scroll_chat(-page(self.chat_height)),
+ KeyCode::Up => move_line(draft, -1),
+ KeyCode::Down => move_line(draft, 1),
+ _ => {
+ draft.key(k);
+ }
+ }
+ }
+
+ fn scroll_chat(&mut self, delta: isize) {
+ self.chat_scroll = self.chat_scroll.saturating_add_signed(delta);
+ }
+
+ fn scroll_trace(&mut self, delta: isize) {
+ self.trace_scroll = self.trace_scroll.saturating_add_signed(delta);
+ }
+
+ fn nav_key(&mut self, k: KeyEvent) {
+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
+ let half = page(self.chat_height) / 2;
+ let narrow = self.width == Width::Narrow;
+ let roster_page = narrow && !self.chat_page;
+ match k.code {
+ KeyCode::Char('c') if ctrl => self.flash("q quits"),
+ KeyCode::Char('d') if ctrl => self.scroll_focused(-half),
+ KeyCode::Char('u') if ctrl => self.scroll_focused(half),
+ KeyCode::Char('q') => self.quit = true,
+ KeyCode::Char('I') if self.error.is_some() && self.bots.is_empty() => self.install_host(),
+ KeyCode::Char('?') => self.overlays.push(Overlay::Help(Editor::default())),
+ KeyCode::Char('!') => self.jump(Mark::Need),
+ KeyCode::Char('u') => self.jump(Mark::Unread),
+ KeyCode::Char('[') => self.move_bot(-1),
+ KeyCode::Char(']') => self.move_bot(1),
+ KeyCode::Char(c @ '1'..='9') => {
+ let i = (c as usize) - ('1' as usize);
+ let pending = if roster_page { None } else { self.pending().map(|e| (e.id.clone(), e.options())) };
+ match pending {
+ Some((entry, opts)) if !opts.is_empty() => {
+ if let Some((option, _, _)) = opts.get(i) {
+ self.answer(&entry, option);
+ }
+ }
+ _ => {
+ if let Some(id) = self.roster().get(i).map(|b| b.id.clone()) {
+ self.select(&id);
+ }
+ }
+ }
+ }
+ KeyCode::Char(c @ ('y' | 'a' | 'n' | 'N')) if !roster_page && self.pending().is_some() => {
+ self.answer_kind(c);
+ }
+ KeyCode::Char('n') => self.new_bot(),
+ KeyCode::Char('i') if !roster_page => self.start_typing(),
+ KeyCode::Enter => {
+ if roster_page || self.focus == Focus::Roster {
+ if self.selected.is_some() {
+ self.chat_page = true;
+ self.focus = Focus::Chat;
+ self.start_typing();
+ }
+ } else {
+ self.start_typing();
+ }
+ }
+ KeyCode::Esc | KeyCode::Backspace => {
+ if self.trace == TraceMode::Full {
+ self.trace = TraceMode::Off;
+ self.focus = Focus::Chat;
+ } else if narrow && self.chat_page {
+ self.chat_page = false;
+ self.focus = Focus::Roster;
+ } else if self.focus == Focus::Trace {
+ self.focus = Focus::Chat;
+ }
+ }
+ KeyCode::Tab | KeyCode::BackTab => self.cycle_focus(k.code == KeyCode::BackTab),
+ KeyCode::Char('h') | KeyCode::Left => self.focus_side(-1),
+ KeyCode::Char('l') | KeyCode::Right => self.focus_side(1),
+ KeyCode::Char('j') | KeyCode::Down => self.line(1),
+ KeyCode::Char('k') | KeyCode::Up => self.line(-1),
+ KeyCode::PageDown => self.scroll_focused(-page(self.chat_height)),
+ KeyCode::PageUp => self.scroll_focused(page(self.chat_height)),
+ KeyCode::Char('g') | KeyCode::Home => {
+ if self.focus == Focus::Trace {
+ self.trace_scroll = 0;
+ } else {
+ self.chat_scroll = usize::MAX / 2;
+ }
+ }
+ KeyCode::Char('G') | KeyCode::End => {
+ if self.focus == Focus::Trace {
+ self.trace_scroll = usize::MAX / 2;
+ } else {
+ self.chat_scroll = 0;
+ }
+ }
+ KeyCode::Char('{') => self.step_turn(-1),
+ KeyCode::Char('}') => self.step_turn(1),
+ KeyCode::Char('t') => {
+ self.trace = if self.trace == TraceMode::Pane { TraceMode::Off } else { TraceMode::Pane };
+ if self.trace == TraceMode::Off && self.focus == Focus::Trace {
+ self.focus = Focus::Chat;
+ }
+ if self.width == Width::Narrow || self.width == Width::Mid {
+ self.trace = if self.trace == TraceMode::Off { TraceMode::Off } else { TraceMode::Full };
+ }
+ }
+ KeyCode::Char('T') => {
+ self.trace = if self.trace == TraceMode::Full { TraceMode::Off } else { TraceMode::Full };
+ self.focus = if self.trace == TraceMode::Full { Focus::Trace } else { Focus::Chat };
+ }
+ KeyCode::Char('o') => {
+ let Some(id) = self.selected.clone() else { return };
+ // The newest turn that did something.
+ self.trace_turn = self
+ .entries
+ .get(&id)
+ .and_then(|m| m.values().rev().find(|e| matches!(e.kind, Kind::Tool | Kind::Plan)).map(|e| e.turn));
+ self.trace_scroll = 0;
+ if self.trace == TraceMode::Off {
+ self.trace = if matches!(self.width, Width::Narrow | Width::Mid) {
+ TraceMode::Full
+ } else {
+ TraceMode::Pane
+ };
+ }
+ self.focus = Focus::Trace;
+ }
+ KeyCode::Char('b') => self.compact = !self.compact,
+ KeyCode::Char('U') => self.overlays.push(Overlay::Usage),
+ KeyCode::Char('P') => self.open_pair(),
+ KeyCode::Char('s') => {
+ if let Some(b) = self.bot() {
+ if matches!(b.status, Status::Working | Status::NeedsInput) {
+ let id = b.id.clone();
+ self.call("stop", json!({"botId": id}), After::Nothing);
+ self.flash("Stopping…");
+ } else {
+ self.flash("Not working right now");
+ }
+ }
+ }
+ KeyCode::Char('S') => {
+ if let Some(b) = self.bot() {
+ let c = Confirm {
+ title: format!("Start a new session for {}?", b.name),
+ detail: "The agent forgets this conversation's context.".into(),
+ note: "The transcript stays here.".into(),
+ button: "New session",
+ act: ConfirmAct::NewSession(b.id.clone()),
+ };
+ self.overlays.push(Overlay::Confirm(c));
+ }
+ }
+ KeyCode::Char('x') => {
+ if let Some(b) = self.bot() {
+ let c = Confirm {
+ title: format!("Delete {}?", b.name),
+ detail: "Its conversation and settings go away.".into(),
+ note: format!("Files in {} stay where they are.", tilde(&b.cwd, &self.home)),
+ button: "Delete",
+ act: ConfirmAct::Delete(b.id.clone()),
+ };
+ self.overlays.push(Overlay::Confirm(c));
+ }
+ }
+ KeyCode::Char('e') => self.edit_bot(),
+ KeyCode::Char('p') => {
+ if let Some(b) = self.bot() {
+ let (id, pinned) = (b.id.clone(), !b.pinned);
+ self.call("updateBot", json!({"id": id, "pinned": pinned}), After::Nothing);
+ }
+ }
+ KeyCode::Char('c') => self.copy_last(),
+ _ => {}
+ }
+ }
+
+ /// `codync-host install` with this same binary, for when nothing is listening yet.
+ fn install_host(&mut self) {
+ let Ok(exe) = std::env::current_exe() else { return };
+ self.flash("Installing the host…");
+ let tx = self.tx.clone();
+ tokio::spawn(async move {
+ let out = tokio::process::Command::new(exe).arg("install").output().await;
+ let r = match out {
+ Ok(o) if o.status.success() => Ok(Value::Null),
+ Ok(o) => Err(String::from_utf8_lossy(&o.stderr).trim().to_owned()),
+ Err(e) => Err(e.to_string()),
+ };
+ let _ = tx.send(Msg::Reply(After::Installed, r));
+ });
+ }
+
+ fn start_typing(&mut self) {
+ if self.selected.is_some() {
+ self.typing = true;
+ self.chat_page = true;
+ self.focus = Focus::Chat;
+ if self.trace == TraceMode::Full {
+ self.trace = TraceMode::Off;
+ }
+ }
+ }
+
+ fn line(&mut self, d: isize) {
+ match self.focus {
+ Focus::Roster => self.move_bot(d),
+ Focus::Chat if self.width == Width::Narrow && !self.chat_page => self.move_bot(d),
+ Focus::Chat => self.scroll_chat(-d),
+ Focus::Trace => self.scroll_trace(d),
+ }
+ }
+
+ fn scroll_focused(&mut self, up: isize) {
+ if self.focus == Focus::Trace {
+ self.scroll_trace(-up);
+ } else {
+ self.scroll_chat(up);
+ }
+ }
+
+ fn panes(&self) -> Vec<Focus> {
+ let mut p = vec![];
+ if self.width != Width::Narrow {
+ p.push(Focus::Roster);
+ }
+ if self.trace != TraceMode::Full {
+ p.push(Focus::Chat);
+ }
+ if self.trace != TraceMode::Off {
+ p.push(Focus::Trace);
+ }
+ p
+ }
+
+ fn cycle_focus(&mut self, back: bool) {
+ let p = self.panes();
+ let i = p.iter().position(|f| *f == self.focus).unwrap_or(0);
+ let n = p.len();
+ self.focus = p[if back { (i + n - 1) % n } else { (i + 1) % n }];
+ }
+
+ fn focus_side(&mut self, d: isize) {
+ let p = self.panes();
+ let i = p.iter().position(|f| *f == self.focus).unwrap_or(0);
+ let j = i.saturating_add_signed(d).min(p.len() - 1);
+ self.focus = p[j];
+ }
+
+ fn step_turn(&mut self, d: i64) {
+ let Some(id) = self.selected.clone() else { return };
+ let Some(latest) = self.latest_turn(&id) else { return };
+ let cur = self.trace_turn.unwrap_or(latest);
+ let next = (cur + d).clamp(1, latest);
+ self.trace_turn = if next == latest { None } else { Some(next) };
+ self.trace_scroll = 0;
+ if self.trace == TraceMode::Off {
+ self.trace =
+ if matches!(self.width, Width::Narrow | Width::Mid) { TraceMode::Full } else { TraceMode::Pane };
+ }
+ }
+
+ fn answer(&mut self, entry: &str, option: &str) {
+ self.call("respondPermission", json!({"entryId": entry, "optionId": option}), After::Nothing);
+ }
+
+ fn answer_kind(&mut self, key: char) {
+ let Some(e) = self.pending() else { return };
+ let (entry, opts) = (e.id.clone(), e.options());
+ let want: &[&str] = match key {
+ 'y' => &["allow_once", "allow_always"],
+ 'a' => &["allow_always", "allow_once"],
+ _ => &["reject_once", "reject_always"],
+ };
+ let pick = want.iter().find_map(|k| opts.iter().find(|(_, _, kind)| kind == k));
+ match pick {
+ Some((option, _, _)) => {
+ let option = option.clone();
+ self.answer(&entry, &option);
+ if key == 'N' {
+ self.start_typing();
+ }
+ }
+ None => self.flash("That choice isn't offered; use 1–9"),
+ }
+ }
+
+ fn copy_last(&mut self) {
+ let Some(id) = self.selected.clone() else { return };
+ let Some(text) =
+ self.entries.get(&id).and_then(|m| m.values().rev().find(|e| e.is_final()).map(|e| e.text().to_owned()))
+ else {
+ self.flash("No reply to copy");
+ return;
+ };
+ // OSC 52: the terminal puts it on the clipboard, over SSH too.
+ let mut out = std::io::stdout();
+ let _ = write!(out, "\x1b]52;c;{}\x07", base64(text.as_bytes()));
+ let _ = out.flush();
+ self.flash("Copied the last reply");
+ }
+
+ fn open_pair(&mut self) {
+ self.overlays.push(Overlay::Pair(None));
+ self.call("pairing", json!({}), After::Pairing);
+ }
+
+ fn new_bot(&mut self) {
+ if self.backends.is_empty() {
+ self.call("hello", json!({}), After::Hello);
+ }
+ self.overlays.push(Overlay::Agents(AgentPicker { query: Editor::default(), cursor: 0 }));
+ }
+
+ fn edit_bot(&mut self) {
+ let Some(b) = self.bot().cloned() else { return };
+ let mut f = Form {
+ bot_id: Some(b.id.clone()),
+ name: Editor::with(&b.name),
+ instructions: Editor::with(&b.description),
+ backend: b.backend.clone(),
+ model: Editor::with(b.model.as_deref().unwrap_or_default()),
+ cwd: b.cwd.clone(),
+ auto: b.auto,
+ notify: b.notify,
+ color: COLORS.iter().position(|c| *c == b.color).unwrap_or(7),
+ shape: SHAPES.iter().position(|s| *s == b.shape).unwrap_or(0),
+ connectors: b.connectors.iter().map(|id| Toggle { id: id.clone(), name: id.clone(), on: true }).collect(),
+ skills: b.skills.iter().map(|id| Toggle { id: id.clone(), name: id.clone(), on: true }).collect(),
+ field: 0,
+ sub: 0,
+ error: None,
+ saving: false,
+ };
+ merge_toggles(&mut f.connectors, &self.market.0);
+ merge_toggles(&mut f.skills, &self.market.1);
+ self.overlays.push(Overlay::Form(Box::new(f)));
+ self.call("connectors", json!({}), After::Connectors);
+ self.call("skills", json!({}), After::Skills);
+ }
+
+ /// Agents offered for a new bot: runnable ones on this computer first.
+ pub fn agent_choices(&self, query: &str) -> Vec<&Value> {
+ let mut v: Vec<&Value> = self
+ .backends
+ .iter()
+ .filter(|b| b["available"].as_bool().unwrap_or(false) || b["registry"].is_string())
+ .filter(|b| fuzzy(query, &[b["name"].as_str().unwrap_or_default(), b["id"].as_str().unwrap_or_default()]))
+ .collect();
+ v.sort_by_key(|b| !b["installed"].as_bool().unwrap_or(false));
+ v
+ }
+
+ pub fn goto_items(&self, g: &Goto) -> Vec<GotoItem> {
+ let q = g.query.text.trim();
+ let want = FILTERS[g.filter].1;
+ let mut bots: Vec<&Bot> = self
+ .bots
+ .values()
+ .filter(|b| want.is_none_or(|m| b.mark() == m))
+ .filter(|b| fuzzy(q, &[&b.name, &b.backend]) || contains(q, &[&b.cwd, &b.last_message]))
+ .collect();
+ bots.sort_by(|a, b| {
+ b.mark().priority().cmp(&a.mark().priority()).then(b.last_at.cmp(&a.last_at)).then(a.name.cmp(&b.name))
+ });
+ let mut items: Vec<GotoItem> = bots.into_iter().map(|b| GotoItem::Bot(b.id.clone())).collect();
+ if want.is_none() {
+ items.extend(
+ ACTIONS.iter().filter(|(label, _, _)| fuzzy(q, &[label])).map(|(_, _, a)| GotoItem::Action(*a)),
+ );
+ }
+ items
+ }
+
+ fn run_action(&mut self, a: Action) {
+ match a {
+ Action::NewBot => self.new_bot(),
+ Action::RefreshAgents => self.call("refreshBackends", json!({}), After::Backends),
+ Action::Pair => self.open_pair(),
+ Action::Usage => self.overlays.push(Overlay::Usage),
+ Action::Keys => self.overlays.push(Overlay::Help(Editor::default())),
+ }
+ }
+
+ fn overlay_key(&mut self, k: KeyEvent) {
+ let Some(top) = self.overlays.pop() else { return };
+ let depth = self.overlays.len();
+ let keep = match top {
+ Overlay::Goto(g) => self.goto_key(g, k),
+ Overlay::Help(mut e) => {
+ if k.code == KeyCode::Esc || k.code == KeyCode::Char('?') && e.text.is_empty() {
+ None
+ } else {
+ if k.code != KeyCode::Char('/') || !e.text.is_empty() {
+ e.key(k);
+ }
+ Some(Overlay::Help(e))
+ }
+ }
+ Overlay::Confirm(c) => match k.code {
+ KeyCode::Enter => {
+ match &c.act {
+ ConfirmAct::Delete(id) => self.call("deleteBot", json!({"botId": id}), After::Nothing),
+ ConfirmAct::NewSession(id) => self.call("newSession", json!({"botId": id}), After::Nothing),
+ }
+ None
+ }
+ KeyCode::Esc | KeyCode::Char('q') => None,
+ _ => Some(Overlay::Confirm(c)),
+ },
+ Overlay::Agents(a) => self.agents_key(a, k),
+ Overlay::Folder(p) => self.folder_key(p, k),
+ Overlay::Form(f) => self.form_key(f, k),
+ o @ (Overlay::Usage | Overlay::Pair(_)) => {
+ if matches!(k.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | 'U' | 'P')) {
+ None
+ } else {
+ Some(o)
+ }
+ }
+ };
+ if let Some(o) = keep {
+ // Anything the handler opened stays on top of the overlay it came from.
+ self.overlays.insert(depth.min(self.overlays.len()), o);
+ }
+ }
+
+ fn goto_key(&mut self, mut g: Goto, k: KeyEvent) -> Option<Overlay> {
+ let items_len = self.goto_items(&g).len();
+ match k.code {
+ KeyCode::Esc => return None,
+ KeyCode::Tab => {
+ g.filter = (g.filter + 1) % FILTERS.len();
+ g.cursor = 0;
+ }
+ KeyCode::BackTab => {
+ g.filter = (g.filter + FILTERS.len() - 1) % FILTERS.len();
+ g.cursor = 0;
+ }
+ KeyCode::Down => g.cursor = (g.cursor + 1).min(items_len.saturating_sub(1)),
+ KeyCode::Up => g.cursor = g.cursor.saturating_sub(1),
+ KeyCode::Char('n' | 'j') if k.modifiers.contains(KeyModifiers::CONTROL) => {
+ g.cursor = (g.cursor + 1).min(items_len.saturating_sub(1));
+ }
+ KeyCode::Char('p') if k.modifiers.contains(KeyModifiers::CONTROL) => g.cursor = g.cursor.saturating_sub(1),
+ KeyCode::Enter => {
+ let items = self.goto_items(&g);
+ match items.get(g.cursor) {
+ Some(GotoItem::Bot(id)) => {
+ let id = id.clone();
+ self.select(&id);
+ self.start_typing();
+ }
+ Some(GotoItem::Action(a)) => self.run_action(*a),
+ None => {}
+ }
+ return None;
+ }
+ _ => {
+ if g.query.key(k) {
+ g.cursor = 0;
+ }
+ }
+ }
+ Some(Overlay::Goto(g))
+ }
+
+ fn agents_key(&mut self, mut a: AgentPicker, k: KeyEvent) -> Option<Overlay> {
+ let n = self.agent_choices(&a.query.text).len();
+ match k.code {
+ KeyCode::Esc => return None,
+ KeyCode::Down => a.cursor = (a.cursor + 1).min(n.saturating_sub(1)),
+ KeyCode::Up => a.cursor = a.cursor.saturating_sub(1),
+ KeyCode::Enter => {
+ let backend =
+ self.agent_choices(&a.query.text).get(a.cursor).and_then(|b| b["id"].as_str()).map(str::to_owned);
+ if let Some(backend) = backend {
+ let start = self.bot().map(|b| parent_dir(&b.cwd)).unwrap_or_default();
+ self.overlays.push(Overlay::Agents(a));
+ self.open_folder(Some(backend), &start);
+ return None;
+ }
+ }
+ _ => {
+ if a.query.key(k) {
+ a.cursor = 0;
+ }
+ }
+ }
+ Some(Overlay::Agents(a))
+ }
+
+ fn open_folder(&mut self, new_bot: Option<String>, start: &str) {
+ self.overlays.push(Overlay::Folder(FolderPicker {
+ path: start.to_owned(),
+ parent: None,
+ dirs: vec![],
+ query: Editor::default(),
+ cursor: 0,
+ error: None,
+ new_bot,
+ }));
+ let body = if start.is_empty() { json!({}) } else { json!({"path": start}) };
+ self.call("listDirs", body, After::Dirs);
+ }
+
+ pub fn folder_matches(p: &FolderPicker) -> Vec<&Dir> {
+ p.dirs.iter().filter(|d| fuzzy(&p.query.text, &[&d.name])).collect()
+ }
+
+ fn folder_key(&mut self, mut p: FolderPicker, k: KeyEvent) -> Option<Overlay> {
+ let matches: Vec<Dir> = Self::folder_matches(&p).into_iter().cloned().collect();
+ match k.code {
+ KeyCode::Esc => return None,
+ KeyCode::Down => p.cursor = (p.cursor + 1).min(matches.len().saturating_sub(1)),
+ KeyCode::Up => p.cursor = p.cursor.saturating_sub(1),
+ KeyCode::Right | KeyCode::Tab => {
+ if let Some(d) = matches.get(p.cursor) {
+ let path = d.path.clone();
+ self.call("listDirs", json!({"path": path}), After::Dirs);
+ }
+ }
+ KeyCode::Left | KeyCode::Backspace if p.query.text.is_empty() => {
+ if let Some(parent) = p.parent.clone() {
+ self.call("listDirs", json!({"path": parent}), After::Dirs);
+ }
+ }
+ KeyCode::Enter => {
+ // Enter on a highlighted child uses it; with nothing typed and no match, the current folder.
+ let chosen = if p.query.text.is_empty() && k.modifiers.contains(KeyModifiers::ALT) {
+ p.path.clone()
+ } else {
+ matches.get(p.cursor).map_or_else(|| p.path.clone(), |d| d.path.clone())
+ };
+ self.folder_chosen(p.new_bot.take(), chosen);
+ return None;
+ }
+ KeyCode::Char('.') if p.query.text.is_empty() => {
+ let chosen = p.path.clone();
+ self.folder_chosen(p.new_bot.take(), chosen);
+ return None;
+ }
+ _ => {
+ if p.query.key(k) {
+ p.cursor = 0;
+ }
+ }
+ }
+ Some(Overlay::Folder(p))
+ }
+
+ fn folder_chosen(&mut self, new_bot: Option<String>, path: String) {
+ if let Some(backend) = new_bot {
+ // Step 3: name and looks, prefilled.
+ if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Agents(_))) {
+ self.overlays.truncate(i);
+ }
+ let n = self.bots.len() + usize::try_from(crate::store::now_ms() % 97).unwrap_or(0);
+ let name = NAMES[n % NAMES.len()].to_owned();
+ let f = Form {
+ bot_id: None,
+ name: Editor::with(&name),
+ instructions: Editor::default(),
+ backend,
+ model: Editor::default(),
+ cwd: path,
+ auto: false,
+ notify: true,
+ color: (n * 7) % COLORS.len(),
+ shape: n % SHAPES.len(),
+ connectors: self
+ .market
+ .0
+ .iter()
+ .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: false })
+ .collect(),
+ skills: self
+ .market
+ .1
+ .iter()
+ .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: false })
+ .collect(),
+ field: 0,
+ sub: 0,
+ error: None,
+ saving: false,
+ };
+ self.overlays.push(Overlay::Form(Box::new(f)));
+ self.call("connectors", json!({}), After::Connectors);
+ self.call("skills", json!({}), After::Skills);
+ } else if let Some(Overlay::Form(f)) = self.overlays.last_mut() {
+ f.cwd = path;
+ }
+ }
+
+ fn form_key(&mut self, mut f: Box<Form>, k: KeyEvent) -> Option<Overlay> {
+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
+ let field = f.current();
+ match k.code {
+ KeyCode::Esc => return None,
+ KeyCode::Char('s') if ctrl => {
+ self.save_form(&mut f);
+ }
+ KeyCode::Tab | KeyCode::Down => {
+ f.field = (f.field + 1) % FIELDS.len();
+ f.sub = 0;
+ }
+ KeyCode::BackTab | KeyCode::Up => {
+ f.field = (f.field + FIELDS.len() - 1) % FIELDS.len();
+ f.sub = 0;
+ }
+ KeyCode::Enter
+ if field == Field::Instructions && k.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) =>
+ {
+ f.instructions.insert("\n");
+ }
+ KeyCode::Char('j') if ctrl && field == Field::Instructions => f.instructions.insert("\n"),
+ KeyCode::Enter if field == Field::Folder => {
+ let start = f.cwd.clone();
+ self.overlays.push(Overlay::Form(f));
+ self.open_folder(None, &start);
+ return None;
+ }
+ KeyCode::Enter => self.save_form(&mut f),
+ KeyCode::Left | KeyCode::Right | KeyCode::Char(' ')
+ if matches!(
+ field,
+ Field::Agent
+ | Field::Approvals
+ | Field::Notify
+ | Field::Color
+ | Field::Shape
+ | Field::Connectors
+ | Field::Skills
+ ) =>
+ {
+ let d: isize = if k.code == KeyCode::Left { -1 } else { 1 };
+ let space = k.code == KeyCode::Char(' ');
+ match field {
+ Field::Agent if !space => {
+ let ids: Vec<String> =
+ self.agent_choices("").iter().filter_map(|b| b["id"].as_str().map(str::to_owned)).collect();
+ if !ids.is_empty() {
+ let i = ids.iter().position(|x| *x == f.backend).unwrap_or(0);
+ f.backend.clone_from(&ids[cycle(i, d, ids.len())]);
+ }
+ }
+ Field::Approvals => f.auto = !f.auto,
+ Field::Notify => f.notify = !f.notify,
+ Field::Color if !space => f.color = cycle(f.color, d, COLORS.len()),
+ Field::Shape if !space => f.shape = cycle(f.shape, d, SHAPES.len()),
+ Field::Connectors | Field::Skills => {
+ let list = if field == Field::Connectors { &mut f.connectors } else { &mut f.skills };
+ if space {
+ if let Some(t) = list.get_mut(f.sub) {
+ t.on = !t.on;
+ }
+ } else if !list.is_empty() {
+ f.sub = cycle(f.sub, d, list.len());
+ }
+ }
+ _ => {}
+ }
+ }
+ _ => {
+ let ed = match field {
+ Field::Name => Some(&mut f.name),
+ Field::Instructions => Some(&mut f.instructions),
+ Field::Model => Some(&mut f.model),
+ _ => None,
+ };
+ if let Some(ed) = ed {
+ ed.key(k);
+ }
+ }
+ }
+ Some(Overlay::Form(f))
+ }
+
+ fn save_form(&mut self, f: &mut Form) {
+ if f.saving {
+ return;
+ }
+ if f.name.text.trim().is_empty() {
+ f.error = Some("Give the bot a name.".into());
+ return;
+ }
+ let model = f.model.text.trim();
+ let mut body = json!({
+ "name": f.name.text.trim(),
+ "description": f.instructions.text.trim(),
+ "backend": f.backend,
+ "cwd": f.cwd,
+ "permission": if f.auto { "auto" } else { "ask" },
+ "model": if model.is_empty() { Value::Null } else { model.into() },
+ "notify": f.notify,
+ "avatarColor": COLORS[f.color],
+ "avatarShape": SHAPES[f.shape],
+ "connectors": f.connectors.iter().filter(|t| t.on).map(|t| t.id.clone()).collect::<Vec<_>>(),
+ "skills": f.skills.iter().filter(|t| t.on).map(|t| t.id.clone()).collect::<Vec<_>>(),
+ });
+ f.saving = true;
+ f.error = None;
+ match &f.bot_id {
+ Some(id) => {
+ body["id"] = id.clone().into();
+ self.call("updateBot", body, After::Saved);
+ }
+ None => self.call("createBot", body, After::Saved),
+ }
+ }
+
+ // ---------- mouse ----------
+
+ pub fn on_mouse(&mut self, m: MouseEvent) {
+ let at = Position::new(m.column, m.row);
+ match m.kind {
+ MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
+ let d: isize = if m.kind == MouseEventKind::ScrollUp { -3 } else { 3 };
+ if self.hits.trace.contains(at) {
+ self.scroll_trace(d);
+ } else if self.hits.chat.contains(at) {
+ self.scroll_chat(-d);
+ } else if self.hits.roster.contains(at) {
+ self.move_bot(d.signum());
+ }
+ }
+ MouseEventKind::Down(MouseButton::Left) => {
+ let hit = self.hits.clicks.iter().rev().find(|(r, _)| r.contains(at)).map(|(_, c)| c.clone());
+ match hit {
+ Some(Click::Bot(id)) => {
+ self.overlays.clear();
+ self.select(&id);
+ self.focus = Focus::Roster;
+ if self.width == Width::Narrow {
+ self.chat_page = true;
+ self.focus = Focus::Chat;
+ }
+ }
+ Some(Click::Option { entry, option }) => self.answer(&entry, &option),
+ Some(Click::Filter(i)) => {
+ if let Some(Overlay::Goto(g)) = self.overlays.last_mut() {
+ g.filter = i;
+ g.cursor = 0;
+ } else {
+ self.overlays.push(Overlay::Goto(Goto { query: Editor::default(), filter: i, cursor: 0 }));
+ }
+ }
+ Some(Click::Composer) => self.start_typing(),
+ None => {
+ if self.overlays.is_empty() {
+ if self.hits.trace.contains(at) {
+ self.focus = Focus::Trace;
+ } else if self.hits.chat.contains(at) {
+ self.focus = Focus::Chat;
+ } else if self.hits.roster.contains(at) {
+ self.focus = Focus::Roster;
+ }
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+const NAMES: [&str; 24] = [
+ "Ada", "Rex", "Mia", "Sol", "Kit", "Oli", "Ivy", "Max", "Zoe", "Leo", "Ari", "Bea", "Cal", "Dot", "Eli", "Fay",
+ "Gus", "Hal", "Ida", "Jin", "Kai", "Lux", "Nia", "Otto",
+];
+
+fn page(h: usize) -> isize {
+ isize::try_from(h.max(4)).unwrap_or(20) - 2
+}
+
+fn cycle(i: usize, d: isize, n: usize) -> usize {
+ let n = isize::try_from(n).unwrap_or(1).max(1);
+ usize::try_from((isize::try_from(i).unwrap_or(0) + d).rem_euclid(n)).unwrap_or(0)
+}
+
+fn merge_toggles(have: &mut Vec<Toggle>, all: &[Toggle]) {
+ for t in all {
+ match have.iter_mut().find(|h| h.id == t.id) {
+ Some(h) => h.name.clone_from(&t.name),
+ None => have.push(Toggle { id: t.id.clone(), name: t.name.clone(), on: false }),
+ }
+ }
+}
+
+fn move_line(e: &mut Editor, d: isize) {
+ let start = e.text[..e.cursor].rfind('\n').map_or(0, |i| i + 1);
+ let col = e.text[start..e.cursor].chars().count();
+ let target_start = if d < 0 {
+ if start == 0 {
+ return;
+ }
+ e.text[..start - 1].rfind('\n').map_or(0, |i| i + 1)
+ } else {
+ match e.text[e.cursor..].find('\n') {
+ Some(i) => e.cursor + i + 1,
+ None => return,
+ }
+ };
+ let line_end = e.text[target_start..].find('\n').map_or(e.text.len(), |i| target_start + i);
+ e.cursor = e.text[target_start..line_end].char_indices().nth(col).map_or(line_end, |(i, _)| target_start + i);
+}
+
+/// Case-insensitive substring match: for long fields where a subsequence matches almost anything.
+fn contains(query: &str, fields: &[&str]) -> bool {
+ let q = query.to_lowercase();
+ fields.iter().any(|f| f.to_lowercase().contains(&q))
+}
+
+/// Subsequence match, case-insensitive, over any of the fields.
+pub fn fuzzy(query: &str, fields: &[&str]) -> bool {
+ let q: Vec<char> = query.to_lowercase().chars().filter(|c| !c.is_whitespace()).collect();
+ if q.is_empty() {
+ return true;
+ }
+ fields.iter().any(|f| {
+ let mut it = q.iter().peekable();
+ for c in f.to_lowercase().chars() {
+ if it.peek() == Some(&&c) {
+ it.next();
+ }
+ }
+ it.peek().is_none()
+ })
+}
+
+pub fn tilde(path: &str, home: &str) -> String {
+ match path.strip_prefix(home) {
+ Some(rest) if !home.is_empty() => format!("~{rest}"),
+ _ => path.to_owned(),
+ }
+}
+
+fn parent_dir(path: &str) -> String {
+ std::path::Path::new(path).parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default()
+}
+
+fn base64(data: &[u8]) -> String {
+ const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
+ for chunk in data.chunks(3) {
+ let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
+ let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
+ for i in 0..4 {
+ if i <= chunk.len() {
+ out.push(char::from(T[((n >> (18 - 6 * i)) & 63) as usize]));
+ } else {
+ out.push('=');
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn base64_matches_rfc4648() {
+ assert_eq!(base64(b""), "");
+ assert_eq!(base64(b"f"), "Zg==");
+ assert_eq!(base64(b"fo"), "Zm8=");
+ assert_eq!(base64(b"foo"), "Zm9v");
+ assert_eq!(base64(b"foobar"), "Zm9vYmFy");
+ }
+
+ #[test]
+ fn fuzzy_is_a_subsequence_match() {
+ assert!(fuzzy("rx", &["Rex"]));
+ assert!(fuzzy("", &["anything"]));
+ assert!(!fuzzy("xr", &["Rex"]));
+ assert!(fuzzy("web", &["Rex", "~/mycode/web"]));
+ }
+
+ #[test]
+ fn editor_words_and_cuts() {
+ let mut e = Editor::with("hello brave world");
+ e.key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL));
+ assert_eq!(e.text, "hello brave ");
+ e.key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL));
+ assert_eq!(e.cursor, 0);
+ e.key(KeyEvent::new(KeyCode::Char('你'), KeyModifiers::NONE));
+ assert_eq!(e.text, "你hello brave ");
+ e.key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ assert_eq!(e.text, "hello brave ");
+ }
+
+ #[test]
+ fn permission_options_follow_app_order() {
+ let e = Entry {
+ id: "p".into(),
+ seq: 1,
+ turn: 1,
+ kind: Kind::Permission,
+ data: json!({"status": "pending", "options": [
+ {"optionId": "r", "name": "Reject", "kind": "reject_once"},
+ {"optionId": "a", "name": "Allow", "kind": "allow_once"},
+ ]}),
+ created_at: 0,
+ };
+ assert!(e.pending());
+ let kinds: Vec<String> = e.options().into_iter().map(|o| o.2).collect();
+ assert_eq!(kinds, ["allow_once", "reject_once"]);
+ }
+
+ #[test]
+ fn line_moves_keep_the_column() {
+ let mut e = Editor::with("abc\nde");
+ move_line(&mut e, -1);
+ assert_eq!(e.cursor, 2);
+ move_line(&mut e, 1);
+ assert_eq!(e.cursor, 6);
+ }
+}
diff --git a/host/src/tui/md.rs b/host/src/tui/md.rs
new file mode 100644
index 00000000..3df8bed7
--- /dev/null
+++ b/host/src/tui/md.rs
@@ -0,0 +1,293 @@
+//! Text layout for the terminal: a Markdown subset to styled lines, and wrapping
+//! that counts display width (CJK and emoji take two cells).
+
+use ratatui::style::{Modifier, Style};
+use ratatui::text::{Line, Span};
+use unicode_width::UnicodeWidthChar;
+
+use super::view::theme;
+
+pub fn width(s: &str) -> usize {
+ unicode_width::UnicodeWidthStr::width(s)
+}
+
+/// Cuts `s` to at most `max` cells, ending in `…` when it had to cut.
+pub fn truncate(s: &str, max: usize) -> String {
+ let s = s.lines().next().unwrap_or_default();
+ if width(s) <= max {
+ return s.to_owned();
+ }
+ let mut out = String::new();
+ let mut w = 0;
+ for c in s.chars() {
+ let cw = c.width().unwrap_or(0);
+ if w + cw + 1 > max {
+ break;
+ }
+ w += cw;
+ out.push(c);
+ }
+ out.push('…');
+ out
+}
+
+/// Wraps styled text to `width` cells. Breaks after spaces when it can, anywhere
+/// otherwise (so CJK text wraps between characters). `first` / `rest` prefix each line.
+pub fn wrap(
+ spans: &[Span<'static>],
+ width: usize,
+ first: &[Span<'static>],
+ rest: &[Span<'static>],
+) -> Vec<Line<'static>> {
+ let cells: Vec<(char, Style)> =
+ spans.iter().flat_map(|s| s.content.chars().map(move |c| (c, s.style))).filter(|(c, _)| *c != '\r').collect();
+ let mut out = vec![];
+ let mut i = 0;
+ let mut is_first = true;
+ loop {
+ let prefix = if is_first { first } else { rest };
+ let room = width.saturating_sub(prefix.iter().map(|s| self::width(&s.content)).sum()).max(1);
+ let (mut end, mut w, mut brk) = (i, 0, None);
+ while end < cells.len() {
+ let c = cells[end].0;
+ if c == '\n' {
+ break;
+ }
+ let cw = c.width().unwrap_or(0);
+ if w + cw > room {
+ break;
+ }
+ w += cw;
+ end += 1;
+ if c == ' ' {
+ brk = Some(end);
+ }
+ }
+ if end == i && end < cells.len() && cells[end].0 != '\n' {
+ end += 1; // a glyph wider than the room still has to go somewhere
+ }
+ let mut next = end;
+ if end < cells.len() && !matches!(cells[end].0, '\n' | ' ') {
+ if let Some(b) = brk.filter(|&b| b > i) {
+ end = b;
+ next = b;
+ }
+ } else if end < cells.len() && cells[end].0 == '\n' {
+ next = end + 1; // skip the newline
+ }
+ let mut line: Vec<Span<'static>> = prefix.to_vec();
+ let mut shown = end;
+ while shown > i && cells[shown - 1].0 == ' ' && next != cells.len() {
+ shown -= 1; // no trailing spaces at a soft break
+ }
+ push_cells(&mut line, &cells[i..shown]);
+ out.push(Line::from(line));
+ is_first = false;
+ if next >= cells.len() {
+ break;
+ }
+ i = next;
+ // Leading spaces after a soft break are dropped.
+ if cells[i - 1].0 != '\n' {
+ while i < cells.len() && cells[i].0 == ' ' {
+ i += 1;
+ }
+ if i >= cells.len() {
+ break;
+ }
+ }
+ }
+ out
+}
+
+fn push_cells(line: &mut Vec<Span<'static>>, cells: &[(char, Style)]) {
+ let mut run = String::new();
+ let mut style = None;
+ for &(c, s) in cells {
+ if style != Some(s) && !run.is_empty() {
+ line.push(Span::styled(std::mem::take(&mut run), style.unwrap_or_default()));
+ }
+ style = Some(s);
+ run.push(c);
+ }
+ if !run.is_empty() {
+ line.push(Span::styled(run, style.unwrap_or_default()));
+ }
+}
+
+/// Inline Markdown: `code`, **bold**, *italic* / _italic_, [text](url).
+pub fn inline(text: &str, base: Style) -> Vec<Span<'static>> {
+ let t = theme();
+ let mut out = vec![];
+ let mut run = String::new();
+ let (mut bold, mut italic) = (false, false);
+ let style = |bold: bool, italic: bool| {
+ let mut s = base;
+ if bold {
+ s = s.add_modifier(Modifier::BOLD);
+ }
+ if italic {
+ s = s.add_modifier(Modifier::ITALIC);
+ }
+ s
+ };
+ let chars: Vec<char> = text.chars().collect();
+ let mut i = 0;
+ let flush = |run: &mut String, out: &mut Vec<Span<'static>>, s: Style| {
+ if !run.is_empty() {
+ out.push(Span::styled(std::mem::take(run), s));
+ }
+ };
+ while i < chars.len() {
+ let c = chars[i];
+ if c == '`'
+ && let Some(len) = chars[i + 1..].iter().position(|&x| x == '`')
+ {
+ flush(&mut run, &mut out, style(bold, italic));
+ let code: String = chars[i + 1..i + 1 + len].iter().collect();
+ out.push(Span::styled(code, t.code));
+ i += len + 2;
+ continue;
+ }
+ if c == '*' && chars.get(i + 1) == Some(&'*') {
+ flush(&mut run, &mut out, style(bold, italic));
+ bold = !bold;
+ i += 2;
+ continue;
+ }
+ let word_edge = |j: usize| j == 0 || !chars[j - 1].is_alphanumeric();
+ if (c == '*' || (c == '_' && word_edge(i)) || (c == '_' && italic))
+ && (italic || chars[i + 1..].contains(&c))
+ && chars.get(i + 1).is_some_and(|n| !n.is_whitespace() || italic)
+ {
+ flush(&mut run, &mut out, style(bold, italic));
+ italic = !italic;
+ i += 1;
+ continue;
+ }
+ if c == '['
+ && let Some(close) = chars[i..].iter().position(|&x| x == ']').map(|p| p + i)
+ && chars.get(close + 1) == Some(&'(')
+ && let Some(end) = chars[close..].iter().position(|&x| x == ')').map(|p| p + close)
+ {
+ flush(&mut run, &mut out, style(bold, italic));
+ let label: String = chars[i + 1..close].iter().collect();
+ out.push(Span::styled(label, style(bold, italic).add_modifier(Modifier::UNDERLINED)));
+ i = end + 1;
+ continue;
+ }
+ run.push(c);
+ i += 1;
+ }
+ flush(&mut run, &mut out, style(bold, italic));
+ out
+}
+
+/// Block Markdown to wrapped lines: headings, lists, quotes, fenced code, rules.
+pub fn render(text: &str, width: usize, indent: usize) -> Vec<Line<'static>> {
+ let t = theme();
+ let pad = Span::raw(" ".repeat(indent));
+ let mut out = vec![];
+ let mut in_code = false;
+ for raw in text.lines() {
+ let trimmed = raw.trim_start();
+ if trimmed.starts_with("```") {
+ in_code = !in_code;
+ continue;
+ }
+ if in_code {
+ let code = raw.replace('\t', " ");
+ let room = width.saturating_sub(indent + 2).max(1);
+ let body = if self::width(&code) > room { truncate(&code, room) } else { code };
+ let fill = room.saturating_sub(self::width(&body));
+ out.push(Line::from(vec![
+ pad.clone(),
+ Span::styled(format!(" {body}{} ", " ".repeat(fill)), t.code_block),
+ ]));
+ continue;
+ }
+ if trimmed.is_empty() {
+ out.push(Line::default());
+ continue;
+ }
+ if let Some(h) = trimmed.strip_prefix('#') {
+ let h = h.trim_start_matches('#').trim();
+ out.extend(wrap(
+ &inline(h, t.text.add_modifier(Modifier::BOLD)),
+ width,
+ std::slice::from_ref(&pad),
+ std::slice::from_ref(&pad),
+ ));
+ continue;
+ }
+ if matches!(trimmed, "---" | "***" | "___") {
+ out.push(Line::from(vec![
+ pad.clone(),
+ Span::styled("─".repeat(width.saturating_sub(indent).min(40)), t.line),
+ ]));
+ continue;
+ }
+ if let Some(q) = trimmed.strip_prefix('>') {
+ let bar = Span::styled("▎ ", t.dim);
+ out.extend(wrap(&inline(q.trim(), t.secondary), width, &[pad.clone(), bar.clone()], &[pad.clone(), bar]));
+ continue;
+ }
+ let lead = raw.len() - trimmed.len();
+ let nest = " ".repeat(lead.min(8));
+ let bullet = ["- ", "* ", "+ "].iter().find_map(|b| trimmed.strip_prefix(b).map(|r| ("• ".to_owned(), r)));
+ let numbered = || {
+ let digits = trimmed.chars().take_while(char::is_ascii_digit).count();
+ (digits > 0 && trimmed[digits..].starts_with(". "))
+ .then(|| (format!("{} ", &trimmed[..=digits]), &trimmed[digits + 2..]))
+ };
+ if let Some((mark, body)) = bullet.or_else(numbered) {
+ let hang = " ".repeat(self::width(&mark));
+ let first = [pad.clone(), Span::raw(nest.clone()), Span::styled(mark, t.secondary)];
+ let rest = [pad.clone(), Span::raw(nest), Span::raw(hang)];
+ out.extend(wrap(&inline(body, t.text), width, &first, &rest));
+ continue;
+ }
+ out.extend(wrap(&inline(trimmed, t.text), width, std::slice::from_ref(&pad), std::slice::from_ref(&pad)));
+ }
+ while out.last().is_some_and(|l| l.spans.iter().all(|s| s.content.trim().is_empty())) {
+ out.pop();
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn text(lines: &[Line<'_>]) -> Vec<String> {
+ lines.iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect()).collect()
+ }
+
+ #[test]
+ fn wraps_at_spaces_and_between_cjk() {
+ let l = wrap(&[Span::raw("hello brave new world")], 11, &[], &[]);
+ assert_eq!(text(&l), ["hello brave", "new world"]);
+ let l = wrap(&[Span::raw("你好世界再見")], 5, &[], &[]);
+ assert_eq!(text(&l), ["你好", "世界", "再見"]);
+ }
+
+ #[test]
+ fn keeps_hard_newlines_and_prefixes() {
+ let l = wrap(&[Span::raw("a\nb")], 10, &[Span::raw("> ")], &[Span::raw(" ")]);
+ assert_eq!(text(&l), ["> a", " b"]);
+ }
+
+ #[test]
+ fn inline_code_and_bold() {
+ let s = inline("run `cargo` **now**", Style::default());
+ let parts: Vec<&str> = s.iter().map(|s| s.content.as_ref()).collect();
+ assert_eq!(parts, ["run ", "cargo", " ", "now"]);
+ }
+
+ #[test]
+ fn truncates_by_width() {
+ assert_eq!(truncate("abcdef", 4), "abc…");
+ assert_eq!(truncate("你好世界", 5), "你好…");
+ assert_eq!(truncate("ok", 5), "ok");
+ }
+}
diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rs
new file mode 100644
index 00000000..f3d44877
--- /dev/null
+++ b/host/src/tui/mod.rs
@@ -0,0 +1,103 @@
+//! `codync-host tui`: the Codync client for a terminal. It talks to a host over the
+//! same HTTP + SSE API as the phone and desktop apps (locally: no pairing needed).
+
+mod app;
+mod md;
+mod net;
+mod view;
+
+use anyhow::{Context, Result};
+use crossterm::event::{
+ DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste, EnableFocusChange,
+ EnableMouseCapture, Event, EventStream, KeyEventKind, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
+ PushKeyboardEnhancementFlags,
+};
+use crossterm::execute;
+use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
+use futures::StreamExt;
+use ratatui::Terminal;
+use ratatui::backend::CrosstermBackend;
+use std::time::Duration;
+
+/// Puts the terminal back however we leave (including a panic).
+struct Restore {
+ enhanced: bool,
+}
+
+impl Drop for Restore {
+ fn drop(&mut self) {
+ restore(self.enhanced);
+ }
+}
+
+fn restore(enhanced: bool) {
+ let mut out = std::io::stdout();
+ if enhanced {
+ let _ = execute!(out, PopKeyboardEnhancementFlags);
+ }
+ let _ = execute!(out, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, LeaveAlternateScreen);
+ let _ = terminal::disable_raw_mode();
+}
+
+pub async fn run(url: String, token: Option<String>) -> Result<()> {
+ let client = net::Client::new(&url, token.as_deref());
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = app::App::new(client.clone(), tx.clone(), url);
+
+ terminal::enable_raw_mode().context("this needs an interactive terminal")?;
+ let mut out = std::io::stdout();
+ execute!(out, EnterAlternateScreen, EnableMouseCapture, EnableBracketedPaste, EnableFocusChange)?;
+ // Lets terminals that support it report shift+enter apart from enter.
+ let enhanced = terminal::supports_keyboard_enhancement().unwrap_or(false)
+ && execute!(out, PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)).is_ok();
+ let _restore = Restore { enhanced };
+ let hook = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ restore(enhanced);
+ hook(info);
+ }));
+ let mut term = Terminal::new(CrosstermBackend::new(out))?;
+
+ app.call("hello", serde_json::json!({}), app::After::Hello);
+ client.spawn_stream(tx);
+ let mut events = EventStream::new();
+ let mut tick = tokio::time::interval(Duration::from_millis(100));
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ let mut dirty = true;
+ loop {
+ if dirty {
+ app.tick();
+ term.draw(|f| view::draw(f, &mut app))?;
+ dirty = false;
+ }
+ tokio::select! {
+ ev = events.next() => match ev {
+ Some(Ok(Event::Key(k))) if k.kind != KeyEventKind::Release => app.on_key(k),
+ Some(Ok(Event::Paste(s))) => app.on_paste(&s),
+ Some(Ok(Event::Mouse(m))) => app.on_mouse(m),
+ Some(Ok(Event::FocusGained)) => app.term_focused = true,
+ Some(Ok(Event::FocusLost)) => app.term_focused = false,
+ Some(Ok(_)) => {}
+ Some(Err(_)) | None => break,
+ },
+ Some(msg) = rx.recv() => {
+ app.on_msg(msg);
+ // Apply a burst (catch-up) before drawing once.
+ while let Ok(msg) = rx.try_recv() {
+ app.on_msg(msg);
+ }
+ }
+ _ = tick.tick() => {
+ if !app.animating() {
+ continue;
+ }
+ app.frame += 1;
+ }
+ }
+ dirty = true;
+ if app.quit {
+ break;
+ }
+ }
+ Ok(())
+}
diff --git a/host/src/tui/net.rs b/host/src/tui/net.rs
new file mode 100644
index 00000000..aaef633c
--- /dev/null
+++ b/host/src/tui/net.rs
@@ -0,0 +1,108 @@
+//! Host API over HTTP: JSON commands and the SSE event stream (same wire as the apps).
+
+use futures::StreamExt;
+use serde_json::Value;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicI64, Ordering};
+use std::time::Duration;
+use tokio::sync::mpsc::UnboundedSender;
+
+use super::app::{After, Msg};
+
+pub const NOT_INSTALLED: &str = "The Codync host isn't set up on this computer yet.";
+
+#[derive(Clone)]
+pub struct Client {
+ base: Arc<str>,
+ /// `None`: this computer's token file, read on every use so an install mid-session is picked up.
+ token: Option<Arc<str>>,
+ /// Highest rev seen; the stream reconnects from here (0 = full catch-up).
+ pub rev: Arc<AtomicI64>,
+}
+
+impl Client {
+ pub fn new(base: &str, token: Option<&str>) -> Self {
+ Self { base: base.trim_end_matches('/').into(), token: token.map(Into::into), rev: Arc::default() }
+ }
+
+ pub fn token(&self) -> Option<String> {
+ match &self.token {
+ Some(t) => Some(t.to_string()),
+ None => std::fs::read_to_string(crate::service::data_dir().join("token"))
+ .ok()
+ .map(|t| t.trim().to_owned())
+ .filter(|t| !t.is_empty()),
+ }
+ }
+
+ pub async fn call(&self, method: &str, body: &Value) -> Result<Value, String> {
+ let token = self.token().ok_or(NOT_INSTALLED)?;
+ let res = crate::http()
+ .post(format!("{}/api/{method}", self.base))
+ .bearer_auth(token)
+ .json(body)
+ .timeout(Duration::from_secs(60))
+ .send()
+ .await
+ .map_err(|_| format!("Can't reach codync-host at {}. Is it running?", self.base))?;
+ let ok = res.status().is_success();
+ let v: Value = res.json().await.unwrap_or(Value::Null);
+ if ok { Ok(v) } else { Err(v["error"].as_str().unwrap_or("The host refused that.").to_owned()) }
+ }
+
+ /// Runs a command in the background; the reply comes back as `Msg::Reply`.
+ pub fn spawn_call(&self, method: &'static str, body: Value, after: After, tx: UnboundedSender<Msg>) {
+ let c = self.clone();
+ tokio::spawn(async move {
+ let r = c.call(method, &body).await;
+ let _ = tx.send(Msg::Reply(after, r));
+ });
+ }
+
+ /// Streams host events forever, reconnecting with `since = last rev`.
+ pub fn spawn_stream(&self, tx: UnboundedSender<Msg>) {
+ let c = self.clone();
+ tokio::spawn(async move {
+ loop {
+ let url = format!("{}/events?since={}&client=tui", c.base, c.rev.load(Ordering::Relaxed));
+ if let Some(token) = c.token()
+ && let Ok(res) = crate::http().get(url).bearer_auth(token).send().await
+ && res.status().is_success()
+ {
+ if tx.send(Msg::Online(true)).is_err() {
+ return;
+ }
+ let mut body = res.bytes_stream();
+ let mut buf = Vec::new();
+ 'read: while let Some(Ok(chunk)) = body.next().await {
+ buf.extend_from_slice(&chunk);
+ while let Some(i) = buf.iter().position(|&b| b == b'\n') {
+ let line: Vec<u8> = buf.drain(..=i).collect();
+ let line = String::from_utf8_lossy(&line);
+ let Some(data) = line.trim_end().strip_prefix("data:") else { continue };
+ let Ok(v) = serde_json::from_str::<Value>(data.trim_start()) else {
+ // Never skip what we can't read: start over from scratch.
+ c.rev.store(0, Ordering::Relaxed);
+ let _ = tx.send(Msg::Rewind);
+ break 'read;
+ };
+ if v["type"] == "resync" {
+ break 'read;
+ }
+ if let Some(rev) = v["rev"].as_i64() {
+ c.rev.fetch_max(rev, Ordering::Relaxed);
+ }
+ if tx.send(Msg::Event(v)).is_err() {
+ return;
+ }
+ }
+ }
+ }
+ if tx.send(Msg::Online(false)).is_err() {
+ return;
+ }
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+ });
+ }
+}
diff --git a/host/src/tui/view.rs b/host/src/tui/view.rs
new file mode 100644
index 00000000..04234675
--- /dev/null
+++ b/host/src/tui/view.rs
@@ -0,0 +1,2016 @@
+//! Drawing. Black and white: color comes only from the bots; amber means
+//! "needs you" and red means an error. Every state also has its own glyph.
+
+// Colors are written as #RRGGBB, like the apps' Theme.swift.
+#![allow(clippy::unreadable_literal)]
+// Drawing code reads best with x / y / w / t (theme) / r (rect).
+#![allow(clippy::many_single_char_names, clippy::similar_names)]
+
+use ratatui::Frame;
+use ratatui::buffer::Buffer;
+use ratatui::layout::{Position, Rect};
+use ratatui::style::{Color, Modifier, Style};
+use ratatui::text::{Line, Span};
+use std::collections::{BTreeSet, HashMap};
+use std::sync::LazyLock;
+
+use super::app::{
+ ACTIONS, App, Bot, COLORS, Click, Editor, Entry, FIELDS, FILTERS, Field, Focus, Form, GotoItem, Kind, Mark,
+ Overlay, SHAPES, Status, TraceMode, Width, tilde,
+};
+use super::md::{self, truncate, width as w};
+
+pub struct Theme {
+ pub color: bool,
+ pub text: Style,
+ pub bold: Style,
+ pub secondary: Style,
+ pub dim: Style,
+ pub line: Style,
+ pub amber: Style,
+ pub red: Style,
+ pub green: Style,
+ pub code: Style,
+ pub code_block: Style,
+ pub band: Style,
+ pub sel: Style,
+ pub panel: Style,
+ pub btn: Style,
+ pub btn_primary: Style,
+ pub added: Style,
+ pub removed: Style,
+ pub on_color: Color,
+ pub shade: Color,
+}
+
+fn rgb(hex: u32) -> Color {
+ Color::Rgb(((hex >> 16) & 0xFF) as u8, ((hex >> 8) & 0xFF) as u8, (hex & 0xFF) as u8)
+}
+
+pub fn theme() -> &'static Theme {
+ static T: LazyLock<Theme> = LazyLock::new(|| {
+ let color = std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty());
+ // COLORFGBG="15;0" is a dark background; "0;15" a light one. CODYNC_THEME wins.
+ let light = match std::env::var("CODYNC_THEME").as_deref() {
+ Ok("light") => true,
+ Ok("dark") => false,
+ _ => std::env::var("COLORFGBG")
+ .ok()
+ .and_then(|v| v.rsplit(';').next().and_then(|b| b.parse::<u8>().ok()))
+ .is_some_and(|bg| bg == 7 || bg == 15),
+ };
+ let s = Style::default();
+ if !color {
+ let rev = s.add_modifier(Modifier::REVERSED);
+ return Theme {
+ color,
+ text: s,
+ bold: s.add_modifier(Modifier::BOLD),
+ secondary: s,
+ dim: s.add_modifier(Modifier::DIM),
+ line: s.add_modifier(Modifier::DIM),
+ amber: s.add_modifier(Modifier::BOLD),
+ red: s.add_modifier(Modifier::BOLD),
+ green: s,
+ code: s.add_modifier(Modifier::BOLD),
+ code_block: s,
+ band: s,
+ sel: rev,
+ panel: s,
+ btn: s,
+ btn_primary: rev.add_modifier(Modifier::BOLD),
+ added: s,
+ removed: s.add_modifier(Modifier::DIM),
+ on_color: Color::Reset,
+ shade: Color::Reset,
+ };
+ }
+ let (text, second, dim, line, band, sel, panel, btn, green, red, add_bg, rm_bg) = if light {
+ (
+ 0x141414, 0x5F5F5F, 0x8E8E8E, 0xD6D6D6, 0xEFEFEF, 0xE2E2E2, 0xF7F7F7, 0xE4E4E4, 0x2E7D32, 0xC23A2B,
+ 0xE3F3E4, 0xF9E3E0,
+ )
+ } else {
+ (
+ 0xF2F2F2, 0x9A9A9A, 0x6E6E6E, 0x333333, 0x1C1C1C, 0x262626, 0x141414, 0x2A2A2A, 0x8FD18B, 0xF0A7A7,
+ 0x14261A, 0x2A1616,
+ )
+ };
+ let fg = |h| s.fg(rgb(h));
+ Theme {
+ color,
+ text: s,
+ bold: s.add_modifier(Modifier::BOLD),
+ secondary: fg(second),
+ dim: fg(dim),
+ line: fg(line),
+ amber: fg(if light { 0xB8700A } else { 0xF0A030 }),
+ red: fg(red),
+ green: fg(green),
+ code: s.bg(rgb(band)),
+ code_block: s.bg(rgb(band)),
+ band: s.bg(rgb(band)),
+ sel: s.bg(rgb(sel)),
+ panel: s.bg(rgb(panel)),
+ btn: s.bg(rgb(btn)),
+ btn_primary: s.fg(rgb(if light { 0xFFFFFF } else { 0x0A0A0A })).bg(rgb(text)).add_modifier(Modifier::BOLD),
+ added: s.fg(rgb(green)).bg(rgb(add_bg)),
+ removed: s.fg(rgb(red)).bg(rgb(rm_bg)),
+ on_color: rgb(0x0A0A0A),
+ shade: rgb(if light { 0xB0B0B0 } else { 0x3A3A3A }),
+ }
+ });
+ &T
+}
+
+pub fn bot_color(name: &str) -> Color {
+ let hex = match name {
+ "black" => 0x8A8A8A,
+ "brown" => 0x936439,
+ "red" => 0xFF263C,
+ "orange" => 0xFF6700,
+ "yellow" => 0xFF9800,
+ "green" => 0x00C972,
+ "cyan" => 0x00BCA6,
+ "violet" => 0x9159FE,
+ "magenta" => 0xFF309B,
+ "gray" => 0x777777,
+ _ => 0x1084FE,
+ };
+ rgb(hex)
+}
+
+const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
+
+fn spin(app: &App) -> &'static str {
+ SPINNER[usize::try_from(app.frame % 10).unwrap_or(0)]
+}
+
+pub fn glyph(app: &App, m: Mark) -> (&'static str, Style) {
+ let t = theme();
+ match m {
+ Mark::Need => ("◆", t.amber),
+ Mark::Work => (spin(app), t.secondary),
+ Mark::Unread => ("●", t.bold),
+ Mark::Idle => ("○", t.dim),
+ Mark::Error => ("×", t.red),
+ }
+}
+
+fn avatar(b: &Bot) -> Span<'static> {
+ let t = theme();
+ if t.color {
+ Span::styled("••", Style::default().fg(t.on_color).bg(bot_color(&b.color)).add_modifier(Modifier::BOLD))
+ } else {
+ Span::styled("[]", t.bold)
+ }
+}
+
+pub const FACE: [&str; 7] = [
+ "⠀⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⠀",
+ "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿",
+ "⣿⣿⣿⣿⠀⣿⣿⣿⠀⣿⣿⣿⣿",
+ "⣿⣿⣿⣿⣤⣿⣿⣿⣤⣿⣿⣿⣿",
+ "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿",
+ "⠛⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛",
+ "⠀⠀⠛⠛⠛⠛⠛⠛⠛⠛⠛⠀⠀",
+];
+
+fn face_style(color: &str) -> Style {
+ let t = theme();
+ if t.color { Style::default().fg(bot_color(color)) } else { t.text }
+}
+
+// ---------- time ----------
+
+fn now_ms() -> i64 {
+ crate::store::now_ms()
+}
+
+/// Local UTC offset in seconds, read once from `date +%z` (no tz database needed).
+fn utc_offset() -> i64 {
+ static OFF: LazyLock<i64> = LazyLock::new(|| {
+ let out = std::process::Command::new("date").arg("+%z").output().ok();
+ let s = out.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()).unwrap_or_default();
+ if s.len() != 5 {
+ return 0;
+ }
+ let sign = if s.starts_with('-') { -1 } else { 1 };
+ let h: i64 = s[1..3].parse().unwrap_or(0);
+ let m: i64 = s[3..5].parse().unwrap_or(0);
+ sign * (h * 3600 + m * 60)
+ });
+ *OFF
+}
+
+/// (days since epoch, seconds into the local day)
+fn local(ms: i64) -> (i64, i64) {
+ let s = ms.div_euclid(1000) + utc_offset();
+ (s.div_euclid(86_400), s.rem_euclid(86_400))
+}
+
+fn month_day(days: i64) -> (usize, i64) {
+ // Howard Hinnant's civil_from_days.
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z - era * 146_097;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ (usize::try_from(m - 1).unwrap_or(0), d)
+}
+
+const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+const DAYS: [&str; 7] = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"];
+
+pub fn clock(ms: i64) -> String {
+ let (_, secs) = local(ms);
+ format!("{:02}:{:02}", secs / 3600, secs % 3600 / 60)
+}
+
+/// Roster time: 12:31 today, Tue this week, Sep 19 before.
+pub fn when(ms: i64) -> String {
+ if ms <= 0 {
+ return String::new();
+ }
+ let (day, _) = local(ms);
+ let (today, _) = local(now_ms());
+ if now_ms() - ms < 60_000 {
+ "now".into()
+ } else if day == today {
+ clock(ms)
+ } else if today - day < 7 {
+ DAYS[usize::try_from(day.rem_euclid(7)).unwrap_or(0)].into()
+ } else {
+ let (m, d) = month_day(day);
+ format!("{} {d}", MONTHS[m])
+ }
+}
+
+pub fn elapsed(start: Option<i64>) -> String {
+ let Some(start) = start else { return String::new() };
+ let s = ((now_ms() - start) / 1000).max(0);
+ if s < 60 {
+ format!("{s}s")
+ } else if s < 3600 {
+ format!("{}m{:02}s", s / 60, s % 60)
+ } else {
+ format!("{}h{:02}m", s / 3600, s % 3600 / 60)
+ }
+}
+
+// ---------- buffer helpers ----------
+
+fn put(buf: &mut Buffer, x: u16, y: u16, max: u16, s: &str, style: Style) -> u16 {
+ if max == 0 || y >= buf.area.bottom() {
+ return x;
+ }
+ let (end, _) = buf.set_stringn(x, y, s, usize::from(max), style);
+ end
+}
+
+fn put_line(buf: &mut Buffer, x: u16, y: u16, max: u16, line: &Line<'_>) -> u16 {
+ if y >= buf.area.bottom() {
+ return x;
+ }
+ let (end, _) = buf.set_line(x, y, line, max);
+ end
+}
+
+fn rput(buf: &mut Buffer, right: u16, y: u16, s: &str, style: Style) -> u16 {
+ let width = u16::try_from(w(s)).unwrap_or(0);
+ let x = right.saturating_sub(width);
+ put(buf, x, y, width, s, style);
+ x
+}
+
+fn fill(buf: &mut Buffer, r: Rect, style: Style) {
+ for y in r.top()..r.bottom() {
+ for x in r.left()..r.right() {
+ if let Some(c) = buf.cell_mut(Position::new(x, y)) {
+ c.set_symbol(" ");
+ c.set_style(style);
+ }
+ }
+ }
+}
+
+fn restyle(buf: &mut Buffer, r: Rect, style: Style) {
+ buf.set_style(r, style);
+}
+
+fn hline(buf: &mut Buffer, x: u16, y: u16, width: u16, style: Style) {
+ put(buf, x, y, width, &"─".repeat(usize::from(width)), style);
+}
+
+fn vline(buf: &mut Buffer, x: u16, y: u16, h: u16, style: Style) {
+ for yy in y..y + h {
+ put(buf, x, yy, 1, "│", style);
+ }
+}
+
+fn frame_box(buf: &mut Buffer, r: Rect, border: Style, bg: Style, title: Option<(&str, Style)>) -> Rect {
+ fill(buf, r, bg);
+ if r.width < 2 || r.height < 2 {
+ return r;
+ }
+ let inner = usize::from(r.width - 2);
+ let b = border.patch(bg);
+ put(buf, r.x, r.y, r.width, &format!("╭{}╮", "─".repeat(inner)), b);
+ for y in r.y + 1..r.bottom() - 1 {
+ put(buf, r.x, y, 1, "│", b);
+ put(buf, r.right() - 1, y, 1, "│", b);
+ }
+ put(buf, r.x, r.bottom() - 1, r.width, &format!("╰{}╯", "─".repeat(inner)), b);
+ if let Some((t, s)) = title {
+ put(buf, r.x + 2, r.y, r.width.saturating_sub(4), &format!(" {t} "), s.patch(bg).add_modifier(Modifier::BOLD));
+ }
+ Rect::new(r.x + 2, r.y + 1, r.width.saturating_sub(4), r.height.saturating_sub(2))
+}
+
+fn dim_all(buf: &mut Buffer) {
+ let shade = theme().shade;
+ for c in &mut buf.content {
+ c.set_style(Style::default().fg(shade).bg(Color::Reset).remove_modifier(Modifier::all()));
+ }
+}
+
+fn centered(area: Rect, width: u16, height: u16) -> Rect {
+ let wd = width.min(area.width.saturating_sub(2));
+ let h = height.min(area.height.saturating_sub(2));
+ Rect::new(area.x + (area.width - wd) / 2, area.y + (area.height - h) / 3, wd, h)
+}
+
+fn u(n: usize) -> u16 {
+ u16::try_from(n).unwrap_or(u16::MAX)
+}
+
+// ---------- layout ----------
+
+pub fn draw(f: &mut Frame<'_>, app: &mut App) {
+ let area = f.area();
+ app.hits = super::app::Hits::default();
+ app.width = match area.width {
+ 0..80 => Width::Narrow,
+ 80..100 => Width::Mid,
+ 100..150 => Width::Wide,
+ _ => Width::Huge,
+ };
+ let buf = f.buffer_mut();
+ if area.width < 40 || area.height < 12 {
+ let c = app.counts();
+ put(buf, 0, 0, area.width, "Make the window bigger", theme().bold);
+ put(buf, 0, 1, area.width, &format!("◆{} ⠹{} ●{} ×{}", c[0], c[1], c[2], c[3]), theme().secondary);
+ return;
+ }
+ let body = Rect::new(area.x, area.y, area.width, area.height - 1);
+ status_line(buf, Rect::new(area.x, area.bottom() - 1, area.width, 1), app);
+
+ if app.width == Width::Narrow {
+ if app.chat_page && app.selected.is_some() {
+ if app.trace == TraceMode::Full {
+ trace(buf, body, app);
+ } else {
+ chat(buf, body, app, true);
+ }
+ } else {
+ app.chat_page = false;
+ if app.focus != Focus::Roster {
+ app.focus = Focus::Roster;
+ }
+ roster(buf, body, app, true);
+ }
+ } else {
+ let compact =
+ app.compact || app.width == Width::Mid || (app.width == Width::Wide && app.trace == TraceMode::Pane);
+ let rw: u16 = if compact { 5 } else { 32 };
+ let r = Rect::new(body.x, body.y, rw, body.height);
+ if compact {
+ compact_roster(buf, r, app);
+ } else {
+ roster(buf, r, app, false);
+ }
+ vline(buf, body.x + rw, body.y, body.height, theme().line);
+ let main = Rect::new(body.x + rw + 1, body.y, body.width - rw - 1, body.height);
+ match app.trace {
+ TraceMode::Full => trace(buf, main, app),
+ TraceMode::Pane => {
+ let cw = main.width * 55 / 100;
+ chat(buf, Rect::new(main.x, main.y, cw, main.height), app, false);
+ vline(buf, main.x + cw, main.y, main.height, theme().line);
+ trace(buf, Rect::new(main.x + cw + 1, main.y, main.width - cw - 1, main.height), app);
+ }
+ TraceMode::Off => chat(buf, main, app, false),
+ }
+ }
+ overlays(f, app);
+ let buf = f.buffer_mut();
+ toasts(buf, area, app);
+ if let Some(pos) = CURSOR.with(std::cell::Cell::take) {
+ f.set_cursor_position(pos);
+ }
+}
+
+thread_local! {
+ static CURSOR: std::cell::Cell<Option<Position>> = const { std::cell::Cell::new(None) };
+}
+
+fn set_cursor(p: Position) {
+ CURSOR.with(|c| c.set(Some(p)));
+}
+
+fn status_line(buf: &mut Buffer, r: Rect, app: &mut App) {
+ let t = theme();
+ fill(buf, r, t.panel);
+ let insert = app.typing && app.overlays.is_empty();
+ let pill = if insert { " INSERT " } else { " NAV " };
+ let pill_style = if insert {
+ Style::default().fg(t.on_color).bg(rgb(0xF0A030)).add_modifier(Modifier::BOLD)
+ } else {
+ t.btn_primary
+ };
+ let pill_style = if t.color { pill_style } else { t.sel };
+ let mut x = put(buf, r.x, r.y, r.width, pill, pill_style) + 1;
+ let host = if app.host.is_empty() { "codync" } else { &app.host };
+ x = put(buf, x, r.y, 24, host, t.bold.patch(t.panel)) + 2;
+ let c = app.counts();
+ let marks = [("◆", t.amber, 1), ("⠹", t.secondary, 2), ("●", t.bold, 3), ("×", t.red, 4)];
+ for (i, (g, s, filter)) in marks.into_iter().enumerate() {
+ if c[i] == 0 {
+ continue;
+ }
+ let start = x;
+ x = put(buf, x, r.y, 2, g, s.patch(t.panel)) + 1;
+ x = put(buf, x, r.y, 4, &c[i].to_string(), t.secondary.patch(t.panel)) + 2;
+ app.hits.clicks.push((Rect::new(start, r.y, x - start, 1), Click::Filter(filter)));
+ }
+ if !app.online {
+ x = put(buf, x, r.y, 20, "offline", t.amber.patch(t.panel)) + 2;
+ }
+ if let Some((h, _)) = &app.hint {
+ put(buf, x, r.y, r.right().saturating_sub(x), h, t.amber.patch(t.panel));
+ }
+ let hint = if insert { "↵ send · esc nav" } else { "? keys" };
+ let mut right = rput(buf, r.right() - 1, r.y, hint, t.dim.patch(t.panel)).saturating_sub(3);
+ // Usage: the first provider that has numbers, narrowest windows first.
+ if r.width >= 100
+ && let Some(p) = app.usage["providers"]
+ .as_array()
+ .and_then(|ps| ps.iter().find(|p| p["windows"].as_array().is_some_and(|w| !w.is_empty())))
+ {
+ let wins = p["windows"].as_array().cloned().unwrap_or_default();
+ for win in wins.iter().take(2).rev() {
+ let pct = win["percent"].as_f64().unwrap_or(0.0).clamp(0.0, 100.0);
+ let label = short_window(win["label"].as_str().unwrap_or_default());
+ let seg = format!("{label} ▰▰▰▰▰▰▰▰ {pct:.0}%");
+ let sx = right.saturating_sub(u(w(&seg)));
+ let on = filled(pct, 8);
+ let mut px = put(buf, sx, r.y, 8, &format!("{label} "), t.dim.patch(t.panel));
+ let bar_style = if pct >= 80.0 { t.amber } else { t.text };
+ px = put(buf, px, r.y, 8, &"▰".repeat(on), bar_style.patch(t.panel));
+ px = put(buf, px, r.y, 8, &"▱".repeat(8 - on.min(8)), t.line.patch(t.panel));
+ put(buf, px, r.y, 6, &format!(" {pct:.0}%"), t.secondary.patch(t.panel));
+ right = sx.saturating_sub(3);
+ }
+ let name = p["name"].as_str().unwrap_or_default().to_lowercase();
+ rput(buf, right + 1, r.y, &name, t.dim.patch(t.panel));
+ }
+}
+
+/// How many of `n` bar cells a percentage fills (rounded).
+fn filled(pct: f64, n: u32) -> usize {
+ (0..n).filter(|&i| (f64::from(i) + 0.5) * 100.0 / f64::from(n) < pct).count()
+}
+
+fn short_window(label: &str) -> String {
+ let l = label.to_lowercase();
+ if l.contains('5') && l.contains('h') {
+ "5h".into()
+ } else if l.contains("week") || l.contains('7') {
+ "wk".into()
+ } else {
+ truncate(label, 6)
+ }
+}
+
+// ---------- roster ----------
+
+fn roster(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
+ let t = theme();
+ app.hits.roster = r;
+ let focused = app.focus == Focus::Roster || narrow;
+ let bots: Vec<Bot> = app.roster().into_iter().cloned().collect();
+ let x0 = r.x;
+ let wd = r.width;
+ if narrow {
+ fill(buf, Rect::new(r.x, r.y, r.width, 1), t.panel);
+ }
+ put(buf, x0 + 1, r.y, wd.saturating_sub(10), if app.host.is_empty() { "codync" } else { &app.host }, t.bold);
+ rput(buf, r.right() - 1, r.y, &format!("{} bots", bots.len()), t.dim);
+ if !narrow {
+ hline(buf, x0, r.y + 1, wd, t.line);
+ }
+ let top = r.y + if narrow { 1 } else { 2 };
+ let bottom = r.bottom().saturating_sub(1);
+ if bots.is_empty() {
+ let msg: Vec<(String, Style)> = if let Some(e) = &app.error {
+ let mut m = vec![(e.clone(), t.amber)];
+ if app.url.contains("127.0.0.1") || app.url.contains("localhost") {
+ m.push(("Press I to install and start it here.".into(), t.bold));
+ }
+ m
+ } else if !app.online {
+ vec![("Connecting…".into(), t.secondary)]
+ } else {
+ vec![("No bots yet.".into(), t.text), ("n creates one.".into(), t.dim)]
+ };
+ let mut y = top + 1;
+ for (m, s) in &msg {
+ for l in md::wrap(&[Span::styled(m.clone(), *s)], usize::from(wd.saturating_sub(2)), &[], &[]) {
+ put_line(buf, x0 + 1, y, wd - 2, &l);
+ y += 1;
+ }
+ y += 1;
+ }
+ }
+ // Rows: an optional section label, then 2 lines per bot and a gap.
+ let any_pinned = bots.iter().any(|b| b.pinned);
+ let mut rows: Vec<(u16, Option<&'static str>, Option<usize>)> = vec![];
+ let mut y = 0u16;
+ for (i, b) in bots.iter().enumerate() {
+ if any_pinned && (i == 0 || (bots[i - 1].pinned && !b.pinned)) {
+ rows.push((y, Some(if b.pinned { "PINNED" } else { "BOTS" }), None));
+ y += 1;
+ }
+ rows.push((y, None, Some(i)));
+ y += 3;
+ }
+ let sel_idx = app.selected.as_ref().and_then(|s| bots.iter().position(|b| &b.id == s));
+ let view_h = bottom.saturating_sub(top);
+ let sel_y = sel_idx.and_then(|i| rows.iter().find(|r| r.2 == Some(i)).map(|r| r.0)).unwrap_or(0);
+ let offset = (sel_y + 3).saturating_sub(view_h);
+ for (ry, label, idx) in rows {
+ let Some(yy) = (top + ry).checked_sub(offset) else { continue };
+ if ry < offset || yy + 1 >= bottom {
+ continue;
+ }
+ if let Some(l) = label {
+ put(buf, x0 + 1, yy, wd, l, t.dim.add_modifier(Modifier::BOLD));
+ continue;
+ }
+ let Some(i) = idx else { continue };
+ let b = &bots[i];
+ let selected = Some(i) == sel_idx;
+ let row = Rect::new(x0, yy, wd, 2);
+ app.hits.clicks.push((row, Click::Bot(b.id.clone())));
+ if selected {
+ restyle(buf, row, t.sel);
+ let bar = if focused { t.bold } else { t.secondary };
+ put(buf, x0, yy, 1, "▌", bar);
+ put(buf, x0, yy + 1, 1, "▌", bar);
+ }
+ put_line(buf, x0 + 2, yy, 2, &Line::from(avatar(b)));
+ let (g, gs) = glyph(app, b.mark());
+ let time = if b.status == Status::Working { elapsed(b.started_at) } else { when(b.last_at) };
+ let tx = rput(buf, r.right() - 1, yy, &time, if b.unread > 0 { t.bold } else { t.dim });
+ let gx = tx.saturating_sub(2);
+ put(buf, gx, yy, 1, g, gs);
+ put(buf, x0 + 5, yy, gx.saturating_sub(x0 + 6), &b.name, t.bold);
+ let (pv, ps) = preview(b);
+ let badge = if b.unread > 0 { format!(" {} ", b.unread) } else { String::new() };
+ let room = usize::from(wd.saturating_sub(7)).saturating_sub(w(&badge) + usize::from(!badge.is_empty()));
+ put(buf, x0 + 5, yy + 1, u(room), &truncate(&pv, room), ps);
+ if !badge.is_empty() {
+ rput(buf, r.right() - 1, yy + 1, &badge, t.btn_primary);
+ }
+ }
+ if !narrow {
+ let hy = r.bottom() - 1;
+ let mut x = put(buf, x0 + 1, hy, 2, "n", t.secondary.add_modifier(Modifier::BOLD)) + 1;
+ x = put(buf, x, hy, 10, "new bot", t.dim) + 3;
+ x = put(buf, x, hy, 3, "^k", t.secondary.add_modifier(Modifier::BOLD)) + 1;
+ put(buf, x, hy, 8, "go to", t.dim);
+ }
+}
+
+/// A one-line preview without Markdown punctuation.
+fn plain(s: &str) -> String {
+ let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default();
+ line.trim_start_matches(['#', '>', '-', '*', ' ']).replace("**", "").replace('`', "")
+}
+
+fn preview(b: &Bot) -> (String, Style) {
+ let (text, style) = preview_raw(b);
+ (plain(&text), style)
+}
+
+fn preview_raw(b: &Bot) -> (String, Style) {
+ let t = theme();
+ match b.mark() {
+ Mark::Need => (if b.activity.is_empty() { "Needs your approval".into() } else { b.activity.clone() }, t.amber),
+ Mark::Work => (if b.activity.is_empty() { "Working…".into() } else { b.activity.clone() }, t.secondary),
+ Mark::Error => {
+ (if b.last_message.is_empty() { "Something went wrong".into() } else { b.last_message.clone() }, t.red)
+ }
+ Mark::Unread => (b.last_message.clone(), t.text),
+ Mark::Idle if b.last_message.is_empty() => ("No messages yet".into(), t.dim),
+ Mark::Idle => (b.last_message.clone(), t.secondary),
+ }
+}
+
+fn compact_roster(buf: &mut Buffer, r: Rect, app: &mut App) {
+ let t = theme();
+ app.hits.roster = r;
+ let bots: Vec<Bot> = app.roster().into_iter().cloned().collect();
+ let sel = app.selected.clone();
+ let sel_idx = sel.as_ref().and_then(|s| bots.iter().position(|b| &b.id == s)).unwrap_or(0);
+ let per = 2u16;
+ let view = r.height.saturating_sub(1) / per;
+ let offset = (u(sel_idx) + 1).saturating_sub(view);
+ for (i, b) in bots.iter().enumerate().skip(usize::from(offset)) {
+ let y = r.y + 1 + (u(i) - offset) * per;
+ if y >= r.bottom() {
+ break;
+ }
+ let row = Rect::new(r.x, y, r.width, 1);
+ app.hits.clicks.push((row, Click::Bot(b.id.clone())));
+ if sel.as_deref() == Some(b.id.as_str()) {
+ restyle(buf, row, t.sel);
+ put(buf, r.x, y, 1, "▌", if app.focus == Focus::Roster { t.bold } else { t.secondary });
+ }
+ put_line(buf, r.x + 1, y, 2, &Line::from(avatar(b)));
+ let (g, gs) = glyph(app, b.mark());
+ put(buf, r.x + 3, y, 1, g, gs);
+ }
+}
+
+// ---------- chat ----------
+
+struct Built {
+ lines: Vec<Line<'static>>,
+ /// (line index, x offset, width, click)
+ buttons: Vec<(usize, u16, u16, Click)>,
+}
+
+fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
+ let t = theme();
+ app.hits.chat = r;
+ let Some(b) = app.bot().cloned() else {
+ let msg = match &app.error {
+ Some(e) if app.bots.is_empty() => e.as_str(),
+ _ if app.bots.is_empty() && !app.online => "Connecting…",
+ _ if app.bots.is_empty() => "n creates your first bot",
+ _ => "Pick a bot",
+ };
+ put(buf, r.x + 2, r.y + 1, r.width.saturating_sub(2), msg, t.dim);
+ return;
+ };
+ // Header.
+ let mut x = r.x + 1;
+ if narrow {
+ fill(buf, Rect::new(r.x, r.y, r.width, 1), t.panel);
+ x = put(buf, x, r.y, 2, "‹", t.bold) + 1;
+ }
+ put_line(buf, x, r.y, 2, &Line::from(avatar(&b)));
+ x = put(buf, x + 3, r.y, r.width / 3, &b.name, t.bold) + 2;
+ let (status, ss) = match b.mark() {
+ Mark::Need => ("◆ needs you".to_owned(), t.amber),
+ Mark::Work => (format!("{} working {}", spin(app), elapsed(b.started_at)), t.secondary),
+ Mark::Error => ("× error".to_owned(), t.red),
+ _ => (String::new(), t.dim),
+ };
+ let sx = rput(buf, r.right() - 1, r.y, &status, ss.add_modifier(Modifier::BOLD));
+ if !narrow {
+ let meta = format!("{} · {} · {}", b.backend, tilde(&b.cwd, &app.home), if b.auto { "auto" } else { "ask" });
+ put(buf, x, r.y, sx.saturating_sub(x + 2), &meta, t.secondary);
+ }
+ let mut top = r.y + 1;
+ if !narrow {
+ hline(buf, r.x, top, r.width, t.line);
+ top += 1;
+ }
+ if !app.online {
+ let bar = Rect::new(r.x, top, r.width, 1);
+ let s = if t.color { Style::default().fg(t.on_color).bg(rgb(0xF0A030)) } else { t.sel };
+ fill(buf, bar, s);
+ put(
+ buf,
+ r.x + 1,
+ top,
+ r.width - 2,
+ &format!("{} Reconnecting to {}…", spin(app), if app.host.is_empty() { &app.url } else { &app.host }),
+ s.add_modifier(Modifier::BOLD),
+ );
+ top += 1;
+ }
+
+ // Composer at the bottom.
+ let draft = app.drafts.get(&b.id).cloned().unwrap_or_default();
+ let inner = usize::from(r.width.saturating_sub(4)).max(1);
+ let (clines, cursor) = composer_lines(&draft, inner);
+ let ch = u(clines.len().clamp(1, 8));
+ let comp_top = r.bottom().saturating_sub(ch + 2);
+ let typing = app.typing && app.overlays.is_empty();
+ let rule = if typing { t.text } else { t.line };
+ hline(buf, r.x, comp_top, r.width, rule);
+ hline(buf, r.x, comp_top + ch + 1, r.width, rule);
+ put(buf, r.x + 1, comp_top + 1, 1, "›", if typing { t.bold } else { t.dim });
+ let comp_rect = Rect::new(r.x, comp_top, r.width, ch + 2);
+ app.hits.clicks.push((comp_rect, Click::Composer));
+ let first = clines.len().saturating_sub(usize::from(ch)).min(cursor.1.saturating_sub(usize::from(ch) - 1));
+ if draft.text.is_empty() {
+ put(buf, r.x + 3, comp_top + 1, r.width.saturating_sub(4), &format!("Message {}…", b.name), t.dim);
+ } else {
+ for (i, l) in clines.iter().skip(first).take(usize::from(ch)).enumerate() {
+ put(buf, r.x + 3, comp_top + 1 + u(i), r.width.saturating_sub(4), l, t.text);
+ }
+ }
+ let chip = if typing {
+ match b.status {
+ Status::Working => "sends after this turn",
+ Status::NeedsInput => "sends after the approval",
+ _ => "",
+ }
+ } else if matches!(b.status, Status::Working) {
+ "s stops"
+ } else {
+ "i to type"
+ };
+ if draft.text.is_empty() || !typing {
+ rput(buf, r.right() - 1, comp_top + 1, chip, t.dim);
+ }
+ if typing {
+ let cy = comp_top + 1 + u(cursor.1.saturating_sub(first));
+ set_cursor(Position::new(r.x + 3 + u(cursor.0), cy.min(comp_top + ch)));
+ }
+
+ // Transcript.
+ let body = Rect::new(r.x, top + 1, r.width, comp_top.saturating_sub(top + 1));
+ app.chat_height = usize::from(body.height);
+ let built = build_chat(app, &b, usize::from(body.width.saturating_sub(1)));
+ let total = built.lines.len();
+ let h = usize::from(body.height);
+ let max = total.saturating_sub(h);
+ app.chat_scroll = app.chat_scroll.min(max);
+ app.chat_top = total > 0 && app.chat_scroll == max;
+ let start = total.saturating_sub(h + app.chat_scroll);
+ for (i, l) in built.lines.iter().skip(start).take(h).enumerate() {
+ put_line(buf, body.x, body.y + u(i), body.width, l);
+ }
+ for (li, bx, bw, click) in built.buttons {
+ if li >= start && li < start + h {
+ let y = body.y + u(li - start);
+ app.hits.clicks.push((Rect::new(body.x + bx, y, bw, 1), click));
+ }
+ }
+ if app.chat_scroll > 0 {
+ let s = format!(" ↓ {} more ", app.chat_scroll);
+ rput(buf, r.right() - 1, comp_top.saturating_sub(1), &s, t.btn);
+ }
+}
+
+/// Wraps the draft; returns display lines and the cursor's (column, line).
+fn composer_lines(e: &Editor, width: usize) -> (Vec<String>, (usize, usize)) {
+ let mut lines = vec![String::new()];
+ let mut col = 0;
+ let mut cur = (0, 0);
+ for (i, c) in e.text.char_indices() {
+ if i == e.cursor {
+ cur = (col, lines.len() - 1);
+ }
+ if c == '\n' {
+ lines.push(String::new());
+ col = 0;
+ continue;
+ }
+ let cw = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
+ if col + cw > width {
+ lines.push(String::new());
+ col = 0;
+ if i == e.cursor {
+ cur = (0, lines.len() - 1);
+ }
+ }
+ if let Some(l) = lines.last_mut() {
+ l.push(c);
+ }
+ col += cw;
+ }
+ if e.cursor >= e.text.len() {
+ cur = (col, lines.len() - 1);
+ if col >= width {
+ lines.push(String::new());
+ cur = (0, lines.len() - 1);
+ }
+ }
+ (lines, cur)
+}
+
+fn with_bg(lines: Vec<Line<'static>>, width: usize, bg: Style) -> Vec<Line<'static>> {
+ lines
+ .into_iter()
+ .map(|l| {
+ let used: usize = l.spans.iter().map(|s| w(&s.content)).sum();
+ let mut spans: Vec<Span<'static>> =
+ l.spans.into_iter().map(|s| Span::styled(s.content, s.style.patch(bg))).collect();
+ spans.push(Span::styled(" ".repeat(width.saturating_sub(used)), bg));
+ Line::from(spans)
+ })
+ .collect()
+}
+
+struct TurnInfo {
+ steps: usize,
+ files: BTreeSet<String>,
+ has_final: bool,
+}
+
+fn turn_info(entries: &[&Entry]) -> HashMap<i64, TurnInfo> {
+ let mut m: HashMap<i64, TurnInfo> = HashMap::new();
+ for e in entries {
+ let ti = m.entry(e.turn).or_insert_with(|| TurnInfo { steps: 0, files: BTreeSet::new(), has_final: false });
+ match e.kind {
+ Kind::Tool => {
+ ti.steps += 1;
+ for d in e.data["diffs"].as_array().into_iter().flatten() {
+ if let Some(p) = d["path"].as_str() {
+ ti.files.insert(p.to_owned());
+ }
+ }
+ }
+ Kind::Agent if e.is_final() => ti.has_final = true,
+ _ => {}
+ }
+ }
+ m
+}
+
+fn build_chat(app: &App, b: &Bot, width: usize) -> Built {
+ let t = theme();
+ let mut out = Built { lines: vec![], buttons: vec![] };
+ let mut entries: Vec<&Entry> = app.entries.get(&b.id).map(|m| m.values().collect()).unwrap_or_default();
+ // A message sent mid-turn belongs after that turn's reply.
+ entries.sort_by_key(|e| (e.turn, e.seq));
+ let info = turn_info(&entries);
+ let name_style =
+ if t.color { Style::default().fg(bot_color(&b.color)).add_modifier(Modifier::BOLD) } else { t.bold };
+ let gap = |out: &mut Built| {
+ if !out.lines.is_empty() {
+ out.lines.push(Line::default());
+ }
+ };
+ if entries.is_empty() {
+ out.lines.push(Line::default());
+ for row in FACE {
+ out.lines.push(Line::from(vec![Span::raw(" "), Span::styled(row, face_style(&b.color))]));
+ }
+ out.lines.push(Line::default());
+ out.lines.push(Line::from(vec![Span::raw(" "), Span::styled(b.name.clone(), t.bold)]));
+ out.lines.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(format!("{} · {}", b.backend, tilde(&b.cwd, &app.home)), t.secondary),
+ ]));
+ out.lines.push(Line::default());
+ let hello =
+ format!("Say what you need. {} works in the background and pings you when it's done or needs you.", b.name);
+ out.lines.extend(md::wrap(&[Span::styled(hello, t.dim)], width, &[Span::raw(" ")], &[Span::raw(" ")]));
+ return out;
+ }
+ if !app.history_complete(&b.id) {
+ out.lines.push(Line::from(Span::styled(" ↑ older messages load when you scroll up", t.dim)));
+ }
+ for e in &entries {
+ match e.kind {
+ Kind::User => {
+ gap(&mut out);
+ let mut head = vec![
+ Span::styled(" you", t.secondary.add_modifier(Modifier::BOLD)),
+ Span::styled(format!(" {}", clock(e.created_at)), t.dim),
+ ];
+ match e.data["status"].as_str() {
+ Some("queued") => head.push(Span::styled(" · queued", t.dim)),
+ Some("cancelled") => head.push(Span::styled(" · not sent", t.red)),
+ _ => {}
+ }
+ out.lines.push(Line::from(head));
+ let body = md::wrap(
+ &[Span::styled(e.text().to_owned(), t.text)],
+ width.saturating_sub(1),
+ &[Span::raw(" › ")],
+ &[Span::raw(" ")],
+ );
+ out.lines.extend(with_bg(body, width, t.band));
+ }
+ Kind::Agent if e.is_final() => {
+ gap(&mut out);
+ out.lines.push(Line::from(vec![
+ Span::styled(format!(" {}", b.name), name_style),
+ Span::styled(format!(" {}", clock(e.created_at)), t.dim),
+ ]));
+ out.lines.extend(md::render(e.text(), width, 1));
+ if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0) {
+ let files = if ti.files.is_empty() {
+ String::new()
+ } else {
+ format!(" · {} file{} changed", ti.files.len(), if ti.files.len() == 1 { "" } else { "s" })
+ };
+ out.lines.push(Line::from(Span::styled(
+ format!(" ↳ {} step{}{files} · o opens them", ti.steps, if ti.steps == 1 { "" } else { "s" }),
+ t.dim,
+ )));
+ }
+ }
+ Kind::Permission => {
+ gap(&mut out);
+ if e.pending() {
+ permission_card(&mut out, e, b, width, &app.home);
+ } else {
+ decided_line(&mut out, e);
+ }
+ }
+ Kind::Notice => {
+ let text = e.text().to_owned();
+ match e.data["style"].as_str() {
+ Some("divider") => {
+ gap(&mut out);
+ let label = format!(" {text} · {} ", clock(e.created_at));
+ let side = width.saturating_sub(w(&label) + 4);
+ out.lines.push(Line::from(Span::styled(format!(" ───{label}{}", "─".repeat(side)), t.dim)));
+ }
+ Some("error") => {
+ gap(&mut out);
+ out.lines.extend(md::wrap(
+ &[Span::styled(text, t.red)],
+ width,
+ &[Span::styled(" × ", t.red)],
+ &[Span::raw(" ")],
+ ));
+ }
+ _ => {
+ gap(&mut out);
+ out.lines.extend(md::wrap(
+ &[Span::styled(text, t.dim)],
+ width,
+ &[Span::styled(" · ", t.dim)],
+ &[Span::raw(" ")],
+ ));
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ // A turn in flight: who's on it and what they're doing.
+ let last_turn = entries.iter().map(|e| e.turn).max().unwrap_or(0);
+ let in_flight = info.get(&last_turn).is_none_or(|ti| !ti.has_final);
+ if b.status == Status::Working && in_flight {
+ gap(&mut out);
+ out.lines.push(Line::from(Span::styled(format!(" {}", b.name), name_style)));
+ let act = if b.activity.is_empty() { "Working…".to_owned() } else { b.activity.clone() };
+ out.lines.push(Line::from(vec![
+ Span::styled(format!(" {} ", spin(app)), t.secondary),
+ Span::styled(truncate(&act, width.saturating_sub(4)), t.secondary),
+ ]));
+ let steps = info.get(&last_turn).map_or(0, |ti| ti.steps);
+ if steps > 0 {
+ out.lines.push(Line::from(Span::styled(
+ format!(" {steps} step{} so far · t shows them live", if steps == 1 { "" } else { "s" }),
+ t.dim,
+ )));
+ }
+ }
+ out
+}
+
+/// Keys printed on approval buttons: y / a / n for the usual kinds, digits otherwise.
+fn option_keys(opts: &[(String, String, String)]) -> Vec<String> {
+ let mut used = vec![];
+ opts.iter()
+ .enumerate()
+ .map(|(i, (_, _, kind))| {
+ let k = match kind.as_str() {
+ "allow_once" => "y",
+ "allow_always" => "a",
+ "reject_once" | "reject_always" => "n",
+ _ => "",
+ };
+ let k = if k.is_empty() || used.contains(&k) { (i + 1).to_string() } else { k.to_owned() };
+ if k.len() == 1 && k.chars().all(char::is_alphabetic) {
+ used.push(match k.as_str() {
+ "y" => "y",
+ "a" => "a",
+ _ => "n",
+ });
+ }
+ k
+ })
+ .collect()
+}
+
+fn permission_card(out: &mut Built, e: &Entry, b: &Bot, width: usize, home: &str) {
+ let t = theme();
+ let bw = width.saturating_sub(1).max(20);
+ let inner = bw.saturating_sub(4);
+ let title = e.data["title"].as_str().unwrap_or("Use a tool");
+ let head = format!(" ◆ {} wants to: {} ", b.name, truncate(title, inner.saturating_sub(w(&b.name) + 14)));
+ let side = bw.saturating_sub(w(&head) + 3);
+ out.lines.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled("╭─", t.amber),
+ Span::styled(head, t.amber.add_modifier(Modifier::BOLD)),
+ Span::styled(format!("{}╮", "─".repeat(side)), t.amber),
+ ]));
+ let row = |content: Vec<Span<'static>>| -> Line<'static> {
+ let used: usize = content.iter().map(|s| w(&s.content)).sum();
+ let mut spans = vec![Span::raw(" "), Span::styled("│ ", t.amber)];
+ spans.extend(content);
+ spans.push(Span::raw(" ".repeat(inner.saturating_sub(used))));
+ spans.push(Span::styled(" │", t.amber));
+ Line::from(spans)
+ };
+ if let Some(cmd) = e.data["command"].as_str().filter(|c| !c.is_empty()) {
+ for (i, l) in md::wrap(&[Span::styled(cmd.to_owned(), t.bold)], inner.saturating_sub(2), &[], &[])
+ .into_iter()
+ .take(6)
+ .enumerate()
+ {
+ let mut c = vec![Span::styled(if i == 0 { "$ " } else { " " }, t.dim)];
+ c.extend(l.spans);
+ out.lines.push(row(c));
+ }
+ let cwd = tilde(e.data["cwd"].as_str().unwrap_or(&b.cwd), home);
+ out.lines.push(row(vec![Span::styled(format!(" in {}", truncate(&cwd, inner.saturating_sub(5))), t.dim)]));
+ }
+ for d in e.data["diffs"].as_array().into_iter().flatten().take(3) {
+ let path = tilde(d["path"].as_str().unwrap_or_default(), home);
+ let stat = format!("+{} −{}", d["added"].as_u64().unwrap_or(0), d["removed"].as_u64().unwrap_or(0));
+ let p = truncate(&path, inner.saturating_sub(w(&stat) + 2));
+ let pad = inner.saturating_sub(w(&p) + w(&stat));
+ out.lines.push(row(vec![Span::styled(p, t.bold), Span::raw(" ".repeat(pad)), Span::styled(stat, t.secondary)]));
+ let patch = d["patch"].as_str().unwrap_or_default();
+ let n = patch.lines().count();
+ for l in patch.lines().take(6) {
+ let s = if l.starts_with('+') {
+ t.added
+ } else if l.starts_with('-') {
+ t.removed
+ } else {
+ t.secondary
+ };
+ let body = truncate(l, inner);
+ let padded = format!("{body}{}", " ".repeat(inner.saturating_sub(w(&body))));
+ out.lines.push(row(vec![Span::styled(padded, s)]));
+ }
+ if n > 6 {
+ out.lines.push(row(vec![Span::styled(format!("… {} more lines · t shows the whole diff", n - 6), t.dim)]));
+ }
+ }
+ if let Some(detail) = e.data["detail"].as_str().filter(|d| !d.trim().is_empty() && e.data["command"].is_null()) {
+ for l in detail.lines().take(4) {
+ out.lines.push(row(vec![Span::styled(truncate(l, inner), t.secondary)]));
+ }
+ }
+ out.lines.push(row(vec![]));
+ // Buttons, wrapping onto more lines when narrow.
+ let opts = e.options();
+ let keys = option_keys(&opts);
+ let mut line: Vec<Span<'static>> = vec![];
+ let mut used = 0usize;
+ let mut pending: Vec<(u16, u16, Click)> = vec![];
+ let flush =
+ |out: &mut Built, line: &mut Vec<Span<'static>>, used: &mut usize, pending: &mut Vec<(u16, u16, Click)>| {
+ let li = out.lines.len();
+ out.lines.push(row(std::mem::take(line)));
+ for (x, bw, c) in pending.drain(..) {
+ out.buttons.push((li, x, bw, c));
+ }
+ *used = 0;
+ };
+ for (i, (id, name, kind)) in opts.iter().enumerate() {
+ let key = format!(" {} ", keys[i]);
+ let label = format!("{name} ");
+ let bw_ = w(&key) + w(&label);
+ if used > 0 && used + bw_ + 1 > inner {
+ flush(out, &mut line, &mut used, &mut pending);
+ }
+ let style = if i == 0 {
+ t.btn_primary
+ } else if kind.starts_with("reject") {
+ t.red.patch(t.btn)
+ } else {
+ t.text.patch(t.btn)
+ };
+ if used > 0 {
+ line.push(Span::raw(" "));
+ used += 1;
+ }
+ pending.push((u(3 + used), u(bw_), Click::Option { entry: e.id.clone(), option: id.clone() }));
+ line.push(Span::styled(key, style.add_modifier(Modifier::BOLD)));
+ line.push(Span::styled(label, style));
+ used += bw_;
+ }
+ if !line.is_empty() {
+ let hint = "N reject + say why";
+ if used + w(hint) + 3 <= inner {
+ line.push(Span::raw(" ".repeat(inner - used - w(hint))));
+ line.push(Span::styled(hint, t.dim));
+ }
+ flush(out, &mut line, &mut used, &mut pending);
+ }
+ out.lines.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(format!("╰{}╯", "─".repeat(bw.saturating_sub(2))), t.amber),
+ ]));
+}
+
+fn decided_line(out: &mut Built, e: &Entry) {
+ let t = theme();
+ let title = e.data["title"].as_str().unwrap_or("Use a tool");
+ let sel = e.data["selected"].as_str();
+ let chosen = sel.and_then(|s| e.options().into_iter().find(|o| o.0 == s));
+ let (g, gs, what) = match (e.data["status"].as_str(), chosen) {
+ (Some("answered"), Some((_, name, kind))) if kind.starts_with("allow") => ("✓", t.green, name),
+ (Some("answered"), Some((_, name, _))) => ("×", t.red, name),
+ (Some("expired"), _) => ("·", t.dim, "Expired".to_owned()),
+ _ => ("·", t.dim, "Cancelled".to_owned()),
+ };
+ out.lines.push(Line::from(vec![
+ Span::styled(format!(" {g} "), gs),
+ Span::styled(what, t.secondary),
+ Span::styled(format!(" · {title}"), t.dim),
+ Span::styled(format!(" · {}", clock(e.created_at)), t.dim),
+ ]));
+}
+
+// ---------- trace ----------
+
+fn trace(buf: &mut Buffer, r: Rect, app: &mut App) {
+ let t = theme();
+ app.hits.trace = r;
+ let full = app.trace == TraceMode::Full;
+ let Some(b) = app.bot().cloned() else { return };
+ let latest = app.latest_turn(&b.id).unwrap_or(0);
+ let turn = app.trace_turn.unwrap_or(latest);
+ let live = turn == latest && b.status == Status::Working;
+ let mut x = put(
+ buf,
+ r.x + 1,
+ r.y,
+ 6,
+ "TRACE",
+ if app.focus == Focus::Trace { t.bold } else { t.secondary.add_modifier(Modifier::BOLD) },
+ );
+ x = put(
+ buf,
+ x + 1,
+ r.y,
+ r.width.saturating_sub(20),
+ &format!("· {} · turn {turn}{}", b.name, if live { " · live" } else { "" }),
+ t.dim,
+ );
+ let _ = x;
+ rput(buf, r.right() - 1, r.y, if full { "{ } turns · esc close" } else { "{ } turns · T full" }, t.dim);
+ hline(buf, r.x, r.y + 1, r.width, t.line);
+ let body = Rect::new(r.x, r.y + 2, r.width, r.height.saturating_sub(2));
+ let lines = build_trace(app, &b, turn, usize::from(body.width.saturating_sub(1)), full);
+ let h = usize::from(body.height);
+ let max = lines.len().saturating_sub(h);
+ if live && app.focus != Focus::Trace {
+ app.trace_scroll = max; // follow along while it works
+ }
+ app.trace_scroll = app.trace_scroll.min(max);
+ for (i, l) in lines.iter().skip(app.trace_scroll).take(h).enumerate() {
+ put_line(buf, body.x, body.y + u(i), body.width, l);
+ }
+ if lines.is_empty() {
+ put(buf, body.x + 2, body.y, body.width.saturating_sub(2), "Nothing happened in this turn yet.", t.dim);
+ }
+}
+
+fn tool_label(kind: &str) -> &str {
+ match kind {
+ "execute" => "bash",
+ "other" => "tool",
+ k => k,
+ }
+}
+
+fn build_trace(app: &App, b: &Bot, turn: i64, width: usize, full: bool) -> Vec<Line<'static>> {
+ let t = theme();
+ let mut out: Vec<Line<'static>> = vec![];
+ let Some(map) = app.entries.get(&b.id) else { return out };
+ let label = |s: &str| Span::styled(format!("{s:<8} "), t.secondary);
+ let text_rest = |width: usize| width.saturating_sub(13);
+ let (diff_max, out_max) = if full { (400, 400) } else { (14, 6) };
+ for e in map.values().filter(|e| e.turn == turn) {
+ match e.kind {
+ Kind::User => out.push(Line::from(vec![
+ Span::styled(" › ", t.dim),
+ label("you"),
+ Span::styled(truncate(e.text(), text_rest(width)), t.text),
+ ])),
+ Kind::Thought | Kind::Agent => {
+ let (g, lab) = if e.kind == Kind::Thought {
+ ("✱", "thought")
+ } else if e.is_final() {
+ ("●", "reply")
+ } else {
+ ("✱", "says")
+ };
+ let s = if e.kind == Kind::Thought { t.dim } else { t.text };
+ if full {
+ let first = [Span::styled(format!(" {g} "), t.dim), label(lab)];
+ let rest = [Span::raw(" ".repeat(12))];
+ out.extend(md::wrap(&[Span::styled(e.text().trim().to_owned(), s)], width, &first, &rest));
+ } else {
+ out.push(Line::from(vec![
+ Span::styled(format!(" {g} "), t.dim),
+ label(lab),
+ Span::styled(truncate(e.text().trim(), text_rest(width)), s),
+ ]));
+ }
+ }
+ Kind::Tool => {
+ let (g, gs) = match e.data["status"].as_str() {
+ Some("completed") => ("✓".to_owned(), t.green),
+ Some("failed") => ("×".to_owned(), t.red),
+ _ => (spin(app).to_owned(), t.secondary),
+ };
+ let kind = tool_label(e.data["toolKind"].as_str().unwrap_or("tool")).to_owned();
+ let title = e.data["title"].as_str().unwrap_or("Tool");
+ out.push(Line::from(vec![
+ Span::styled(format!(" {g} "), gs),
+ label(&kind),
+ Span::styled(truncate(title, text_rest(width)), t.text),
+ ]));
+ for d in e.data["diffs"].as_array().into_iter().flatten() {
+ let stat = format!("+{} −{}", d["added"].as_u64().unwrap_or(0), d["removed"].as_u64().unwrap_or(0));
+ let path = tilde(d["path"].as_str().unwrap_or_default(), &app.home);
+ out.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(truncate(&path, width.saturating_sub(12)), t.bold),
+ Span::styled(format!(" {stat}"), t.secondary),
+ ]));
+ let start = d["startLine"].as_u64().unwrap_or(1);
+ out.push(Line::from(Span::styled(format!(" @@ line {start} @@"), t.dim)));
+ let patch = d["patch"].as_str().unwrap_or_default();
+ let n = patch.lines().count();
+ for l in patch.lines().take(diff_max) {
+ let s = if l.starts_with('+') {
+ t.added
+ } else if l.starts_with('-') {
+ t.removed
+ } else {
+ t.secondary
+ };
+ let body = truncate(l, width.saturating_sub(4));
+ let pad = width.saturating_sub(4 + w(&body));
+ out.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(format!("{body}{}", " ".repeat(pad)), s),
+ ]));
+ }
+ if n > diff_max {
+ out.push(Line::from(Span::styled(
+ format!(" … {} more lines · T shows everything", n - diff_max),
+ t.dim,
+ )));
+ }
+ }
+ let output = e.data["output"].as_str().unwrap_or_default().trim_end();
+ if !output.is_empty() {
+ let lines: Vec<&str> = output.lines().collect();
+ let skip = lines.len().saturating_sub(out_max);
+ if skip > 0 {
+ out.push(Line::from(Span::styled(format!(" … {skip} earlier lines"), t.dim)));
+ }
+ for l in &lines[skip..] {
+ out.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(truncate(l, width.saturating_sub(12)), t.dim),
+ ]));
+ }
+ }
+ }
+ Kind::Plan => {
+ let items = e.data["entries"].as_array().cloned().unwrap_or_default();
+ let done = items.iter().filter(|i| i["status"] == "completed").count();
+ out.push(Line::from(vec![
+ Span::styled(" ☐ ", t.secondary),
+ label("plan"),
+ Span::styled(format!("{done}/{}", items.len()), t.text),
+ ]));
+ for i in &items {
+ let (g, s) = match i["status"].as_str() {
+ Some("completed") => ("✓", t.green),
+ Some("in_progress") => ("▸", t.bold),
+ _ => ("☐", t.dim),
+ };
+ out.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(format!("{g} "), s),
+ Span::styled(
+ truncate(i["content"].as_str().unwrap_or_default(), width.saturating_sub(6)),
+ t.secondary,
+ ),
+ ]));
+ }
+ }
+ Kind::Permission => {
+ let st = e.data["status"].as_str().unwrap_or_default();
+ out.push(Line::from(vec![
+ Span::styled(" ◆ ", t.amber),
+ label("asked"),
+ Span::styled(
+ truncate(e.data["title"].as_str().unwrap_or_default(), text_rest(width).saturating_sub(12)),
+ t.text,
+ ),
+ Span::styled(format!(" {st}"), t.dim),
+ ]));
+ }
+ Kind::Notice => out.push(Line::from(vec![
+ Span::styled(" · ", t.dim),
+ Span::styled(truncate(e.text(), width.saturating_sub(4)), t.dim),
+ ])),
+ Kind::Other => {}
+ }
+ }
+ out
+}
+
+// ---------- overlays ----------
+
+fn overlays(f: &mut Frame<'_>, app: &mut App) {
+ if app.overlays.is_empty() {
+ return;
+ }
+ let area = f.area();
+ let buf = f.buffer_mut();
+ dim_all(buf);
+ app.hits.clicks.clear();
+ // Only the top overlay is live; draw it alone over the dimmed screen.
+ let ovs = std::mem::take(&mut app.overlays);
+ if let Some(top) = ovs.last() {
+ overlay(buf, area, app, top);
+ }
+ app.overlays = ovs;
+}
+
+fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay) {
+ match top {
+ Overlay::Goto(g) => {
+ let items = app.goto_items(g);
+ goto(buf, area, app, g, &items);
+ }
+ Overlay::Help(filter) => help(buf, area, filter),
+ Overlay::Confirm(c) => {
+ let t = theme();
+ let r = centered(area, 62, 8);
+ let inner = frame_box(buf, r, t.red, t.panel, None);
+ put(buf, inner.x, inner.y, inner.width, &c.title, t.red.patch(t.panel).add_modifier(Modifier::BOLD));
+ put(buf, inner.x, inner.y + 1, inner.width, &c.detail, t.text.patch(t.panel));
+ put(buf, inner.x, inner.y + 2, inner.width, &c.note, t.secondary.patch(t.panel));
+ let danger = if t.color {
+ Style::default().fg(t.on_color).bg(rgb(0xF0A7A7)).add_modifier(Modifier::BOLD)
+ } else {
+ t.sel
+ };
+ let x = put(buf, inner.x, inner.y + 4, 30, &format!(" ↵ {} ", c.button), danger) + 1;
+ put(buf, x, inner.y + 4, 14, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));
+ }
+ Overlay::Agents(a) => {
+ let t = theme();
+ let choices: Vec<serde_json::Value> = app.agent_choices(&a.query.text).into_iter().cloned().collect();
+ let h = u(choices.len() + 8).min(area.height.saturating_sub(2)).max(10);
+ let r = centered(area, 74, h);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("New bot · 1/3 agent", t.text)));
+ field_line(buf, inner, inner.y, &a.query, "type to filter", true);
+ let list_h = usize::from(inner.height.saturating_sub(4));
+ let off = a.cursor.saturating_sub(list_h.saturating_sub(1));
+ if choices.is_empty() {
+ put(
+ buf,
+ inner.x,
+ inner.y + 2,
+ inner.width,
+ if app.backends.is_empty() { "Loading agents…" } else { "No agent matches" },
+ t.dim.patch(t.panel),
+ );
+ }
+ for (y, (i, c)) in (inner.y + 2..).zip(choices.iter().enumerate().skip(off).take(list_h)) {
+ let row = Rect::new(inner.x - 1, y, inner.width + 2, 1);
+ let sel = i == a.cursor;
+ if sel {
+ restyle(buf, row, t.sel);
+ }
+ let installed = c["installed"].as_bool().unwrap_or(false);
+ let base = if sel { t.sel } else { t.panel };
+ put(
+ buf,
+ inner.x,
+ y,
+ 2,
+ if installed { "✓" } else { "↓" },
+ if installed { t.green } else { t.dim }.patch(base),
+ );
+ put(
+ buf,
+ inner.x + 2,
+ y,
+ inner.width / 2,
+ c["name"].as_str().unwrap_or_default(),
+ if sel { t.bold } else { t.text }.patch(base),
+ );
+ let how = if installed { "on this computer".to_owned() } else { "fetched on first use".to_owned() };
+ rput(buf, inner.right(), y, &how, t.dim.patch(base));
+ }
+ put(
+ buf,
+ inner.x,
+ inner.bottom() - 1,
+ inner.width,
+ "↵ next: folder ↑↓ move esc cancel",
+ t.dim.patch(t.panel),
+ );
+ }
+ Overlay::Folder(p) => {
+ let t = theme();
+ let matches = App::folder_matches(p);
+ let r = centered(area, 74, 22);
+ let title = if p.new_bot.is_some() { "New bot · 2/3 folder" } else { "Folder" };
+ let inner = frame_box(buf, r, t.text, t.panel, Some((title, t.text)));
+ let shown = tilde(&p.path, &app.home);
+ let path = format!("{}/", shown.trim_end_matches('/'));
+ let x = put(
+ buf,
+ inner.x,
+ inner.y,
+ inner.width / 2,
+ &truncate(&path, usize::from(inner.width / 2)),
+ t.secondary.patch(t.panel),
+ );
+ field_line(buf, Rect::new(x, inner.y, inner.right().saturating_sub(x), 1), inner.y, &p.query, "", true);
+ let list_h = usize::from(inner.height.saturating_sub(5));
+ let off = p.cursor.saturating_sub(list_h.saturating_sub(1));
+ let mut y = inner.y + 2;
+ if let Some(e) = &p.error {
+ put(buf, inner.x, y, inner.width, e, t.red.patch(t.panel));
+ y += 1;
+ }
+ for (i, d) in matches.iter().enumerate().skip(off).take(list_h) {
+ let sel = i == p.cursor;
+ let base = if sel { t.sel } else { t.panel };
+ if sel {
+ restyle(buf, Rect::new(inner.x - 1, y, inner.width + 2, 1), t.sel);
+ }
+ put(buf, inner.x, y, 2, "▸", t.secondary.patch(base));
+ put(
+ buf,
+ inner.x + 2,
+ y,
+ inner.width - 10,
+ &format!("{}/", d.name),
+ if sel { t.bold } else { t.text }.patch(base),
+ );
+ if d.git {
+ rput(buf, inner.right(), y, "git", t.dim.patch(base));
+ }
+ y += 1;
+ }
+ let chosen = matches.get(p.cursor).map_or(shown.clone(), |d| tilde(&d.path, &app.home));
+ put(
+ buf,
+ inner.x,
+ inner.bottom() - 2,
+ inner.width,
+ &format!("↵ use {}", truncate(&chosen, usize::from(inner.width.saturating_sub(8)))),
+ t.text.patch(t.panel),
+ );
+ put(
+ buf,
+ inner.x,
+ inner.bottom() - 1,
+ inner.width,
+ "→ open ← up . use this folder esc back",
+ t.dim.patch(t.panel),
+ );
+ }
+ Overlay::Form(form) => form_view(buf, area, app, form),
+ Overlay::Usage => usage(buf, area, app),
+ Overlay::Pair(url) => pair(buf, area, url.as_deref()),
+ }
+}
+
+fn field_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool) {
+ let t = theme();
+ // An empty placeholder means the caller drew its own prefix (the folder path).
+ let x = if placeholder.is_empty() { r.x } else { put(buf, r.x, y, 2, "/ ", t.dim.patch(t.panel)) };
+ if e.text.is_empty() {
+ if active {
+ set_cursor(Position::new(x, y));
+ }
+ put(buf, x, y, r.right().saturating_sub(x), placeholder, t.dim.patch(t.panel));
+ } else {
+ let room = usize::from(r.right().saturating_sub(x + 1));
+ let text = e.text.replace('\n', " ");
+ let before = w(&e.text[..e.cursor]);
+ let skip = before.saturating_sub(room);
+ let shown: String = text.chars().skip(skip).collect();
+ put(buf, x, y, u(room), &shown, t.bold.patch(t.panel));
+ if active {
+ set_cursor(Position::new(x + u(before - skip), y));
+ }
+ }
+}
+
+fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, items: &[GotoItem]) {
+ let t = theme();
+ let r = centered(area, 80, 24);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Go to", t.text)));
+ let nbots = items.iter().filter(|i| matches!(i, GotoItem::Bot(_))).count();
+ rput(buf, inner.right(), inner.y, &format!("{nbots} of {}", app.bots.len()), t.dim.patch(t.panel));
+ field_line(
+ buf,
+ Rect::new(inner.x, inner.y, inner.width.saturating_sub(10), 1),
+ inner.y,
+ &g.query,
+ "search bots",
+ true,
+ );
+ // Filter chips.
+ let counts = app.counts();
+ let mut x = inner.x;
+ for (i, (label, mark)) in FILTERS.iter().enumerate() {
+ let n = match mark {
+ Some(Mark::Need) => format!(" {}", counts[0]),
+ Some(Mark::Work) => format!(" {}", counts[1]),
+ Some(Mark::Unread) => format!(" {}", counts[2]),
+ Some(Mark::Error) => format!(" {}", counts[3]),
+ _ => String::new(),
+ };
+ let chip = format!(" {label}{n} ");
+ let s = if i == g.filter { t.btn_primary } else { t.secondary.patch(t.btn) };
+ let start = x;
+ x = put(buf, x, inner.y + 2, inner.right().saturating_sub(x), &chip, s) + 1;
+ app.hits.clicks.push((Rect::new(start, inner.y + 2, x - start, 1), Click::Filter(i)));
+ }
+ let list_top = inner.y + 4;
+ let list_h = usize::from(inner.bottom().saturating_sub(list_top + 3));
+ let off = g.cursor.saturating_sub(list_h.saturating_sub(1));
+ let mut y = list_top;
+ let mut shown_actions = false;
+ for (i, item) in items.iter().enumerate().skip(off).take(list_h) {
+ let sel = i == g.cursor;
+ let base = if sel { t.sel } else { t.panel };
+ match item {
+ GotoItem::Bot(id) => {
+ let Some(b) = app.bots.get(id) else { continue };
+ if sel {
+ restyle(buf, Rect::new(inner.x - 1, y, inner.width + 2, 1), t.sel);
+ }
+ app.hits.clicks.push((Rect::new(inner.x - 1, y, inner.width + 2, 1), Click::Bot(id.clone())));
+ let (gl, gs) = glyph(app, b.mark());
+ put(buf, inner.x, y, 1, gl, gs.patch(base));
+ put_line(buf, inner.x + 2, y, 2, &Line::from(avatar(b)));
+ put(buf, inner.x + 5, y, 10, &b.name, t.bold.patch(base));
+ put(buf, inner.x + 16, y, 10, &b.backend, t.secondary.patch(base));
+ let cwd = truncate(&tilde(&b.cwd, &app.home), 18);
+ put(buf, inner.x + 27, y, 19, &cwd, t.secondary.patch(base));
+ let (pv, ps) = preview(b);
+ let room = inner.width.saturating_sub(47);
+ put(buf, inner.x + 47, y, room, &truncate(&pv, usize::from(room)), ps.patch(base));
+ }
+ GotoItem::Action(a) => {
+ if !shown_actions {
+ shown_actions = true;
+ if y > list_top {
+ y += 1;
+ }
+ put(buf, inner.x, y, inner.width, "ACTIONS", t.dim.patch(t.panel).add_modifier(Modifier::BOLD));
+ y += 1;
+ }
+ if sel {
+ restyle(buf, Rect::new(inner.x - 1, y, inner.width + 2, 1), t.sel);
+ }
+ if let Some((label, key, _)) = ACTIONS.iter().find(|x| x.2 == *a) {
+ put(buf, inner.x + 2, y, inner.width, label, if sel { t.bold } else { t.secondary }.patch(base));
+ rput(buf, inner.right(), y, key, t.dim.patch(base));
+ }
+ }
+ }
+ y += 1;
+ if y >= inner.bottom().saturating_sub(3) {
+ break;
+ }
+ }
+ if items.is_empty() {
+ put(buf, inner.x, list_top, inner.width, "Nothing matches", t.dim.patch(t.panel));
+ }
+ hline(buf, inner.x, inner.bottom() - 3, inner.width, t.line.patch(t.panel));
+ if let Some(GotoItem::Bot(id)) = items.get(g.cursor)
+ && let Some(b) = app.bots.get(id)
+ {
+ put(
+ buf,
+ inner.x,
+ inner.bottom() - 2,
+ inner.width,
+ &format!("{} · {} · {}", b.name, b.backend, tilde(&b.cwd, &app.home)),
+ t.secondary.patch(t.panel),
+ );
+ }
+ put(
+ buf,
+ inner.x,
+ inner.bottom() - 1,
+ inner.width,
+ "↵ open tab filter ↑↓ move esc close",
+ t.dim.patch(t.panel),
+ );
+}
+
+const HELP: [(&str, &str, &str); 40] = [
+ ("MOVE", "j k ↑ ↓", "next / previous bot"),
+ ("MOVE", "[ ]", "previous / next bot"),
+ ("MOVE", "1…9", "jump to bot 1–9"),
+ ("MOVE", "!", "next bot that needs you"),
+ ("MOVE", "u", "next unread bot"),
+ ("MOVE", "^k", "go to…"),
+ ("MOVE", "tab h l", "roster ⇄ chat ⇄ trace"),
+ ("MOVE", "^d ^u", "half page down / up"),
+ ("MOVE", "g G", "top / bottom"),
+ ("CHAT", "i ↵", "type a message"),
+ ("CHAT", "y", "allow once"),
+ ("CHAT", "a", "always allow"),
+ ("CHAT", "n", "reject"),
+ ("CHAT", "N", "reject and say why"),
+ ("CHAT", "1…9", "pick an approval option"),
+ ("CHAT", "s", "stop the bot"),
+ ("CHAT", "o", "last turn's steps"),
+ ("CHAT", "c", "copy the last reply"),
+ ("TYPE", "↵", "send"),
+ ("TYPE", "⇧↵ alt↵ ^j", "new line"),
+ ("TYPE", "esc", "back to NAV"),
+ ("TYPE", "^c", "clear the message"),
+ ("TYPE", "^a ^e", "line start / end"),
+ ("TYPE", "alt b / f", "word left / right"),
+ ("TYPE", "^w ^u", "delete word / line"),
+ ("BOTS", "n", "new bot"),
+ ("BOTS", "e", "edit bot"),
+ ("BOTS", "p", "pin / unpin"),
+ ("BOTS", "S", "new session"),
+ ("BOTS", "x", "delete bot"),
+ ("VIEW", "t", "trace pane"),
+ ("VIEW", "T", "trace full screen"),
+ ("VIEW", "{ }", "previous / next turn"),
+ ("VIEW", "b", "compact roster"),
+ ("VIEW", "U", "usage"),
+ ("VIEW", "P", "pair a phone"),
+ ("VIEW", "esc", "close / go back"),
+ ("VIEW", "q", "quit; bots keep going"),
+ ("MOUSE", "click", "open bot, press button"),
+ ("MOUSE", "wheel", "scroll under pointer"),
+];
+
+fn help(buf: &mut Buffer, area: Rect, filter: &Editor) {
+ let t = theme();
+ let r = centered(area, 80, 30);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Keys", t.text)));
+ field_line(buf, inner, inner.y, filter, "filter actions and keys", true);
+ let q = filter.text.to_lowercase();
+ let items: Vec<&(&str, &str, &str)> = HELP
+ .iter()
+ .filter(|(_, k, d)| q.is_empty() || d.to_lowercase().contains(&q) || k.to_lowercase().contains(&q))
+ .collect();
+ let col_w = inner.width / 2;
+ let rows = usize::from(inner.height.saturating_sub(3));
+ let (mut col, mut y, mut section) = (0u16, inner.y + 2, "");
+ for (sec, k, d) in items {
+ let need = if *sec == section { 1 } else { 2 + u16::from(!section.is_empty()) };
+ if y + need > inner.y + 2 + u(rows) {
+ if col == 1 {
+ break;
+ }
+ col = 1;
+ y = inner.y + 2;
+ section = "";
+ }
+ let x = inner.x + col * col_w;
+ if *sec != section {
+ if !section.is_empty() {
+ y += 1;
+ }
+ put(buf, x, y, col_w, sec, t.dim.patch(t.panel).add_modifier(Modifier::BOLD));
+ y += 1;
+ section = sec;
+ }
+ put(buf, x, y, 11, k, t.bold.patch(t.panel));
+ put(buf, x + 12, y, col_w.saturating_sub(13), d, t.secondary.patch(t.panel));
+ y += 1;
+ }
+ put(buf, inner.x, inner.bottom() - 1, inner.width, "esc close", t.dim.patch(t.panel));
+}
+
+fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
+ let t = theme();
+ let r = centered(area, 88, 30);
+ let title = match &f.bot_id {
+ Some(_) => format!("Edit {}", f.name.text),
+ None => "New bot · 3/3 name and looks".into(),
+ };
+ let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));
+ let wide = inner.width >= 70;
+ let fx = if wide { inner.x + 18 } else { inner.x };
+ if wide {
+ for (i, row) in FACE.iter().enumerate() {
+ put(buf, inner.x + 1, inner.y + 1 + u(i), 13, row, face_style(COLORS[f.color]).patch(t.panel));
+ }
+ put(buf, inner.x + 1, inner.y + 9, 16, COLORS[f.color], t.secondary.patch(t.panel));
+ put(buf, inner.x + 1, inner.y + 10, 16, SHAPES[f.shape], t.dim.patch(t.panel));
+ }
+ let label_w = 13u16;
+ let vx = fx + label_w;
+ let vw = inner.right().saturating_sub(vx);
+ let mut y = inner.y + 1;
+ let agent_name = app
+ .backends
+ .iter()
+ .find(|b| b["id"].as_str() == Some(f.backend.as_str()))
+ .and_then(|b| b["name"].as_str())
+ .unwrap_or(&f.backend)
+ .to_owned();
+ for (i, field) in FIELDS.iter().enumerate() {
+ let active = i == f.field;
+ let base = if active { t.sel } else { t.panel };
+ let lab = match field {
+ Field::Name => "Name",
+ Field::Instructions => "Instructions",
+ Field::Agent => "Agent",
+ Field::Model => "Model",
+ Field::Folder => "Folder",
+ Field::Approvals => "Approvals",
+ Field::Notify => "Notify",
+ Field::Color => "Color",
+ Field::Shape => "Shape",
+ Field::Connectors => "Connectors",
+ Field::Skills => "Skills",
+ };
+ put(buf, fx, y, label_w, lab, if active { t.bold } else { t.secondary }.patch(t.panel));
+ let rows = if *field == Field::Instructions { 3 } else { 1 };
+ if active {
+ restyle(buf, Rect::new(vx.saturating_sub(1), y, vw + 1, rows), t.sel);
+ }
+ let text_field = |buf: &mut Buffer, e: &Editor, placeholder: &str, y: u16| {
+ if e.text.is_empty() {
+ put(buf, vx, y, vw, placeholder, t.dim.patch(base));
+ if active {
+ set_cursor(Position::new(vx, y));
+ }
+ } else {
+ let (lines, cur) = composer_lines(e, usize::from(vw.saturating_sub(1)).max(1));
+ let first = cur.1.saturating_sub(usize::from(rows) - 1);
+ for (j, l) in lines.iter().skip(first).take(usize::from(rows)).enumerate() {
+ put(buf, vx, y + u(j), vw, l, t.text.patch(base));
+ }
+ if active {
+ set_cursor(Position::new(vx + u(cur.0), y + u(cur.1 - first)));
+ }
+ }
+ };
+ match field {
+ Field::Name => text_field(buf, &f.name, "Name", y),
+ Field::Instructions => {
+ text_field(buf, &f.instructions, "e.g. Reviews PRs. Never pushes without asking.", y);
+ }
+ Field::Model => text_field(buf, &f.model, "default", y),
+ Field::Agent => {
+ put(buf, vx, y, vw, &format!("‹ {agent_name} ›"), t.text.patch(base));
+ }
+ Field::Folder => {
+ put(
+ buf,
+ vx,
+ y,
+ vw,
+ &format!("{} ▸", truncate(&tilde(&f.cwd, &app.home), usize::from(vw.saturating_sub(4)))),
+ t.text.patch(base),
+ );
+ }
+ Field::Approvals => {
+ let s = if f.auto { "○ Ask ◉ Auto (approve every request)" } else { "◉ Ask ○ Auto" };
+ put(buf, vx, y, vw, s, t.text.patch(base));
+ }
+ Field::Notify => {
+ let s = if f.notify { "◉ Done and needs-you ○ Off" } else { "○ Done and needs-you ◉ Off" };
+ put(buf, vx, y, vw, s, t.text.patch(base));
+ }
+ Field::Color => {
+ let mut x = vx;
+ for (ci, c) in COLORS.iter().enumerate() {
+ let s = if t.color { Style::default().bg(bot_color(c)) } else { t.text };
+ let mark = if ci == f.color { "◆ " } else { " " };
+ x = put(buf, x, y, 2, mark, s.fg(t.on_color)) + 1;
+ }
+ }
+ Field::Shape => {
+ put(buf, vx, y, vw, &format!("‹ {} ›", SHAPES[f.shape]), t.text.patch(base));
+ }
+ Field::Connectors | Field::Skills => {
+ let list = if *field == Field::Connectors { &f.connectors } else { &f.skills };
+ if list.is_empty() {
+ put(buf, vx, y, vw, "none installed", t.dim.patch(base));
+ } else {
+ let mut x = vx;
+ for (j, tg) in list.iter().enumerate() {
+ let item = format!("{} {}", if tg.on { "☑" } else { "☐" }, tg.name);
+ let s = if active && j == f.sub { t.bold.add_modifier(Modifier::UNDERLINED) } else { t.text };
+ if x + u(w(&item)) >= inner.right() {
+ put(buf, x, y, 2, "…", t.dim.patch(base));
+ break;
+ }
+ x = put(buf, x, y, u(w(&item)), &item, s.patch(base)) + 2;
+ }
+ }
+ }
+ }
+ y += rows + 1;
+ if y >= inner.bottom().saturating_sub(2) {
+ break;
+ }
+ }
+ let by = inner.bottom() - 1;
+ if let Some(e) = &f.error {
+ put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));
+ }
+ let save = if f.saving {
+ " … Saving "
+ } else if f.bot_id.is_some() {
+ " ↵ Save "
+ } else {
+ " ↵ Create "
+ };
+ let x = put(buf, inner.x, by, 14, save, t.btn_primary) + 1;
+ put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));
+ let hint = match f.current() {
+ Field::Folder => "↵ browse · tab next field",
+ Field::Connectors | Field::Skills => "←→ move · space toggle · tab next",
+ Field::Agent | Field::Color | Field::Shape | Field::Approvals | Field::Notify => "←→ change · tab next field",
+ Field::Instructions => "⇧↵ new line · tab next field",
+ _ => "tab next field · ^s save",
+ };
+ rput(buf, inner.right(), by, hint, t.dim.patch(t.panel));
+}
+
+fn usage(buf: &mut Buffer, area: Rect, app: &App) {
+ let t = theme();
+ let providers = app.usage["providers"].as_array().cloned().unwrap_or_default();
+ let rows: usize = providers.iter().map(|p| 2 + p["windows"].as_array().map_or(0, Vec::len)).sum();
+ let r = centered(area, 78, u(rows + 5).max(8));
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Usage", t.text)));
+ let mut y = inner.y + 1;
+ if providers.is_empty() {
+ put(buf, inner.x, y, inner.width, "No usage numbers yet.", t.secondary.patch(t.panel));
+ }
+ for p in &providers {
+ put(buf, inner.x, y, inner.width, p["name"].as_str().unwrap_or_default(), t.bold.patch(t.panel));
+ y += 1;
+ for win in p["windows"].as_array().into_iter().flatten() {
+ let pct = win["percent"].as_f64().unwrap_or(0.0).clamp(0.0, 100.0);
+ let on = filled(pct, 16);
+ put(
+ buf,
+ inner.x + 2,
+ y,
+ 18,
+ &truncate(win["label"].as_str().unwrap_or_default(), 18),
+ t.secondary.patch(t.panel),
+ );
+ let mut x = put(
+ buf,
+ inner.x + 21,
+ y,
+ 16,
+ &"▰".repeat(on.min(16)),
+ if pct >= 80.0 { t.amber } else { t.text }.patch(t.panel),
+ );
+ x = put(buf, x, y, 16, &"▱".repeat(16 - on.min(16)), t.line.patch(t.panel));
+ put(buf, x + 1, y, 5, &format!("{pct:>3.0}%"), t.text.patch(t.panel));
+ let reset = win["resetsAt"]
+ .as_i64()
+ .map(|ms| format!("resets {}", when_future(ms)))
+ .or_else(|| {
+ // "Sep 26 at 11:59am (Asia/Taipei)": the zone is this computer's own.
+ win["resetsText"].as_str().map(|s| truncate(s.split(" (").next().unwrap_or(s), 24))
+ })
+ .unwrap_or_default();
+ rput(buf, inner.right(), y, &reset, t.dim.patch(t.panel));
+ y += 1;
+ }
+ y += 1;
+ }
+ put(buf, inner.x, inner.bottom() - 1, inner.width, "From your local installs. esc close", t.dim.patch(t.panel));
+}
+
+fn when_future(ms: i64) -> String {
+ let (day, _) = local(ms);
+ let (today, _) = local(now_ms());
+ if day == today {
+ clock(ms)
+ } else if day - today < 7 {
+ format!("{} {}", DAYS[usize::try_from(day.rem_euclid(7)).unwrap_or(0)], clock(ms))
+ } else {
+ let (m, d) = month_day(day);
+ format!("{} {d}", MONTHS[m])
+ }
+}
+
+fn pair(buf: &mut Buffer, area: Rect, url: Option<&str>) {
+ let t = theme();
+ let Some(url) = url else {
+ let r = centered(area, 40, 5);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
+ put(buf, inner.x, inner.y + 1, inner.width, "Getting the pairing code…", t.secondary.patch(t.panel));
+ return;
+ };
+ let qr = qrcode::QrCode::new(url.as_bytes())
+ .map(|c| c.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build())
+ .unwrap_or_default();
+ let lines: Vec<&str> = qr.lines().collect();
+ let qw = lines.first().map_or(0, |l| w(l));
+ let fits = u(lines.len() + 6) <= area.height && u(qw + 4) <= area.width;
+ let (bw, bh) = if fits { (u(qw.max(50) + 4), u(lines.len() + 6)) } else { (70, 8) };
+ let r = centered(area, bw, bh);
+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
+ let mut y = inner.y;
+ if fits {
+ // The QR needs light modules on dark ones regardless of the terminal theme.
+ let qs = Style::default().fg(Color::White).bg(Color::Black);
+ let x = inner.x + inner.width.saturating_sub(u(qw)) / 2;
+ for l in &lines {
+ put(buf, x, y, u(qw), l, qs);
+ y += 1;
+ }
+ } else {
+ put(buf, inner.x, y, inner.width, "Make the window taller to show the QR code.", t.secondary.patch(t.panel));
+ y += 1;
+ }
+ put(
+ buf,
+ inner.x,
+ y,
+ inner.width,
+ "Scan with the Codync iPhone app, or open on the phone:",
+ t.secondary.patch(t.panel),
+ );
+ put(buf, inner.x, y + 1, inner.width, &truncate(url, usize::from(inner.width)), t.dim.patch(t.panel));
+}
+
+fn toasts(buf: &mut Buffer, area: Rect, app: &App) {
+ let t = theme();
+ let mut y = area.y + 1;
+ for toast in &app.toasts {
+ let text = format!("{} {}", if toast.need { "◆" } else { "●" }, toast.text);
+ let hint = if toast.need { "! jump" } else { "u jump" };
+ let bw = u(w(&text) + w(hint) + 7).min(area.width.saturating_sub(2));
+ let r = Rect::new(area.right().saturating_sub(bw + 1), y, bw, 3);
+ let inner = frame_box(buf, r, if toast.need { t.amber } else { t.line }, t.panel, None);
+ put(buf, inner.x, inner.y, inner.width, &text, t.bold.patch(t.panel));
+ if toast.need {
+ put(buf, inner.x, inner.y, 1, "◆", t.amber.patch(t.panel));
+ }
+ rput(buf, inner.right(), inner.y, hint, t.dim.patch(t.panel));
+ y += 3;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn civil_dates() {
+ assert_eq!(month_day(0), (0, 1)); // 1970-01-01
+ assert_eq!(month_day(20_454), (0, 1)); // 2026-01-01
+ assert_eq!(month_day(20_721), (8, 25)); // 2026-09-25
+ assert_eq!(DAYS[usize::try_from(20_721_i64.rem_euclid(7)).unwrap_or(0)], "Fri");
+ }
+
+ #[test]
+ fn composer_cursor_tracks_wraps_and_newlines() {
+ let (l, c) = composer_lines(&Editor::with("ab\ncd"), 10);
+ assert_eq!(l, ["ab", "cd"]);
+ assert_eq!(c, (2, 1));
+ let (l, c) = composer_lines(&Editor::with("abcdef"), 3);
+ assert_eq!(l, ["abc", "def", ""]);
+ assert_eq!(c, (0, 2));
+ }
+
+ #[test]
+ fn option_keys_use_letters_then_digits() {
+ let o = |k: &str| (String::new(), String::new(), k.to_owned());
+ let keys = option_keys(&[o("allow_once"), o("allow_always"), o("reject_once"), o("reject_always")]);
+ assert_eq!(keys, ["y", "a", "n", "4"]);
+ }
+}
diff --git a/kit/Package.swift b/kit/Package.swift
index 2801c104..5fada50b 100644
--- a/kit/Package.swift
+++ b/kit/Package.swift
@@ -8,9 +8,17 @@ let package = Package(
.library(name: "CodyncKit", targets: ["CodyncKit"]),
.library(name: "CodyncUI", targets: ["CodyncUI"]),
],
+ dependencies: [
+ // libwebrtc for the remote screen viewer (hardware H.264 over WebRTC).
+ .package(url: "https://github.com/stasel/WebRTC.git", exact: "153.0.0"),
+ ],
targets: [
.target(name: "CodyncKit"),
- .target(name: "CodyncUI", dependencies: ["CodyncKit"], resources: [.process("Resources")]),
+ .target(
+ name: "CodyncUI",
+ dependencies: ["CodyncKit", .product(name: "WebRTC", package: "WebRTC", condition: .when(platforms: [.iOS]))],
+ resources: [.process("Resources")]
+ ),
.testTarget(name: "CodyncKitTests", dependencies: ["CodyncKit"], resources: [.copy("Fixtures")]),
]
)
diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swift
index 2ca0e485..311e881a 100644
--- a/kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/kit/Sources/CodyncKit/Client/HostClient.swift
@@ -46,11 +46,12 @@ public enum HostError: LocalizedError, Sendable {
}
public enum HostEvent: Sendable {
- case hello(hostId: String, rev: Int64, usage: Usage)
+ case hello(hostId: String, rev: Int64, usage: Usage, screen: ScreenState?)
case bot(Bot)
case botDeleted(id: String, rev: Int64)
case entry(Entry)
case usage(Usage)
+ case screen(ScreenState)
case resync
/// An event this app version couldn't decode (host newer/older than the app).
case undecodable(type: String)
@@ -157,12 +158,14 @@ public struct HostClient: Sendable {
struct StubWrap: Decodable { var bot: BotStub }
struct EntryWrap: Decodable { var entry: Entry }
struct UsageWrap: Decodable { var usage: Usage }
+ struct ScreenWrap: Decodable { var screen: ScreenState }
let d = decoder
guard let env = try? d.decode(Envelope.self, from: data) else { return nil }
switch env.type {
case "hello":
let usage = (try? d.decode(UsageWrap.self, from: data))?.usage ?? Usage()
- return .hello(hostId: env.hostId ?? "", rev: env.rev ?? 0, usage: usage)
+ let screen = (try? d.decode(ScreenWrap.self, from: data))?.screen
+ return .hello(hostId: env.hostId ?? "", rev: env.rev ?? 0, usage: usage, screen: screen)
case "bot":
if let stub = try? d.decode(StubWrap.self, from: data), stub.bot.deleted == true {
return .botDeleted(id: stub.bot.id, rev: stub.bot.rev)
@@ -172,6 +175,8 @@ public struct HostClient: Sendable {
return (try? d.decode(EntryWrap.self, from: data)).map { .entry($0.entry) } ?? .undecodable(type: "entry")
case "usage":
return (try? d.decode(UsageWrap.self, from: data)).map { .usage($0.usage) }
+ case "screen":
+ return (try? d.decode(ScreenWrap.self, from: data)).map { .screen($0.screen) }
case "resync":
return .resync
default:
@@ -254,4 +259,34 @@ public extension HostClient {
struct Body: Encodable { var path: String? }
return try await call("listDirs", Body(path: path))
}
+
+ // MARK: remote screen
+
+ func screenStatus() async throws -> ScreenState { try await call("screenStatus") }
+
+ /// Sends a WebRTC offer (with all its ICE candidates); returns the session id and the answer.
+ /// Passing `session` restarts ICE on an existing session.
+ func screenOffer(sdp: String, session: String?, display: UInt32?) async throws -> ScreenAnswer {
+ struct Body: Encodable { var sdp: String; var session: String?; var display: UInt32? }
+ return try await call("screenOffer", Body(sdp: sdp, session: session, display: display), timeout: 30)
+ }
+
+ func screenClose(session: String) async throws {
+ let _: Empty = try await call("screenClose", ["session": session])
+ }
+
+ /// Takes control from bots (they can still look) or hands it back.
+ func screenTakeover(_ on: Bool) async throws -> ScreenState {
+ try await call("screenTakeover", ["on": on])
+ }
+
+ /// Only accepted from the computer itself.
+ func setScreenEnabled(_ on: Bool) async throws -> ScreenState {
+ try await call("setScreenEnabled", ["enabled": on])
+ }
+}
+
+public struct ScreenAnswer: Codable, Sendable {
+ public var session: String
+ public var sdp: String
}
diff --git a/kit/Sources/CodyncKit/Client/Tailscale.swift b/kit/Sources/CodyncKit/Client/Tailscale.swift
new file mode 100644
index 00000000..91e72ea4
--- /dev/null
+++ b/kit/Sources/CodyncKit/Client/Tailscale.swift
@@ -0,0 +1,35 @@
+import Darwin
+import Foundation
+
+/// Tailscale gives every device an address in 100.64.0.0/10 on a VPN (`utun`) interface.
+public enum Tailscale {
+ public static let downloadURL = URL(string: "https://tailscale.com/download")!
+
+ /// A host address that only works over Tailscale (its IP range or MagicDNS name).
+ public static func isAddress(_ url: String) -> Bool {
+ guard let host = URL(string: url)?.host() else { return false }
+ if host.hasSuffix(".ts.net") { return true }
+ let o = host.split(separator: ".").compactMap { UInt8($0) }
+ return o.count == 4 && isRange(o[0], o[1])
+ }
+
+ /// Tailscale is connected on this device right now.
+ public static var isConnected: Bool {
+ var head: UnsafeMutablePointer<ifaddrs>?
+ guard getifaddrs(&head) == 0 else { return false }
+ defer { freeifaddrs(head) }
+ var next = head
+ while let ifa = next?.pointee {
+ next = ifa.ifa_next
+ // Only VPN interfaces: some carriers hand out 100.64/10 addresses on cellular too.
+ guard String(cString: ifa.ifa_name).hasPrefix("utun"),
+ let addr = ifa.ifa_addr, addr.pointee.sa_family == UInt8(AF_INET) else { continue }
+ let ip = addr.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr.s_addr }
+ let o = withUnsafeBytes(of: ip) { Array($0) }
+ if isRange(o[0], o[1]) { return true }
+ }
+ return false
+ }
+
+ private static func isRange(_ a: UInt8, _ b: UInt8) -> Bool { a == 100 && (64..<128).contains(b) }
+}
diff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swift
index d4c37a02..0b25f69f 100644
--- a/kit/Sources/CodyncKit/Models/Models.swift
+++ b/kit/Sources/CodyncKit/Models/Models.swift
@@ -21,6 +21,8 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
/// Installed connector / skill ids this bot uses (see `Market.swift`).
public var connectors: [String]
public var skills: [String]
+ /// The bot can see and operate the computer's desktop (the built-in `computer` tools).
+ public var computer: Bool
public var createdAt: Int64
// Runtime, filled in by the host.
@@ -214,6 +216,55 @@ public struct Hello: Codable, Sendable {
public var home: String?
public var backends: [Backend]
public var rev: Int64
+ /// Missing from hosts that predate remote screen.
+ public var screen: ScreenState?
+ /// The host's current addresses, so pairings pick up Tailscale set up after pairing.
+ public var urls: [String]?
+}
+
+/// The computer's remote screen: whether phones can view/control it, and who's in control.
+public struct ScreenState: Codable, Equatable, Sendable {
+ public var enabled = false
+ /// The screen helper is running.
+ public var connected = false
+ public var platform = ""
+ /// Screen recording is permitted.
+ public var capture = false
+ /// Input injection is permitted.
+ public var input = false
+ public var displays: [ScreenDisplay] = []
+ /// A phone took over: bots may only look.
+ public var userControl = false
+ /// The bot using the computer right now.
+ public var agentBot: String?
+ public var viewers = 0
+
+ public init() {}
+
+ public var available: Bool { enabled && connected && capture }
+ public var mainDisplay: ScreenDisplay? { displays.first(where: \.main) ?? displays.first }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ enabled = try c.decodeIfPresent(Bool.self, forKey: .enabled) ?? false
+ connected = try c.decodeIfPresent(Bool.self, forKey: .connected) ?? false
+ platform = try c.decodeIfPresent(String.self, forKey: .platform) ?? ""
+ capture = try c.decodeIfPresent(Bool.self, forKey: .capture) ?? false
+ input = try c.decodeIfPresent(Bool.self, forKey: .input) ?? false
+ displays = try c.decodeIfPresent([ScreenDisplay].self, forKey: .displays) ?? []
+ userControl = try c.decodeIfPresent(Bool.self, forKey: .userControl) ?? false
+ agentBot = try c.decodeIfPresent(String.self, forKey: .agentBot)
+ viewers = try c.decodeIfPresent(Int.self, forKey: .viewers) ?? 0
+ }
+}
+
+public struct ScreenDisplay: Codable, Hashable, Identifiable, Sendable {
+ public var id: UInt32
+ public var name: String
+ /// Size in points: the coordinate space of screen input.
+ public var width: Double
+ public var height: Double
+ public var main: Bool
}
public struct SyncResponse: Codable, Sendable {
@@ -260,6 +311,7 @@ public struct BotDraft: Codable, Hashable, Sendable {
public var notify: Bool?
public var connectors: [String]?
public var skills: [String]?
+ public var computer: Bool?
public init(name: String = "", description: String = "", avatarColor: String = AvatarPalette.colors.randomElement()!.id,
avatarShape: String = AvatarPalette.shapes.randomElement()!, backend: String = "claude", cwd: String = "",
@@ -289,6 +341,7 @@ public struct BotDraft: Codable, Hashable, Sendable {
notify = bot.notify
connectors = bot.connectors
skills = bot.skills
+ computer = bot.computer
}
}
@@ -315,6 +368,7 @@ extension Bot {
notify = try c.decodeIfPresent(Bool.self, forKey: .notify)
connectors = try c.decodeIfPresent([String].self, forKey: .connectors) ?? []
skills = try c.decodeIfPresent([String].self, forKey: .skills) ?? []
+ computer = try c.decodeIfPresent(Bool.self, forKey: .computer) ?? false
createdAt = try c.decodeIfPresent(Int64.self, forKey: .createdAt) ?? 0
rev = try c.decodeIfPresent(Int64.self, forKey: .rev) ?? 0
status = try c.decodeIfPresent(String.self, forKey: .status) ?? "idle"
diff --git a/kit/Sources/CodyncKit/Models/ScreenViewport.swift b/kit/Sources/CodyncKit/Models/ScreenViewport.swift
new file mode 100644
index 00000000..0d60972f
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/ScreenViewport.swift
@@ -0,0 +1,98 @@
+import CoreGraphics
+
+/// Which part of a remote display the viewer shows, and the mapping between
+/// view points and display points. Zoom 1 fits the whole display; beyond that
+/// the visible region takes the view's aspect and is kept on the display.
+public struct ScreenViewport: Equatable, Sendable {
+ /// Display size in points.
+ public var display: CGSize
+ /// Viewer size in points.
+ public var view: CGSize
+ public private(set) var zoom: CGFloat = 1
+ /// The display point at the middle of the view.
+ public private(set) var center: CGPoint
+ /// Closest zoom: one display point spans this many view points.
+ private static let maxPointScale: CGFloat = 4
+
+ public init(display: CGSize, view: CGSize) {
+ self.display = display
+ self.view = view
+ center = CGPoint(x: display.width / 2, y: display.height / 2)
+ }
+
+ private var fitScale: CGFloat {
+ // Before layout the view is 0×0: any positive scale keeps the math finite.
+ guard display.width > 0, display.height > 0, view.width > 0, view.height > 0 else { return 1 }
+ return min(view.width / display.width, view.height / display.height)
+ }
+
+ public var maxZoom: CGFloat { max(1, Self.maxPointScale / max(fitScale, 0.0001)) }
+
+ /// View points per display point.
+ public var scale: CGFloat { fitScale * zoom }
+
+ /// The display region the view covers (may extend past the display when letterboxed).
+ public var visible: CGRect {
+ let size = CGSize(width: view.width / scale, height: view.height / scale)
+ return CGRect(x: center.x - size.width / 2, y: center.y - size.height / 2, width: size.width, height: size.height)
+ }
+
+ public var displayBounds: CGRect { CGRect(origin: .zero, size: display) }
+
+ /// The region to stream: `nil` while the whole display is in view.
+ public var crop: CGRect? {
+ zoom <= 1.001 ? nil : visible.intersection(displayBounds)
+ }
+
+ public func toDisplay(_ p: CGPoint) -> CGPoint {
+ let v = visible
+ return CGPoint(x: v.minX + p.x / scale, y: v.minY + p.y / scale)
+ }
+
+ public func toView(_ p: CGPoint) -> CGPoint {
+ let v = visible
+ return CGPoint(x: (p.x - v.minX) * scale, y: (p.y - v.minY) * scale)
+ }
+
+ /// Where a streamed region (display points) sits in the view.
+ public func frame(of region: CGRect) -> CGRect {
+ let o = toView(region.origin)
+ return CGRect(x: o.x, y: o.y, width: region.width * scale, height: region.height * scale)
+ }
+
+ /// Pinch: zoom by `factor` keeping the display point under `anchor` (view point) in place.
+ public mutating func zoom(by factor: CGFloat, at anchor: CGPoint) {
+ let fixed = toDisplay(anchor)
+ zoom = min(max(zoom * factor, 1), maxZoom)
+ center = CGPoint(x: fixed.x - (anchor.x - view.width / 2) / scale, y: fixed.y - (anchor.y - view.height / 2) / scale)
+ clamp()
+ }
+
+ /// Moves the view by a drag of `delta` view points.
+ public mutating func pan(by delta: CGPoint) {
+ center = CGPoint(x: center.x - delta.x / scale, y: center.y - delta.y / scale)
+ clamp()
+ }
+
+ /// Scrolls just enough to keep `p` (display point) inside the inner 80% of the view.
+ public mutating func follow(_ p: CGPoint) {
+ let v = visible
+ let mx = v.width * 0.1, my = v.height * 0.1
+ var c = center
+ if p.x < v.minX + mx { c.x -= v.minX + mx - p.x } else if p.x > v.maxX - mx { c.x += p.x - (v.maxX - mx) }
+ if p.y < v.minY + my { c.y -= v.minY + my - p.y } else if p.y > v.maxY - my { c.y += p.y - (v.maxY - my) }
+ center = c
+ clamp()
+ }
+
+ public mutating func reset() {
+ zoom = 1
+ center = CGPoint(x: display.width / 2, y: display.height / 2)
+ }
+
+ private mutating func clamp() {
+ let v = visible.size
+ center.x = v.width >= display.width ? display.width / 2 : min(max(center.x, v.width / 2), display.width - v.width / 2)
+ center.y = v.height >= display.height ? display.height / 2 : min(max(center.y, v.height / 2), display.height - v.height / 2)
+ }
+}
diff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
index 83594706..7437c280 100644
--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -170,6 +170,19 @@ struct BotSettingsForm: View {
}
.toggleStyle(.switch)
.tint(Palette.switchOn)
+ if model.screen != nil {
+ Toggle(isOn: Binding(get: { draft.computer ?? false }, set: { draft.computer = $0 })) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Use the computer").foregroundStyle(Palette.text)
+ Text(model.screen?.enabled == true
+ ? "Let this bot see the screen and use the mouse and keyboard. You can watch and take over from your phone."
+ : "Let this bot see the screen and use the mouse and keyboard. Turn on Remote screen in Codync's menu on the computer first.")
+ .font(.subheadline).foregroundStyle(Palette.secondary)
+ }
+ }
+ .toggleStyle(.switch)
+ .tint(Palette.switchOn)
+ }
}
.padding(.horizontal, 18)
.padding(.vertical, 20)
diff --git a/kit/Sources/CodyncUI/Bots/BotRow.swift b/kit/Sources/CodyncUI/Bots/BotRow.swift
index dfe786a4..d7a84387 100644
--- a/kit/Sources/CodyncUI/Bots/BotRow.swift
+++ b/kit/Sources/CodyncUI/Bots/BotRow.swift
@@ -30,6 +30,12 @@ public struct BotRow: View {
.font(.body.weight(.semibold))
.foregroundStyle(Palette.text)
.lineLimit(1)
+ if model.screen?.agentBot == bot.id {
+ Image(systemName: "cursorarrow.motionlines")
+ .font(.caption)
+ .foregroundStyle(Palette.accent)
+ .accessibilityLabel("Using the computer")
+ }
Spacer(minLength: 8)
Text(RelativeTime.day(Date(milliseconds: bot.lastAt)))
.font(.subheadline)
@@ -102,6 +108,9 @@ public struct ConnectionBanner: View {
VStack(alignment: .leading, spacing: 2) {
Text("\(model.hostName) is offline").font(.footnote.weight(.semibold)).foregroundStyle(Palette.text)
Text(reason).font(.footnote).foregroundStyle(Palette.secondary)
+ #if os(iOS)
+ if reason == HostError.unreachable.localizedDescription { tailscaleHint }
+ #endif
}
Spacer()
Button("Retry", systemImage: "arrow.clockwise") { model.restartStream() }
@@ -112,4 +121,18 @@ public struct ConnectionBanner: View {
.background(Palette.surface, in: RoundedRectangle(cornerRadius: 10))
}
}
+
+ /// Away from home the phone needs Tailscale: say whether it's off here or not set up at all.
+ @ViewBuilder private var tailscaleHint: some View {
+ if model.pairing?.urls.contains(where: Tailscale.isAddress) == true {
+ if !Tailscale.isConnected {
+ Text("Tailscale is off on this iPhone. Turn it on to reach \(model.hostName) away from home.")
+ .font(.footnote.weight(.medium))
+ .foregroundStyle(Palette.warning)
+ }
+ } else {
+ Link("Away from home? Set up Tailscale", destination: Tailscale.downloadURL)
+ .font(.footnote.weight(.medium))
+ }
+ }
}
diff --git a/kit/Sources/CodyncUI/ComputerBadge.swift b/kit/Sources/CodyncUI/ComputerBadge.swift
index 5ec68eb2..90f027c4 100644
--- a/kit/Sources/CodyncUI/ComputerBadge.swift
+++ b/kit/Sources/CodyncUI/ComputerBadge.swift
@@ -1,7 +1,7 @@
import CodyncKit
import SwiftUI
-/// A computer's round badge showing what it is (laptop, Mac mini, Linux…), in the color picked for it:
+/// A computer's icon showing what it is (laptop, Mac mini, Linux…), in the color picked for it:
/// the profile button and the rows that switch computers.
public struct ComputerBadge: View {
let computer: Pairing?
@@ -13,11 +13,8 @@ public struct ComputerBadge: View {
}
public var body: some View {
- let top = computer?.color.map(AvatarPalette.color) ?? Color(hex: 0x5A5A5A)
- Circle()
- .fill(top)
- .overlay(Circle().fill(LinearGradient(colors: [.clear, .black.opacity(0.45)], startPoint: .top, endPoint: .bottom)))
- .overlay { icon.foregroundStyle(.white) }
+ icon
+ .foregroundStyle(computer?.color.map(AvatarPalette.color) ?? Palette.text)
.frame(width: size, height: size)
.accessibilityHidden(true)
}
@@ -25,8 +22,8 @@ public struct ComputerBadge: View {
@ViewBuilder private var icon: some View {
switch computer?.device {
// SF Symbols has no penguin.
- case "linux": Image("computer-linux", bundle: .module).resizable().scaledToFit().frame(width: size * 0.5)
- case let device: Image(systemName: Self.symbol(device)).font(.system(size: size * 0.4, weight: .medium))
+ case "linux": Image("computer-linux", bundle: .module).resizable().scaledToFit().frame(width: size * 0.55)
+ case let device: Image(systemName: Self.symbol(device)).font(.system(size: size * 0.5, weight: .medium))
}
}
diff --git a/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift b/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift
new file mode 100644
index 00000000..995cca47
--- /dev/null
+++ b/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift
@@ -0,0 +1,436 @@
+#if os(iOS)
+import CodyncKit
+import SwiftUI
+import UIKit
+@preconcurrency import WebRTC
+
+public enum TouchMode: String, Sendable {
+ /// The phone is a trackpad: drag moves the pointer, tap clicks where it is.
+ case trackpad
+ /// Tap clicks where you touch.
+ case direct
+}
+
+/// The video plus every touch and key gesture, in UIKit where gestures and
+/// keyboard input are precise. Coordinates leave here as display points.
+final class ScreenCanvas: UIView, UIGestureRecognizerDelegate {
+ var send: ([String: Any]) -> Void = { _ in }
+ /// Asks the computer to stream a region (points; `nil` = everything) at a pixel size.
+ var requestView: (CGRect?, CGSize) -> Void = { _, _ in }
+ var onArmedConsumed: () -> Void = {}
+ var onZoomChanged: (Bool) -> Void = { _ in }
+
+ var mode: TouchMode = .trackpad
+ var interactive = true
+ /// One-shot modifiers from the on-screen bar, applied to the next key.
+ var armed: [String] = []
+
+ private let video = RTCMTLVideoView()
+ private let keys = KeyProxyField()
+ private weak var track: RTCVideoTrack?
+ private var viewport = ScreenViewport(display: CGSize(width: 1, height: 1), view: CGSize(width: 1, height: 1))
+ private var streamRegion: CGRect?
+ private var cursor = CGPoint.zero
+ private var lastTap: (at: Date, point: CGPoint, count: Int)?
+ private var dragging = false
+ private var pinching = false
+ private var viewRequest: Task<Void, Never>?
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ backgroundColor = .black
+ clipsToBounds = true
+ video.videoContentMode = .scaleAspectFit
+ video.isUserInteractionEnabled = false
+ addSubview(video)
+ keys.onText = { [weak self] in self?.typed($0) }
+ keys.onKey = { [weak self] key, mods in self?.pressKey(key, mods) }
+ addSubview(keys)
+ installGestures()
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
+
+ // MARK: state from SwiftUI
+
+ func attach(_ newTrack: RTCVideoTrack?) {
+ guard newTrack !== track else { return }
+ track?.remove(video)
+ track = newTrack
+ newTrack?.add(video)
+ }
+
+ func setDisplay(_ d: ScreenDisplay) {
+ let size = CGSize(width: d.width, height: d.height)
+ guard size != viewport.display else { return }
+ viewport = ScreenViewport(display: size, view: bounds.size)
+ cursor = CGPoint(x: d.width / 2, y: d.height / 2)
+ streamRegion = nil
+ layoutVideo()
+ scheduleViewRequest()
+ }
+
+ func setStreamRegion(_ crop: CGRect?) {
+ streamRegion = crop
+ layoutVideo()
+ }
+
+ func setKeyboard(_ shown: Bool) {
+ keys.showsSoftKeyboard = shown
+ }
+
+ func resetZoom() {
+ viewport.reset()
+ viewportChanged()
+ }
+
+ // MARK: layout
+
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ if viewport.view != bounds.size {
+ viewport.view = bounds.size
+ viewport.pan(by: .zero)
+ scheduleViewRequest()
+ }
+ keys.frame = CGRect(x: 0, y: 0, width: 1, height: 1)
+ layoutVideo()
+ }
+
+ override func didMoveToWindow() {
+ super.didMoveToWindow()
+ // First responder even with the keyboard hidden, so a hardware keyboard just works.
+ if window != nil { keys.becomeFirstResponder() }
+ }
+
+ private func layoutVideo() {
+ guard bounds.width > 0, bounds.height > 0 else { return }
+ video.frame = viewport.frame(of: streamRegion ?? viewport.displayBounds)
+ }
+
+ private func viewportChanged() {
+ layoutVideo()
+ onZoomChanged(viewport.crop != nil)
+ scheduleViewRequest()
+ }
+
+ /// Streams just the visible region at the view's pixel size, once the gesture settles.
+ private func scheduleViewRequest() {
+ viewRequest?.cancel()
+ viewRequest = Task { @MainActor [weak self] in
+ try? await Task.sleep(for: .milliseconds(180))
+ guard let self, !Task.isCancelled, !self.pinching else { return }
+ let scale = self.window?.screen.scale ?? 3
+ self.requestView(self.viewport.crop, CGSize(width: self.bounds.width * scale, height: self.bounds.height * scale))
+ }
+ }
+
+ // MARK: gestures
+
+ private func installGestures() {
+ let pan = UIPanGestureRecognizer(target: self, action: #selector(onePan(_:)))
+ pan.maximumNumberOfTouches = 1
+ let tap = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
+ let rightTap = UITapGestureRecognizer(target: self, action: #selector(twoFingerTap(_:)))
+ rightTap.numberOfTouchesRequired = 2
+ let press = UILongPressGestureRecognizer(target: self, action: #selector(press(_:)))
+ press.minimumPressDuration = 0.35
+ let scroll = UIPanGestureRecognizer(target: self, action: #selector(twoPan(_:)))
+ scroll.minimumNumberOfTouches = 2
+ scroll.maximumNumberOfTouches = 2
+ let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinch(_:)))
+ for g in [pan, tap, rightTap, press, scroll, pinch] as [UIGestureRecognizer] {
+ g.delegate = self
+ addGestureRecognizer(g)
+ }
+ pan.require(toFail: press)
+ tap.require(toFail: rightTap)
+ }
+
+ func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
+ // Pinch and two-finger pan together: zoom and move the view.
+ (g is UIPinchGestureRecognizer && other is UIPanGestureRecognizer) || (g is UIPanGestureRecognizer && other is UIPinchGestureRecognizer)
+ }
+
+ @objc private func onePan(_ g: UIPanGestureRecognizer) {
+ let delta = g.translation(in: self)
+ g.setTranslation(.zero, in: self)
+ guard interactive else {
+ viewport.pan(by: delta)
+ viewportChanged()
+ return
+ }
+ switch mode {
+ case .trackpad:
+ // Pointer speed grows with finger speed, like a real trackpad.
+ let speed = g.velocity(in: self)
+ let accel = min(2.5, max(1, hypot(speed.x, speed.y) / 900))
+ moveCursor(by: CGPoint(x: delta.x * accel / viewport.scale, y: delta.y * accel / viewport.scale))
+ case .direct:
+ if viewport.crop != nil {
+ viewport.pan(by: delta)
+ viewportChanged()
+ } else {
+ send(["type": "scroll", "x": cursor.x, "y": cursor.y, "dx": -delta.x, "dy": -delta.y, "units": "pixel"])
+ }
+ }
+ }
+
+ private func moveCursor(by d: CGPoint) {
+ let bounds = viewport.displayBounds
+ cursor = CGPoint(x: min(max(cursor.x + d.x, 0), bounds.width - 1), y: min(max(cursor.y + d.y, 0), bounds.height - 1))
+ send(["type": "move", "x": cursor.x, "y": cursor.y])
+ let before = viewport
+ viewport.follow(cursor)
+ if viewport != before { viewportChanged() }
+ }
+
+ private func point(for g: UIGestureRecognizer) -> CGPoint {
+ mode == .direct ? clampToDisplay(viewport.toDisplay(g.location(in: self))) : cursor
+ }
+
+ private func clampToDisplay(_ p: CGPoint) -> CGPoint {
+ CGPoint(x: min(max(p.x, 0), viewport.display.width - 1), y: min(max(p.y, 0), viewport.display.height - 1))
+ }
+
+ @objc private func tap(_ g: UITapGestureRecognizer) {
+ guard interactive else { return }
+ let p = point(for: g)
+ cursor = p
+ // Successive quick taps become double/triple clicks without waiting to tell them apart.
+ let now = Date()
+ var count = 1
+ if let last = lastTap, now.timeIntervalSince(last.at) < 0.35, hypot(last.point.x - p.x, last.point.y - p.y) < 8 / viewport.scale {
+ count = min(last.count + 1, 3)
+ }
+ lastTap = (now, p, count)
+ send(["type": "click", "x": p.x, "y": p.y, "button": "left", "count": count, "modifiers": consumeArmed()])
+ }
+
+ @objc private func twoFingerTap(_ g: UITapGestureRecognizer) {
+ guard interactive else { return }
+ let p = point(for: g)
+ send(["type": "click", "x": p.x, "y": p.y, "button": "right", "count": 1, "modifiers": consumeArmed()])
+ }
+
+ /// Long-press then move: drag (select text, move windows).
+ @objc private func press(_ g: UILongPressGestureRecognizer) {
+ guard interactive else { return }
+ switch g.state {
+ case .began:
+ let p = point(for: g)
+ cursor = p
+ dragging = true
+ UIImpactFeedbackGenerator(style: .medium).impactOccurred()
+ send(["type": "down", "x": p.x, "y": p.y, "button": "left"])
+ lastPress = g.location(in: self)
+ case .changed:
+ let loc = g.location(in: self)
+ if mode == .direct {
+ cursor = clampToDisplay(viewport.toDisplay(loc))
+ send(["type": "move", "x": cursor.x, "y": cursor.y])
+ } else {
+ moveCursor(by: CGPoint(x: (loc.x - lastPress.x) / viewport.scale, y: (loc.y - lastPress.y) / viewport.scale))
+ }
+ lastPress = loc
+ default:
+ if dragging {
+ send(["type": "up", "x": cursor.x, "y": cursor.y, "button": "left"])
+ dragging = false
+ }
+ }
+ }
+
+ private var lastPress = CGPoint.zero
+
+ @objc private func twoPan(_ g: UIPanGestureRecognizer) {
+ let delta = g.translation(in: self)
+ g.setTranslation(.zero, in: self)
+ if pinching || !interactive {
+ viewport.pan(by: delta)
+ viewportChanged()
+ return
+ }
+ // Natural scrolling: content follows the fingers.
+ let at = mode == .direct ? clampToDisplay(viewport.toDisplay(g.location(in: self))) : cursor
+ send(["type": "scroll", "x": at.x, "y": at.y, "dx": -delta.x * 1.5, "dy": -delta.y * 1.5, "units": "pixel"])
+ }
+
+ @objc private func pinch(_ g: UIPinchGestureRecognizer) {
+ switch g.state {
+ case .began:
+ pinching = true
+ case .changed:
+ viewport.zoom(by: g.scale, at: g.location(in: self))
+ g.scale = 1
+ layoutVideo()
+ default:
+ pinching = false
+ viewportChanged()
+ }
+ }
+
+ // MARK: keys
+
+ private func consumeArmed() -> [String] {
+ let mods = armed
+ if !mods.isEmpty {
+ armed = []
+ onArmedConsumed()
+ }
+ return mods
+ }
+
+ private func typed(_ text: String) {
+ guard interactive else { return }
+ let mods = consumeArmed()
+ if !mods.isEmpty, text.count == 1 {
+ send(["type": "key", "key": text.lowercased(), "modifiers": mods])
+ } else {
+ send(["type": "text", "text": text])
+ }
+ }
+
+ func pressKey(_ key: String, _ modifiers: [String] = []) {
+ guard interactive else { return }
+ let mods = Array(Set(modifiers + consumeArmed()))
+ send(["type": "key", "key": key, "modifiers": mods])
+ }
+}
+
+/// Invisible text field that turns the iOS keyboard (including IME input such as
+/// Zhuyin or Pinyin) and hardware keys into events for the computer.
+private final class KeyProxyField: UITextField, UITextFieldDelegate {
+ var onText: (String) -> Void = { _ in }
+ var onKey: (String, [String]) -> Void = { _, _ in }
+
+ /// With the soft keyboard hidden the field stays first responder, so hardware keys still arrive.
+ var showsSoftKeyboard = false {
+ didSet {
+ guard showsSoftKeyboard != oldValue else { return }
+ inputView = showsSoftKeyboard ? nil : UIView()
+ reloadInputViews()
+ if !isFirstResponder { becomeFirstResponder() }
+ }
+ }
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ delegate = self
+ alpha = 0.02
+ tintColor = .clear
+ autocorrectionType = .no
+ autocapitalizationType = .none
+ spellCheckingType = .no
+ smartQuotesType = .no
+ smartDashesType = .no
+ smartInsertDeleteType = .no
+ inlinePredictionType = .no
+ inputView = UIView()
+ inputAssistantItem.leadingBarButtonGroups = []
+ inputAssistantItem.trailingBarButtonGroups = []
+ addTarget(self, action: #selector(changed), for: .editingChanged)
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
+
+ /// Sends committed text; text still being composed by an IME waits.
+ @objc private func changed() {
+ guard markedTextRange == nil, let t = text, !t.isEmpty else { return }
+ onText(t)
+ text = ""
+ }
+
+ override func deleteBackward() {
+ if (text ?? "").isEmpty { onKey("delete", []) }
+ super.deleteBackward()
+ }
+
+ func textFieldShouldReturn(_ textField: UITextField) -> Bool {
+ onKey("return", [])
+ return false
+ }
+
+ override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
+ var unhandled = Set<UIPress>()
+ for press in presses {
+ guard let key = press.key, let (name, mods) = Self.map(key) else {
+ unhandled.insert(press)
+ continue
+ }
+ onKey(name, mods)
+ }
+ if !unhandled.isEmpty { super.pressesBegan(unhandled, with: event) }
+ }
+
+ /// Shortcuts and special keys go straight through; plain typing takes the text path (IME-aware).
+ private static func map(_ key: UIKey) -> (String, [String])? {
+ var mods: [String] = []
+ if key.modifierFlags.contains(.command) { mods.append("cmd") }
+ if key.modifierFlags.contains(.alternate) { mods.append("option") }
+ if key.modifierFlags.contains(.control) { mods.append("ctrl") }
+ if key.modifierFlags.contains(.shift) { mods.append("shift") }
+ if let special = special[key.keyCode] { return (special, mods) }
+ let chord = mods.contains("cmd") || mods.contains("ctrl") || mods.contains("option")
+ guard chord, let c = key.charactersIgnoringModifiers.lowercased().first else { return nil }
+ return (String(c), mods)
+ }
+
+ private static let special: [UIKeyboardHIDUsage: String] = [
+ .keyboardUpArrow: "up", .keyboardDownArrow: "down", .keyboardLeftArrow: "left", .keyboardRightArrow: "right",
+ .keyboardEscape: "escape", .keyboardTab: "tab", .keyboardReturnOrEnter: "return", .keypadEnter: "return",
+ .keyboardDeleteOrBackspace: "delete", .keyboardDeleteForward: "forwardDelete",
+ .keyboardHome: "home", .keyboardEnd: "end", .keyboardPageUp: "pageUp", .keyboardPageDown: "pageDown",
+ .keyboardF1: "f1", .keyboardF2: "f2", .keyboardF3: "f3", .keyboardF4: "f4", .keyboardF5: "f5", .keyboardF6: "f6",
+ .keyboardF7: "f7", .keyboardF8: "f8", .keyboardF9: "f9", .keyboardF10: "f10", .keyboardF11: "f11", .keyboardF12: "f12",
+ ]
+}
+
+/// SwiftUI host for the canvas.
+struct ScreenCanvasView: UIViewRepresentable {
+ let session: ScreenSession
+ let display: ScreenDisplay
+ let mode: TouchMode
+ let interactive: Bool
+ let keyboard: Bool
+ @Binding var armed: [String]
+ @Binding var zoomed: Bool
+ let resetToken: Int
+
+ func makeUIView(context: Context) -> ScreenCanvas {
+ let canvas = ScreenCanvas()
+ canvas.send = { [weak session] in session?.send($0) }
+ canvas.requestView = { [weak session] crop, pixels in session?.view(crop: crop, pixels: pixels) }
+ return canvas
+ }
+
+ func updateUIView(_ canvas: ScreenCanvas, context: Context) {
+ canvas.onArmedConsumed = { armed = [] }
+ canvas.onZoomChanged = { z in if zoomed != z { zoomed = z } }
+ canvas.attach(session.track)
+ canvas.setDisplay(display)
+ canvas.setStreamRegion(session.streamCrop)
+ canvas.mode = mode
+ canvas.interactive = interactive
+ canvas.armed = armed
+ canvas.setKeyboard(keyboard)
+ if context.coordinator.resetToken != resetToken {
+ context.coordinator.resetToken = resetToken
+ canvas.resetZoom()
+ }
+ }
+
+ func makeCoordinator() -> Coordinator { Coordinator(resetToken: resetToken) }
+
+ final class Coordinator {
+ var resetToken: Int
+ init(resetToken: Int) { self.resetToken = resetToken }
+ }
+
+ static func dismantleUIView(_ canvas: ScreenCanvas, coordinator: Coordinator) {
+ canvas.attach(nil)
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Screen/ScreenSession.swift b/kit/Sources/CodyncUI/Screen/ScreenSession.swift
new file mode 100644
index 00000000..4f6a89b1
--- /dev/null
+++ b/kit/Sources/CodyncUI/Screen/ScreenSession.swift
@@ -0,0 +1,280 @@
+#if os(iOS)
+import CodyncKit
+import Foundation
+import Observation
+import os
+@preconcurrency import WebRTC
+
+private let log = Logger(subsystem: "com.pokai.Codync", category: "Screen")
+
+/// One live view of the computer's screen: a WebRTC peer that receives the
+/// display as H.264 and sends input over two data channels (`input` reliable,
+/// `input-fast` unordered for pointer moves). Signaling goes through the host
+/// API, non-trickle (offer and answer carry every candidate).
+@MainActor
+@Observable
+public final class ScreenSession {
+ public enum Phase: Equatable {
+ case connecting
+ case live
+ case reconnecting
+ case failed(String)
+ case closed
+ }
+
+ public private(set) var phase: Phase = .connecting
+ public private(set) var track: RTCVideoTrack?
+ /// Text the computer copied, waiting for the user to pull it onto the phone.
+ public private(set) var remoteClipboard: String?
+ public private(set) var lastError: String?
+ public private(set) var display: ScreenDisplay?
+ /// The display region the video currently shows (points; `nil` = all of it), as confirmed by the computer.
+ public private(set) var streamCrop: CGRect?
+
+ private let client: HostClient
+ private var session: String?
+ private var pc: RTCPeerConnection?
+ private var reliable: RTCDataChannel?
+ private var fast: RTCDataChannel?
+ private var events: PeerEvents?
+ private var gathered: CheckedContinuation<Void, Never>?
+ private var recoverTask: Task<Void, Never>?
+
+ static let factory: RTCPeerConnectionFactory = {
+ RTCInitializeSSL()
+ return RTCPeerConnectionFactory(encoderFactory: RTCDefaultVideoEncoderFactory(), decoderFactory: RTCDefaultVideoDecoderFactory())
+ }()
+
+ public init(client: HostClient, display: ScreenDisplay?) {
+ self.client = client
+ self.display = display
+ }
+
+ // MARK: connection
+
+ public func start() async {
+ phase = .connecting
+ do {
+ try await connect()
+ } catch {
+ phase = .failed(error.localizedDescription)
+ }
+ }
+
+ private func connect() async throws {
+ teardown()
+ let config = RTCConfiguration()
+ config.sdpSemantics = .unifiedPlan
+ config.iceServers = []
+ config.tcpCandidatePolicy = .enabled
+ config.continualGatheringPolicy = .gatherOnce
+ config.bundlePolicy = .maxBundle
+ let events = PeerEvents(owner: self)
+ guard let pc = Self.factory.peerConnection(with: config, constraints: Self.noConstraints, delegate: events) else {
+ throw HostError.http(0, "Couldn't start the video connection.")
+ }
+ self.events = events
+ self.pc = pc
+
+ let initVideo = RTCRtpTransceiverInit()
+ initVideo.direction = .recvOnly
+ guard let video = pc.addTransceiver(of: .video, init: initVideo) else {
+ throw HostError.http(0, "Couldn't start the video connection.")
+ }
+ // Hardware H.264 first (High, then Constrained Baseline); the rest only as a fallback.
+ let codecs = Self.factory.rtpReceiverCapabilities(forKind: kRTCMediaStreamTrackKindVideo).codecs
+ let h264 = codecs.filter { $0.name == kRTCVideoCodecH264Name }
+ .sorted { ($0.parameters["profile-level-id"] ?? "").hasPrefix("640c") && !($1.parameters["profile-level-id"] ?? "").hasPrefix("640c") }
+ try? video.setCodecPreferences(h264 + codecs.filter { $0.name != kRTCVideoCodecH264Name }, error: ())
+ track = video.receiver.track as? RTCVideoTrack
+
+ reliable = pc.dataChannel(forLabel: "input", configuration: RTCDataChannelConfiguration())
+ let unordered = RTCDataChannelConfiguration()
+ unordered.isOrdered = false
+ unordered.maxRetransmits = 0
+ fast = pc.dataChannel(forLabel: "input-fast", configuration: unordered)
+ reliable?.delegate = events
+
+ try await negotiate(pc)
+ }
+
+ /// Offer → host → answer. Also used for ICE restarts on the same session.
+ private func negotiate(_ pc: RTCPeerConnection) async throws {
+ let offer = try await pc.offer(for: Self.noConstraints)
+ try await pc.setLocalDescription(offer)
+ await waitForCandidates(pc)
+ let sdp = pc.localDescription?.sdp ?? offer.sdp
+ let answer = try await client.screenOffer(sdp: sdp, session: session, display: display?.id)
+ session = answer.session
+ try await pc.setRemoteDescription(RTCSessionDescription(type: .answer, sdp: answer.sdp))
+ }
+
+ private func waitForCandidates(_ pc: RTCPeerConnection) async {
+ guard pc.iceGatheringState != .complete else { return }
+ Task {
+ try? await Task.sleep(for: .seconds(3))
+ self.finishGathering()
+ }
+ await withCheckedContinuation { gathered = $0 }
+ }
+
+ fileprivate func finishGathering() {
+ gathered?.resume()
+ gathered = nil
+ }
+
+ fileprivate func iceChanged(_ state: RTCIceConnectionState) {
+ switch state {
+ case .connected, .completed:
+ recoverTask?.cancel()
+ recoverTask = nil
+ phase = .live
+ lastError = nil
+ case .disconnected:
+ // Often recovers by itself (Wi-Fi ↔ cellular); restart ICE if it doesn't.
+ phase = .reconnecting
+ scheduleRecovery(after: .seconds(2), restartIce: true)
+ case .failed:
+ phase = .reconnecting
+ scheduleRecovery(after: .zero, restartIce: false)
+ default:
+ break
+ }
+ }
+
+ private func scheduleRecovery(after delay: Duration, restartIce: Bool) {
+ recoverTask?.cancel()
+ recoverTask = Task { [weak self] in
+ var attempt = 0
+ try? await Task.sleep(for: delay)
+ while let self, !Task.isCancelled, self.phase == .reconnecting {
+ do {
+ if restartIce, attempt == 0, let pc = self.pc {
+ pc.restartIce()
+ try await self.negotiate(pc)
+ } else {
+ try await self.connect()
+ }
+ return
+ } catch {
+ log.info("screen reconnect failed: \(error.localizedDescription)")
+ attempt += 1
+ try? await Task.sleep(for: .seconds(min(Double(attempt) * 2, 10)))
+ }
+ }
+ }
+ }
+
+ public func close() {
+ recoverTask?.cancel()
+ phase = .closed
+ if let session {
+ let client = client
+ Task { try? await client.screenClose(session: session) }
+ }
+ session = nil
+ teardown()
+ }
+
+ private func teardown() {
+ finishGathering()
+ reliable?.close()
+ fast?.close()
+ pc?.close()
+ reliable = nil
+ fast = nil
+ pc = nil
+ events = nil
+ track = nil
+ }
+
+ // MARK: input
+
+ /// Sends one input event (display points). Pointer moves go unordered: a late move is useless.
+ public func send(_ event: [String: Any]) {
+ let isMove = event["type"] as? String == "move"
+ let channel = isMove ? (fast?.readyState == .open ? fast : reliable) : reliable
+ guard let channel, channel.readyState == .open, let data = try? JSONSerialization.data(withJSONObject: event) else { return }
+ channel.sendData(RTCDataBuffer(data: data, isBinary: false))
+ }
+
+ /// What to stream: a region of the display (points; `nil` = all of it) at the viewer's pixel size.
+ public func view(crop: CGRect?, pixels: CGSize) {
+ var msg: [String: Any] = ["type": "view", "long": max(pixels.width, pixels.height), "short": min(pixels.width, pixels.height)]
+ if let display { msg["display"] = display.id }
+ if let crop { msg["crop"] = [crop.minX, crop.minY, crop.width, crop.height] }
+ send(msg)
+ }
+
+ public func switchDisplay(_ d: ScreenDisplay) {
+ display = d
+ send(["type": "view", "display": d.id])
+ }
+
+ public func pushClipboard(_ text: String) {
+ send(["type": "clipboard", "text": text])
+ }
+
+ public func takeRemoteClipboard() -> String? {
+ defer { remoteClipboard = nil }
+ return remoteClipboard
+ }
+
+ fileprivate func received(_ data: Data) {
+ guard let msg = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return }
+ switch msg["type"] as? String {
+ case "clipboard": remoteClipboard = msg["text"] as? String
+ case "view":
+ if let c = msg["crop"] as? [Double], c.count == 4 {
+ streamCrop = CGRect(x: c[0], y: c[1], width: c[2], height: c[3])
+ } else {
+ streamCrop = nil
+ }
+ case "error": lastError = msg["message"] as? String
+ default: break
+ }
+ }
+
+ private static let noConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
+}
+
+/// WebRTC delegate callbacks arrive on its signaling thread; this hops them to the main actor.
+private final class PeerEvents: NSObject, RTCPeerConnectionDelegate, RTCDataChannelDelegate, Sendable {
+ private let owner: WeakBox
+
+ @MainActor init(owner: ScreenSession) {
+ self.owner = WeakBox(owner)
+ }
+
+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {}
+ func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {}
+ func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {}
+ func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {}
+
+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
+ let owner = owner
+ Task { @MainActor in owner.value?.iceChanged(newState) }
+ }
+
+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {
+ guard newState == .complete else { return }
+ let owner = owner
+ Task { @MainActor in owner.value?.finishGathering() }
+ }
+
+ func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {
+ let data = buffer.data
+ let owner = owner
+ Task { @MainActor in owner.value?.received(data) }
+ }
+}
+
+private final class WeakBox: Sendable {
+ @MainActor weak var value: ScreenSession?
+ @MainActor init(_ value: ScreenSession) { self.value = value }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Screen/ScreenView.swift b/kit/Sources/CodyncUI/Screen/ScreenView.swift
new file mode 100644
index 00000000..9b1f56db
--- /dev/null
+++ b/kit/Sources/CodyncUI/Screen/ScreenView.swift
@@ -0,0 +1,305 @@
+#if os(iOS)
+import CodyncKit
+import SwiftUI
+import UIKit
+
+/// The computer's screen, full screen on the phone. Opened from the roster (to use
+/// the computer) or from a bot's live chip (to watch it work, then take over).
+public struct ScreenView: View {
+ @Environment(BotStore.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ /// The bot being watched, when opened from its chat.
+ private let watching: String?
+
+ @State private var session: ScreenSession?
+ @State private var display: ScreenDisplay?
+ @State private var interactive = false
+ @State private var mode: TouchMode = .trackpad
+ @State private var keyboard = false
+ @State private var armed: [String] = []
+ @State private var zoomed = false
+ @State private var resetToken = 0
+ @State private var tookOver = false
+
+ public init(watching: String? = nil) {
+ self.watching = watching
+ }
+
+ private var screen: ScreenState? { model.screen }
+ private var agent: Bot? { screen?.agentBot.flatMap { model.bots[$0] } }
+
+ public var body: some View {
+ ZStack {
+ Color.black.ignoresSafeArea()
+ if let session, let display, screen?.available == true {
+ ScreenCanvasView(session: session, display: display, mode: mode, interactive: interactive,
+ keyboard: keyboard, armed: $armed, zoomed: $zoomed, resetToken: resetToken)
+ .ignoresSafeArea(.container)
+ .ignoresSafeArea(.keyboard)
+ status(session)
+ } else {
+ unavailable
+ }
+ }
+ .overlay(alignment: .top) { topBar }
+ .safeAreaInset(edge: .bottom) {
+ if keyboard && interactive { ModifierBar(armed: $armed) { session?.send(["type": "key", "key": $0, "modifiers": armed]); armed = [] } }
+ }
+ .statusBarHidden()
+ .persistentSystemOverlays(.hidden)
+ .preferredColorScheme(.dark)
+ .onAppear(perform: start)
+ .onDisappear(perform: stop)
+ .onChange(of: screen?.available) { _, available in
+ if available == true, session == nil { start() }
+ }
+ }
+
+ // MARK: lifecycle
+
+ private func start() {
+ OrientationLock.set(.allButUpsideDown, prefer: .landscapeRight)
+ guard session == nil, let client = model.client, let screen, screen.available, let d = display ?? screen.mainDisplay else { return }
+ display = d
+ let s = ScreenSession(client: client, display: d)
+ session = s
+ Task { await s.start() }
+ // Watching a bot: look first. Otherwise take the screen (bots may still look).
+ setInteractive(watching == nil)
+ }
+
+ private func stop() {
+ session?.close()
+ session = nil
+ if tookOver { model.screenTakeover(false) }
+ tookOver = false
+ OrientationLock.set(.portrait, prefer: .portrait)
+ }
+
+ private func setInteractive(_ on: Bool) {
+ interactive = on
+ if on != tookOver {
+ tookOver = on
+ model.screenTakeover(on)
+ }
+ if !on { keyboard = false }
+ }
+
+ // MARK: chrome
+
+ private var topBar: some View {
+ HStack(spacing: 8) {
+ IconButton("Close", "xmark") { dismiss() }
+ if let agent, !interactive {
+ Label("\(agent.name) is using the computer", systemImage: "cursorarrow.motionlines")
+ .font(.caption.weight(.medium))
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(.ultraThinMaterial, in: Capsule())
+ }
+ Spacer()
+ if session != nil {
+ if interactive {
+ IconButton(keyboard ? "Hide keyboard" : "Keyboard", keyboard ? "keyboard.chevron.compact.down" : "keyboard") { keyboard.toggle() }
+ IconButton(mode == .trackpad ? "Touch mode: trackpad" : "Touch mode: direct", mode == .trackpad ? "rectangle.and.hand.point.up.left" : "hand.point.up.left") {
+ mode = mode == .trackpad ? .direct : .trackpad
+ }
+ clipboardMenu
+ }
+ if zoomed {
+ IconButton("Fit screen", "arrow.down.right.and.arrow.up.left") { resetToken += 1 }
+ }
+ if let displays = screen?.displays, displays.count > 1 {
+ Menu {
+ ForEach(displays) { d in
+ Button(d.name, systemImage: d.id == display?.id ? "checkmark" : "display") {
+ display = d
+ session?.switchDisplay(d)
+ resetToken += 1
+ }
+ }
+ } label: { IconLabel("Displays", "display.2") }
+ }
+ IconButton(interactive ? "Hand back to bots" : "Take over", interactive ? "hand.raised.slash" : "hand.raised") {
+ setInteractive(!interactive)
+ }
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.top, 6)
+ }
+
+ private var clipboardMenu: some View {
+ Menu {
+ Button("Send my clipboard", systemImage: "arrow.up.doc.on.clipboard") {
+ if let text = UIPasteboard.general.string { session?.pushClipboard(text) }
+ }
+ .disabled(!UIPasteboard.general.hasStrings)
+ Button("Copy from computer", systemImage: "arrow.down.doc.on.clipboard") {
+ if let text = session?.takeRemoteClipboard() { UIPasteboard.general.string = text }
+ }
+ .disabled(session?.remoteClipboard == nil)
+ } label: {
+ IconLabel("Clipboard", session?.remoteClipboard == nil ? "doc.on.clipboard" : "doc.on.clipboard.fill")
+ }
+ }
+
+ @ViewBuilder private func status(_ session: ScreenSession) -> some View {
+ switch session.phase {
+ case .connecting:
+ Overlay(icon: nil, text: "Connecting to the screen…")
+ case .reconnecting:
+ Overlay(icon: nil, text: "Reconnecting…")
+ case let .failed(message):
+ Overlay(icon: "exclamationmark.triangle", text: message) {
+ Task { await session.start() }
+ }
+ case .live, .closed:
+ if let error = session.lastError {
+ Text(error)
+ .font(.caption)
+ .padding(8)
+ .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 8))
+ .frame(maxHeight: .infinity, alignment: .bottom)
+ .padding(.bottom, 24)
+ }
+ }
+ }
+
+ @ViewBuilder private var unavailable: some View {
+ let s = screen
+ let (icon, text): (String, String) =
+ if model.connection != .online { ("wifi.slash", "This computer is offline.") }
+ else if s == nil { ("arrow.down.circle", "Update Codync on your computer to use its screen from here.") }
+ else if s?.enabled != true { ("lock.display", "Remote screen is off. Turn it on in Codync's menu on the computer.") }
+ else if s?.connected != true { ("display.trianglebadge.exclamationmark", "Codync Screen isn't running on the computer. Turn Remote screen off and on again in Codync's menu there.") }
+ else { ("record.circle", "Allow Codync Screen to record the screen: System Settings → Privacy & Security → Screen & System Audio Recording, on the computer.") }
+ Overlay(icon: icon, text: text)
+ }
+}
+
+private struct Overlay: View {
+ let icon: String?
+ let text: String
+ var retry: (() -> Void)?
+
+ var body: some View {
+ VStack(spacing: 12) {
+ if let icon {
+ Image(systemName: icon).font(.largeTitle).foregroundStyle(.secondary)
+ } else {
+ ProgressView()
+ }
+ Text(text).font(.callout).multilineTextAlignment(.center).foregroundStyle(.secondary)
+ if let retry {
+ Button("Try again", systemImage: "arrow.clockwise", action: retry)
+ .labelStyle(.iconOnly)
+ .buttonStyle(.bordered)
+ }
+ }
+ .padding(32)
+ .frame(maxWidth: 420)
+ }
+}
+
+private struct IconButton: View {
+ let label: String
+ let icon: String
+ let action: () -> Void
+
+ init(_ label: String, _ icon: String, action: @escaping () -> Void) {
+ self.label = label
+ self.icon = icon
+ self.action = action
+ }
+
+ var body: some View {
+ Button(action: action) { IconLabel(label, icon) }
+ }
+}
+
+private struct IconLabel: View {
+ let label: String
+ let icon: String
+
+ init(_ label: String, _ icon: String) {
+ self.label = label
+ self.icon = icon
+ }
+
+ var body: some View {
+ Image(systemName: icon)
+ .font(.system(size: 15, weight: .semibold))
+ .frame(width: 36, height: 36)
+ .background(.ultraThinMaterial, in: Circle())
+ .foregroundStyle(.white)
+ .accessibilityLabel(label)
+ }
+}
+
+/// Keys the iOS keyboard lacks. Modifiers arm for the next key or click.
+private struct ModifierBar: View {
+ @Binding var armed: [String]
+ let press: (String) -> Void
+
+ private static let modifiers = [("cmd", "command"), ("option", "option"), ("ctrl", "control"), ("shift", "shift")]
+ private static let keys = [("escape", "escape"), ("tab", "arrow.right.to.line"), ("left", "arrow.left"), ("up", "arrow.up"), ("down", "arrow.down"), ("right", "arrow.right")]
+
+ var body: some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ ForEach(Self.modifiers, id: \.0) { name, icon in
+ let on = armed.contains(name)
+ Button {
+ if on { armed.removeAll { $0 == name } } else { armed.append(name) }
+ } label: {
+ Image(systemName: icon).frame(width: 40, height: 34)
+ .background(on ? Color.white : Color.white.opacity(0.12), in: RoundedRectangle(cornerRadius: 8))
+ .foregroundStyle(on ? Color.black : Color.white)
+ }
+ .accessibilityLabel(name)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+ Divider().frame(height: 24).overlay(.white.opacity(0.3))
+ ForEach(Self.keys, id: \.0) { name, icon in
+ Button { press(name) } label: {
+ Image(systemName: icon).frame(width: 40, height: 34)
+ .background(Color.white.opacity(0.12), in: RoundedRectangle(cornerRadius: 8))
+ .foregroundStyle(.white)
+ }
+ .accessibilityLabel(name)
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ }
+ .background(.black.opacity(0.85))
+ }
+}
+
+/// iPhone is portrait-only except while the screen viewer is open. The app delegate
+/// answers `supportedInterfaceOrientationsFor` with `OrientationLock.mask`.
+@MainActor
+public enum OrientationLock {
+ public static var mask: UIInterfaceOrientationMask = UIDevice.current.userInterfaceIdiom == .pad ? .all : .portrait
+
+ static func set(_ newMask: UIInterfaceOrientationMask, prefer: UIInterfaceOrientationMask) {
+ guard UIDevice.current.userInterfaceIdiom == .phone else { return }
+ mask = newMask
+ // Once the full-screen cover is up: every controller in the chain re-reads the mask, then rotate.
+ Task { @MainActor in
+ try? await Task.sleep(for: .milliseconds(100))
+ for case let scene as UIWindowScene in UIApplication.shared.connectedScenes {
+ var vc = scene.keyWindow?.rootViewController
+ while let current = vc {
+ current.setNeedsUpdateOfSupportedInterfaceOrientations()
+ vc = current.presentedViewController
+ }
+ try? await Task.sleep(for: .milliseconds(150))
+ // Best effort: turning the phone always works once the mask allows it.
+ scene.requestGeometryUpdate(.iOS(interfaceOrientations: prefer))
+ }
+ }
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swift
index 3bdb302c..c4822e3b 100644
--- a/kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/kit/Sources/CodyncUI/Store/BotStore.swift
@@ -7,6 +7,13 @@ private let log = Logger(subsystem: "com.pokai.Codync", category: "BotStore")
/// Single source of truth for a Codync client (iPhone app, Mac window): mirrors
/// the host's bots and transcripts via one SSE stream (catch-up since `rev`, then live).
+/// Opens the screen viewer, optionally watching a bot that's using the computer.
+public struct ScreenRequest: Identifiable, Hashable, Sendable {
+ public var watching: String?
+ public var id: String { watching ?? "computer" }
+ public init(watching: String? = nil) { self.watching = watching }
+}
+
@MainActor
@Observable
public final class BotStore {
@@ -26,6 +33,8 @@ public final class BotStore {
public private(set) var bots: [String: Bot] = [:]
public private(set) var entries: [String: [Entry]] = [:]
public private(set) var usage = SharedStore.usage ?? Usage()
+ /// The computer's remote screen (`nil`: the host predates it).
+ public private(set) var screen: ScreenState?
/// Installed on the computer, for the Plugins screen and bot settings.
public private(set) var installedConnectors: [InstalledConnector] = []
public private(set) var installedSkills: [InstalledSkill] = []
@@ -38,6 +47,8 @@ public final class BotStore {
public var showProfile = false
/// The Plugins screen on its own; `codync://plugins` opens it.
public var showPlugins = false
+ /// The remote screen viewer (iPhone); `codync://screen` opens it.
+ public var screenRequest: ScreenRequest?
// Platform hooks (push registration, Live Activities, widgets).
public var onPaired: (@MainActor (BotStore) -> Void)?
@@ -150,6 +161,7 @@ public final class BotStore {
rev = 0
hostId = nil
historyComplete = []
+ screen = nil
saveCache()
}
@@ -193,6 +205,11 @@ public final class BotStore {
if let device = h.device, self.pairing?.device != device, let token = self.pairing?.token {
updateComputer(token) { $0.device = device }
}
+ // Addresses the host gained since pairing (say, Tailscale installed later) join the list.
+ if let urls = h.urls, let token = self.pairing?.token,
+ let known = self.pairing?.urls, !Set(urls).isSubset(of: Set(known)) {
+ updateComputer(token) { p in p.urls += urls.filter { !p.urls.contains($0) } }
+ }
// Host upgraded since the cache was written: its data may carry new fields.
if let stamp = cacheStamp, stamp != "\(Self.appBuild)/\(h.version)" {
rev = 0
@@ -223,13 +240,14 @@ public final class BotStore {
private func apply(_ event: HostEvent) {
switch event {
- case let .hello(id, hostRev, newUsage):
+ case let .hello(id, hostRev, newUsage, newScreen):
if let hostId, hostId != id {
// Different host database: start over.
resetMirror()
}
hostId = id
setUsage(newUsage)
+ screen = newScreen
if hostRev < rev { rev = 0 }
case let .bot(bot):
bots[bot.id] = bot
@@ -244,6 +262,8 @@ public final class BotStore {
bump(e.rev)
case let .usage(u):
setUsage(u)
+ case let .screen(s):
+ screen = s
case .resync:
restartStream()
case let .undecodable(type):
@@ -334,6 +354,18 @@ public final class BotStore {
public func stop(_ botId: String) { perform { try await $0.stop(botId) } }
public func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }
+ // MARK: remote screen
+
+ /// Takes control from bots (they can still look) or hands it back.
+ public func screenTakeover(_ on: Bool) {
+ perform { [weak self] in self?.screen = try await $0.screenTakeover(on) }
+ }
+
+ /// Only the computer itself may turn remote screen on (the Mac menu).
+ public func setScreenEnabled(_ on: Bool) async throws {
+ screen = try await require().setScreenEnabled(on)
+ }
+
public func respond(_ entry: Entry, option: String?) {
perform { try await $0.respondPermission(entryId: entry.id, optionId: option) }
}
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index a1f486d6..9874c03d 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -70,6 +70,18 @@ public struct ThreadView: View {
.inlineNavigationTitle()
.toolbar {
ToolbarItem(placement: .principal) { header }
+ #if os(iOS)
+ if model.screen?.agentBot == botId {
+ ToolbarItem(placement: .primaryAction) {
+ // The bot is operating the computer: watch it live (and take over from there).
+ Button("Watch the screen", systemImage: "cursorarrow.motionlines") {
+ model.screenRequest = ScreenRequest(watching: botId)
+ }
+ .symbolEffect(.pulse, options: .repeating)
+ .tint(Palette.accent)
+ }
+ }
+ #endif
ToolbarItem(placement: .primaryAction) { menu }
#if os(macOS)
ToolbarItem(placement: .primaryAction) {
diff --git a/kit/Tests/CodyncKitTests/CodyncKitTests.swift b/kit/Tests/CodyncKitTests/CodyncKitTests.swift
index 7ea4337e..3fac73e9 100644
--- a/kit/Tests/CodyncKitTests/CodyncKitTests.swift
+++ b/kit/Tests/CodyncKitTests/CodyncKitTests.swift
@@ -7,7 +7,7 @@ import Testing
let lines = try String(contentsOf: url, encoding: .utf8).split(separator: "\n")
let events = lines.compactMap { HostClient.parseEvent(Data($0.dropFirst(5).utf8)) }
#expect(events.count == 6)
- guard case let .hello(hostId, rev, usage) = events[0] else { Issue.record("hello"); return }
+ guard case let .hello(hostId, rev, usage, _) = events[0] else { Issue.record("hello"); return }
#expect(hostId == "h1" && rev == 42 && usage.providers.first?.windows.first?.percent == 8)
guard case let .bot(bot) = events[1] else { Issue.record("bot"); return }
#expect(bot.name == "Rex" && bot.command == nil && !bot.isWorking)
@@ -34,6 +34,49 @@ import Testing
#expect(RelativeTime.short(now.addingTimeInterval(-7200), now: now) == "2h")
}
+@Test func parsesScreenEvents() throws {
+ let e = HostClient.parseEvent(Data(#"{"type":"screen","screen":{"enabled":true,"connected":true,"capture":true,"displays":[{"id":1,"name":"Built-in","width":1512,"height":982,"main":true}],"agentBot":"b1"}}"#.utf8))
+ guard case let .screen(s) = e else { Issue.record("screen"); return }
+ #expect(s.available && s.agentBot == "b1" && s.mainDisplay?.width == 1512 && !s.userControl)
+}
+
+@Test func screenViewportMapsAndZooms() {
+ // A 16:10 display in a wider landscape phone view: letterboxed left and right.
+ var v = ScreenViewport(display: CGSize(width: 1600, height: 1000), view: CGSize(width: 800, height: 400))
+ #expect(v.scale == 0.4)
+ #expect(v.crop == nil)
+ #expect(v.toDisplay(CGPoint(x: 400, y: 200)) == CGPoint(x: 800, y: 500))
+ #expect(v.frame(of: v.displayBounds) == CGRect(x: 80, y: 0, width: 640, height: 400))
+
+ // Pinch keeps the point under the fingers still.
+ let anchor = CGPoint(x: 600, y: 100)
+ let before = v.toDisplay(anchor)
+ v.zoom(by: 2, at: anchor)
+ let after = v.toDisplay(anchor)
+ #expect(abs(before.x - after.x) < 0.001 && abs(before.y - after.y) < 0.001)
+ let crop = v.crop!
+ #expect(v.displayBounds.contains(crop))
+ #expect(abs(crop.width / crop.height - 2) < 0.001)
+
+ // Panning never leaves the display.
+ v.pan(by: CGPoint(x: 10_000, y: 10_000))
+ #expect(v.visible.minX == 0 && v.visible.minY == 0)
+
+ // The cursor pulls the view along.
+ v.follow(CGPoint(x: 1590, y: 990))
+ #expect(v.visible.maxX == 1600 && v.visible.maxY == 1000)
+
+ v.zoom(by: 1000, at: .zero)
+ #expect(v.zoom == v.maxZoom && v.scale == 4)
+}
+
+@Test func tailscaleAddresses() {
+ #expect(Tailscale.isAddress("http://100.101.2.3:19222"))
+ #expect(Tailscale.isAddress("http://mac.tail1234.ts.net:19222"))
+ #expect(!Tailscale.isAddress("http://100.200.2.3:19222"))
+ #expect(!Tailscale.isAddress("http://192.168.1.5:19222"))
+}
+
@Test func parsesClaudeResetText() throws {
let taipei = try #require(TimeZone(identifier: "Asia/Taipei"))
var cal = Calendar(identifier: .gregorian)
diff --git a/project.yml b/project.yml
index 723ad17d..6800df2f 100644
--- a/project.yml
+++ b/project.yml
@@ -9,9 +9,12 @@ options:
packages:
CodyncKit:
path: kit
+ WebRTC:
+ url: https://github.com/stasel/WebRTC
+ exactVersion: 153.0.0
settings:
base:
- MARKETING_VERSION: 2.0.0
+ MARKETING_VERSION: 2.1.0
CURRENT_PROJECT_VERSION: 17
SWIFT_VERSION: "6.0"
SWIFT_STRICT_CONCURRENCY: complete
@@ -24,12 +27,26 @@ targets:
type: application
platform: macOS
sources:
- - apps/macos
+ - path: apps/macos
+ excludes:
+ - LaunchAgents
+ # Registered with SMAppService.agent when Remote screen is turned on.
+ - path: apps/macos/LaunchAgents/com.pokai.Codync.screen.plist
+ buildPhase:
+ copyFiles:
+ destination: wrapper
+ subpath: Contents/Library/LaunchAgents
dependencies:
- package: CodyncKit
product: CodyncKit
- package: CodyncKit
product: CodyncUI
+ - target: Screen
+ embed: true
+ codeSign: true
+ copy:
+ destination: wrapper
+ subpath: Contents/Library/LoginItems
settings:
base:
PRODUCT_NAME: Codync
@@ -75,6 +92,26 @@ targets:
if [ -n "$EXPANDED_CODE_SIGN_IDENTITY" ] && [ "$CODE_SIGNING_ALLOWED" != "NO" ]; then
codesign --force --options runtime --timestamp=none --sign "$EXPANDED_CODE_SIGN_IDENTITY" "$DEST"
fi
+ # Screen capture, input and WebRTC for Remote screen. A separate signed bundle so
+ # macOS's Screen Recording / Accessibility grants belong to it (see host/src/screen.rs).
+ Screen:
+ type: application
+ platform: macOS
+ sources:
+ - apps/screen
+ dependencies:
+ - package: WebRTC
+ settings:
+ base:
+ PRODUCT_NAME: CodyncScreen
+ PRODUCT_BUNDLE_IDENTIFIER: com.pokai.Codync.screen
+ GENERATE_INFOPLIST_FILE: YES
+ INFOPLIST_KEY_LSUIElement: YES
+ INFOPLIST_KEY_CFBundleDisplayName: Codync Screen
+ INFOPLIST_KEY_NSHumanReadableCopyright: ""
+ ENABLE_HARDENED_RUNTIME: YES
+ ENABLE_APP_SANDBOX: NO
+ SKIP_INSTALL: YES
iOS:
type: application
platform: iOS
@@ -106,7 +143,8 @@ targets:
INFOPLIST_KEY_NSSupportsLiveActivities: YES
INFOPLIST_KEY_NSCameraUsageDescription: Scan the pairing code shown on your computer.
INFOPLIST_KEY_NSLocalNetworkUsageDescription: Codync connects to the computer running your bots on your local network.
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: UIInterfaceOrientationPortrait
+ # Portrait everywhere except the screen viewer (AppDelegate + OrientationLock).
+ INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
Widgets: