@kortix/ui 0.16.4 → 0.16.5

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 (100) hide show
  1. package/dist/customize/sections/view/review-center-connected.js +64 -71
  2. package/dist/customize/sections/view/secret-delivery.d.ts +11 -20
  3. package/dist/customize/sections/view/secret-delivery.js +20 -29
  4. package/dist/customize/sections/view/secrets-view.js +9 -24
  5. package/dist/i18n/en.d.ts +116 -13
  6. package/dist/i18n/en.js +127 -24
  7. package/dist/i18n/ui-catalog/product-catalog-translation-keys.generated.js +2 -0
  8. package/dist/internal/auth/auth-card-shell.d.ts +24 -3
  9. package/dist/internal/auth/auth-card-shell.js +15 -8
  10. package/dist/internal/auth/auth-primitives.d.ts +15 -2
  11. package/dist/internal/auth/auth-primitives.js +22 -5
  12. package/dist/internal/components/agent-mark.d.ts +2 -1
  13. package/dist/internal/components/agent-mark.js +14 -3
  14. package/dist/internal/hooks/use-review-session-summary.d.ts +1 -1
  15. package/dist/internal/hooks/use-review-session-summary.js +1 -1
  16. package/dist/internal/layout/project-nav-row.d.ts +3 -1
  17. package/dist/internal/layout/project-nav-row.js +2 -2
  18. package/dist/markdown/setup-links/secret-intake-form.d.ts +4 -1
  19. package/dist/markdown/setup-links/secret-intake-form.js +60 -16
  20. package/dist/markdown/setup-links/setup-link-button.js +6 -1
  21. package/dist/session/agents/agent-hover-card.d.ts +26 -0
  22. package/dist/session/agents/agent-hover-card.js +70 -0
  23. package/dist/session/agents/agent-strip.js +33 -7
  24. package/dist/session/agents/agent-surface.d.ts +26 -1
  25. package/dist/session/agents/agent-surface.js +57 -6
  26. package/dist/session/agents/held-messages.js +2 -2
  27. package/dist/session/agents/subagent-dialog-content.js +2 -2
  28. package/dist/session/composer/ComposerCard.js +4 -1
  29. package/dist/session/composer/composer-toolbar.d.ts +8 -1
  30. package/dist/session/composer/composer-toolbar.js +2 -2
  31. package/dist/session/composer/dictation/dictation-control.d.ts +10 -0
  32. package/dist/session/composer/dictation/dictation-control.js +28 -0
  33. package/dist/session/composer/dictation/dictation-state.d.ts +26 -0
  34. package/dist/session/composer/dictation/dictation-state.js +71 -0
  35. package/dist/session/composer/dictation/recorder.d.ts +30 -0
  36. package/dist/session/composer/dictation/recorder.js +129 -0
  37. package/dist/session/composer/dictation/use-composer-dictation.d.ts +25 -0
  38. package/dist/session/composer/dictation/use-composer-dictation.js +218 -0
  39. package/dist/session/composer/queued-prompt-list.js +5 -1
  40. package/dist/session/panel/easy/apps-card.js +3 -10
  41. package/dist/session/panel/easy/background-tasks-card.d.ts +23 -0
  42. package/dist/session/panel/easy/background-tasks-card.js +119 -0
  43. package/dist/session/panel/easy/change-requests-card.js +1 -1
  44. package/dist/session/panel/easy/changes-card.js +4 -6
  45. package/dist/session/panel/easy/context-card.js +8 -9
  46. package/dist/session/panel/easy/context-meter.d.ts +2 -0
  47. package/dist/session/panel/easy/context-meter.js +18 -4
  48. package/dist/session/panel/easy/detail-view.js +4 -2
  49. package/dist/session/panel/easy/easy-panel-logic.d.ts +4 -15
  50. package/dist/session/panel/easy/easy-panel-logic.js +4 -17
  51. package/dist/session/panel/easy/easy-panel.js +5 -4
  52. package/dist/session/panel/easy/outputs-card.d.ts +1 -13
  53. package/dist/session/panel/easy/outputs-card.js +14 -40
  54. package/dist/session/panel/easy/panel-card.d.ts +13 -40
  55. package/dist/session/panel/easy/panel-card.js +17 -55
  56. package/dist/session/panel/easy/plan-card.js +4 -7
  57. package/dist/session/panel/model-switch-event.d.ts +2 -2
  58. package/dist/session/panel/model-switch-event.js +13 -9
  59. package/dist/session/panel/session-panel-provider.d.ts +2 -1
  60. package/dist/session/panel/session-panel-provider.js +3 -3
  61. package/dist/session/panel/shared/derive-panels.js +14 -1
  62. package/dist/session/panel/shared/use-panel-handoffs.d.ts +0 -1
  63. package/dist/session/panel/shared/use-panel-handoffs.js +3 -15
  64. package/dist/session/thread/chat-minimap.js +7 -1
  65. package/dist/session/thread/session-chat.js +59 -15
  66. package/dist/session/tool/shared/infrastructure-contexts.d.ts +2 -0
  67. package/dist/session/tool/shared/infrastructure-contexts.js +2 -0
  68. package/dist/session/tool/shared/infrastructure-row-header.js +4 -1
  69. package/dist/session/tool/shared/infrastructure-rows.js +19 -19
  70. package/dist/session/tool/tool-part-renderer.js +23 -9
  71. package/dist/session/tool/tools/bash-tool.js +3 -2
  72. package/dist/session/tool/tools/codemode-tool.d.ts +15 -0
  73. package/dist/session/tool/tools/codemode-tool.js +54 -2
  74. package/dist/session/tool/tools/kortix-action-tool.d.ts +1 -0
  75. package/dist/session/tool/tools/kortix-action-tool.js +19 -8
  76. package/dist/session/tool/tools/multi-agent-tool-bodies.d.ts +8 -1
  77. package/dist/session/tool/tools/multi-agent-tool-bodies.js +76 -10
  78. package/dist/session/tool/tools/task-tool.js +17 -5
  79. package/dist/session/turn/peer-message-row.d.ts +3 -0
  80. package/dist/session/turn/peer-message-row.js +8 -2
  81. package/dist/session/turn/subagent-notice-row.js +5 -3
  82. package/dist/styles.css +1 -1
  83. package/dist/test-utils/intl.d.ts +116 -13
  84. package/dist/workspace/projects/modal/project-icon-field.d.ts +3 -1
  85. package/dist/workspace/projects/modal/project-icon-field.js +3 -3
  86. package/dist/workspace/review/review-center.d.ts +9 -1
  87. package/dist/workspace/review/review-center.js +107 -14
  88. package/dist/workspace/review/review-detail.d.ts +19 -0
  89. package/dist/workspace/review/review-detail.js +18 -3
  90. package/dist/workspace/review/review-swipe-deck.d.ts +27 -0
  91. package/dist/workspace/review/review-swipe-deck.js +304 -0
  92. package/dist/workspace/review/review-swipe.d.ts +17 -0
  93. package/dist/workspace/review/review-swipe.js +10 -0
  94. package/dist/workspace/sidebar/footer/project-review-nav.d.ts +13 -0
  95. package/dist/workspace/sidebar/footer/project-review-nav.js +29 -0
  96. package/dist/workspace/sidebar/project-nav-items.d.ts +3 -1
  97. package/dist/workspace/sidebar/project-nav-items.js +24 -5
  98. package/dist/workspace/sidebar/project-spaces-nav.js +3 -10
  99. package/dist/workspace/sidebar/sidebar-more-group.js +1 -1
  100. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import type { SessionDisplayStatus } from '../actions/session-label.js';
