Repository navigation
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.
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.
-
Upstream baseline: Forked from t3code
v0.0.22, retainingweb/src/components/ui/(unstyled@base-ui/reactprimitives and shadcn-style wrappers) and the theme CSS tokens / layout variables inweb/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/xterm6, andmonaco-editor+shiki/@shikijs/monaco. -
Path alias and build output:
web/tsconfig.jsonmaps~/*toweb/src/*. During development,web/vite.config.tsserves on127.0.0.1:5733and proxies/trizano.hub.v1.and/nodes/(including WebSockets) toTRIZANO_HUB(defaulthttp://127.0.0.1:47900).vite buildwrites artifacts toserver/hub/webui/dist, which both the Hub (-tags embedweb) and desktop app (reusingserver/hub/webui) embed.server/hub/webui/webui.goserves/assets/*withCache-Control: private, max-age=31536000, immutable, and returns a short development notice when built withoutembedweb.
web/src/rpc/client.ts creates two Connect transports:
-
Hub client (
hub): Targetswindow.location.originand bindsAuthService,DeviceService,NodeService,EventService,OrchestrationService, andUsageService. -
Node client (
nodeApi(nodeId)): Cached per Node ID, creating a Connect transport withbaseUrlset to${window.location.origin}/nodes/${nodeId}and bindingAgentService,WorkspaceService,SessionService,TerminalService,PortService,BrowserService,SystemService,FileService,GitService,ReviewService, andUsageService. -
Unified auth-expiry interceptor: Every transport shares
signOutWhenRefused. Whether a unary call fails or a server-stream throwsCode.Unauthenticatedmid-stream (for example, when a device is revoked), it clearsuseAuth'smestate 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 |

-
Standalone IDE window and lazy Monaco: Routes
/ideand/ide/$node/$workspacerender the full-windowIdeWindow(hiding the main app sidebar; mobile viewports prompt the user to switch to a desktop screen instead of loading the editor).Workbench.tsxuses 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 loadsEditorView.tsxviaReact.lazy, whilevite.config.tssplits Monaco into a dedicatedmonacochunk viarolldownOptions.output.codeSplitting.monaco-core.tsimports editing features selectively and skips built-in Monarch grammars, delegating syntax highlighting inmonaco.tsto the shared Shiki instance (@shikijs/monaco) while loading only the JSON worker and per-languageLanguageConfigurationon demand. -
Binary split tree (
web/src/state/split.ts): The main Agents stage renders insideSplitStage, with routes/and/s/$node/$sessionmounted under a single pathless_stagelayout 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 toMAX_PANES = 4leaves (Sessions or embedded New Session views), clamps split ratios to[0.15, 0.85], enforces a minimum leaf size of320×260px, and persists layout inlocalStorage(trizano:split:v1). Dragging a Session from the sidebar splits or replaces depending on drop zone; shortcuts aremod+alt+d(split right),mod+alt+shift+d(split down), andmod+alt+x(close pane). Duplicate Sessions are deduplicated automatically, and viewports narrower thanSPLIT_MIN_STAGE_WIDTH = 900px or mobile devices collapse cleanly to showing only the focused pane.
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).
-
Project layout: Single
appmodule with package name andapplicationIdtop.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.protopoints directly at../../proto. The Gradle protobuf plugin generatesjava(lite),kotlin(lite), andconnect-kotlinclients 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 enableisMinifyEnabled = trueandisShrinkResources = true. Becauseconnect-kotlinreflects on each message class's staticgetDefaultInstance()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 and Multi-Entry (
net/Hub.kt,auth/Account.kt): Uses OkHttp withGoogleJavaLiteProtobufStrategy(binary protobuf encoding). The default 10s per-call timeout inconnect-kotlinis 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 forWatchPortsand WebSockets (never timing out while idle, with 20s WebSocket pings), and 120s for attachments and file transfers. An interceptor enforcesHellosignature verification and public-key pinning (clock skew ≤ 5 min) before sending any ticket to an Entry, persists renewed tickets fromX-Trizano-Tokenautomatically, and fails over across Entries usingraceEntries(250 ms staggered race) andstate/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.ktowns the globalStorebound to the active sign-in; after sign-in,MainActivity.ktstartsConnectionService(notify/ConnectionService.kt,FOREGROUND_SERVICE_TYPE_DATA_SYNC, low-priorityconnectionnotification channel), which runsstore.sync()continuously and observes state transitions. When the app is in the background (!app.foreground.value):- When a non-subagent Session's
session.attentionturnstrue, it fetches the pendingPromptand posts a high-priority notification (waitingchannel). Tool Approvals and plan cards expose inline Allow / Deny action buttons (PromptActionReceivercallingAnswerPrompt, with Allow settingsetAuthenticationRequired(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
donechannel. Once any client resolves a pending prompt, the corresponding notification cancels automatically.
- When a non-subagent Session's
In PreviewScreen.kt, Android renders remote dev servers in a local WebView backed by net/PreviewForwarder.kt:
-
acquire(nodeId, remotePort)binds a localServerSocketon127.0.0.1:<port>with the exact same port number; if already in use by another process or Node, it throwsIOExceptionrather than picking a random port, preservingHost, 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 lastLeasestops listening and closes connections without needing an extra foreground service. - Each accepted local TCP connection opens an independent WebSocket via
Hub.dialPreviewSocketto/nodes/{node}/trizano.node.v1.PreviewService/Dial, sendsDialRequest{open: {port, annotate: true}}as the first frame, forwardsdataframes bidirectionally, and propagatesclose_writehalf-closes. If the tunnel fails before any response bytes are written to the local socket, it returns anHTTP/1.1 502 Bad Gatewaypage explaining the error.
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
-
Data directory (
internal/store/paths.go): The app identifier is kept attop.onemolchuan.code.desktopfor backward compatibility so existingdevice_key.pem,hubs.json,standalone-hub/, andstandalone-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)
- macOS:
-
Local server and origin guard (
internal/proxy/proxy.go): Binds127.0.0.1:47801(desktop.PreferredProxyPort) first so the WebView keeps a stable origin forlocalStoragepreferences and split layouts, falling back to127.0.0.1:0if occupied. The outermost middlewarerequireWindowverifies thatr.Hostexactly matches the listener address and that anyOriginheader is unique and matches the local origin, returning HTTP 403 otherwise to block DNS rebinding and cross-site access. -
Three responsibilities:
-
Static Web assets: Serves remaining paths from
server/hub/webui.Handler()(built with-tags=embedweb). -
/_desktop/*control API: Generates a random 32-byte hex secret on startup (cmd/trizano/main.go) and injectswindow.__TRIZANO_DESKTOP_INFO__viaPreloadScript. Every/_desktop/*endpoint enforcesrequireSecretagainstX-Trizano-Desktop-Secretusingsubtle.ConstantTimeCompare. The frontend bridge inweb/src/lib/desktop.tscovers 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. -
Upstream reverse proxy (
internal/proxy/upstream.go): Forwards/trizano.*and/nodes/*(HTTP and WebSocket) to the active Hub, strips browser-sideCookie/Authorization, injects the storedAuthorization: Bearer <token>, rewritesOriginto the target Entry's origin, and stripsSet-CookieandX-Trizano-Tokenfrom responses (persisting renewed tickets silently without exposing them to page scripts).
-
Static Web assets: Serves remaining paths from
-
Standalone mode (
internal/standalone/standalone.go): Starts an HTTP/h2c Hub in-process viahub.Newwithout needing a separatetrizano-carbonsidecar 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) binds0.0.0.0:<port>. - Before starting, inspects
standalone-hub/hub.lockandhub.pidto terminate any stale process by PID and wait for lock release. -
AutoApprovecallsDecidePairingonh.AdminHandler()over an in-memoryhandlerTransportwithout spawning a subprocess. - Installers staged via
desktop-go/scripts/stage-resources.shbundle only the hosttrizano-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 vianode.Stop; quitting the desktop app stops only the Hub.
- Listens on
-
Remote mode: Connects to an external Hub (storing multiple Hub groups in
hubs.json, each holding user-configured URLs plus Roster Entries synced viaListEntries). PerformsHelloverification 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 arosterTaptoEventService/Watchto refresh the Entry list in the background wheneverRosterChangedarrives.
-
Single instance and system tray (
cmd/trizano/main.go,tray.go): Enforces single-instance execution viamygo.App.RequestSingleInstanceLock(), focusing the existing window onOnSecondInstance. 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 frontendtagvalues to notification IDs for deduplicated replacement and focuses the window viaOnNotificationClick. macOS queries and requests permission directly againstUNUserNotificationCenterviapurego/objc; Windows and Linux returngranted. -
Preview port forwarding (
internal/forward/forward.go,/_desktop/forwards/*):GET /_desktop/forwards,POST /_desktop/forwards/start, andPOST /_desktop/forwards/stopmanage local127.0.0.1:<port>TCP listeners (same-port binding; returns HTTP 409 on conflict without substituting a random port). Each connection dialsPreviewService.Dialover WebSocket against the active Hub usingserver/gennodev1.DialRequest/DialResponseframes (annotate = true, fullclose_writehalf-close, and HTTP 502 error pages). -
Custom titlebar: Uses
mygo.TitleBarHiddenInseton macOS andmygo.TitleBarHidden(TitleBarHeight: 36) on Windows and Linux. The preload script injects CSS marking[data-drag-region]with--app-region: dragand interactive elements withno-drag(making/_desktop/draga 200 no-op under MyGo); the Web UI reads--mygo-titlebar-inset-left/rightfor traffic-light/caption padding and calls/_desktop/window-theme(win.SetWindowButtonsTheme) so native window controls follow light/dark theme changes.
English
Getting Started
Deployment & Networking
Architecture & Nodes
Agents
Clients & Development
Project & Community
中文文档
新手指引
部署与网络
架构与节点
智能体
客户端与开发
项目与社区