Skip to content

Client Internals

root edited this page Dec 4, 2026 · 6 revisions

Client Internals

🌐 English · 简体中文

This page documents the tech stack, module layout, and key implementation details of Trizano's three clients (Web, Kotlin Android, and MyGo Desktop) for contributors modifying the frontend, mobile app, or desktop shell. For the event-sync state machine, see Event Sync; for authentication and tickets, see Security.

Web Client (web/)

The Web client is a single-page application shared across desktop browsers and the native desktop WebView. Its UI primitives derive from t3code v0.0.22, while all business logic and state management are rewritten directly against this repository's Protobuf contracts.

Baseline, Licensing, and Stack

  • Upstream baseline: Forked from t3code v0.0.22, retaining web/src/components/ui/ (unstyled @base-ui/react primitives and shadcn-style wrappers) and the theme CSS tokens / layout variables in web/src/index.css. All application components and stores have been rewritten to consume types generated in @trizano/proto.
  • Licensing and branding: The repository is licensed under AGPL-3.0 while retaining web/LICENSE-t3code (MIT license notice) for the retained t3code files, without using T3 brand names, icons, or visual assets.
  • Core dependencies (web/package.json): React 19, Vite 8, TanStack Router, Tailwind CSS v4 (@tailwindcss/vite), zustand 5, @connectrpc/connect-web + @bufbuild/protobuf, @xterm/xterm 6, and monaco-editor + shiki / @shikijs/monaco.
  • Path alias and build output: web/tsconfig.json maps ~/* to web/src/*. During development, web/vite.config.ts serves on 127.0.0.1:5733 and proxies /trizano.hub.v1. and /nodes/ (including WebSockets) to TRIZANO_HUB (default http://127.0.0.1:47900). vite build writes artifacts to server/hub/webui/dist, which both the Hub (-tags embedweb) and desktop app (reusing server/hub/webui) embed. server/hub/webui/webui.go serves /assets/* with Cache-Control: private, max-age=31536000, immutable, and returns a short development notice when built without embedweb.

RPC Transports and Directory Layout

web/src/rpc/client.ts creates two Connect transports:

  • Hub client (hub): Targets window.location.origin and binds AuthService, DeviceService, NodeService, EventService, OrchestrationService, and UsageService.
  • Node client (nodeApi(nodeId)): Cached per Node ID, creating a Connect transport with baseUrl set to ${window.location.origin}/nodes/${nodeId} and binding AgentService, WorkspaceService, SessionService, TerminalService, PortService, BrowserService, SystemService, FileService, GitService, ReviewService, and UsageService.
  • Unified auth-expiry interceptor: Every transport shares signOutWhenRefused. Whether a unary call fails or a server-stream throws Code.Unauthenticated mid-stream (for example, when a device is revoked), it clears useAuth's me state to trigger sign-out and store reset.
Directory Responsibility
web/src/rpc/ Connect transports and per-service client factories (client.ts)
web/src/state/ Global zustand store (store.ts), event sync (sync.ts, timeline.ts), split tree (split.ts), workbench panes (panes.ts), review state (review.ts), overlay stack (overlay.ts), auth (auth.ts)
web/src/lib/ Desktop /_desktop/* bridge (desktop.ts, desktopAuth.ts), keyboard shortcuts (keybindings.ts), notifications, settings, syntax highlighting (highlight.ts), cross-platform path normalization (paths.ts), frontend build-update checks (webBuild.ts)
web/src/components/ui/ Base UI primitives retained from t3code
web/src/components/session/ Main Session view, timeline, Composer, Approval cards, Discussion Rooms, split stage (SplitStage.tsx)
web/src/components/panes/ Right tabbed workbench (Terminal, Files, Diff, Background Tasks, Services, Managed Browser & annotations, Side Chat)
web/src/components/ide/ Standalone full-window IDE (IdeWindow.tsx, Workbench.tsx, EditorArea.tsx, ScmView.tsx, IdeAgentPanel.tsx)
web/src/components/editor/ Lazy-loaded Monaco wrapper (index.tsx, monaco-core.ts, monaco.ts, EditorView.tsx, review hunk view)
web/src/components/machines/, usage/, settings/, terminal/, sidebar/ Machine topology & live probes, usage stats, settings modal, full-screen terminal, main sidebar

Monaco IDE and Split-Pane Tree

Built-in Monaco IDE workbench mode

  • Standalone IDE window and lazy Monaco: Routes /ide and /ide/$node/$workspace render the full-window IdeWindow (hiding the main app sidebar; mobile viewports prompt the user to switch to a desktop screen instead of loading the editor). Workbench.tsx uses a VS Code–style layout: activity bar + primary sidebar (Explorer, Search, Source Control, Review, Extensions), central editor area + bottom terminal panel, side agent conversation panel, and status bar. The editor entry (web/src/components/editor/index.tsx) lazily loads EditorView.tsx via React.lazy, while vite.config.ts splits Monaco into a dedicated monaco chunk via rolldownOptions.output.codeSplitting. monaco-core.ts imports editing features selectively and skips built-in Monarch grammars, delegating syntax highlighting in monaco.ts to the shared Shiki instance (@shikijs/monaco) while loading only the JSON worker and per-language LanguageConfiguration on demand.
  • Binary split tree (web/src/state/split.ts): The main Agents stage renders inside SplitStage, with routes / and /s/$node/$session mounted under a single pathless _stage layout route (web/src/main.tsx) so switching focus between panes never unmounts the tree and the URL simply mirrors the focused leaf. The tree supports up to MAX_PANES = 4 leaves (Sessions or embedded New Session views), clamps split ratios to [0.15, 0.85], enforces a minimum leaf size of 320×260 px, and persists layout in localStorage (trizano:split:v1). Dragging a Session from the sidebar splits or replaces depending on drop zone; shortcuts are mod+alt+d (split right), mod+alt+shift+d (split down), and mod+alt+x (close pane). Duplicate Sessions are deduplicated automatically, and viewports narrower than SPLIT_MIN_STAGE_WIDTH = 900 px or mobile devices collapse cleanly to showing only the focused pane.

Android Client (android/)

The Android client is a native single-module Kotlin + Jetpack Compose app that generates its RPC layer directly from proto/ and uses a foreground service to maintain live sync and notifications without requiring Google Mobile Services (GMS).

Module, Code Generation, and R8 Rules

  • Project layout: Single app module with package name and applicationId top.onemolchuan.code, minSdk = 31 (Android 12 / HarmonyOS 4.3), targetSdk = 34, compileSdk = 36, targeting JVM 17 (android/app/build.gradle.kts).
  • Protobuf + Connect generation: sourceSets.main.proto points directly at ../../proto. The Gradle protobuf plugin generates java (lite), kotlin (lite), and connect-kotlin clients at build time. protoc-gen-connect-kotlin (0.9.0, the final release compatible with Kotlin 2.2) resolves to a single jar path via a dedicated Gradle configuration.
  • Required R8 keep rule (android/app/proguard-rules.pro): Release builds enable isMinifyEnabled = true and isShrinkResources = true. Because connect-kotlin reflects on each message class's static getDefaultInstance() to obtain its parser, the following keep rule is mandatory—without it, release APKs fail to parse every message on the event stream:
    -keepclassmembers class * extends com.google.protobuf.GeneratedMessageLite {
        <fields>;
        public static ** getDefaultInstance();
    }
    

Networking, State Sync, and GMS-Free Background Notifications

  • Networking and Multi-Entry (net/Hub.kt, auth/Account.kt): Uses OkHttp with GoogleJavaLiteProtobufStrategy (binary protobuf encoding). The default 10s per-call timeout in connect-kotlin is disabled (timeoutOracle = { null }) in favor of purpose-specific OkHttpClients: 40s for standard unary calls (covering 25s pairing long-polls), 25s for event streams (paired with the Hub's 10s heartbeat to detect dead streams), 0 ms for WatchPorts and WebSockets (never timing out while idle, with 20s WebSocket pings), and 120s for attachments and file transfers. An interceptor enforces Hello signature verification and public-key pinning (clock skew ≤ 5 min) before sending any ticket to an Entry, persists renewed tickets from X-Trizano-Token automatically, and fails over across Entries using raceEntries (250 ms staggered race) and state/Failover.kt.
  • App-wide Store and GMS-free foreground service: Because many Android phones (such as devices without Google services) lack GMS, the app does not depend on FCM or passkeys (authentication uses an Android Keystore P-256 device key paired with BiometricPrompt). TrizanoApp.kt owns the global Store bound to the active sign-in; after sign-in, MainActivity.kt starts ConnectionService (notify/ConnectionService.kt, FOREGROUND_SERVICE_TYPE_DATA_SYNC, low-priority connection notification channel), which runs store.sync() continuously and observes state transitions. When the app is in the background (!app.foreground.value):
    • When a non-subagent Session's session.attention turns true, it fetches the pending Prompt and posts a high-priority notification (waiting channel). Tool Approvals and plan cards expose inline Allow / Deny action buttons (PromptActionReceiver calling AnswerPrompt, with Allow setting setAuthenticationRequired(true) so the phone must be unlocked); question prompts open the Session on tap.
    • When a running Session finishes or fails, it posts on the done channel. Once any client resolves a pending prompt, the corresponding notification cancels automatically.

Preview Port Forwarding (net/PreviewForwarder.kt)

In PreviewScreen.kt, Android renders remote dev servers in a local WebView backed by net/PreviewForwarder.kt:

  • acquire(nodeId, remotePort) binds a local ServerSocket on 127.0.0.1:<port> with the exact same port number; if already in use by another process or Node, it throws IOException rather than picking a random port, preserving Host, CORS, Cookie, and OAuth callback consistency.
  • Lifecycle is reference-counted via Lease: multiple previews of the same (nodeId, remotePort) share one listener, and releasing the last Lease stops listening and closes connections without needing an extra foreground service.
  • Each accepted local TCP connection opens an independent WebSocket via Hub.dialPreviewSocket to /nodes/{node}/trizano.node.v1.PreviewService/Dial, sends DialRequest{open: {port, annotate: true}} as the first frame, forwards data frames bidirectionally, and propagates close_write half-closes. If the tunnel fails before any response bytes are written to the local socket, it returns an HTTP/1.1 502 Bad Gateway page explaining the error.

Desktop Client (desktop-go/, MyGo)

The desktop app is built with MyGo as a standalone Go module (referencing ../server via replace), cross-compiled with CGO_ENABLED=0, rendering the exact same embedded Web UI inside the OS native WebView (WKWebView on macOS, WebView2 on Windows, WebKitGTK on Linux).

flowchart LR
    WV["MyGo Window & WebView (preloaded secret)"]
    P["Local Proxy 127.0.0.1:47801 (internal/proxy)"]
    UI["Embedded Web UI (server/hub/webui)"]
    CTRL["/_desktop/* Control API (secret verified)"]
    SH["In-Process Standalone Hub (default 47910)"]
    LN["Local Node Process (trizano-h3)"]
    RH["Remote Entry Group (Hello pinning / 250ms race)"]
    FWD["Preview Forwarder 127.0.0.1:port (internal/forward)"]

    WV -->|"Checks Host / Origin"| P
    P --> UI
    P --> CTRL
    P -->|"/trizano.* & /nodes/* (injects ticket)"| SH
    P -->|"/trizano.* & /nodes/* (injects ticket)"| RH
    SH --> LN
    CTRL -->|"/_desktop/forwards/*"| FWD
    FWD -->|"PreviewService.Dial WS"| SH
    FWD -->|"PreviewService.Dial WS"| RH
Loading

Data Directory and Local Loopback Proxy (Port 47801)

  • Data directory (internal/store/paths.go): The app identifier is kept at top.onemolchuan.code.desktop for backward compatibility so existing device_key.pem, hubs.json, standalone-hub/, and standalone-node/ data continues to work across upgrades:
    • macOS: ~/Library/Application Support/top.onemolchuan.code.desktop
    • Windows: %APPDATA%\top.onemolchuan.code.desktop
    • Linux: $XDG_DATA_HOME/top.onemolchuan.code.desktop (default ~/.local/share/top.onemolchuan.code.desktop)
  • Local server and origin guard (internal/proxy/proxy.go): Binds 127.0.0.1:47801 (desktop.PreferredProxyPort) first so the WebView keeps a stable origin for localStorage preferences and split layouts, falling back to 127.0.0.1:0 if occupied. The outermost middleware requireWindow verifies that r.Host exactly matches the listener address and that any Origin header is unique and matches the local origin, returning HTTP 403 otherwise to block DNS rebinding and cross-site access.
  • Three responsibilities:
    1. Static Web assets: Serves remaining paths from server/hub/webui.Handler() (built with -tags=embedweb).
    2. /_desktop/* control API: Generates a random 32-byte hex secret on startup (cmd/trizano/main.go) and injects window.__TRIZANO_DESKTOP_INFO__ via PreloadScript. Every /_desktop/* endpoint enforces requireSecret against X-Trizano-Desktop-Secret using subtle.ConstantTimeCompare. The frontend bridge in web/src/lib/desktop.ts covers mode and Hub switching, standalone lifecycle and auto-approval, device key public key / signing, external links, dock badges, notifications and permissions, window focus, titlebar button themes, and port forwards.
    3. Upstream reverse proxy (internal/proxy/upstream.go): Forwards /trizano.* and /nodes/* (HTTP and WebSocket) to the active Hub, strips browser-side Cookie/Authorization, injects the stored Authorization: Bearer <token>, rewrites Origin to the target Entry's origin, and strips Set-Cookie and X-Trizano-Token from responses (persisting renewed tickets silently without exposing them to page scripts).

Standalone and Remote Modes

  • Standalone mode (internal/standalone/standalone.go): Starts an HTTP/h2c Hub in-process via hub.New without needing a separate trizano-carbon sidecar binary. Hub data lives in <dataDir>/standalone-hub/ and local Node data in <dataDir>/standalone-node/.
    • Listens on 127.0.0.1:47910 (store.DefaultStandalonePort) by default, probing up to 25 consecutive ports on conflict; enabling LAN access (listenAll = true) binds 0.0.0.0:<port>.
    • Before starting, inspects standalone-hub/hub.lock and hub.pid to terminate any stale process by PID and wait for lock release.
    • AutoApprove calls DecidePairing on h.AdminHandler() over an in-memory handlerTransport without spawning a subprocess.
    • Installers staged via desktop-go/scripts/stage-resources.sh bundle only the host trizano-h3 (resources/<os>-<arch>/) plus all 6 cross-platform Node binaries (resources/dist/trizano-h3_<os>_<arch>[.exe]) so the embedded Hub can bootstrap remote SSH/WSL/Windows Nodes. Switching to remote mode (/_desktop/standalone/stop) stops both the Hub and the local Node via node.Stop; quitting the desktop app stops only the Hub.
  • Remote mode: Connects to an external Hub (storing multiple Hub groups in hubs.json, each holding user-configured URLs plus Roster Entries synced via ListEntries). Performs Hello verification and public-key pinning (clock skew ≤ 5 min) before sending any ticket, races multiple Entries with a 250 ms stagger (raceHello) on initial connect or failover, and attaches a rosterTap to EventService/Watch to refresh the Entry list in the background whenever RosterChanged arrives.

Native Shell and Preview Forwarding

  • Single instance and system tray (cmd/trizano/main.go, tray.go): Enforces single-instance execution via mygo.App.RequestSingleInstanceLock(), focusing the existing window on OnSecondInstance. Clicking the window close button hides to the tray (OnClose); exiting stops all preview forwards, the standalone Hub, and the local proxy cleanly. The tray menu provides Open Trizano, live attention/running status (synced with the OS badge and tooltip via /_desktop/badge), Open local Web UI (in standalone mode), Reload UI, and Quit.
  • Native notifications (cmd/trizano/hooks.go, notify_darwin.go, notify_other.go): Maps frontend tag values to notification IDs for deduplicated replacement and focuses the window via OnNotificationClick. macOS queries and requests permission directly against UNUserNotificationCenter via purego/objc; Windows and Linux return granted.
  • Preview port forwarding (internal/forward/forward.go, /_desktop/forwards/*): GET /_desktop/forwards, POST /_desktop/forwards/start, and POST /_desktop/forwards/stop manage local 127.0.0.1:<port> TCP listeners (same-port binding; returns HTTP 409 on conflict without substituting a random port). Each connection dials PreviewService.Dial over WebSocket against the active Hub using server/gen nodev1.DialRequest/DialResponse frames (annotate = true, full close_write half-close, and HTTP 502 error pages).
  • Custom titlebar: Uses mygo.TitleBarHiddenInset on macOS and mygo.TitleBarHidden (TitleBarHeight: 36) on Windows and Linux. The preload script injects CSS marking [data-drag-region] with --app-region: drag and interactive elements with no-drag (making /_desktop/drag a 200 no-op under MyGo); the Web UI reads --mygo-titlebar-inset-left/right for traffic-light/caption padding and calls /_desktop/window-theme (win.SetWindowButtonsTheme) so native window controls follow light/dark theme changes.

Clone this wiki locally