@robota-sdk/agent-ui-web 0.0.0-stage → 3.0.0-beta.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +409 -0
  2. package/LICENSE +661 -0
  3. package/README.md +19 -2
  4. package/dist/browser/index.d.ts +715 -0
  5. package/dist/browser/index.d.ts.map +1 -0
  6. package/dist/browser/index.js +7923 -0
  7. package/dist/browser/index.js.map +1 -0
  8. package/dist/node/index.cjs +7973 -0
  9. package/dist/node/index.d.cts +715 -0
  10. package/dist/node/index.d.cts.map +1 -0
  11. package/dist/node/index.d.ts +715 -0
  12. package/dist/node/index.d.ts.map +1 -0
  13. package/dist/node/index.js +7923 -0
  14. package/dist/node/index.js.map +1 -0
  15. package/docs/README.md +62 -0
  16. package/docs/SPEC.md +124 -0
  17. package/package.json +99 -3
  18. package/src/client/runtime-host.ts +84 -0
  19. package/src/client/ws-session-client.ts +131 -0
  20. package/src/clipboard.ts +81 -0
  21. package/src/components/AgentActivityPanel.tsx +371 -0
  22. package/src/components/AgentSwitcherSheet.tsx +93 -0
  23. package/src/components/Brand.tsx +33 -0
  24. package/src/components/Composer.tsx +685 -0
  25. package/src/components/ConversationView.tsx +772 -0
  26. package/src/components/Dialog.tsx +230 -0
  27. package/src/components/DiffLines.tsx +81 -0
  28. package/src/components/ExecutionDetailSheet.tsx +142 -0
  29. package/src/components/HelpSheet.tsx +104 -0
  30. package/src/components/PermissionPrompt.tsx +661 -0
  31. package/src/components/PersonalUsageDashboard.tsx +39 -0
  32. package/src/components/PersonalUsageDashboardDetails.tsx +368 -0
  33. package/src/components/PersonalUsageDashboardSections.tsx +250 -0
  34. package/src/components/PopupMenu.tsx +166 -0
  35. package/src/components/ProjectPanel.tsx +268 -0
  36. package/src/components/SessionMonitor.tsx +180 -0
  37. package/src/components/SessionSidebar.tsx +429 -0
  38. package/src/components/SessionSurface.tsx +455 -0
  39. package/src/components/SessionSurfaceChrome.tsx +316 -0
  40. package/src/components/SettingsFields.tsx +159 -0
  41. package/src/components/SettingsGeneralSection.tsx +49 -0
  42. package/src/components/SettingsMcpSection.tsx +157 -0
  43. package/src/components/SettingsPermissionsSection.tsx +137 -0
  44. package/src/components/SettingsPluginsSection.tsx +165 -0
  45. package/src/components/SettingsProvidersSection.tsx +211 -0
  46. package/src/components/SettingsScreen.tsx +340 -0
  47. package/src/components/StatusControls.tsx +294 -0
  48. package/src/components/composer-attachments.ts +246 -0
  49. package/src/components/personal-usage-dashboard-types.ts +26 -0
  50. package/src/driver-labels.ts +88 -0
  51. package/src/execution-entry-status.ts +55 -0
  52. package/src/goal-view.ts +19 -0
  53. package/src/hooks/command-menu.ts +65 -0
  54. package/src/hooks/excluded-commands.ts +52 -0
  55. package/src/hooks/prompt-state.ts +83 -0
  56. package/src/hooks/server-message-handling.ts +92 -0
  57. package/src/hooks/session-client-types.ts +329 -0
  58. package/src/hooks/ui-intent-state.ts +74 -0
  59. package/src/hooks/use-agent-switcher-state.ts +125 -0
  60. package/src/hooks/use-execution-detail.ts +118 -0
  61. package/src/hooks/use-media-query.ts +27 -0
  62. package/src/hooks/use-model-list.ts +45 -0
  63. package/src/hooks/use-personal-usage.ts +138 -0
  64. package/src/hooks/use-project-panel.ts +117 -0
  65. package/src/hooks/use-schedules-state.ts +92 -0
  66. package/src/hooks/use-session-directory.ts +202 -0
  67. package/src/hooks/use-settings-state.ts +115 -0
  68. package/src/hooks/useSessionClient.ts +991 -0
  69. package/src/index.ts +66 -0
  70. package/src/product-identity.tsx +26 -0
  71. package/src/schedule-view.ts +92 -0
  72. package/src/styles/surface.css +231 -0
  73. package/src/styles/surface.css.d.mts +1 -0
  74. package/src/styles/theme.css +38 -0
  75. package/src/styles/theme.css.d.mts +1 -0