3
+ import { type AgentInlineDetail } from './agent-hover-card.js';
3
4
  /**
4
5
  * The parts every MyKortix agent surface in the chat is drawn from. An agent
5
6
  * call, an agent's finish, a message to or from another agent and a workflow
@@ -24,13 +25,37 @@ export declare function SmallGlyph({ status, label }: {
24
25
  status: SessionDisplayStatus;
25
26
  label?: string;
26
27
  }): import("react").JSX.Element;
28
+ /**
29
+ * An agent as one chip: its pixel mark and its name in a full-round pill. The
30
+ * fill is the agent's colour (the mark's ink) at a medium tint, so every agent
31
+ * reads as its own colour, grey ones included; the name stays in the
32
+ * foreground ink. Every agent name on a MyKortix surface is this chip.
33
+ * A chip that leads a row starts on the row's left edge, where every other
34
+ * row's icon starts; that row draws no separate face.
35
+ */
36
+ export declare function AgentChip({ handle, name, className, plain, }: {
37
+ handle: string;
38
+ name: ReactNode;
39
+ className?: string;
40
+ /** Mark and name only, no pill: for a header that already has its own surface. */
41
+ plain?: boolean;
42
+ }): import("react").JSX.Element;
27
43
  /**
28
44
  * The title and subtitle of an agent row. The title is a handle or a name, so it
29
45
  * yields past `max-w-40` and the subtitle (what the agent works on) keeps its room.
46
+ * With `handle`, the title is the agent itself: it renders as its chip, after
47
+ * `lead` when the row says something before the name ("To").
30
48
  */
