akanjs 3.2.0-rc.12 → 3.2.0-rc.13

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 (86) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/CHANGELOG.md +18 -0
  3. package/client/csrTypes.ts +2 -0
  4. package/client/index.ts +1 -0
  5. package/client/route/RouteDefinition.ts +24 -7
  6. package/client/route/routeArgs.ts +7 -0
  7. package/client/router.ts +12 -2
  8. package/package.json +1 -1
  9. package/server/akanApp.ts +103 -1270
  10. package/server/akanServer.ts +1 -1
  11. package/server/gateway/childSupervisor.ts +325 -0
  12. package/server/gateway/devHostChannel.ts +40 -0
  13. package/server/gateway/gatewayChildren.ts +135 -0
  14. package/server/gateway/gatewayConfig.ts +182 -0
  15. package/server/gateway/gatewayHttpProxy.ts +231 -0
  16. package/server/gateway/gatewayLogging.ts +111 -0
  17. package/server/gateway/gatewayRooms.ts +134 -0
  18. package/server/gateway/gatewayStatus.ts +116 -0
  19. package/server/gateway/gatewayStatusPage.ts +54 -0
  20. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  21. package/server/mcp/McpDispatcher.ts +6 -24
  22. package/signal/SignalFailure.ts +21 -0
  23. package/signal/agentTurnStream.ts +5 -2
  24. package/types/client/csrTypes.d.ts +2 -0
  25. package/types/client/index.d.ts +1 -1
  26. package/types/client/route/RouteDefinition.d.ts +2 -2
  27. package/types/client/route/routeArgs.d.ts +6 -0
  28. package/types/client/router.d.ts +2 -1
  29. package/types/server/akanApp.d.ts +2 -20
  30. package/types/server/gateway/childSupervisor.d.ts +33 -0
  31. package/types/server/gateway/devHostChannel.d.ts +13 -0
  32. package/types/server/gateway/gatewayChildren.d.ts +47 -0
  33. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  34. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  35. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  36. package/types/server/gateway/gatewayRooms.d.ts +22 -0
  37. package/types/server/gateway/gatewayStatus.d.ts +62 -0
  38. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  39. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  40. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  41. package/types/signal/SignalFailure.d.ts +1 -0
  42. package/types/signal/agentTurnStream.d.ts +1 -0
  43. package/types/ui/Agent/Chat.d.ts +5 -2
  44. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  45. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  46. package/types/ui/overlayLayer.d.ts +6 -1
  47. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  48. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  49. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +14 -10
  50. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  51. package/types/vendor/use-agentic/types.d.ts +6 -0
  52. package/types/webkit/CsrGuards.d.ts +2 -0
  53. package/ui/Agent/Chat.tsx +96 -116
  54. package/ui/Agent/ChatHeader.tsx +59 -0
  55. package/ui/Agent/ChatPendingCards.tsx +49 -0
  56. package/ui/Agent/fetchRunner.ts +8 -1
  57. package/ui/BottomSheet.tsx +1 -1
  58. package/ui/Dialog/LegacyModal.tsx +1 -1
  59. package/ui/Dialog/Modal.tsx +1 -1
  60. package/ui/Popconfirm.tsx +1 -1
  61. package/ui/overlayLayer.ts +22 -1
  62. package/vendor/@akanjs/native/CHANGELOG.md +6 -1
  63. package/vendor/@akanjs/native/native/desktop/src/external.rs +213 -111
  64. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  65. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +275 -0
  66. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  67. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  68. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  69. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  70. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  71. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  72. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  73. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  74. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  75. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +14 -10
  76. package/vendor/use-agentic/AgentSession.ts +11 -11
  77. package/vendor/use-agentic/CHANGELOG.md +6 -0
  78. package/vendor/use-agentic/Compaction.ts +2 -1
  79. package/vendor/use-agentic/ToolRunner.ts +3 -15
  80. package/vendor/use-agentic/Transcript.ts +6 -3
  81. package/vendor/use-agentic/WIRE.md +12 -1
  82. package/vendor/use-agentic/failureCode.ts +44 -0
  83. package/vendor/use-agentic/httpRunner.ts +14 -3
  84. package/vendor/use-agentic/types.ts +6 -0
  85. package/webkit/CsrGuards.ts +7 -2
  86. package/webkit/useLocation.ts +3 -2