package/docs/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # @robota-sdk/agent-ui-web
2
+
3
+ The **GUI presentation layer** for an agent session — the graphical analog of `@robota-sdk/agent-ui-terminal`.
4
+ It reconstructs conversation state from the transport-neutral `TServerMessage` stream and renders it as React
5
+ components. Its public `/client` entry supplies the browser-safe reducer, WebSocket client, session shell
6
+ and runtime-host contract for a consumer-owned renderer. The same components serve the repository's GUI
7
+ web app and browser-remote surface.
8
+
9
+ ## What it owns
10
+
11
+ - `useSessionClient(makeClient)` — the transport-neutral session reducer (generic over the status type).
12
+ - `useWsSession(url)` + `createWsSessionClient` — the localhost WebSocket binding.
13
+ - `resolveClientRuntimeHost(environment)` — a browser endpoint resolver or a narrow desktop bridge
14
+ adapter. The desktop bridge owns trust, endpoint validation and runtime lifecycle; a renderer asks
15
+ `trustQuestion` before `getEndpoint` and calls `signalReady` after connection.
16
+ - Prompt state: `applyPromptEvent`, `permissionResponse`, `askResponse`.
17
+ - UI-intent state: `guiScreenForUiIntent` (the GUI screen a command's UI intent opens, if any) and
18
+ `describeUiIntentForGui` (the explicit "not available on this surface" line otherwise).
19
+ - Components: `SessionSurface`, `CenteredChrome`, `ConversationView`, `AgentActivityPanel`,
20
+ `PermissionPrompt`, `SessionSidebar` (the host's sessions; switch or start one), `SessionMonitor` (a
21
+ self-contained session page for a WebSocket URL), and `PersonalUsageDashboard` (7- and 30-day usage).
22
+ - Brand marks: `ProductMark`, `ProductWordmark` — render them inside a `agent-ui` scope.
23
+ - `styles/surface.css` — the design scoped to `.agent-ui` (bundled Pretendard, light and dark tokens, Tailwind
24
+ token map, base layers); import it into a host app's Tailwind entry to embed the surface.
25
+ - `styles/theme.css` — `surface.css` plus what a page that is only the surface owns (height, background,
26
+ scrollbars); that page puts `agent-ui` on its `<html>`.
27
+
28
+ ## Using it
29
+
30
+ ```tsx
31
+ import { useWsSession, SessionSurface } from '@robota-sdk/agent-ui-web/client';
32
+
33
+ export function App({ url }: { url: string }) {
34
+ const state = useWsSession(url);
35
+ return <SessionSurface state={state} surface="app" />;
36
+ }
37
+ ```
38
+
39
+ The components author Tailwind utility classes and ship **no compiled CSS** — the consumer owns the Tailwind
40
+ entry and sources this package's `src`:
41
+
42
+ ```css
43
+ /* app entry css */
44
+ @import 'tailwindcss';
45
+ @import '@robota-sdk/agent-ui-web/styles/theme.css';
46
+ @source '../../node_modules/@robota-sdk/agent-ui-web/src';
47
+ @source './';
48
+ ```
49
+
50
+ A different transport supplies its own `makeClient` (a `TMakeSessionClient<TStatus>`) and, if it adds
51
+ connection states, instantiates `useSessionClient<ItsStatus>` — see `useRtcSession` in `@robota-sdk/agent-transport-webrtc-web`.
52
+
53
+ See [SPEC.md](./SPEC.md) for the full contract.
54
+
55
+ The source repository's Cedar renderer fixture shows a consumer-owned toolbar calling a custom
56
+ command, desktop trust admission, session restoration and reconnect. Its local-pack
57
+ build is prerelease evidence; a clean registry-installed build is required after publication.
58
+
59
+ The package tarball includes source styles, declarations and its AGPL license. React is a peer dependency;
60
+ the consumer supplies React, React DOM, Tailwind v4 and a bundler. Third-party runtime dependencies are
61
+ declared in `package.json`; a distributable renderer must include their notices and licenses in its own
62
+ artifact. The package does not include the private GUI web app or Electron shell.
package/docs/SPEC.md ADDED
@@ -0,0 +1,124 @@
1
+ # SPEC.md — @robota-sdk/agent-ui-web
2
+
3
+ ## Transport Admission
4
+
5
+ transport-admission: none — a presentation layer. It renders a server-message stream that some
6
+ other transport has already admitted a peer onto, and opens no socket of its own.
7
+
8
+ ## Purpose
9
+
10
+ The GUI presentation layer for a running agent session — the graphical analog of the terminal
11
+ presentation package. It reconstructs conversation state from the transport-neutral server-message
12
+ stream and renders it as React components, and it ships the session shell (title/status bar,
13
+ conversation column, background-activity rail, and a composer with the pending question docked above
14
+ it). It is consumed by the GUI web app — which the desktop app loads and the CLI serves — and by the
15
+ browser-remote surface.
16
+
17
+ This package sits in the transport/presentation layer. It is a pure UI + wire-reducer library — it
18
+ does not own session lifecycle, conversation history, or agent runtime state.
19
+
20
+ ## Contract and guarantees
21
+
22
+ - The session reducer is generic over the connection-status type, so a transport can widen the
23
+ status union (e.g. to add pairing/failure states) without this package depending on that
24
+ transport.
25
+ - Every server-message wire variant is assigned an explicit disposition — a specialized reducer
26
+ path, transport lifecycle handling, or an explicit "intentionally not rendered" marker. An
27
+ unrecognized or not-yet-supported message never falls through silently.
28
+ - The conversation carries what the CLI's transcript carries: a typed command's outcome and a
29
+ finished turn's tool calls sit in it where they happened, and never push the composer out of view —
30
+ the same whether they streamed in live or were rebuilt from a reload, reconnect, or session resume's
31
+ history replay, never falling back to bare text once a tool call is gone from what a live stream
32
+ would have shown. A change made through a status control instead confirms itself through the
33
+ control's own label — never a conversation entry — with a failed change surfaced as a toast instead.
34
+ Session and protocol failures are also toasts, beside the conversation rather than in it.
35
+ - A tool call's diff or output is server-computed and shown on demand, preserving its observation
36
+ types, call identity and success or denial/failure through live delivery and replay. Resource references remain inert because
37
+ displaying a contributor's URI grants no read authority; unsupported media is explained rather than
38
+ silently discarded. Output is never recomputed here or buried behind a truncated path or argument; an internal signal tool never renders as a call,
39
+ and a projected `/command` tool shows the command it ran, not the provider-facing tool name.
40
+ - A UI-intent opens its GUI screen when there is one — the session picker is the session sidebar
41
+ (unless the host cannot list sessions), settings and the plugin manager both open the Settings
42
+ modal (the plugin manager on its Plugins section), and the agent switcher is a sheet listing the
43
+ session's agent definitions with the current one checked. A command with no GUI path at all (its
44
+ presentation belongs to a terminal, or the product has deliberately left it out — see
45
+ `packages/agent-gui-web/docs/SPEC.md`) never reaches the session from this surface in the first
46
+ place: it is caught on the way out and answered with its own plain sentence naming what to use
47
+ instead. Any other UI-intent this surface simply has no screen for yet answers the same way, in its
48
+ own words — never the generic "not available on this surface" line, and never a silent no-op — in
49
+ place of the command's own reply when this surface's command awaits one, at once otherwise; an
50
+ intent kind not yet known when this package was written still gets an explicit, honest line.
51
+ - The session sidebar lists the host's sessions by a stable title — never the latest reply, which
52
+ changes every turn — and never loses one silently: a record unreadable and belonging to this
53
+ workspace is folded into one plain line rather than shown as a row; a record belonging to another
54
+ workspace, or whose workspace cannot be told, is not this surface's business and is left off the
55
+ list entirely. A switch replaces everything the surface shows with what the new session holds; a
56
+ refused switch shows the host's reason. A row can be renamed or deleted from the list itself,
57
+ without switching to it first; a refusal states why.
58
+ - The agent switcher's roster and current selection are a typed read (`get-agent-definitions`), but
59
+ choosing a row is not a dedicated write: it sends `/agent <name>` through the same `command` path
60
+ typing it would, and the sheet shows that command's own reply as a plain line — never a
61
+ conversation card, unlike every other command result this reducer renders.
62
+ - The Agents panel's Scheduled group and Goal row are additive to the execution-workspace rail:
63
+ a schedule or a goal alone (no running background task or loop) still opens the rail, and a
64
+ schedule's Pause/Resume and Delete, and a goal's Cancel, run the same command/control paths their
65
+ slash commands already use — the panel adds no write this package did not already expose.
66
+ - The title bar and the page title both name the workspace folder the session works in, once the
67
+ host has said one; the desktop window follows the page title.
68
+ - A pending permission or ask prompt is visible whatever view is open, because a gated turn waits
69
+ on it. It never takes focus from a field the person is typing in, and its keys answer it only once
70
+ it has that focus; a click answers at once.
71
+ - Nothing typed is lost to a lost connection: while the transport is not `connected`, the composer
72
+ keeps its draft and refuses to submit it, and a banner above the conversation — never a full-screen
73
+ replacement — says so: retrying while attempts continue, and once they give up, either the
74
+ host-supplied reconnect action or how to reopen the page.
75
+ - A session-rename or history-clear broadcast from any other surface is folded into this reducer's
76
+ state, so co-driving surfaces stay in sync.
77
+ - The personal usage dashboard is opt-in per surface (browser/remote consumers stay opted out by
78
+ default) and correlates its own requests, keeping latest-request-wins semantics on responses.
79
+ - A background-activity entry opens a detail sheet (status, what it was asked, its paginated
80
+ transcript, its result) on click — except the main-thread entry, which instead returns to the
81
+ conversation already shown beside it. A stoppable entry's Stop is routed by whether the entry
82
+ carries a loop id, never guessed from its name or task kind: a `/loop`-managed entry (fixed or
83
+ self-paced) sends `/loop stop <id>`, because a self-paced loop's own background-task
84
+ representation, when it has one, is only its disposable wake timer — cancelling that would leave
85
+ the loop itself running. Every other entry sends `cancel-background-task`.
86
+ - The Project panel (git status, one file's diff, project memory) correlates its own requests the
87
+ same way, and every file status it shows is a plain word, never a raw git XY code (#3277 "usable by
88
+ anyone"); a workspace that is not a git repository, or a diff whose path the host refused, is one
89
+ plain sentence, never left as a stuck loading state.
90
+ - A session error finalizes any partial streamed text and clears thinking/running-tool state
91
+ before the next turn begins.
92
+ - Malformed server frames are surfaced through the client's callback path and never thrown inside
93
+ the socket handler.
94
+ - The package ships no compiled CSS — it authors Tailwind utility classes as source, and the
95
+ consumer owns the Tailwind entry point that compiles them. Its design applies only inside the
96
+ `agent-ui` scope that each of its root components opens, so a host with tokens of its own under the
97
+ same names can embed the surface without either overriding the other.
98
+ - Its public browser entry exposes a narrow runtime-host contract: a native host owns trust and
99
+ endpoint authority, while a renderer can ask for trust before connecting, observe lifecycle
100
+ changes, and offer reconnect without importing the native implementation.
101
+
102
+ ## Non-goals / boundaries
103
+
104
+ - Does not own the wire protocol framing (message types) — that belongs to the transport package.
105
+ - Does not own the transport-facing contract types (interaction/event/workspace) — those belong to
106
+ the transport-interface package.
107
+ - Does not own session/runtime contracts or agent-core types, and has no dependency on the
108
+ agent framework, session, or core packages.
109
+ - Does not own the CLI sidecar server.
110
+ - Does not own the WebRTC remote peer or pairing flow — that is a separate package that consumes
111
+ this package's reducer and components and widens the status union.
112
+ - Does not own the Electron shell or sidecar process supervision — that is the desktop app.
113
+ - Is not re-exported through a sibling product package; consumers import it directly.
114
+
115
+ ## Design decisions
116
+
117
+ - The reducer is generic over its status type rather than importing a widened status union from
118
+ the WebRTC package, because importing that union would create a package cycle.
119
+ - The session shell component holds no session/transport logic of its own — it only forwards user
120
+ intent through the reducer's send/answer handles — so a new GUI surface can reuse it purely by
121
+ supplying its own client factory.
122
+ - There is deliberately no built-in screen for every UI-intent kind; unhandled kinds get an
123
+ explicit notice instead of a screen, so a future surface can add a real screen incrementally
124
+ without ever risking a silent drop in the meantime.
package/package.json CHANGED
@@ -1,6 +1,102 @@
1
1
  {
2
2
  "name": "@robota-sdk/agent-ui-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "3.0.0-beta.94",
4
+ "description": "Browser-safe React session presentation, wire reducer, WebSocket client and runtime-host contract for consumer-owned agent renderers.",
5
+ "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
+ "type": "module",
7
+ "main": "dist/node/index.js",
8
+ "types": "dist/node/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "source": "./src/index.ts",
12
+ "import": {
13
+ "types": "./dist/node/index.d.ts",
14
+ "default": "./dist/node/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/node/index.d.cts",
18
+ "default": "./dist/node/index.cjs"
19
+ },
20
+ "default": "./dist/node/index.js"
21
+ },
22
+ "./client": {
23
+ "source": "./src/index.ts",
24
+ "import": {
25
+ "types": "./dist/browser/index.d.ts",
26
+ "default": "./dist/browser/index.js"
27
+ },
28
+ "default": "./dist/browser/index.js"
29
+ },
30
+ "./styles/theme.css": {
31
+ "types": "./src/styles/theme.css.d.mts",
32
+ "browser": "./src/styles/theme.css",
33
+ "import": "./src/styles/theme.css"
34
+ },
35
+ "./styles/surface.css": {
36
+ "types": "./src/styles/surface.css.d.mts",
37
+ "browser": "./src/styles/surface.css",
38
+ "import": "./src/styles/surface.css"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "engines": {
43
+ "node": ">=22.12.0"
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "src",
48
+ "!src/**/__tests__/**",
49
+ "!src/testing/**",
50
+ "README.md",
51
+ "docs/README.md",
52
+ "docs/SPEC.md",
53
+ "CHANGELOG.md",
54
+ "LICENSE"
55
+ ],
56
+ "dependencies": {
57
+ "lucide-react": "^1.26.0",
58
+ "pretendard": "^1.3.9",
59
+ "react-markdown": "^10.1.0",
60
+ "remark-gfm": "^4.0.1",
61
+ "@robota-sdk/agent-interface-command": "3.0.0-beta.94",
62
+ "@robota-sdk/agent-interface-session": "3.0.0-beta.94",
63
+ "@robota-sdk/agent-interface-transport": "3.0.0-beta.94",
64
+ "@robota-sdk/agent-interface-execution": "3.0.0-beta.94",
65
+ "@robota-sdk/agent-transport": "3.0.0-beta.94"
66
+ },
67
+ "peerDependencies": {
68
+ "react": ">=18"
69
+ },
70
+ "devDependencies": {
71
+ "@testing-library/react": "^16.1.0",
72
+ "@types/react": "^19.2.17",
73
+ "@types/react-dom": "^19.2.3",
74
+ "jsdom": "^25.0.1",
75
+ "react": "19.2.8",
76
+ "react-dom": "19.2.8",
77
+ "rimraf": "^5.0.0",
78
+ "tsdown": "^0.22.14",
79
+ "typescript": "^6.0.3",
80
+ "vitest": "^3.2.6"
81
+ },
82
+ "volta": {
83
+ "extends": "../../package.json"
84
+ },
85
+ "repository": {
86
+ "type": "git",
87
+ "url": "https://github.com/woojubb/robota"
88
+ },
89
+ "bugs": {
90
+ "url": "https://github.com/woojubb/robota/issues"
91
+ },
92
+ "homepage": "https://robota.io/",
93
+ "scripts": {
94
+ "build": "rimraf dist && tsdown",
95
+ "build:js": "pnpm run build",
96
+ "build:types": "pnpm run build",
97
+ "typecheck": "tsgo --noEmit",
98
+ "test": "vitest run --passWithNoTests",
99
+ "test:coverage": "vitest run --coverage --passWithNoTests",
100
+ "clean": "rimraf dist"
101
+ }
6
102
  }
@@ -0,0 +1,84 @@
1
+ import type { IPickedFile } from '../components/Composer.js';
2
+
3
+ /** Runtime events delivered by a native host. Browser pages have no process to supervise. */
4
+ export type TClientRuntimeState = 'starting' | 'ready' | 'fatal';
5
+
6
+ /** A folder decision must be shown before requesting the runtime endpoint. */
7
+ export interface IClientTrustQuestion {
8
+ readonly folder: string;
9
+ readonly loads: readonly string[];
10
+ }
11
+
12
+ export type TClientTrustChoice = 'trust' | 'restricted' | 'quit';
13
+
14
+ /**
15
+ * Browser-safe shape for a narrow native preload bridge. The native host implements validation,
16
+ * trust, process lifecycle, and endpoint ownership; the renderer receives only these operations.
17
+ */
18
+ export interface IClientRuntimeBridge {
19
+ readonly runtimeMode?: 'local' | 'remote';
20
+ getEndpoint(): Promise<string | null>;
21
+ signalReady(): void;
22
+ onState(listener: (state: TClientRuntimeState, detail?: string) => void): () => void;
23
+ restartRuntime(): Promise<void>;
24
+ trustQuestion(): Promise<IClientTrustQuestion | null>;
25
+ answerTrust(choice: TClientTrustChoice): Promise<{ error?: string }>;
26
+ pickFiles?(): Promise<readonly IPickedFile[]>;
27
+ getPathForFile?(file: File): string;
28
+ onOpenSettings?(listener: () => void): () => void;
29
+ openPath?(path: string): Promise<{ error?: string }>;
30
+ }
31
+
32
+ /** A React renderer can use this contract with either a desktop bridge or a browser endpoint. */
33
+ export interface IClientRuntimeHost {
34
+ readonly kind: 'desktop' | 'browser';
35
+ getEndpoint(): Promise<string | null>;
36
+ signalReady(): void;
37
+ onState(listener: (state: TClientRuntimeState, detail?: string) => void): () => void;
38
+ readonly restartRuntime?: () => Promise<void>;
39
+ readonly trustQuestion?: () => Promise<IClientTrustQuestion | null>;
40
+ readonly answerTrust?: (choice: TClientTrustChoice) => Promise<{ error?: string }>;
41
+ readonly pickFiles?: () => Promise<readonly IPickedFile[]>;
42
+ readonly getPathForFile?: (file: File) => string;
43
+ onOpenSettings(listener: () => void): () => void;
44
+ readonly openMemoryInEditor?: (path: string) => void;
45
+ }
46
+
47
+ export interface IClientRuntimeEnvironment {
48
+ readonly bridge?: IClientRuntimeBridge;
49
+ readonly document: Pick<Document, 'querySelector'>;
50
+ readonly location: Pick<Location, 'search' | 'host' | 'protocol'>;
51
+ }
52
+
53
+ /** Resolve host capabilities without importing Electron or a Node CLI into the browser graph. */
54
+ export function resolveClientRuntimeHost(environment: IClientRuntimeEnvironment): IClientRuntimeHost {
55
+ const { bridge } = environment;
56
+ if (bridge) {
57
+ const local = bridge.runtimeMode !== 'remote';
58
+ return {
59
+ kind: 'desktop',
60
+ getEndpoint: () => bridge.getEndpoint(),
61
+ signalReady: () => bridge.signalReady(),
62
+ onState: (listener) => bridge.onState(listener),
63
+ restartRuntime: () => bridge.restartRuntime(),
64
+ trustQuestion: local ? () => bridge.trustQuestion() : undefined,
65
+ answerTrust: local ? (choice) => bridge.answerTrust(choice) : undefined,
66
+ pickFiles: local && bridge.pickFiles ? () => bridge.pickFiles!() : undefined,
67
+ getPathForFile: local && bridge.getPathForFile ? (file) => bridge.getPathForFile!(file) : undefined,
68
+ onOpenSettings: (listener) => bridge.onOpenSettings?.(listener) ?? (() => {}),
69
+ openMemoryInEditor: local && bridge.openPath ? (path) => { void bridge.openPath!(path); } : undefined,
70
+ };
71
+ }
72
+
73
+ const injected = environment.document.querySelector('meta[name="ws-url"]')?.getAttribute('content')?.trim();
74
+ const query = new URLSearchParams(environment.location.search).get('ws')?.trim();
75
+ const protocol = environment.location.protocol === 'https:' ? 'wss:' : 'ws:';
76
+ const endpoint = injected || query || `${protocol}//${environment.location.host}`;
77
+ return {
78
+ kind: 'browser',
79
+ getEndpoint: async () => endpoint,
80
+ signalReady: () => {},
81
+ onState: () => () => {},
82
+ onOpenSettings: () => () => {},
83
+ };
84
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Browser WebSocket client for a running agent-cli sidecar session.
3
+ * Wraps the native WebSocket API with typed agent-transport-ws messages.
4
+ */
5
+
6
+ import { decodeFrame, decodeServerMessage } from '@robota-sdk/agent-transport/client';
7
+
8
+ import type { TServerMessage, TClientMessage } from '@robota-sdk/agent-transport';
9
+
10
+ export type { TServerMessage, TClientMessage };
11
+
12
+ export type TConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error';
13
+
14
+ export interface IWsSessionClientCallbacks {
15
+ onMessage: (msg: TServerMessage) => void;
16
+ onStatusChange: (status: TConnectionStatus) => void;
17
+ /**
18
+ * The connection is gone for good: the retries ran out without reaching the server again. The status
19
+ * stays `disconnected`; this is what tells a host the runtime is not coming back by itself.
20
+ */
21
+ onGiveUp?: () => void;
22
+ }
23
+
24
+ export interface IWsSessionClient {
25
+ connect: () => void;
26
+ disconnect: () => void;
27
+ send: (msg: TClientMessage) => void;
28
+ status: () => TConnectionStatus;
29
+ }
30
+
31
+ const RECONNECT_DELAY_MS = 2000;
32
+ const MAX_RECONNECT_ATTEMPTS = 10;
33
+
34
+ export function createWsSessionClient(
35
+ url: string,
36
+ callbacks: IWsSessionClientCallbacks,
37
+ ): IWsSessionClient {
38
+ let ws: WebSocket | null = null;
39
+ let currentStatus: TConnectionStatus = 'disconnected';
40
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
41
+ let reconnectAttempts = 0;
42
+ let intentionalDisconnect = false;
43
+
44
+ function setStatus(s: TConnectionStatus): void {
45
+ currentStatus = s;
46
+ callbacks.onStatusChange(s);
47
+ }
48
+
49
+ function scheduleReconnect(): void {
50
+ if (intentionalDisconnect) return;
51
+ if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
52
+ callbacks.onGiveUp?.();
53
+ return;
54
+ }
55
+ reconnectTimer = setTimeout(() => {
56
+ reconnectAttempts++;
57
+ doConnect();
58
+ }, RECONNECT_DELAY_MS);
59
+ }
60
+
61
+ function doConnect(): void {
62
+ setStatus('connecting');
63
+ ws = new WebSocket(url);
64
+
65
+ ws.onopen = (): void => {
66
+ reconnectAttempts = 0;
67
+ setStatus('connected');
68
+ // Request full message history on connect
69
+ send({ type: 'get-messages' });
70
+ };
71
+
72
+ ws.onmessage = (event: MessageEvent): void => {
73
+ const data = event.data;
74
+ if (typeof data !== 'string') return;
75
+ // Issue #2045: `raw → owner decoder → typed`. A malformed frame (invalid JSON or an invalid
76
+ // shape) must not throw inside the handler (it would break the socket's message pump and
77
+ // freeze the UI) and must not be cast onward; surface it via the normal path.
78
+ const decoded = decodeFrame(data, decodeServerMessage);
79
+ if (!decoded.ok) {
80
+ callbacks.onMessage({
81
+ type: 'protocol_error',
82
+ message: `Malformed message from server (${decoded.reason})`,
83
+ });
84
+ return;
85
+ }
86
+ callbacks.onMessage(decoded.message);
87
+ };
88
+
89
+ ws.onclose = (): void => {
90
+ ws = null;
91
+ if (!intentionalDisconnect) {
92
+ setStatus('disconnected');
93
+ scheduleReconnect();
94
+ } else {
95
+ setStatus('disconnected');
96
+ }
97
+ };
98
+
99
+ ws.onerror = (): void => {
100
+ setStatus('error');
101
+ };
102
+ }
103
+
104
+ function connect(): void {
105
+ intentionalDisconnect = false;
106
+ if (reconnectTimer !== null) {
107
+ clearTimeout(reconnectTimer);
108
+ reconnectTimer = null;
109
+ }
110
+ doConnect();
111
+ }
112
+
113
+ function disconnect(): void {
114
+ intentionalDisconnect = true;
115
+ if (reconnectTimer !== null) {
116
+ clearTimeout(reconnectTimer);
117
+ reconnectTimer = null;
118
+ }
119
+ ws?.close();
120
+ ws = null;
121
+ setStatus('disconnected');
122
+ }
123
+
124
+ function send(msg: TClientMessage): void {
125
+ if (ws?.readyState === WebSocket.OPEN) {
126
+ ws.send(JSON.stringify(msg));
127
+ }
128
+ }
129
+
130
+ return { connect, disconnect, send, status: () => currentStatus };
131
+ }
@@ -0,0 +1,81 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ /**
4
+ * Copies `text` to the clipboard for the "Copy code" / "Copy message" buttons (#3289 §2): the async
5
+ * Clipboard API first, and — for a page that denies it (no permission granted yet, a browser that
6
+ * never implements it, or a context that disallows it outright) — a same-tick `execCommand('copy')`
7
+ * fallback through a throwaway, invisible textarea. Rejects only once both have failed, so a caller
8
+ * can show its own "Couldn't copy" message rather than a browser one.
9
+ */
10
+ export async function copyToClipboard(text: string): Promise<void> {
11
+ if (navigator.clipboard?.writeText) {
12
+ try {
13
+ await navigator.clipboard.writeText(text);
14
+ return;
15
+ } catch {
16
+ // Falls through to the legacy path — some browsers reject outside a user gesture, or before a
17
+ // permission prompt has ever been answered.
18
+ }
19
+ }
20
+ if (!legacyCopy(text)) throw new Error('copy failed');
21
+ }
22
+
23
+ /**
24
+ * `execCommand('copy')` needs a selection in the page, so the text is staged in an offscreen field —
25
+ * which needs focus to be selectable, so whatever had focus (typically the "Copy code" / "Copy
26
+ * message" button a keyboard user just activated) is restored afterward rather than left on `<body>`.
27
+ */
28
+ function legacyCopy(text: string): boolean {
29
+ if (typeof document === 'undefined' || typeof document.execCommand !== 'function') return false;
30
+ const previouslyFocused =
31
+ document.activeElement instanceof HTMLElement ? document.activeElement : null;
32
+ const field = document.createElement('textarea');
33
+ field.value = text;
34
+ field.setAttribute('readonly', '');
35
+ field.style.position = 'fixed';
36
+ field.style.top = '0';
37
+ field.style.left = '0';
38
+ field.style.opacity = '0';
39
+ field.style.pointerEvents = 'none';
40
+ document.body.appendChild(field);
41
+ field.focus();
42
+ field.select();
43
+ let ok = false;
44
+ try {
45
+ ok = document.execCommand('copy');
46
+ } catch {
47
+ ok = false;
48
+ }
49
+ document.body.removeChild(field);
50
+ previouslyFocused?.focus();
51
+ return ok;
52
+ }
53
+
54
+ export type TCopyStatus = 'idle' | 'copied' | 'error';
55
+
56
+ /** How long the "Copied" / "Couldn't copy" feedback holds before the button reads its normal label again. */
57
+ const FEEDBACK_MS = 2000;
58
+
59
+ /**
60
+ * The "Copy code" / "Copy message" buttons' shared feedback state: `copied` or `error` for a couple of
61
+ * seconds, then back to `idle` — drives both the button's own label swap and an `aria-live` region a
62
+ * screen reader announces without moving focus (#3289 §2).
63
+ */
64
+ export function useCopyFeedback(): { status: TCopyStatus; copy: (text: string) => void } {
65
+ const [status, setStatus] = useState<TCopyStatus>('idle');
66
+
67
+ useEffect(() => {
68
+ if (status === 'idle') return undefined;
69
+ const timer = setTimeout(() => setStatus('idle'), FEEDBACK_MS);
70
+ return () => clearTimeout(timer);
71
+ }, [status]);
72
+
73
+ const copy = (text: string): void => {
74
+ copyToClipboard(text).then(
75
+ () => setStatus('copied'),
76
+ () => setStatus('error'),
77
+ );
78
+ };
79
+
80
+ return { status, copy };
81
+ }