31
- export declare function AgentTrigger({ title, subtitle }: {
49
+ export declare function AgentTrigger({ title, subtitle, handle, lead, trail, sessionId, detail, }: {
32
50
  title: string;
33
51
  subtitle?: string | null;
52
+ handle?: string;
53
+ lead?: string;
54
+ trail?: string;
55
+ /** The agent's own session: its chip then opens a hover card with the id and a link. */
56
+ sessionId?: string | null;
57
+ /** An agent without a session of its own: its chip's hover card shows these facts. */
58
+ detail?: AgentInlineDetail;
34
59
  }): import("react").JSX.Element;
35
60
  /**
36
61
  * The right edge of an agent row: the state glyph and its word, muted. A row
@@ -1,13 +1,17 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { ArrowUpRightIcon, CaretRightIcon } from '@phosphor-icons/react';
4
+ import { SolidCheckIcon } from '../../internal/icons/solid-check-icon.js';
4
5
  import { useContext, useId, useState } from 'react';
5
6
  import { useTranslations } from '../../i18n/index.js';
6
7
  import { AgentMarkGlyph, agentMarkTileClass, agentMarkVars } from '../../internal/components/agent-mark.js';
7
8
  import { cn } from '../../lib/utils.js';
8
9
  import { SessionStatusMark } from '../list/session-status-mark.js';
9
10
  import { TextShimmer } from '../../primitives/text-shimmer.js';
10
- import { BoundActivateContext, ToolOutcomeContext, ToolRunningContext, useToolOpen } from '../tool/shared/infrastructure-contexts.js';
11
+ import { Hint } from '../../primitives/hint.js';
12
+ import { BoundActivateContext, ToolOutcomeContext, ToolRunningContext, ToolStartedAtContext, useToolOpen } from '../tool/shared/infrastructure-contexts.js';
13
+ import { ToolSurfaceContext } from '../tool/shared/surface.js';
14
+ import { AgentHoverCard, AgentInlineHoverCard } from './agent-hover-card.js';
11
15
  /**
12
16
  * The parts every MyKortix agent surface in the chat is drawn from. An agent
13
17
  * call, an agent's finish, a message to or from another agent and a workflow
@@ -33,14 +37,48 @@ export function AgentFace({ handle, className }) {
33
37
  export function SmallGlyph({ status, label }) {
34
38
  return (_jsxs(_Fragment, { children: [_jsx("span", { "aria-hidden": true, className: "flex size-3.5 shrink-0 items-center justify-center [&>svg]:size-3.5", children: _jsx(SessionStatusMark, { status: status, waitingOn: "answer" }) }), label && _jsx("span", { className: "sr-only", children: label })] }));
35
39
  }
40
+ /**
41
+ * An agent as one chip: its pixel mark and its name in a full-round pill. The
42
+ * fill is the agent's colour (the mark's ink) at a medium tint, so every agent
43
+ * reads as its own colour, grey ones included; the name stays in the
44
+ * foreground ink. Every agent name on a MyKortix surface is this chip.
45
+ * A chip that leads a row starts on the row's left edge, where every other
46
+ * row's icon starts; that row draws no separate face.
47
+ */
48
+ export function AgentChip({ handle, name, className, plain = false, }) {
49
+ const slug = agentSlug(handle);
50
+ return (_jsxs("span", { "data-tone": "agent", "data-slot": "agent-chip", style: { ...agentMarkVars(slug), ...(plain ? {} : { backgroundColor: 'color-mix(in oklab, var(--mark-ink) 14%, transparent)' }) }, className: cn('text-foreground flex h-6 max-w-44 min-w-0 shrink-0 items-center gap-1.5 text-sm', !plain && 'rounded-full pr-2.5 pl-1.5', className), children: [_jsx("span", { className: "flex w-3.5 shrink-0 justify-center", children: _jsx(AgentMarkGlyph, { slug: slug, size: 14, trim: true }) }), _jsx("span", { className: "min-w-0 truncate", title: typeof name === 'string' ? name : undefined, children: name })] }));
51
+ }
52
+ /** A Kortix session id. An inline run's pi thread id (`ses_pi…`) has no session to open. */
53
+ const PROJECT_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
36
54
  /**
37
55
  * The title and subtitle of an agent row. The title is a handle or a name, so it
38
56
  * yields past `max-w-40` and the subtitle (what the agent works on) keeps its room.
57
+ * With `handle`, the title is the agent itself: it renders as its chip, after
58
+ * `lead` when the row says something before the name ("To").
39
59
  */
40
- export function AgentTrigger({ title, subtitle }) {
60
+ export function AgentTrigger({ title, subtitle, handle, lead, trail, sessionId, detail, }) {
41
61
  const running = useContext(ToolRunningContext);
42
- return (_jsxs(_Fragment, { children: [_jsx("span", { className: "text-foreground max-w-40 min-w-0 shrink-0 truncate text-sm", title: title, children: title }), subtitle &&
43
- (running ? (_jsx(TextShimmer, { className: "min-w-0 flex-1 truncate text-sm", children: subtitle })) : (_jsx("span", { className: "text-muted-foreground min-w-0 flex-1 truncate text-sm", title: subtitle, children: subtitle })))] }));
62
+ // The side panel is narrow: the name keeps its own line and what the agent
63
+ // works on reads below it, so neither is cut to a few letters.
64
+ const panel = useContext(ToolSurfaceContext) === 'panel';
65
+ const startedAt = useContext(ToolStartedAtContext);
66
+ const clock = panel && startedAt ? new Date(startedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : null;
67
+ // In the chat a role name ("Bike delivery operations researcher") keeps its words; the
68
+ // subtitle yields first. The narrow panel lets the chip shrink instead.
69
+ // The panel names the agent by its mark and name, no tinted pill.
70
+ const chip = handle ? _jsx(AgentChip, { handle: handle, name: title, plain: panel, className: panel ? 'max-w-none shrink' : 'max-w-64' }) : null;
71
+ const name = chip ? (sessionId && PROJECT_SESSION_ID.test(sessionId) ? (_jsx(AgentHoverCard, { sessionId: sessionId, name: title, className: panel ? 'shrink' : 'shrink-0', children: chip })) : detail ? (_jsx(AgentInlineHoverCard, { name: title, detail: detail, className: panel ? 'shrink' : 'shrink-0', children: chip })) : (chip)) : (_jsx("span", { className: "text-foreground max-w-40 min-w-0 shrink-0 truncate text-sm", title: title, children: title }));
72
+ const leadWord = lead && _jsx("span", { className: "text-foreground shrink-0 text-sm", children: `${lead} ` });
73
+ const trailWord = trail && _jsx("span", { className: "text-foreground shrink-0 text-sm", children: ` ${trail}` });
74
+ const sub = subtitle &&
75
+ (running ? (_jsx(TextShimmer, { className: "min-w-0 flex-1 truncate text-sm", children: subtitle })) : (_jsx("span", { className: "text-muted-foreground min-w-0 flex-1 truncate text-sm font-normal", title: subtitle, children: subtitle })));
76
+ if (panel) {
77
+ // To whom, then what, then when on the right edge. The message reads in
78
+ // full up to two lines, on the name's edge (past the 14px mark and its gap).
79
+ return (_jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-1.5", children: [leadWord, name, trailWord, clock && _jsx("span", { className: "text-muted-foreground ml-auto shrink-0 pl-2 text-xs font-normal tabular-nums", children: clock })] }), subtitle && (_jsx("p", { className: cn('text-muted-foreground line-clamp-2 text-sm font-normal whitespace-normal', chip && 'pl-5'), title: subtitle, children: subtitle }))] }));
80
+ }
81
+ return (_jsxs(_Fragment, { children: [leadWord, name, trailWord, sub] }));
44
82
  }
45
83
  /**
46
84
  * The right edge of an agent row: the state glyph and its word, muted. A row
@@ -48,6 +86,15 @@ export function AgentTrigger({ title, subtitle }) {
48
86
  */
49
87
  export function AgentStatus({ status, label, time, opens = false, }) {
50
88
  const open = useToolOpen();
89
+ // The side panel is narrow and its row draws its own disclosure caret: there
90
+ // the state is the glyph alone, its word a hint (and read aloud), so the
91
+ // agent's task keeps the width.
92
+ if (useContext(ToolSurfaceContext) === 'panel') {
93
+ // Done and working read from the glyph alone. Every other state (failed,
94
+ // refused, expired, needs you) shares a glyph with others, so its word stays.
95
+ const glyphOnly = status === 'done' || status === 'running';
96
+ return (_jsx(Hint, { label: time ? `${label} · ${time}` : label, side: "left", children: _jsxs("span", { "data-agent-status": status, className: "text-muted-foreground flex shrink-0 items-center gap-1.5 pl-1 text-xs", children: [status === 'done' ? (_jsxs(_Fragment, { children: [_jsx(SolidCheckIcon, { "aria-hidden": true, className: "size-3.5 shrink-0" }), _jsx("span", { className: "sr-only", children: label })] })) : (status && _jsx(SmallGlyph, { status: status, label: glyphOnly ? label : undefined })), (!glyphOnly || !status) && _jsx("span", { className: "whitespace-nowrap", children: label })] }) }));
97
+ }
51
98
  return (_jsxs("span", { "data-agent-status": status, className: "text-muted-foreground flex shrink-0 items-center gap-1.5 pl-3 text-xs", children: [status && _jsx(SmallGlyph, { status: status }), _jsx("span", { className: "whitespace-nowrap", children: label }), time && _jsx("span", { className: "tabular-nums", children: time }), _jsx(CaretRightIcon, { "aria-hidden": true, "data-slot": opens ? 'agent-row-caret' : undefined, className: cn('size-3 shrink-0 transition-transform duration-(--duration-fast) motion-reduce:transition-none', !opens && 'invisible', open && 'rotate-90') })] }));
52
99
  }
53
100
  /**
@@ -55,7 +102,11 @@ export function AgentStatus({ status, label, time, opens = false, }) {
55
102
  * of the 16px face), its text on the title's left edge, at the chat's reading size.
56
103
  */
57
104
  export function AgentRowBody({ children, className }) {
58
- return (_jsx("div", { className: cn('border-border ml-2 flex min-w-0 flex-col gap-2.5 border-l py-1 pl-3 text-sm', className), children: children }));
105
+ // The side panel's card already frames the body: no rail there.
106
+ const panel = useContext(ToolSurfaceContext) === 'panel';
107
+ return (
108
+ // In the panel the body starts on the message column, under the name.
109
+ _jsx("div", { className: cn('flex min-w-0 flex-col gap-2.5 text-sm', panel ? 'py-0.5 pl-5' : 'border-border ml-2 border-l py-1 pl-3', className), children: children }));
59
110
  }
60
111
  /**
61
112
  * The agent rows own their disclosure: a click opens the row in place. The chat
@@ -93,5 +144,5 @@ export function taskGlyphStatus(status) {
93
144
  }
94
145
  /** Who owns a task or sent a message: the agent's face and its handle. */
95
146
  export function AgentHandle({ handle }) {
96
- return (_jsxs("span", { className: "text-muted-foreground flex max-w-36 min-w-0 shrink-0 items-center gap-1.5", children: [_jsx(AgentFace, { handle: handle }), _jsxs("span", { className: "min-w-0 truncate", children: ["@", handle] })] }));
147
+ return (_jsx(AgentChip, { handle: handle, name: `@${handle}`, className: "max-w-36" }));
97
148
  }
@@ -3,7 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { Button } from '../../primitives/button.js';
4
4
  import { errorToast } from '../../primitives/toast.js';
5
5
  import { useTranslations } from '../../i18n/index.js';
6
- import { AgentFace, AgentStatus } from './agent-surface.js';
6
+ import { AgentChip, AgentStatus } from './agent-surface.js';
7
7
  import { peerHandleLabel } from '../../_vendor/kortix-shared.js';
8
8
  import { heldMessages } from '@kortix/sdk';
9
9
  import { usePeerMessages } from '@kortix/sdk/react';
@@ -14,7 +14,7 @@ export function HeldMessageCard({ message, pending, onApprove, onDeny }) {
14
14
  const shutdown = message.type === 'shutdown_request';
15
15
  // A decision, so a card: who, what it would deliver, and the two answers. The rest of the
16
16
  // agent surfaces are rows; this one waits on the person.
17
- return (_jsxs("div", { "data-held-message": message.id, "data-testid": "held-message-card", className: "border-border bg-background flex min-w-0 gap-1.5 rounded-lg border p-3 text-sm", children: [_jsx("span", { className: "flex h-5 shrink-0 items-center", children: _jsx(AgentFace, { handle: handle }) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2.5", children: [_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1", children: [_jsx("span", { className: "text-foreground max-w-40 min-w-0 truncate font-medium", title: name, children: name }), _jsx("span", { className: "text-muted-foreground min-w-0 flex-1", children: shutdown ? t('asksStop') : t('wantsToSend') }), _jsx(AgentStatus, { status: "needs-you", label: t('needsApproval') })] }), message.summary?.trim() && _jsx("p", { className: "text-muted-foreground", children: message.summary.trim() }), _jsx("p", { "data-slot": "held-message-body", className: "text-foreground max-h-60 overflow-y-auto whitespace-pre-wrap wrap-anywhere", children: message.message.trim() }), _jsxs("div", { className: "flex min-w-0 items-center gap-2", children: [_jsx("span", { className: "text-muted-foreground min-w-0 flex-1 truncate text-xs", children: t('expires') }), _jsx(Button, { type: "button", size: "xs", variant: "secondary", disabled: pending !== null, "aria-busy": pending === 'deny', onClick: onDeny, children: t('deny') }), _jsx(Button, { type: "button", size: "xs", disabled: pending !== null, "aria-busy": pending === 'approve', onClick: onApprove, children: t('approve') })] })] })] }));
17
+ return (_jsx("div", { "data-held-message": message.id, "data-testid": "held-message-card", className: "border-border bg-background flex min-w-0 gap-1.5 rounded-lg border p-3 text-sm", children: _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2.5", children: [_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1", children: [_jsx(AgentChip, { handle: handle, name: name }), _jsx("span", { className: "text-muted-foreground min-w-0 flex-1", children: shutdown ? t('asksStop') : t('wantsToSend') }), _jsx(AgentStatus, { status: "needs-you", label: t('needsApproval') })] }), message.summary?.trim() && _jsx("p", { className: "text-muted-foreground", children: message.summary.trim() }), _jsx("p", { "data-slot": "held-message-body", className: "text-foreground max-h-60 overflow-y-auto whitespace-pre-wrap wrap-anywhere", children: message.message.trim() }), _jsxs("div", { className: "flex min-w-0 items-center gap-2", children: [_jsx("span", { className: "text-muted-foreground min-w-0 flex-1 truncate text-xs", children: t('expires') }), _jsx(Button, { type: "button", size: "xs", variant: "secondary", disabled: pending !== null, "aria-busy": pending === 'deny', onClick: onDeny, children: t('deny') }), _jsx(Button, { type: "button", size: "xs", disabled: pending !== null, "aria-busy": pending === 'approve', onClick: onApprove, children: t('approve') })] })] }) }));
18
18
  }