@@ -0,0 +1,62 @@
1
+ import type { Logger } from "akanjs/common";
2
+ import type { AkanMetricsReport } from "akanjs/service";
3
+ import type { GatewayChildren } from "./gatewayChildren.d.ts";
4
+ import type { GatewayConfig } from "./gatewayConfig.d.ts";
5
+ import type { GatewayRooms } from "./gatewayRooms.d.ts";
6
+ export declare class GatewayStatus {
7
+ #private;
8
+ constructor(config: GatewayConfig, children: GatewayChildren, rooms: GatewayRooms, logger: Logger);
9
+ healthStatus(): {
10
+ status: string;
11
+ pid: number;
12
+ children: {
13
+ idx: number;
14
+ role: import("akanjs/service").AkanChildRole;
15
+ status: import("akanjs/service").AkanChildStatus;
16
+ ready: boolean;
17
+ pid: number | undefined;
18
+ upstream: import("akanjs/service").AkanUpstream | undefined;
19
+ restartAttempts: number;
20
+ restartCount: number;
21
+ restartPending: boolean;
22
+ lastExitCode: number | null | undefined;
23
+ lastRestartAt: number | undefined;
24
+ lastRestartReason: string | undefined;
25
+ lastErrorMessage: string | undefined;
26
+ }[];
27
+ };
28
+ readyStatus(): {
29
+ ready: boolean;
30
+ pid: number;
31
+ children: {
32
+ idx: number;
33
+ role: import("akanjs/service").AkanChildRole;
34
+ status: import("akanjs/service").AkanChildStatus;
35
+ ready: boolean;
36
+ }[];
37
+ };
38
+ metricsStatus(): {
39
+ rooms: number;
40
+ sockets: number;
41
+ gateway: AkanMetricsReport;
42
+ proxyHop: {
43
+ count: number;
44
+ meanMs: number;
45
+ maxMs: number;
46
+ } | null;
47
+ children: {
48
+ idx: number;
49
+ role: import("akanjs/service").AkanChildRole;
50
+ metrics: AkanMetricsReport;
51
+ rooms: number;
52
+ restartAttempts: number;
53
+ restartCount: number;
54
+ restartPending: boolean;
55
+ lastExitCode: number | null | undefined;
56
+ lastRestartAt: number | undefined;
57
+ lastRestartReason: string | undefined;
58
+ }[];
59
+ };
60
+ recordProxyHop(durationMs: number): void;
61
+ reportMetrics(): Promise<void>;
62
+ }
@@ -0,0 +1,9 @@
1
+ export declare class GatewayStatusPage {
2
+ #private;
3
+ static headers(contentType: string): Headers;
4
+ static html({ heading, detail, note }: {
5
+ heading: string;
6
+ detail: string;
7
+ note: string;
8
+ }): string;
9
+ }
@@ -0,0 +1,17 @@
1
+ import type { GatewayChildren } from "./gatewayChildren.d.ts";
2
+ import type { GatewayConfig } from "./gatewayConfig.d.ts";
3
+ export interface GatewayWsData {
4
+ childIdx: number;
5
+ upstream: WebSocket;
6
+ clientIp: string | null;
7
+ pending: (string | ArrayBuffer)[];
8
+ pendingBytes: number;
9
+ }
10
+ export declare class GatewayWebSocketRelay {
11
+ #private;
12
+ constructor(config: GatewayConfig, children: GatewayChildren);
13
+ upgrade(req: Request, server: Bun.Server<GatewayWsData>): Response | undefined;
14
+ open(ws: Bun.ServerWebSocket<GatewayWsData>): void;
15
+ message(ws: Bun.ServerWebSocket<GatewayWsData>, message: string | ArrayBuffer | Uint8Array): void;
16
+ close(ws: Bun.ServerWebSocket<GatewayWsData>, code: number, reason: string): void;
17
+ }
@@ -19,5 +19,5 @@ export declare class RotatingLogWriter {
19
19
  static sanitizeFilePart(value: string): string;
20
20
  write(processKey: string, chunk: string): void;
21
21
  close(): Promise<void>;
22
- static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#141@#defaultWarn): number;
22
+ static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#144@#defaultWarn): number;
23
23
  }
@@ -9,6 +9,7 @@ export declare class SignalFailure {
9
9
  statusCode: number;
10
10
  code?: string;
11
11
  };