19
19
  /** The held messages of `usePeerMessages(…, 'in')`, one card each; nothing when none waits. */
20
20
  export function HeldMessageList({ messages, approve, deny, }) {
@@ -22,7 +22,7 @@ import { useSessionIds } from '../../providers/session-ids.js';
22
22
  import { appendMentionRefs } from '../../internal/lib/project-preamble.js';
23
23
  import { SessionChatInput } from '../composer/session-chat-input.js';
24
24
  import { agentRowOf, isActive, shortElapsed } from './agent-model.js';
25
- import { AgentFace, AgentFailure } from './agent-surface.js';
25
+ import { AgentChip, AgentFailure } from './agent-surface.js';
26
26
  import { AgentStateMark } from './agent-state-mark.js';
27
27
  import { LegacySubagentChat } from './legacy-subagent-chat.js';
28
28
  import { SessionPeek } from './session-peek.js';
@@ -149,7 +149,7 @@ export function SubagentPanel({ sessionId, title, handle, projectId: projectIdPr
149
149
  // The chat row's state words ("Done", "Working"), so the row and its panel read the same.
150
150
  const stateText = sub.agent ? tAgent(`state.${sub.agent.state}`) : null;
151
151
  const elapsed = sub.agent?.state === 'working' && sub.agent.workingSinceMs !== null ? shortElapsed(now - sub.agent.workingSinceMs) : null;
152
- return (_jsxs("section", { "data-testid": "subagent-panel", "data-body": sub.kind, "aria-label": name, className: "flex h-full min-h-0 min-w-0 flex-col", children: [_jsxs("header", { className: cn(SESSION_BAR_CLASS, 'gap-2 px-3'), children: [leading, _jsxs(HoverCard, { openDelay: 300, closeDelay: 100, children: [_jsx(HoverCardTrigger, { asChild: true, children: _jsxs("div", { tabIndex: 0, className: "hover:bg-secondary focus-visible:ring-ring duration-fast -ml-1.5 flex h-8 min-w-0 cursor-default items-center gap-2 rounded-md px-1.5 transition-colors outline-none focus-visible:ring-2", children: [_jsx(AgentFace, { handle: face }), _jsx("h2", { "data-agent-state": sub.agent?.state, className: "text-foreground min-w-0 truncate text-sm font-semibold", children: name })] }) }), _jsxs(HoverCardContent, { side: "bottom", align: "start", sideOffset: 6, animated: false, className: "w-64 p-3", children: [_jsx("p", { className: "text-foreground truncate text-sm font-medium", children: name }), sub.agent ? (_jsxs("p", { className: "text-muted-foreground mt-1 flex items-center gap-1.5 text-xs tabular-nums", children: [_jsx(AgentStateMark, { state: sub.agent.state }), _jsx("span", { children: [stateText, elapsed].filter(Boolean).join(' · ') })] })) : null, task ? _jsx("p", { className: "text-muted-foreground border-border mt-2.5 line-clamp-3 border-t pt-2.5 text-xs text-pretty", children: task }) : null] })] }), _jsx("span", { className: "min-w-0 flex-1" }), _jsx(SubagentActions, { sub: sub, projectId: projectId, sessionId: sessionId, onLeave: onClose, children: _jsx(CloseAction, { onClose: onClose }) })] }), failure && (_jsx("div", { "data-testid": "subagent-panel-failure", className: "shrink-0 px-3 pb-2.5 text-sm", children: _jsx(AgentFailure, { sentence: tNotice('failedSentence'), raw: failure }) })), _jsx("div", { className: "flex min-h-0 flex-1 flex-col", children: _jsx(SubagentBody, { sub: sub, projectId: projectId, sessionId: sessionId, density: "compact" }) }), sub.kind === 'peek' && projectId && (_jsx(SubagentMessageBox, { projectId: projectId, sessionId: sessionId, name: name, onSent: sub.refreshRow, className: "px-3 pb-3", autoFocus: false }, sessionId))] }));
152
+ return (_jsxs("section", { "data-testid": "subagent-panel", "data-body": sub.kind, "aria-label": name, className: "flex h-full min-h-0 min-w-0 flex-col", children: [_jsxs("header", { className: cn(SESSION_BAR_CLASS, 'gap-2 px-3'), children: [leading, _jsxs(HoverCard, { openDelay: 300, closeDelay: 100, children: [_jsx(HoverCardTrigger, { asChild: true, children: _jsx("div", { tabIndex: 0, className: "hover:bg-secondary focus-visible:ring-ring duration-fast -ml-1.5 flex h-8 min-w-0 cursor-default items-center gap-2 rounded-md px-1.5 transition-colors outline-none focus-visible:ring-2", children: _jsx("h2", { "data-agent-state": sub.agent?.state, className: "flex min-w-0", children: _jsx(AgentChip, { handle: face, name: name, plain: true, className: "max-w-none" }) }) }) }), _jsxs(HoverCardContent, { side: "bottom", align: "start", sideOffset: 6, animated: false, className: "w-64 p-3", children: [_jsx("p", { className: "text-foreground truncate text-sm font-medium", children: name }), sub.agent ? (_jsxs("p", { className: "text-muted-foreground mt-1 flex items-center gap-1.5 text-xs tabular-nums", children: [_jsx(AgentStateMark, { state: sub.agent.state }), _jsx("span", { children: [stateText, elapsed].filter(Boolean).join(' · ') })] })) : null, task ? _jsx("p", { className: "text-muted-foreground border-border mt-2.5 line-clamp-3 border-t pt-2.5 text-xs text-pretty", children: task }) : null] })] }), _jsx("span", { className: "min-w-0 flex-1" }), _jsx(SubagentActions, { sub: sub, projectId: projectId, sessionId: sessionId, onLeave: onClose, children: _jsx(CloseAction, { onClose: onClose }) })] }), failure && (_jsx("div", { "data-testid": "subagent-panel-failure", className: "shrink-0 px-3 pb-2.5 text-sm", children: _jsx(AgentFailure, { sentence: tNotice('failedSentence'), raw: failure }) })), _jsx("div", { className: "flex min-h-0 flex-1 flex-col", children: _jsx(SubagentBody, { sub: sub, projectId: projectId, sessionId: sessionId, density: "compact" }) }), sub.kind === 'peek' && projectId && (_jsx(SubagentMessageBox, { projectId: projectId, sessionId: sessionId, name: name, onSent: sub.refreshRow, className: "px-3 pb-3", autoFocus: false }, sessionId))] }));
153
153
  }
154
154
  function SessionPeekRowError({ onRetry }) {
155
155
  const t = useTranslations('multiAgent.subagent');
@@ -9,6 +9,8 @@ import { ModelConnectionLayoutContext } from '../models/model-connection-layout.
9
9
  import { ImagesUnsupportedBar, ModelConnectionBar } from '../models/model-connection-gate.js';
10
10
  import { AnimatedComposerPlaceholder } from './animated-placeholder.js';
11
11
  import { AttachmentTiles } from './attachment-tiles.js';
12
+ import { DictationControl } from './dictation/dictation-control.js';
13
+ import { useComposerDictation } from './dictation/use-composer-dictation.js';
12
14
  import { EMPTY_AGENTS, EMPTY_COMMANDS, EMPTY_MODELS, EMPTY_SLASH_FILES, EMPTY_VARIANTS, } from './composer.js';
13
15
  import { shouldFocusEditorFromPadding } from './composer-logic.js';
14
16
  import { ComposerToolbar } from './composer-toolbar.js';
@@ -67,6 +69,7 @@ agents = EMPTY_AGENTS, commands = EMPTY_COMMANDS, slashFiles = EMPTY_SLASH_FILES
67
69
  drawing itself (`ChatInputOverridesProvider`). Off, nothing here changes.
68
70
  */
69
71
  const chatInputEnabled = useFeatureFlag(projectId ?? null, 'chat_input').enabled;
72
+ const dictation = useComposerDictation({ projectId, editorRef });
70
73
  // Inside a space the `@` menu is its people and agents (`menus/space-mentions.ts`).
71
74
  const spaceMentions = useContext(SpaceMentionContext);
72
75
  const chatInputOpen = agentMenuOpen || modelMenuOpen || reasoningMenuOpen;
@@ -173,5 +176,5 @@ agents = EMPTY_AGENTS, commands = EMPTY_COMMANDS, slashFiles = EMPTY_SLASH_FILES
173
176
  toolbarSlot: inlineUnderbar ? toolbarSlot : undefined, rewind: rewind, isSending: isSending, isBusy: isBusy, onStop: onStop, stopDisabled: stopDisabled, canStop: canStop, escCount: escCount, lockForQuestion: lockForQuestion, questionButtonLabel: questionButtonLabel, submitLabel: submitLabel, questionCanAct: questionCanAct, hasText: !isEmpty, canSubmit: canSubmit, submitDisabled: submitDisabled ||
174
177
  attachmentFailed ||
175
178
  modelRejectingImages !== null ||
176
- commandAttachmentPlan.kind === 'refuse', attachmentFailed: attachmentFailed, attachmentUnsupported: imagesUnsupportedReason, disabled: disabled, modelUnavailable: modelUnavailable, agentUnavailable: agentUnavailable, call: call, onSubmit: () => handleSubmit() })] })] })] }), _jsx(ImagesUnsupportedBar, { modelName: noModelsConnected ? null : modelRejectingImages }), inlineUnderbar ? null : (_jsx(ComposerUnderbar, { hideAgentPicker: hideAgentPicker, onAttachClick: handleAttachClick, agents: primaryAgents, selectedAgent: selectedAgent, onAgentChange: onAgentChange, agentMenuOpen: agentMenuOpen, onAgentMenuOpenChange: setAgentMenuOpen, noAccessibleAgents: noAccessibleAgents, agentLocked: agentLocked, messages: messages, models: models, selectedModel: availableSelectedModel, onContextClick: onContextClick, toolbarSlot: toolbarSlot, agentsSlot: underbarSlot, chatInput: chatInput })), connectionsAbove ? null : _jsx(ModelConnectionBar, { show: noModelsConnected }), slashMenuPlacement === 'below' && (_jsx("div", { id: dockId, className: "absolute top-full right-4 left-4 z-99 mt-3.5" }))] }));
179
+ commandAttachmentPlan.kind === 'refuse', attachmentFailed: attachmentFailed, attachmentUnsupported: imagesUnsupportedReason, disabled: disabled, modelUnavailable: modelUnavailable, agentUnavailable: agentUnavailable, call: call, dictation: dictation ? _jsx(DictationControl, { dictation: dictation, disabled: disabled }) : undefined, dictationActive: !!dictation && dictation.phase !== 'idle' && dictation.phase !== 'starting', onSubmit: () => handleSubmit() })] })] })] }), _jsx(ImagesUnsupportedBar, { modelName: noModelsConnected ? null : modelRejectingImages }), inlineUnderbar ? null : (_jsx(ComposerUnderbar, { hideAgentPicker: hideAgentPicker, onAttachClick: handleAttachClick, agents: primaryAgents, selectedAgent: selectedAgent, onAgentChange: onAgentChange, agentMenuOpen: agentMenuOpen, onAgentMenuOpenChange: setAgentMenuOpen, noAccessibleAgents: noAccessibleAgents, agentLocked: agentLocked, messages: messages, models: models, selectedModel: availableSelectedModel, onContextClick: onContextClick, toolbarSlot: toolbarSlot, agentsSlot: underbarSlot, chatInput: chatInput })), connectionsAbove ? null : _jsx(ModelConnectionBar, { show: noModelsConnected }), slashMenuPlacement === 'below' && (_jsx("div", { id: dockId, className: "absolute top-full right-4 left-4 z-99 mt-3.5" }))] }));
177
180
  }
@@ -123,6 +123,13 @@ export interface ComposerToolbarProps {
123
123
  attachmentUnsupported?: string | null;
124
124
  /** The host's voice call, offered in Send's place on an empty composer. See `SendStopControl`. */
125
125
  call?: ComposerCall;
126
+ /** The microphone (`DictationControl`), drawn right before Send. */
127
+ dictation?: React.ReactNode;
128
+ /**
129
+ * A dictation take is running: its Done button is the primary action, so
130
+ * Send steps aside. Stop stays while a turn runs.
131
+ */
132
+ dictationActive?: boolean;
126
133
  onSubmit: () => void;
127
134
  }
128
- export declare function ComposerToolbar({ collapsed, models, modelsLoading, selectedModel, onModelChange, modelDefaultControls, providers, modelRequired, modelMenuOpen, onModelMenuOpenChange, reasoningMenuOpen, onReasoningMenuOpenChange, variants, selectedVariant, onVariantChange, projectId, toolbarSlot, rewind, leading, pickersInChatInput, noModel, isSending, isBusy, onStop, stopDisabled, canStop, escCount, lockForQuestion, questionButtonLabel, submitLabel, questionCanAct, hasText, canSubmit, submitDisabled, disabled, modelUnavailable, agentUnavailable, attachmentFailed, attachmentUnsupported, call, onSubmit, }: ComposerToolbarProps): import("react").JSX.Element;
135
+ export declare function ComposerToolbar({ collapsed, models, modelsLoading, selectedModel, onModelChange, modelDefaultControls, providers, modelRequired, modelMenuOpen, onModelMenuOpenChange, reasoningMenuOpen, onReasoningMenuOpenChange, variants, selectedVariant, onVariantChange, projectId, toolbarSlot, rewind, leading, pickersInChatInput, noModel, isSending, isBusy, onStop, stopDisabled, canStop, escCount, lockForQuestion, questionButtonLabel, submitLabel, questionCanAct, hasText, canSubmit, submitDisabled, disabled, modelUnavailable, agentUnavailable, attachmentFailed, attachmentUnsupported, call, dictation, dictationActive, onSubmit, }: ComposerToolbarProps): import("react").JSX.Element;
@@ -10,7 +10,7 @@ import Loading from '../../primitives/loading.js';
10
10
  import { ModelSelector } from '../models/model-selector.js';