12
+ static codeOf(error: unknown, status: number | undefined): string;
12
13
  static body<Extra extends Record<string, unknown> = Record<string, never>>(error: unknown, extra?: Extra): Extra & {
13
14
  error: string;
14
15
  statusCode: number;
@@ -13,6 +13,7 @@ export declare class AgentTurnStream {
13
13
  /** A domain `Err`'s `data` travels with its key, or the chat could not fill the text's placeholders. */
14
14
  static failure(error: unknown): {
15
15
  message: string;
16
+ code: string;
16
17
  data?: Record<string, string | number>;
17
18
  overflow?: {
18
19
  limit?: number;
@@ -8,7 +8,10 @@ import type { VoiceEngine } from "./voice.d.ts";
8
8
  export interface ChatProps {
9
9
  /** Applied to the launcher while closed and to the panel while open. */
10
10
  className?: string;
11
- title?: string;
11
+ /** The header's title; also the panel's accessible name when it is a string and `label` is left off. */
12
+ title?: ReactNode;
13
+ /** The panel's accessible name, for a `title` that is not plain text. */
14
+ label?: string;
12
15
  /** App-global framing; route-scoped `Agent.Guide`s layer on it. */
13
16
  instructions?: string;
14
17
  /** Defaults to the app's `runAgentTurn` endpoint. */
@@ -63,6 +66,6 @@ export interface ChatProps {
63
66
  /** Speech in and out; a reply is read aloud only when the ask came in by voice. */
64
67
  voice?: VoiceEngine;
65
68
  }
66
- export declare const DefaultChat: ({ className, title, instructions, runner, maxTurns, compact, builtins, onCompact, defaultOpen, open: openProp, onOpenChange, launcher, visual, persist, inline, shortcut, launcherClassName, launcherPlacement, hideLauncherBelow, panelClassName, intro, header, chrome, defaultDraft, attach, attachLimits, reference, mentions, voice, }: ChatProps) => ReactNode;
69
+ export declare const DefaultChat: ({ className, title, label, instructions, runner, maxTurns, compact, builtins, onCompact, defaultOpen, open: openProp, onOpenChange, launcher, visual, persist, inline, shortcut, launcherClassName, launcherPlacement, hideLauncherBelow, panelClassName, intro, header, chrome, defaultDraft, attach, attachLimits, reference, mentions, voice, }: ChatProps) => ReactNode;
67
70
  declare const _default: import("react").ComponentType<ChatProps>;
68
71
  export default _default;
@@ -0,0 +1,13 @@
1
+ import type { ReactNode } from "react";
2
+ export interface ChatHeaderProps {
3
+ title?: ReactNode;
4
+ running: boolean;
5
+ context: {
6
+ used: number;
7
+ compactAt?: number;
8
+ };
9
+ controls?: ReactNode;
10
+ onClear?: () => void;
11
+ onClose?: () => void;
12
+ }
13
+ export declare const ChatHeader: ({ title, running, context, controls, onClear, onClose }: ChatHeaderProps) => import("react").JSX.Element;
@@ -0,0 +1,23 @@
1
+ import type { AgentSession } from "../../vendor/use-agentic.d.ts";
2
+ export declare const isAsking: (session: AgentSession) => boolean;
3
+ export declare const ChatPendingCards: ({ session, portal }: {
4
+ session: AgentSession;
5
+ portal: HTMLElement | null;
6
+ }) => import("react").JSX.Element;
7
+ export declare const usePanelOverlays: () => {
8
+ layer: HTMLElement | null;
9
+ cardLayer: HTMLElement | null;
10
+ hosts: {
11
+ layer: HTMLElement | null;
12
+ onLayer: import("react").Dispatch<import("react").SetStateAction<HTMLElement | null>>;
13
+ onCardLayer: import("react").Dispatch<import("react").SetStateAction<HTMLElement | null>>;
14
+ };
15
+ };
16
+ interface PanelOverlayHostsProps {
17
+ asking: boolean;
18
+ layer: HTMLElement | null;
19
+ onLayer: (layer: HTMLElement | null) => void;
20
+ onCardLayer: (layer: HTMLElement | null) => void;
21
+ }
22
+ export declare const PanelOverlayHosts: ({ asking, layer, onLayer, onCardLayer }: PanelOverlayHostsProps) => import("react").JSX.Element;
23
+ export {};
@@ -9,15 +9,20 @@ export declare const overlayZ: {
9
9
  readonly modal: 120;
10
10
  readonly approval: 130;
11
11
  readonly toast: 140;
12
+ readonly agentPanelOverlaySunk: 145;
12
13
  readonly agentPanel: 150;
14
+ readonly agentPanelOverlay: 160;
15
+ readonly agentPanelCardOverlay: 170;
13
16
  readonly reconnect: 200;
14
17
  };
18
+ export declare const useHoldsScrim: (layer: HTMLElement | null) => boolean;
15
19
  /** Takes the scope from {@link useOverlayScope}. */
16
20
  export declare const OverlayOwnerProvider: import("react").Provider<string>;
17
21
  /** Nests under the enclosing scope as a `parent/child` path. */
18
22
  export declare const useOverlayScope: (id: string) => string;
19
23
  /** Spread onto every root an overlay portals out of its own tree. */
20
- export declare const useOverlayLayerProps: () => {
24
+ export declare const useOverlayLayerProps: (scrim?: boolean) => {
25
+ "data-akan-scrim"?: string | undefined;
21
26
  "data-akan-overlay": string;
22
27
  };
23
28
  /** True when the click landed in an overlay `scope`, or a scope nested in it, rendered; any other is outside. */
@@ -142,9 +142,13 @@ export interface AndroidManifest extends NativeSubset {
142
142
  */
143
143
  minSdk?: number;
144
144
  }
145
+ export declare const DESKTOP_OSES: readonly ["macos", "windows", "linux"];
146
+ export type DesktopOs = (typeof DESKTOP_OSES)[number];
145
147
  /** Desktop Bun module that implements only some methods (the rest are UNSUPPORTED, or web with `web: true`). */
146
148
  export interface DesktopManifest extends NativeSubset {
147
149
  module: string;
150
+ /** The methods one desktop OS lacks: left out of that OS's declaration, so `isSupported()` is false there only. */
151
+ unsupported?: Partial<Record<DesktopOs, string[]>>;
148
152
  }
149
153
  export interface PluginManifest {
150
154
  id: string;
@@ -24,6 +24,7 @@ export declare function recoveryScript(exe: string, moves: [string, string][], s
24
24
  * read as text: an execution policy that refuses .ps1 files does not apply to it, as it does not to -EncodedCommand.
25
25
  */
26
26
  export declare function recoveryCommand(script: string): string | null;
27
+ export declare const appLauncher: (env?: NodeJS.ProcessEnv, exe?: string) => string;
27
28
  /**
28
29
  * Once this process has exited: renames `moves` in order and starts `exe` with this environment. macOS and
29
30
  * Linux rename a running app's folder right away, so only the start waits; Windows refuses that, so a helper
@@ -9,8 +9,10 @@ import { type FileRef } from "../../../packages/core/src/index.ts";
9
9
  * permissions and links another program would open (`mailto:`, a custom scheme) are refused. Listing the plugin in
10
10
  * `native.plugins` is what lets an app open one.
11
11
  *
12
- * Windows has every method. macOS (14 or later, for its separate profile) has all but `sendKey`, `setMuted` and
13
- * `capture`, and sends no `loadFailed` or `consoleMessage`. Linux, iOS and Android: UNSUPPORTED.
12
+ * Windows has every method. Linux has all but `sendKey` and sends no `consoleMessage`; there the visible view shown
13
+ * last holds the keyboard focus inside its window, so keys reach it as the user's own, until a click on the page takes
14
+ * the focus or the view is hidden or closed. macOS (14 or later, for its separate profile) has all but `sendKey`,
15
+ * `setMuted` and `capture`, and sends no `loadFailed` or `consoleMessage`. iOS and Android: UNSUPPORTED.
14
16
  */
15
17
  export type ExternalViewBounds = "fill" | {
16
18
  x: number;
@@ -32,7 +34,7 @@ export interface ExternalViewOpenOptions {
32
34
  * with `evaluate`. It may not declare `__akanTopOnly`, and an empty one registers nothing.
33
35
  */
34
36
  initScript?: string;
35
- /** Windows only: macOS refuses `true` as UNSUPPORTED. */
37
+ /** macOS refuses `true` as UNSUPPORTED. */
36
38
  muted?: boolean;
37
39
  /** Media plays with sound without a gesture first (default true): nobody taps a signage screen. */
38
40
  autoplay?: boolean;
@@ -53,7 +55,7 @@ export interface ExternalViewApi {
53
55
  /**
54
56
  * Opens the view, or brings an open one with this id to these options (a page that mounts again finds it). Another
55
57
  * `initScript` builds the view again and loads its page anew, as does another `console` on Windows and another
56
- * `autoplay` on macOS; Windows refuses another `autoplay` as UNSUPPORTED, before anything is built.
58
+ * `autoplay` on macOS and Linux; Windows refuses another `autoplay` as UNSUPPORTED, before anything is built.
57
59
  */
58
60
  open(args: ExternalViewOpenOptions): Promise<ExternalViewState>;
59
61
  /** Rejects NOT_ALLOWED for a URL on none of its `allowOrigins`. */
@@ -94,7 +96,7 @@ export interface ExternalViewApi {
94
96
  key: string;
95
97
  code: string;
96
98
  }): Promise<void>;
97
- /** The view's own sound only; the system volume is the volume plugin's. Windows only. */
99
+ /** The view's own sound only; the system volume is the volume plugin's. Not on macOS. */
98
100
  setMuted(args: {
99
101
  id: string;
100
102
  muted: boolean;
@@ -103,7 +105,7 @@ export interface ExternalViewApi {
103
105
  clearData(args: {
104
106
  id: string;
105
107
  }): Promise<void>;
106
- /** A PNG of the view's content (not the screen), kept until its next capture or the next launch. Windows only. */
108
+ /** A PNG of the view's content (not the screen), kept until its next capture or the next launch. Not on macOS. */
107
109
  capture(args: {
108
110
  id: string;
109
111
  }): Promise<FileRef & {
@@ -120,7 +122,8 @@ export interface ExternalViewEvents {
120
122
  /**
121
123
  * A navigation that failed. `errorCode`: `http<status>` for a server's 4xx or 5xx page, else WebView2's own
122
124
  * (`hostNameNotResolved`, `cannotConnect`, `timeout`, `certificate`, `disconnected`, …; a refused connection is
123
- * `unknown`). Windows only.
125
+ * `unknown`). Linux names the same failures by those names (a refused connection is `cannotConnect`) and any other
126
+ * `unknown`. Not on macOS.
124
127
  */
125
128
  loadFailed: {
126
129
  id: string;
@@ -128,9 +131,10 @@ export interface ExternalViewEvents {
128
131
  errorCode: string;
129
132
  };
130
133
  /**
131
- * Its web process ended (`reason`: `crashed`, `unresponsive` or `browserExited` on Windows, `terminated` on macOS);
132
- * the view loads its page again by itself, sooner the first times, and an end while that waits is not reported
133
- * again. `rebuildFailed`: after its browser exited the view could not be built again, and is closed; open it again.
134
+ * Its web process ended (`reason`: `crashed`, `unresponsive` or `browserExited` on Windows, `terminated` on macOS,
135
+ * `crashed`, `killed` or `oom` on Linux); the view loads its page again by itself, sooner the first times, and an end
136
+ * while that waits is not reported again. `rebuildFailed`: after its browser exited the view could not be built
137
+ * again, and is closed; open it again.
134
138
  */
135
139
  gone: {
136
140
  id: string;
@@ -0,0 +1,4 @@
1
+ export declare const isFailureCode: (value: unknown) => value is string;
2
+ export declare const codeOfStatus: (status: number) => string;
3
+ export declare const codeOfAnswer: (status: number, body: unknown) => string;
4
+ export declare const failureCodeOf: (value: unknown) => string | undefined;
@@ -246,6 +246,8 @@ export interface ChatMessage {
246
246
  toolResults?: ToolCallResult[];
247
247
  /** A failed or capped turn, recorded in the transcript rather than thrown past it. */
248
248
  error?: string;
249
+ /** The code the runner named that failure by, for a host to branch on where `error` is text. Never sent. */
250
+ errorCode?: string;
249
251
  /**
250
252
  * Host-rendered and never sent: a command's own output belongs in the transcript the user reads but not in the
251
253
  * history the model reads, which would take it for something it had said itself.
@@ -289,10 +291,14 @@ export type RunnerEvent = {
289
291
  *
290
292
  * `overflow` marks the provider refusing a prompt too long for its window — the one refusal a session can undo
291
293
  * on its own, by compacting and asking again. `limit` is the window when the refusal named it.
294
+ *
295
+ * `code` names the failure for a host to branch on, since `message` may reach it already translated: a
296
+ * dictionary key (`<module>.error.<key>`) or a camelCase token, never prose.
292
297
  */
293
298
  | {
294
299
  type: "error";
295
300
  message: string;
301
+ code?: string;
296
302
  data?: Record<string, string | number>;
297
303
  overflow?: {
298
304
  limit?: number;
@@ -4,6 +4,8 @@ interface GuardedLocation {
4
4
  pathRoute: PathRoute;
5
5
  params: Record<string, string>;
6
6
  searchParams: Record<string, string | string[]>;
7
+ pathname?: string;
8
+ search?: string;
7
9
  }
8
10
  /**
9
11
  * A CSR navigation's route guards, run before any of its layers draws. On the client a guard refuses by moving the
package/ui/Agent/Chat.tsx CHANGED
@@ -12,7 +12,6 @@ import {
12
12
  useSyncExternalStore,
13
13
  } from "react";
14
14
  import { createPortal } from "react-dom";
15
- import { AiOutlineClear, AiOutlineClose } from "react-icons/ai";
16
15
  import {
17
16
  type AgentRunner,
18
17
  type AgentSession,
@@ -22,21 +21,19 @@ import {
22
21
  SessionContext,
23
22
  type SessionHistory,
24
23
  } from "../../vendor/use-agentic";
25
- import { overlayZ } from "../overlayLayer";
24
+ import { OverlayPortalProvider, overlayZ, useOverlayPortal } from "../overlayLayer";
26
25
  import { createOverridable } from "../UiOverride";
27
- import Approval from "./Approval";
28
26
  import { agentSessionOf, type BuiltinOption, type PersistOption } from "./agentSessionOf";
29
27
  import type { AttachLimits, AttachReader } from "./attachment";
30
28
  import Bubble from "./Bubble";
31
29
  import { type ChatCommand, ChatCommands } from "./ChatCommands";
30
+ import { ChatHeader } from "./ChatHeader";
31
+ import { ChatPendingCards, isAsking, PanelOverlayHosts, usePanelOverlays } from "./ChatPendingCards";
32
32
  import { Composer, type ComposerHandle } from "./Composer";
33
33
  import { Launcher } from "./Launcher";
34
34
  import Menu from "./Menu";
35
- import Question from "./Question";
36
35
  import Queued from "./Queued";
37
36
  import Steps from "./Steps";
38
- import ToolCard from "./ToolCard";
39
- import { tokenCount } from "./tokenCount";
40
37
  import { useAccountBoundSession } from "./useAccountBoundSession";
41
38
  import { useChatAttachments } from "./useChatAttachments";
42
39
  import { type QueuedMessage, useChatQueue } from "./useChatQueue";
@@ -51,7 +48,10 @@ import type { VoiceEngine } from "./voice";
51
48
  export interface ChatProps {
52
49
  /** Applied to the launcher while closed and to the panel while open. */
53
50
  className?: string;
54
- title?: string;
51
+ /** The header's title; also the panel's accessible name when it is a string and `label` is left off. */
52
+ title?: ReactNode;
53
+ /** The panel's accessible name, for a `title` that is not plain text. */
54
+ label?: string;
55
55
  /** App-global framing; route-scoped `Agent.Guide`s layer on it. */
56
56
  instructions?: string;
57
57
  /** Defaults to the app's `runAgentTurn` endpoint. */
@@ -130,6 +130,7 @@ const stickyEdge = 80;
130
130
  export const DefaultChat = ({
131
131
  className,
132
132
  title,
133
+ label,
133
134
  instructions,
134
135
  runner,
135
136
  maxTurns,
@@ -218,6 +219,9 @@ export const DefaultChat = ({
218
219
  const read = useRef(session.messages.length);
219
220
  const keyboardFrame = useKeyboardFrame();
220
221
  const [overlay, setOverlay] = useState<HTMLElement | null>(null);
222
+ const { layer: panelOverlays, cardLayer: cardOverlays, hosts: overlayHosts } = usePanelOverlays();
223
+
224
+ const enclosingPortal = useOverlayPortal();
221
225
  useEffect(() => {
222
226
  setOverlay(document.body);
223
227
  }, []);
@@ -268,6 +272,11 @@ export const DefaultChat = ({
268
272
  returning.current = true;
269
273
  setOpen(false);
270
274
  };
275
+ const clear = () => {
276
+ files.clear();
277
+ queue.take();
278
+ void session.reset();
279
+ };
271
280
  const runCommand = (command: ChatCommand) => {
272
281
  write("");
273
282
  recall.remember(`/${command.name}`);
@@ -442,117 +451,88 @@ export const DefaultChat = ({
442
451
  : null;
443
452
 
444
453
  return layer(
445
- <aside
446
- aria-label={title ?? l("base.agent")}
447
- data-agent-ui=""
448
- className={cn(
449
- "flex flex-col overflow-hidden border border-border bg-background",
450
- inline ? "h-full w-full rounded-box" : [panelLayer, panelSize, "shadow-xl"],
451
- files.dragging && "border-primary ring-2 ring-primary/40",
452
- className,
453
- panelClassName,
454
- )}
455
- role="dialog"
456
- style={inline ? undefined : { zIndex: overlayZ.agentPanel, ...keyboardFrame }}
457
- {...files.dropProps}
458
- >
459
- {chrome ? (
460
- <header className="flex items-center gap-2 border-foreground/5 border-b px-4 py-3">
461
- <span className="font-semibold text-sm">{title ?? l("base.agent")}</span>
462
- {session.isRunning ? <span className="size-2 animate-pulse rounded-full bg-primary" /> : null}
463
- {context.used ? (
464
- <span
465
- className="shrink-0 whitespace-nowrap text-[10px] text-foreground/40"
466
- title={
467
- context.compactAt ? l("base.agentCompactsAt", { limit: tokenCount(context.compactAt) }) : undefined
468
- }
469
- >
470
- {context.compactAt
471
- ? l("base.agentTokensOf", { count: tokenCount(context.used), limit: tokenCount(context.compactAt) })
472
- : l("base.agentTokens", { count: tokenCount(context.used) })}
473
- </span>
454
+ <>
455
+ <aside
456
+ aria-label={label ?? (typeof title === "string" ? title : l("base.agent"))}
457
+ data-agent-ui=""
458
+ className={cn(
459
+ "flex flex-col overflow-hidden border border-border bg-background",
460
+ inline ? "h-full w-full rounded-box" : [panelLayer, panelSize, "shadow-xl"],
461
+ files.dragging && "border-primary ring-2 ring-primary/40",
462
+ className,
463
+ panelClassName,
464
+ )}
465
+ role="dialog"
466
+ style={inline ? undefined : { zIndex: overlayZ.agentPanel, ...keyboardFrame }}
467
+ {...files.dropProps}
468
+ >
469
+ <OverlayPortalProvider value={inline ? enclosingPortal : panelOverlays}>
470
+ {chrome ? (
471
+ <ChatHeader
472
+ context={context}
473
+ controls={header}
474
+ running={session.isRunning}
475
+ title={title}
476
+ onClear={session.messages.length ? clear : undefined}
477
+ onClose={closable ? dismiss : undefined}
478
+ />
474
479
  ) : null}
475
- <span className="ml-auto flex items-center gap-2">
476
- {header}
477
- {session.messages.length ? (
478
- <button
479
- aria-label={l("base.agentClear")}
480
- className="text-foreground/50 hover:text-foreground"
481
- onClick={() => {
482
- files.clear();
483
- queue.take();
484
- void session.reset();
485
- }}
486
- type="button"
487
- >
488
- <AiOutlineClear />
489
- </button>
490
- ) : null}
491
- {closable ? (
492
- <button
493
- aria-label={l("base.cancel")}
494
- className="text-foreground/50 hover:text-foreground"
495
- onClick={dismiss}
496
- type="button"
497
- >
498
- <AiOutlineClose />
499
- </button>
480
+ <div
481
+ aria-busy={session.isRunning}
482
+ aria-live="polite"
483
+ className="scrollbar-thin flex flex-1 flex-col gap-2 overflow-y-auto px-4 py-3"
484
+ onScroll={() => {
485
+ const list = listRef.current;
486
+ if (list) sticky.current = list.scrollHeight - list.scrollTop - list.clientHeight < stickyEdge;
487
+ }}
488
+ ref={listRef}
489
+ role="log"
490
+ >
491
+ {bubbles.length
492
+ ? bubbles
493
+ : (intro ?? <p className="py-6 text-center text-foreground/40 text-sm">{l("base.agentIntro")}</p>)}
494
+ {session.isCompacting ? (
495
+ <p className="flex items-center gap-2 text-foreground/50 text-xs">
496
+ <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-primary" />
497
+ {l("base.agentSummarizing")}
498
+ </p>
500
499
  ) : null}
501
- </span>
502
- </header>
503
- ) : null}
504
- <div
505
- aria-busy={session.isRunning}
506
- aria-live="polite"
507
- className="scrollbar-thin flex flex-1 flex-col gap-2 overflow-y-auto px-4 py-3"
508
- onScroll={() => {
509
- const list = listRef.current;
510
- if (list) sticky.current = list.scrollHeight - list.scrollTop - list.clientHeight < stickyEdge;
511
- }}
512
- ref={listRef}
513
- role="log"
514
- >
515
- {bubbles.length
516
- ? bubbles
517
- : (intro ?? <p className="py-6 text-center text-foreground/40 text-sm">{l("base.agentIntro")}</p>)}
518
- {session.isCompacting ? (
519
- <p className="flex items-center gap-2 text-foreground/50 text-xs">
520
- <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-primary" />
521
- {l("base.agentSummarizing")}
522
- </p>
523
- ) : null}
524
- </div>
525
- {session.pendingApproval ? <Approval approval={session.pendingApproval} /> : null}
526
- {session.pendingCard ? <ToolCard card={session.pendingCard} key={session.pendingCard.callId} /> : null}
527
- {session.pendingQuestion ? (
528
- <Question key={session.pendingQuestion.callId} question={session.pendingQuestion} />
529
- ) : null}
530
- {queue.queued ? <Queued message={queue.queued} onCancel={() => queue.take()} onEdit={unpark} /> : null}
531
- <Menu onPick={(row) => row.pick()} prefix={list === menu ? "/" : "@"} rows={list.rows} selected={list.selected} />
532
- <Composer
533
- attached={files.attached}
534
- pending={files.pending}
535
- draft={draft}
536
- handleRef={handleRef}
537
- inputRef={inputRef}
538
- isMenuOpen={!!list.at()}
539
- mentions={mentions ?? !!reference?.length}
540
- {...(speech.canListen ? { mic: { listening: speech.listening, onToggle: speech.toggle } } : {})}
541
- onDraft={write}
542
- onFiles={(picked) => void files.add(picked)}
543
- onKeyDown={onKeyDown}
544
- onRemoveFile={files.remove}
545
- onRemoveReference={refs.remove}
546
- onSend={send}
547
- references={refs.references}
548
- onStop={() => {
549
- speech.silence();
550
- unpark();
551
- session.abort();
552
- }}
553
- session={session}
554
- />
555
- </aside>,
500
+ </div>
501
+ <ChatPendingCards portal={inline ? enclosingPortal : cardOverlays} session={session} />
502
+ {queue.queued ? <Queued message={queue.queued} onCancel={() => queue.take()} onEdit={unpark} /> : null}
503
+ <Menu
504
+ onPick={(row) => row.pick()}
505
+ prefix={list === menu ? "/" : "@"}
506
+ rows={list.rows}
507
+ selected={list.selected}
508
+ />
509
+ <Composer
510
+ attached={files.attached}
511
+ pending={files.pending}
512
+ draft={draft}
513
+ handleRef={handleRef}
514
+ inputRef={inputRef}
515
+ isMenuOpen={!!list.at()}
516
+ mentions={mentions ?? !!reference?.length}
517
+ {...(speech.canListen ? { mic: { listening: speech.listening, onToggle: speech.toggle } } : {})}
518
+ onDraft={write}
519
+ onFiles={(picked) => void files.add(picked)}
520
+ onKeyDown={onKeyDown}
521
+ onRemoveFile={files.remove}
522
+ onRemoveReference={refs.remove}
523
+ onSend={send}
524
+ references={refs.references}
525
+ onStop={() => {
526
+ speech.silence();
527
+ unpark();
528
+ session.abort();
529
+ }}
530
+ session={session}
531
+ />
532
+ </OverlayPortalProvider>
533
+ </aside>
534
+ {inline ? null : <PanelOverlayHosts asking={isAsking(session)} {...overlayHosts} />}
535
+ </>,
556
536
  );
557
537
  };
558
538