11
11
  import { ReasoningEffortSelector } from './reasoning-effort-selector.js';
12
12
  import { SendStopControl } from './send-stop-control.js';
13
- export function ComposerToolbar({ collapsed = false, models, modelsLoading, selectedModel, onModelChange, modelDefaultControls, providers, modelRequired, modelMenuOpen, onModelMenuOpenChange, reasoningMenuOpen, onReasoningMenuOpenChange, variants, selectedVariant, onVariantChange, projectId, toolbarSlot, rewind, leading, pickersInChatInput = false, noModel = false, isSending, isBusy, onStop, stopDisabled, canStop, escCount, lockForQuestion, questionButtonLabel, submitLabel, questionCanAct, hasText, canSubmit, submitDisabled, disabled, modelUnavailable, agentUnavailable = false, attachmentFailed = false, attachmentUnsupported = null, call, onSubmit, }) {
13
+ export function ComposerToolbar({ collapsed = false, models, modelsLoading, selectedModel, onModelChange, modelDefaultControls, providers, modelRequired, modelMenuOpen, onModelMenuOpenChange, reasoningMenuOpen, onReasoningMenuOpenChange, variants, selectedVariant, onVariantChange, projectId, toolbarSlot, rewind, leading, pickersInChatInput = false, noModel = false, isSending, isBusy, onStop, stopDisabled, canStop, escCount, lockForQuestion, questionButtonLabel, submitLabel, questionCanAct, hasText, canSubmit, submitDisabled, disabled, modelUnavailable, agentUnavailable = false, attachmentFailed = false, attachmentUnsupported = null, call, dictation, dictationActive = false, onSubmit, }) {
14
14
  const tI18nComplete = useTranslations('hardcodedUi.i18nComplete');
15
15
  const { modelPickerEnabled } = useUiHostConfig();
16
16
  const showModel = !noModel && !pickersInChatInput && modelPickerEnabled && (models.length > 0 || modelRequired) && !!onModelChange;
@@ -28,5 +28,5 @@ export function ComposerToolbar({ collapsed = false, models, modelsLoading, sele
28
28
  // become the row's first and last columns, either side of the editor.
29
29
  _jsxs("div", { className: cn('kortix-composer-toolbar overflow-visible', collapsed ? 'contents' : 'flex items-center justify-between gap-1'), children: [_jsxs("div", { className: cn('flex min-w-0 items-center gap-1 overflow-visible', collapsed && 'col-start-1 row-start-1'), children: [leading, showModel && (_jsx(ModelSelector, { models: models, modelsLoading: modelsLoading, selectedModel: selectedModel, onSelect: onModelChange, providers: providers, defaultControls: modelDefaultControls, triggerLabelClassName: "max-w-[7rem]", projectId: projectId, offerProviderAccounts: true, open: pickerOpen, onOpenChange: onPickerOpenChange, reasoning: { variants, selectedVariant, onVariantChange } })), !showModel && !noModel && modelPickerEnabled && !pickersInChatInput && _jsx(ReasoningEffortSelector, { variants: variants, selectedVariant: selectedVariant, onVariantChange: onVariantChange, open: reasoningMenuOpen, onOpenChange: onReasoningMenuOpenChange })] }), _jsxs("div", { className: cn('flex shrink-0 items-center gap-1.5', collapsed && 'col-start-3 row-start-1'), children: [rewind && (_jsxs(HoverCard, { openDelay: 0, closeDelay: 0, children: [_jsx(HoverCardTrigger, { asChild: true, children: _jsx("span", { className: "inline-flex", children: _jsxs(Button, { type: "button", variant: "ghost", size: "sm", disabled: rewind.pending || rewind.disabled, onClick: rewind.onRestore, className: "text-muted-foreground hover:text-foreground gap-1.5", children: [rewind.pending ? (_jsx(Loading, { className: "size-3.5 shrink-0" })) : (_jsx(ArrowCounterClockwiseIcon, { className: "size-3.5 shrink-0" })), tI18nComplete.raw('texta76e13b98392')] }) }) }), _jsx(HoverCardContent, { className: "px-3 py-2 text-sm text-balance", children: rewind.disabled && !rewind.pending
30
30
  ? tI18nComplete.raw('text98433e61649a')
31
- : tI18nComplete.raw('text4c25090df9ea') })] })), toolbarSlot, _jsx(SendStopControl, { isSending: isSending, isBusy: isBusy, onStop: onStop, stopDisabled: stopDisabled, canStop: canStop, escCount: escCount, lockForQuestion: lockForQuestion, questionButtonLabel: questionButtonLabel, submitLabel: submitLabel, questionCanAct: questionCanAct, hasText: hasText, canSubmit: canSubmit, submitDisabled: submitDisabled, disabled: disabled, modelUnavailable: modelUnavailable, agentUnavailable: agentUnavailable, attachmentFailed: attachmentFailed, attachmentUnsupported: attachmentUnsupported, call: call, onSubmit: onSubmit })] })] }));
31
+ : tI18nComplete.raw('text4c25090df9ea') })] })), toolbarSlot, dictation, (!dictationActive || isBusy) && _jsx(SendStopControl, { isSending: isSending, isBusy: isBusy, onStop: onStop, stopDisabled: stopDisabled, canStop: canStop, escCount: escCount, lockForQuestion: lockForQuestion, questionButtonLabel: questionButtonLabel, submitLabel: submitLabel, questionCanAct: questionCanAct, hasText: hasText, canSubmit: canSubmit, submitDisabled: submitDisabled, disabled: disabled, modelUnavailable: modelUnavailable, agentUnavailable: agentUnavailable, attachmentFailed: attachmentFailed, attachmentUnsupported: attachmentUnsupported, call: call, onSubmit: onSubmit })] })] }));
32
32
  }
@@ -0,0 +1,10 @@
1
+ import type { ComposerDictation } from './use-composer-dictation.js';
2
+ /**
3
+ * The composer's microphone. Idle: one ghost button before Send. Recording:
4
+ * Discard, the live level, the time, and Done in its place. Done puts the
5
+ * words at the caret; Escape discards.
6
+ */
7
+ export declare function DictationControl({ dictation, disabled }: {
8
+ dictation: ComposerDictation;
9
+ disabled?: boolean;
10
+ }): import("react").JSX.Element;
@@ -0,0 +1,28 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { CheckIcon, MicrophoneIcon, XIcon } from '@phosphor-icons/react';
4
+ import { useReducedMotion } from 'motion/react';
5
+ import { useTranslations } from '../../../i18n/index.js';
6
+ import { cn } from '../../../lib/utils.js';
7
+ import { Button } from '../../../primitives/button.js';
8
+ import Hint from '../../../primitives/hint.js';
9
+ import Loading from '../../../primitives/loading.js';
10
+ import { DICTATION_BARS, formatElapsed } from './dictation-state.js';
11
+ /** The composer's other icon buttons: round, a press scale, color on hover. */
12
+ const ICON_BUTTON = 'shrink-0 rounded-full p-0 hit-area-3 text-muted-foreground hover:text-foreground transition-[color,background-color,scale] active:scale-[0.96] active:duration-(--duration-normal) duration-(--duration-fast) ease-out motion-reduce:active:scale-100';
13
+ /**
14
+ * The composer's microphone. Idle: one ghost button before Send. Recording:
15
+ * Discard, the live level, the time, and Done in its place. Done puts the
16
+ * words at the caret; Escape discards.
17
+ */
18
+ export function DictationControl({ dictation, disabled = false }) {
19
+ const t = useTranslations('dictation');
20
+ const reduceMotion = useReducedMotion();
21
+ const { phase } = dictation;
22
+ if (phase === 'idle' || phase === 'starting') {
23
+ return (_jsx(Hint, { side: "top", label: _jsxs("span", { className: "flex flex-col", children: [_jsx("span", { children: t('start') }), _jsx("span", { className: "text-muted-foreground", children: t('price', { credits: dictation.creditsPerMinute }) })] }), children: _jsx("span", { className: "inline-flex", children: _jsx(Button, { type: "button", variant: "ghost", size: "icon-base", "aria-label": t('start'), disabled: disabled || phase === 'starting', onClick: dictation.start, className: ICON_BUTTON, children: _jsx(MicrophoneIcon, { className: "size-4" }) }) }) }));
24
+ }
25
+ const transcribing = phase === 'transcribing';
26
+ const padded = [...Array(Math.max(0, DICTATION_BARS - dictation.levels.length)).fill(0), ...dictation.levels];
27
+ return (_jsxs("div", { className: "flex items-center gap-1", role: "group", "aria-label": t('recording'), children: [_jsx(Hint, { side: "top", label: t('discard'), children: _jsx("span", { className: "inline-flex", children: _jsx(Button, { type: "button", variant: "ghost", size: "icon-base", "aria-label": t('discard'), onClick: dictation.cancel, className: ICON_BUTTON, children: _jsx(XIcon, { className: "size-4" }) }) }) }), !reduceMotion && (_jsx("div", { "aria-hidden": true, className: cn('flex h-4 items-center gap-0.5', transcribing && 'text-muted-foreground'), children: padded.map((level, i) => (_jsx("span", { className: "bg-current w-0.5 rounded-full", style: { height: `${Math.round(2 + level * 14)}px` } }, i))) })), _jsx("span", { className: "text-muted-foreground min-w-9 text-right text-xs tabular-nums", "aria-live": "off", children: transcribing ? t('transcribing') : formatElapsed(dictation.elapsedMs) }), _jsx(Hint, { side: "top", label: t('finish'), children: _jsx("span", { className: "inline-flex", children: _jsx(Button, { type: "button", size: "icon-base", "aria-label": transcribing ? t('transcribing') : t('finish'), disabled: transcribing, onClick: dictation.finish, className: "shrink-0 rounded-full p-0 hit-area-3", children: transcribing ? _jsx(Loading, { className: "size-3.5 shrink-0" }) : _jsx(CheckIcon, { weight: "bold", className: "size-4" }) }) }) })] }));
28
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Dictation — pure rules for the composer's microphone (web and desktop).
3
+ * The recorder (`recorder.ts`) and the hook (`use-composer-dictation.ts`) hold
4
+ * the browser state; everything here is a value in, a value out.
5
+ */
6
+ /** Bars in the live level meter, newest on the right. */
7
+ export declare const DICTATION_BARS = 24;
8
+ /** The MIME type to record, or '' to let the browser choose. */
9
+ export declare function pickRecordingType(isTypeSupported: (type: string) => boolean): string;
10
+ /**
11
+ * A meter level (0..1) from the RMS of the last samples. Speech sits between
12
+ * about -45 and -10 dBFS; -60 dBFS and below is silence.
13
+ */
14
+ export declare function levelFromRms(rms: number): number;
15
+ export declare function pushLevel(history: readonly number[], level: number, bars?: number): number[];
16
+ /** `m:ss` for the recording timer: `0:07`, `1:05`, `10:00`. */
17
+ export declare function formatElapsed(ms: number): string;
18
+ /**
19
+ * The text to insert after `before` (the character left of the caret, or '').
20
+ * A word right before the caret gets a space; punctuation that opens the
21
+ * transcript joins it as written.
22
+ */
23
+ export declare function dictationInsert(before: string, text: string): string;
24
+ /** What went wrong with the microphone, from a `getUserMedia` refusal. */
25
+ export type MicrophoneProblem = 'denied' | 'missing' | 'busy' | 'unsupported';
26
+ export declare function microphoneProblem(error: unknown): MicrophoneProblem;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Dictation — pure rules for the composer's microphone (web and desktop).
3
+ * The recorder (`recorder.ts`) and the hook (`use-composer-dictation.ts`) hold
4
+ * the browser state; everything here is a value in, a value out.
5
+ */
6
+ /** Bars in the live level meter, newest on the right. */
7
+ export const DICTATION_BARS = 24;
8
+ /**
9
+ * The containers a browser may record, best first. Chrome, Edge, Firefox and
10
+ * Electron take WebM/Opus; Safari takes MP4/AAC. Whisper reads all of them.
11
+ */
12
+ const RECORDING_TYPES = [
13
+ 'audio/webm;codecs=opus',
14
+ 'audio/webm',
15
+ 'audio/mp4;codecs=mp4a.40.2',
16
+ 'audio/mp4',
17
+ 'audio/ogg;codecs=opus',
18
+ ];
19
+ /** The MIME type to record, or '' to let the browser choose. */
20
+ export function pickRecordingType(isTypeSupported) {
21
+ return RECORDING_TYPES.find((type) => {
22
+ try {
23
+ return isTypeSupported(type);
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }) ?? '';
29
+ }
30
+ /**
31
+ * A meter level (0..1) from the RMS of the last samples. Speech sits between
32
+ * about -45 and -10 dBFS; -60 dBFS and below is silence.
33
+ */
34
+ export function levelFromRms(rms) {
35
+ if (!Number.isFinite(rms) || rms <= 0)
36
+ return 0;
37
+ const db = 20 * Math.log10(rms);
38
+ return Math.max(0, Math.min(1, (db + 60) / 50));
39
+ }
40
+ export function pushLevel(history, level, bars = DICTATION_BARS) {
41
+ const next = [...history, level];
42
+ return next.length > bars ? next.slice(next.length - bars) : next;
43
+ }
44
+ /** `m:ss` for the recording timer: `0:07`, `1:05`, `10:00`. */
45
+ export function formatElapsed(ms) {
46
+ const total = Math.max(0, Math.floor(ms / 1000));
47
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
48
+ }
49
+ /**
50
+ * The text to insert after `before` (the character left of the caret, or '').
51
+ * A word right before the caret gets a space; punctuation that opens the
52
+ * transcript joins it as written.
53
+ */
54
+ export function dictationInsert(before, text) {
55
+ const words = text.trim();
56
+ if (!words)
57
+ return '';
58
+ if (!before || /\s/.test(before) || /^[,.;:!?)]/.test(words))
59
+ return words;
60
+ return ` ${words}`;
61
+ }
62
+ export function microphoneProblem(error) {
63
+ const name = error && typeof error === 'object' && 'name' in error ? String(error.name) : '';
64
+ if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError')
65
+ return 'denied';
66
+ if (name === 'NotFoundError' || name === 'OverconstrainedError' || name === 'DevicesNotFoundError')
67
+ return 'missing';
68
+ if (name === 'NotReadableError' || name === 'TrackStartError' || name === 'AbortError')
69
+ return 'busy';
70
+ return 'unsupported';
71
+ }
@@ -0,0 +1,30 @@
1
+ import { type MicrophoneProblem } from './dictation-state.js';
2
+ /** The microphone refused, with the reason a person can act on. */
3
+ export declare class MicrophoneError extends Error {
4
+ readonly problem: MicrophoneProblem;
5
+ constructor(problem: MicrophoneProblem);
6
+ }
7
+ /**
8
+ * One dictation's microphone: `MediaRecorder` for the clip, an `AnalyserNode`
9
+ * for the live level. `stop` resolves the clip; `cancel` drops it. Either one
10
+ * releases the microphone, so the browser's recording indicator goes out.
11
+ */
12
+ export declare class DictationRecorder {
13
+ private stream?;
14
+ private recorder?;
15
+ private context?;
16
+ private analyser?;
17
+ private chunks;
18
+ private readonly samples;
19
+ private released;
20
+ static supported(): boolean;
21
+ /** Asks for the microphone and starts recording. Throws `MicrophoneError`. */
22
+ start(): Promise<void>;
23
+ /** The microphone level now, 0..1. */
24
+ level(): number;
25
+ /** Ends the take and resolves the clip (empty when nothing was recorded). */
26
+ stop(): Promise<Blob>;
27
+ /** Drops the take and releases the microphone. */
28
+ cancel(): void;
29
+ private release;
30
+ }
@@ -0,0 +1,129 @@
1
+ import { desktopPlatform } from '../../../internal/lib/desktop-detect.js';
2
+ import { levelFromRms, microphoneProblem, pickRecordingType } from './dictation-state.js';
3
+ /** The microphone refused, with the reason a person can act on. */
4
+ export class MicrophoneError extends Error {
5
+ problem;
6
+ constructor(problem) {
7
+ super(`microphone ${problem}`);
8
+ this.problem = problem;
9
+ this.name = 'MicrophoneError';
10
+ }
11
+ }
12
+ // Speech, not music: the browser's own echo and noise handling, one channel.
13
+ const MICROPHONE = {
14
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 },
15
+ };
16
+ /** 32 kb/s Opus or AAC: ten minutes is about 2.4 MB, well under the 25 MB clip cap. */
17
+ const BITS_PER_SECOND = 32_000;
18
+ /**
19
+ * One dictation's microphone: `MediaRecorder` for the clip, an `AnalyserNode`
20
+ * for the live level. `stop` resolves the clip; `cancel` drops it. Either one
21
+ * releases the microphone, so the browser's recording indicator goes out.
22
+ */
23
+ export class DictationRecorder {
24
+ stream;
25
+ recorder;
26
+ context;
27
+ analyser;
28
+ chunks = [];
29
+ samples = new Float32Array(1024);
30
+ released = false;
31
+ static supported() {
32
+ if (typeof window === 'undefined' || typeof MediaRecorder === 'undefined' || !navigator.mediaDevices?.getUserMedia) {
33
+ return false;
34
+ }
35
+ // A macOS desktop build without the microphone entitlement never gets a
36
+ // microphone: macOS refuses it without a prompt. Such a build does not
37
+ // announce `microphone` on its bridge (apps/desktop-electron/src/preload.js).
38
+ if (desktopPlatform() === 'macos') {
39
+ return window.kortixDesktop?.microphone === true;
40
+ }
41
+ return true;
42
+ }
43
+ /** Asks for the microphone and starts recording. Throws `MicrophoneError`. */
44
+ async start() {
45
+ if (!DictationRecorder.supported())
46
+ throw new MicrophoneError('unsupported');
47
+ let stream;
48
+ try {
49
+ stream = await navigator.mediaDevices.getUserMedia(MICROPHONE);
50
+ }
51
+ catch (error) {
52
+ throw new MicrophoneError(microphoneProblem(error));
53
+ }
54
+ if (this.released) {
55
+ stream.getTracks().forEach((track) => track.stop());
56
+ return;
57
+ }
58
+ this.stream = stream;
59
+ const type = pickRecordingType((t) => MediaRecorder.isTypeSupported(t));
60
+ const recorder = new MediaRecorder(stream, {
61
+ ...(type ? { mimeType: type } : {}),
62
+ audioBitsPerSecond: BITS_PER_SECOND,
63
+ });
64
+ recorder.ondataavailable = (event) => {
65
+ if (event.data.size > 0)
66
+ this.chunks.push(event.data);
67
+ };
68
+ this.recorder = recorder;
69
+ // A slice a second: a long take is never held as one buffer only.
70
+ recorder.start(1000);
71
+ try {
72
+ const context = new AudioContext();
73
+ const analyser = context.createAnalyser();
74
+ analyser.fftSize = 1024;
75
+ context.createMediaStreamSource(stream).connect(analyser);
76
+ if (context.state === 'suspended')
77
+ void context.resume().catch(() => { });
78
+ this.context = context;
79
+ this.analyser = analyser;
80
+ }
81
+ catch {
82
+ // No meter is not a failure: the clip still records.
83
+ }
84
+ }
85
+ /** The microphone level now, 0..1. */
86
+ level() {
87
+ if (!this.analyser)
88
+ return 0;
89
+ this.analyser.getFloatTimeDomainData(this.samples);
90
+ let sum = 0;
91
+ for (const sample of this.samples)
92
+ sum += sample * sample;
93
+ return levelFromRms(Math.sqrt(sum / this.samples.length));
94
+ }
95
+ /** Ends the take and resolves the clip (empty when nothing was recorded). */
96
+ stop() {
97
+ const recorder = this.recorder;
98
+ if (!recorder || recorder.state === 'inactive') {
99
+ this.release();
100
+ return Promise.resolve(new Blob(this.chunks, { type: recorder?.mimeType || 'audio/webm' }));
101
+ }
102
+ return new Promise((resolve) => {
103
+ recorder.onstop = () => {
104
+ const clip = new Blob(this.chunks, { type: recorder.mimeType || 'audio/webm' });
105
+ this.release();
106
+ resolve(clip);
107
+ };
108
+ recorder.stop();
109
+ });
110
+ }
111
+ /** Drops the take and releases the microphone. */
112
+ cancel() {
113
+ this.chunks = [];
114
+ if (this.recorder && this.recorder.state !== 'inactive') {
115
+ this.recorder.onstop = null;
116
+ this.recorder.stop();
117
+ }
118
+ this.release();
119
+ }
120
+ release() {
121
+ this.released = true;
122
+ this.stream?.getTracks().forEach((track) => track.stop());
123
+ if (this.context && this.context.state !== 'closed')
124
+ void this.context.close().catch(() => { });
125
+ this.stream = undefined;
126
+ this.context = undefined;
127
+ this.analyser = undefined;
128
+ }
129
+ }
@@ -0,0 +1,25 @@
1
+ import { type RefObject } from 'react';
2
+ import type { ComposerEditorHandle } from '../editor/composer-editor.js';
3
+ export type DictationPhase = 'idle' | 'starting' | 'recording' | 'transcribing';
4
+ export interface ComposerDictation {
5
+ phase: DictationPhase;
6
+ /** Live meter levels (0..1), newest last. */
7
+ levels: number[];
8
+ elapsedMs: number;
9
+ maxSeconds: number;
10
+ creditsPerMinute: number;
11
+ start: () => void;
12
+ /** Stop recording and put the words into the composer. */
13
+ finish: () => void;
14
+ /** Drop the recording, or stop waiting for its text. */
15
+ cancel: () => void;
16
+ }
17
+ /**
18
+ * The composer's dictation, or null where it is not offered: no project, no
19
+ * microphone API, or a server without managed models (`available: false`).
20
+ * One recording at a time; the words land at the caret.
21
+ */
22
+ export declare function useComposerDictation({ projectId, editorRef, }: {
23
+ projectId: string | null | undefined;
24
+ editorRef: RefObject<ComposerEditorHandle | null>;
25
+ }): ComposerDictation | null;