@kortix/ui 0.15.10 → 0.15.11

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 (93) hide show
  1. package/dist/_vendor/kortix-shared.js +396 -2
  2. package/dist/_vendor/shared/app-config.d.ts +6 -30
  3. package/dist/_vendor/shared/channel-descriptors.d.ts +0 -34
  4. package/dist/_vendor/shared/channel-header.d.ts +2 -1
  5. package/dist/_vendor/shared/connector-sections.d.ts +0 -25
  6. package/dist/_vendor/shared/file-tags.d.ts +2 -1
  7. package/dist/_vendor/shared/pasted-content.d.ts +0 -4
  8. package/dist/_vendor/shared/pixel-mark.d.ts +0 -17
  9. package/dist/_vendor/shared/project-glyphs.d.ts +0 -1
  10. package/dist/customize/agents/agent-model-view.d.ts +11 -1
  11. package/dist/customize/agents/agent-model-view.js +12 -1
  12. package/dist/customize/agents/agent-page.js +19 -6
  13. package/dist/customize/agents/agent-tabs.d.ts +2 -0
  14. package/dist/customize/agents/agent-tabs.js +2 -0
  15. package/dist/customize/connectors/detail/connector-triggers.js +1 -1
  16. package/dist/customize/connectors/use-agent-access.d.ts +1 -0
  17. package/dist/customize/sections/component/teams-byo-wizard.js +4 -1
  18. package/dist/customize/triggers/runtime-triggers.js +13 -2
  19. package/dist/customize/triggers/schedule/event-trigger-copy.js +1 -1
  20. package/dist/customize/triggers/schedule/schedule-detail-sheet.js +5 -4
  21. package/dist/customize/triggers/schedule/then-fields.d.ts +5 -1
  22. package/dist/customize/triggers/schedule/then-fields.js +23 -3
  23. package/dist/customize/triggers/schedule/trigger-callouts.js +1 -1
  24. package/dist/customize/triggers/schedule/trigger-composer-logic.d.ts +27 -0
  25. package/dist/customize/triggers/schedule/trigger-composer-logic.js +51 -5
  26. package/dist/customize/triggers/schedule/trigger-composer.js +19 -13
  27. package/dist/customize/triggers/schedule/trigger-edit-logic.js +25 -5
  28. package/dist/customize/triggers/schedule/trigger-filter.d.ts +10 -3
  29. package/dist/customize/triggers/schedule/trigger-filter.js +7 -6
  30. package/dist/customize/triggers/schedule/trigger-readonly.js +1 -1
  31. package/dist/customize/triggers/schedule/trigger-runs-panel.js +1 -1
  32. package/dist/customize/triggers/schedule/when-event.js +1 -1
  33. package/dist/customize/triggers/schedule/when-schedule.d.ts +5 -1
  34. package/dist/customize/triggers/schedule/when-schedule.js +16 -1
  35. package/dist/customize/triggers/schedule-view.js +4 -2
  36. package/dist/i18n/en.d.ts +49 -0
  37. package/dist/i18n/en.js +57 -8
  38. package/dist/internal/layout/project-settings-nav.d.ts +17 -0
  39. package/dist/internal/layout/project-settings-nav.js +24 -0
  40. package/dist/internal/lib/capability-tab-routes.d.ts +8 -0
  41. package/dist/internal/lib/capability-tab-routes.js +11 -0
  42. package/dist/internal/stores/composer-prefill-store.d.ts +7 -0
  43. package/dist/internal/stores/composer-prefill-store.js +1 -0
  44. package/dist/session/actions/session-label.js +2 -2
  45. package/dist/session/agents/agent-strip.d.ts +10 -5
  46. package/dist/session/agents/agent-strip.js +40 -12
  47. package/dist/session/agents/held-messages.d.ts +6 -2
  48. package/dist/session/agents/held-messages.js +6 -3
  49. package/dist/session/composer/ComposerCard.js +4 -1
  50. package/dist/session/composer/agent-selector.d.ts +2 -0
  51. package/dist/session/composer/agent-selector.js +5 -0
  52. package/dist/session/composer/composer-chat-input.d.ts +1 -0
  53. package/dist/session/composer/composer-logic.d.ts +7 -0
  54. package/dist/session/composer/composer-logic.js +18 -0
  55. package/dist/session/composer/composer-reset.d.ts +8 -14
  56. package/dist/session/composer/composer-toolbar.d.ts +3 -1
  57. package/dist/session/composer/composer-toolbar.js +3 -3
  58. package/dist/session/composer/composer.d.ts +7 -0
  59. package/dist/session/composer/composer.js +17 -3
  60. package/dist/session/composer/editor/composer-editor.js +6 -4
  61. package/dist/session/header/session-site-header.d.ts +3 -1
  62. package/dist/session/header/session-site-header.js +3 -2
  63. package/dist/session/models/connect-model-step.d.ts +29 -0
  64. package/dist/session/models/connect-model-step.js +50 -0
  65. package/dist/session/models/use-workspace-model-gate.d.ts +11 -0
  66. package/dist/session/models/use-workspace-model-gate.js +62 -0
  67. package/dist/session/models/workspace-model-gate.d.ts +46 -0
  68. package/dist/session/models/workspace-model-gate.js +66 -0
  69. package/dist/session/prompts/session-connect-card.d.ts +63 -0
  70. package/dist/session/prompts/{session-connect-prompt.js → session-connect-card.js} +53 -42
  71. package/dist/session/thread/session-chat.js +294 -298
  72. package/dist/session/thread/transcript.d.ts +2 -1
  73. package/dist/session/thread/transcript.js +7 -3
  74. package/dist/session/tool/tool-part-renderer.js +7 -2
  75. package/dist/session/tool/tools/kortix-action-tool.js +10 -2
  76. package/dist/session/turn/turn-viewport.d.ts +66 -10
  77. package/dist/session/turn/turn-viewport.js +92 -12
  78. package/dist/session/turn/user-message.js +7 -5
  79. package/dist/styles.css +1 -1
  80. package/dist/test-utils/intl.d.ts +49 -0
  81. package/dist/workspace/admin/project-admin-dashboard.js +2 -4
  82. package/dist/workspace/home/existing-repo-setup-prompt.d.ts +5 -8
  83. package/dist/workspace/home/existing-repo-setup-prompt.js +16 -42
  84. package/dist/workspace/home/no-agent-home.d.ts +3 -1
  85. package/dist/workspace/home/no-agent-home.js +2 -2
  86. package/dist/workspace/layout/project-home.js +16 -9
  87. package/dist/workspace/sidebar/session-grouping.d.ts +1 -1
  88. package/dist/workspace/sidebar/session-grouping.js +1 -1
  89. package/dist/workspace/spaces/space-details-panel.js +2 -2
  90. package/dist/workspace/spaces/space-triggers.js +2 -2
  91. package/dist/workspace/spaces/space-view.js +11 -5
  92. package/package.json +15 -3
  93. package/dist/session/prompts/session-connect-prompt.d.ts +0 -40
@@ -14,7 +14,7 @@ import { cn } from '../../lib/utils.js';
14
14
  import { AgentStateMark } from './agent-state-mark.js';
15
15
  import { SubagentDialog } from './subagent-view.js';
16
16
  import { ArrowUpRightIcon, CaretUpIcon, SquareIcon } from '@phosphor-icons/react';
17
- import { useMemo, useState } from 'react';
17
+ import { useEffect, useMemo, useRef, useState } from 'react';
18
18
  import { useMutation, useQueryClient } from '@tanstack/react-query';
19
19
  import { stopProjectSession } from '@kortix/sdk';
20
20
  import { qk, useFeatureFlag, useNow, useSessionChildren, useSessionWorkflows, useTeamTasks, useTeammates, } from '@kortix/sdk/react';
@@ -37,8 +37,10 @@ import { isLargeRun, LargeRunBadge, useLiveWorkflowRun, useRestartAgent, Workflo
37
37
  * started nothing, and it never holds the composer: the agents run in their own
38
38
  * sessions, and the person keeps talking to this one.
39
39
  */
40
- /** How often the child list polls while the line is mounted. */
40
+ /** How often the child list polls while the session works. */
41
41
  const CHILDREN_POLL_MS = 5_000;
42
+ /** An idle session starts no agent: its children poll every 30 s. */
43
+ const IDLE_CHILDREN_POLL_MS = 30_000;
42
44
  /** A finished workflow run stays listed this long after it ended. */
43
45
  const RECENT_RUN_MS = 60 * 60_000;
44
46
  /** The popover lists at most this many runs. */
@@ -195,23 +197,45 @@ function WorkflowLineRow({ projectId, sessionId, run: listed, onOpen, }) {
195
197
  return (_jsxs("li", { "data-testid": "agents-line-row", "data-workflow-run": run.runId, children: [_jsxs("div", { className: "group/row hover:bg-hover focus-within:bg-hover flex min-w-0 items-center gap-1 rounded-sm", children: [_jsxs("button", { type: "button", "aria-expanded": open, onClick: () => setOpen((value) => !value), className: "flex min-w-0 flex-1 cursor-pointer items-center gap-2 py-1.5 pl-2 text-left text-xs outline-none", children: [_jsx(RunProgressRing, { done: counts.done, failed: counts.failed, total: Math.max(counts.total, 1), ended: run.status === 'done' ? 'done' : run.status === 'stopped' ? 'stopped' : undefined }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex min-w-0 items-baseline gap-2", children: [_jsx("span", { className: "text-foreground min-w-0 truncate font-medium", title: title, children: title }), _jsx("span", { className: "text-muted-foreground shrink-0", children: t(`state.${RUN_STATE[run.status]}`) })] }), line && _jsx("p", { className: "text-muted-foreground truncate tabular-nums", children: line })] })] }), isLargeRun(run) && _jsx(LargeRunBadge, {}), _jsxs("div", { className: cn(ROW_ACTIONS, 'pr-1'), children: [run.background && (_jsx(Hint, { label: t('openRun'), side: "top", children: _jsx(Button, { type: "button", variant: "ghost", size: "icon-xs", "aria-label": t('openRun'), onClick: () => onOpen({ sessionId: run.background.sessionId, title }), className: "text-muted-foreground hover:text-foreground", children: _jsx(ArrowUpRightIcon, { className: "size-3.5 shrink-0" }) }) })), _jsx(WorkflowRunControls, { projectId: projectId, controlSessionId: live ? controlSessionId : undefined, ownerSessionId: sessionId, run: run })] })] }), open && run.agents.length > 0 && (_jsx("div", { className: "pl-5", children: _jsx(WorkflowRunRows, { run: run, live: live, now: now, onOpen: (agent) => agent.sessionId && onOpen({ sessionId: agent.sessionId, title: agent.label }), stop: stop }) })), open && run.agents.length === 0 && (_jsx(Badge, { variant: "muted", size: "sm", className: "ml-7", children: t('runNoAgents') }))] }));
196
198
  }
197
199
  /**
198
- * The agents of one session, read live: its children (polled every 5 s), its
199
- * teammates and team tasks (flag `agent_teams`) and its workflow runs; and the
200
- * stop of one agent.
200
+ * The agents of one session, read live: its children, its teammates and team
201
+ * tasks (flag `agent_teams`) and its workflow runs; and the stop of one agent.
202
+ * The lists poll every 5 s while the session works (`live`) and every 30 s
203
+ * while it is idle.
201
204
  */
202
- export function useAgentsLine(projectId, sessionId) {
205
+ export function useAgentsLine(projectId, sessionId, { live = false } = {}) {
203
206
  const t = useTranslations('multiAgent.strip');
204
207
  const pid = projectId ?? '';
205
208
  const sid = sessionId ?? '';
206
209
  const ready = !!projectId && !!sessionId;
207
210
  const teams = useFeatureFlag(projectId, 'agent_teams').enabled;
208
- const childList = useSessionChildren(pid, sid, { enabled: ready, refetchInterval: CHILDREN_POLL_MS, limit: 50 });
211
+ // A child or teammate can keep working after the lead's turn ends: the lists
212
+ // stay at 5 s while any of them works.
213
+ const [agentsActive, setAgentsActive] = useState(false);
214
+ const fast = live || agentsActive;
215
+ const childList = useSessionChildren(pid, sid, {
216
+ enabled: ready,
217
+ refetchInterval: fast ? CHILDREN_POLL_MS : IDLE_CHILDREN_POLL_MS,
218
+ limit: 50,
219
+ });
209
220
  const children = childList.sessions;
210
- const { data: teammates, dataUpdatedAt: teammatesAt } = useTeammates(projectId, sessionId, { enabled: ready && teams });
211
- const { data: tasks } = useTeamTasks(projectId, sessionId, { enabled: ready && teams });
212
- const { data: runData, dataUpdatedAt: runsAt } = useSessionWorkflows(projectId, sessionId, { enabled: ready });
221
+ const { data: teammates, dataUpdatedAt: teammatesAt } = useTeammates(projectId, sessionId, {
222
+ enabled: ready && teams,
223
+ live: fast,
224
+ });
225
+ const { data: tasks } = useTeamTasks(projectId, sessionId, { enabled: ready && teams, live: fast });
226
+ const { data: runData, dataUpdatedAt: runsAt } = useSessionWorkflows(projectId, sessionId, { enabled: ready, live: fast });
213
227
  const [stopping, setStopping] = useState(() => new Set());
214
228
  const queryClient = useQueryClient();
229
+ // A turn that ends may have started an agent or a run in its last seconds:
230
+ // read the lists once now instead of waiting for the next idle poll.
231
+ const wasLive = useRef(live);
232
+ useEffect(() => {
233
+ if (wasLive.current && !live && ready) {
234
+ void queryClient.invalidateQueries({ queryKey: qk.project.sessionChildren(pid, sid) });
235
+ void queryClient.invalidateQueries({ queryKey: qk.project.sessionAgents(pid, sid) });
236
+ }
237
+ wasLive.current = live;
238
+ }, [live, ready, pid, sid, queryClient]);
215
239
  const stopMutation = useMutation({
216
240
  mutationFn: (row) => stopProjectSession(pid, row.sessionId),
217
241
  onSettled: (_data, _error, row) => {
@@ -234,6 +258,10 @@ export function useAgentsLine(projectId, sessionId) {
234
258
  exclude: runSessionIds(runs),
235
259
  now,
236
260
  }), [sid, children, teammates, runs, now]);
261
+ const anyActive = [...groups.agents, ...groups.team].some((row) => row.state === 'working');
262
+ // Adjusted during render (React's derived-state pattern): the lists read it next render.
263
+ if (anyActive !== agentsActive)
264
+ setAgentsActive(anyActive);
237
265
  const leadsTeam = teams && ((teammates?.length ?? 0) > 0 || (tasks?.length ?? 0) > 0);
238
266
  return {
239
267
  ready,
@@ -253,8 +281,8 @@ export function useAgentsLine(projectId, sessionId) {
253
281
  * (`SessionChatInputProps.underbarSlot`). Nothing renders while the session
254
282
  * started no agent and no workflow run.
255
283
  */
256
- export function AgentsLine({ projectId, sessionId, compact = false, }) {
257
- const line = useAgentsLine(projectId, sessionId);
284
+ export function AgentsLine({ projectId, sessionId, compact = false, live = false, }) {
285
+ const line = useAgentsLine(projectId, sessionId, { live });
258
286
  const [open, setOpen] = useState(null);
259
287
  if (!line.ready)
260
288
  return null;
@@ -21,9 +21,13 @@ export declare function HeldMessageList({ messages, approve, deny, }: {
21
21
  approve: PeerMessagesQuery['approve'];
22
22
  deny: PeerMessagesQuery['deny'];
23
23
  }): import("react").JSX.Element | null;
24
- /** A session's held messages, read on their own (for a host without the agent strip). */
25
- export declare function HeldMessages({ projectId, sessionId }: {
24
+ /**
25
+ * A session's held messages, read on their own (for a host without the agent
26
+ * strip). They poll every 5 s while the session works (`live`), every 30 s idle.
27
+ */
28
+ export declare function HeldMessages({ projectId, sessionId, live, }: {
26
29
  projectId: string | undefined;
27
30
  sessionId: string | undefined;
31
+ live?: boolean;
28
32
  }): import("react").JSX.Element;
29
33
  export {};
@@ -26,8 +26,11 @@ export function HeldMessageList({ messages, approve, deny, }) {
26
26
  const fail = (key) => (error) => errorToast(t(key), { description: error instanceof Error ? error.message : undefined });
27
27
  return (_jsx("div", { "aria-label": t('label'), role: "group", className: "space-y-1.5", children: held.map((message) => (_jsx(HeldMessageCard, { message: message, pending: pendingFor(message.id), onApprove: () => approve.mutate(message.id, { onError: fail('approveFailed') }), onDeny: () => deny.mutate(message.id, { onError: fail('denyFailed') }) }, message.id))) }));
28
28
  }
29
- /** A session's held messages, read on their own (for a host without the agent strip). */
30
- export function HeldMessages({ projectId, sessionId }) {
31
- const { data, approve, deny } = usePeerMessages(projectId, sessionId, 'in');
29
+ /**
30
+ * A session's held messages, read on their own (for a host without the agent
31
+ * strip). They poll every 5 s while the session works (`live`), every 30 s idle.
32
+ */
33
+ export function HeldMessages({ projectId, sessionId, live = false, }) {
34
+ const { data, approve, deny } = usePeerMessages(projectId, sessionId, 'in', { live });
32
35
  return _jsx(HeldMessageList, { messages: data, approve: approve, deny: deny });
33
36
  }
@@ -14,6 +14,7 @@ import { shouldFocusEditorFromPadding } from './composer-logic.js';
14
14
  import { ComposerToolbar } from './composer-toolbar.js';
15
15
  import { ComposerUnderbar } from './composer-underbar.js';
16
16
  import { ChatInputOverridesProvider } from './chat-input/chat-input-overrides.js';
17
+ import { resolveProgramAgent } from './agent-selector.js';
17
18
  import { useUiHostConfig } from '../../providers/ui-provider.js';
18
19
  /** What the attach picker offers when the host names no list. */
19
20
  const DEFAULT_ATTACH_ACCEPT = 'image/*,.pdf,.txt,.md,.json,.csv,.xml,.yaml,.yml,.toml,.js,.ts,.jsx,.tsx,.py,.rb,.go,.rs,.java,.c,.cpp,.h,.css,.html,.vue,.svelte,.log,.sql,.zip,.tar,.gz,.rar';
@@ -41,6 +42,8 @@ agents = EMPTY_AGENTS, commands = EMPTY_COMMANDS, slashFiles = EMPTY_SLASH_FILES
41
42
  // Inside a space the `@` menu is its people and agents (`menus/space-mentions.ts`).
42
43
  const spaceMentions = useContext(SpaceMentionContext);
43
44
  const chatInputOpen = agentMenuOpen || modelMenuOpen || reasoningMenuOpen;
45
+ // A program agent (`run` in kortix.yaml) has no model: its listing names provider `program`.
46
+ const programAgent = resolveProgramAgent(primaryAgents, selectedAgent);
44
47
  const chatInput = useMemo(() => {
45
48
  if (!chatInputEnabled)
46
49
  return undefined;
@@ -118,7 +121,7 @@ agents = EMPTY_AGENTS, commands = EMPTY_COMMANDS, slashFiles = EMPTY_SLASH_FILES
118
121
  // the div and immediately fights the caret we are placing.
119
122
  e.preventDefault();
120
123
  editorRef.current?.focus();
121
- }, children: [_jsx(AnimatedComposerPlaceholder, { placeholder: editorPlaceholder, active: animatePlaceholder }), _jsx(Suspense, { fallback: _jsx(ComposerEditorFallback, {}), children: _jsx(ComposerEditorLazy, { ref: setEditorRef, placeholder: animatePlaceholder ? '' : editorPlaceholder, disabled: editorDisabled, onSubmit: handleSubmit, onArrowUpAtStart: handleArrowUpAtStart, onArrowDownAtEnd: handleArrowDownAtEnd, onEmptyChange: setIsEmpty, onDocChange: handleDocChange, agents: agents, sessions: allSessions ?? [], currentSessionId: sessionId, spaceMentions: spaceMentions, commands: commands, actions: slashActions, files: slashFiles, onSelectAction: handleSelectAction, slashDockSelector: `#${dockId}`, onMenuOpenChange: setMenuOpen }) })] }), _jsx("input", { ref: fileInputRef, type: "file", accept: attachAccept ?? DEFAULT_ATTACH_ACCEPT, multiple: true, className: "hidden", onChange: handleFileSelect }), _jsx(ComposerToolbar, { leading: inlineUnderbar ? (_jsx(ComposerUnderbar, { variant: "inline", agentPickerCompact: agentPickerCompact, onAttachClick: handleAttachClick, agents: primaryAgents, selectedAgent: selectedAgent, onAgentChange: onAgentChange, agentMenuOpen: agentMenuOpen, onAgentMenuOpenChange: setAgentMenuOpen, noAccessibleAgents: noAccessibleAgents, agentLocked: agentLocked, messages: messages, models: models, selectedModel: availableSelectedModel, onContextClick: onContextClick, agentsSlot: underbarSlot, chatInput: chatInput })) : null, pickersInChatInput: chatInputEnabled, modelsLoading: modelsLoading, models: models, selectedModel: availableSelectedModel, onModelChange: onModelChange, modelDefaultControls: modelDefaultControls, providers: providers, modelRequired: modelRequired, modelMenuOpen: modelMenuOpen, onModelMenuOpenChange: setModelMenuOpen, reasoningMenuOpen: reasoningMenuOpen, onReasoningMenuOpenChange: setReasoningMenuOpen, variants: variants, selectedVariant: selectedVariant, onVariantChange: onVariantChange, projectId: projectId,
124
+ }, children: [_jsx(AnimatedComposerPlaceholder, { placeholder: editorPlaceholder, active: animatePlaceholder }), _jsx(Suspense, { fallback: _jsx(ComposerEditorFallback, {}), children: _jsx(ComposerEditorLazy, { ref: setEditorRef, placeholder: animatePlaceholder ? '' : editorPlaceholder, disabled: editorDisabled, onSubmit: handleSubmit, onArrowUpAtStart: handleArrowUpAtStart, onArrowDownAtEnd: handleArrowDownAtEnd, onEmptyChange: setIsEmpty, onDocChange: handleDocChange, agents: agents, sessions: allSessions ?? [], currentSessionId: sessionId, spaceMentions: spaceMentions, commands: commands, actions: slashActions, files: slashFiles, onSelectAction: handleSelectAction, slashDockSelector: `#${dockId}`, onMenuOpenChange: setMenuOpen }) })] }), _jsx("input", { ref: fileInputRef, type: "file", accept: attachAccept ?? DEFAULT_ATTACH_ACCEPT, multiple: true, className: "hidden", onChange: handleFileSelect }), _jsx(ComposerToolbar, { noModel: programAgent, leading: inlineUnderbar ? (_jsx(ComposerUnderbar, { variant: "inline", agentPickerCompact: agentPickerCompact, onAttachClick: handleAttachClick, agents: primaryAgents, selectedAgent: selectedAgent, onAgentChange: onAgentChange, agentMenuOpen: agentMenuOpen, onAgentMenuOpenChange: setAgentMenuOpen, noAccessibleAgents: noAccessibleAgents, agentLocked: agentLocked, messages: messages, models: models, selectedModel: availableSelectedModel, onContextClick: onContextClick, agentsSlot: underbarSlot, chatInput: chatInput })) : null, pickersInChatInput: chatInputEnabled, modelsLoading: modelsLoading, models: models, selectedModel: availableSelectedModel, onModelChange: onModelChange, modelDefaultControls: modelDefaultControls, providers: providers, modelRequired: modelRequired, modelMenuOpen: modelMenuOpen, onModelMenuOpenChange: setModelMenuOpen, reasoningMenuOpen: reasoningMenuOpen, onReasoningMenuOpenChange: setReasoningMenuOpen, variants: variants, selectedVariant: selectedVariant, onVariantChange: onVariantChange, projectId: projectId,
122
125
  // Inline placement has no under-row, so the slot (the session
123
126
  // overrides gear, meta indicator) rides the toolbar itself. With
124
127
  // the 'below' placement the ComposerUnderbar further down renders
@@ -14,6 +14,8 @@ export declare const FeaturedAgentsContext: import("react").Context<{
14
14
  * else the first selectable agent. One rule for the trigger and the chat composer.
15
15
  */
16
16
  export declare function resolveDisplayedAgentName(primaryAgents: Agent[], selectedAgent: string | null): string;
17
+ /** Is the displayed agent a program agent (`run`)? Its runtime listing names provider `program`: it has no model to pick. */
18
+ export declare function resolveProgramAgent(primaryAgents: Agent[], selectedAgent: string | null): boolean;
17
19
  /** The label `AgentSelector` shows for a selection (null = nothing picked). Other surfaces that name the agent reuse it. */
18
20
  export declare function agentDisplayLabel(agents: Agent[], selectedAgent: string | null): string;
19
21
  /**
@@ -36,6 +36,11 @@ export function resolveDisplayedAgentName(primaryAgents, selectedAgent) {
36
36
  const current = primaryAgents.find((a) => a.name === selectedAgent);
37
37
  return current?.name ?? selectedAgent ?? primaryAgents[0]?.name;
38
38
  }
39
+ /** Is the displayed agent a program agent (`run`)? Its runtime listing names provider `program`: it has no model to pick. */
40
+ export function resolveProgramAgent(primaryAgents, selectedAgent) {
41
+ const name = resolveDisplayedAgentName(primaryAgents, selectedAgent);
42
+ return primaryAgents.find((a) => a.name === name)?.model?.providerID === 'program';
43
+ }
39
44
  /** The label `AgentSelector` shows for a selection (null = nothing picked). Other surfaces that name the agent reuse it. */
40
45
  export function agentDisplayLabel(agents, selectedAgent) {
41
46
  const name = resolveDisplayedAgentName(composerSelectableAgents(agents), selectedAgent);
@@ -67,6 +67,7 @@ export declare function ComposerChatInput({ onSend, onCommand, sessionId, projec
67
67
  id: number;
68
68
  files?: AttachedFile[];
69
69
  mode?: 'replace' | 'merge';
70
+ restoreDraft?: boolean;
70
71
  options?: SessionPromptOverrides | null;
71
72
  submit?: boolean | 'when-ready';
72
73
  } | null;
@@ -194,6 +194,13 @@ export declare function planPrefillMerge(input: {
194
194
  /** `editorRef.current.isEmpty()`. */
195
195
  currentIsEmpty: boolean;
196
196
  }): JSONContent | null;
197
+ /**
198
+ * `doc` with `text` added to the end of its last paragraph (or in a new
199
+ * paragraph when the last block is not one). Keys typed before the editor
200
+ * existed continue the restored draft this way (`prefill.restoreDraft`).
201
+ * `text` must be non-empty: ProseMirror text nodes cannot be empty.
202
+ */
203
+ export declare function appendTextToDocument(doc: JSONContent, text: string): JSONContent;
197
204
  export interface ShouldApplyPrefillInput {
198
205
  /** `prefill?.id` — `undefined` means "no prefill at all". */
199
206
  prefillId: number | undefined;
@@ -194,6 +194,24 @@ export function planPrefillMerge(input) {
194
194
  const merged = mergeFailedSubmissionDocument(input.currentDoc, input.currentIsEmpty, input.prefillDoc, input.prefillIsEmpty);
195
195
  return merged === input.currentDoc ? null : merged;
196
196
  }
197
+ /**
198
+ * `doc` with `text` added to the end of its last paragraph (or in a new
199
+ * paragraph when the last block is not one). Keys typed before the editor
200
+ * existed continue the restored draft this way (`prefill.restoreDraft`).
201
+ * `text` must be non-empty: ProseMirror text nodes cannot be empty.
202
+ */
203
+ export function appendTextToDocument(doc, text) {
204
+ const content = [...(doc.content ?? [])];
205
+ const last = content[content.length - 1];
206
+ const node = { type: 'text', text };
207
+ if (last?.type === 'paragraph') {
208
+ content[content.length - 1] = { ...last, content: [...(last.content ?? []), node] };
209
+ }
210
+ else {
211
+ content.push({ type: 'paragraph', content: [node] });
212
+ }
213
+ return { ...doc, type: 'doc', content };
214
+ }
197
215
  /**
198
216
  * Whether a `prefill` prop should be applied right now.
199
217
  *
@@ -4,21 +4,15 @@ import type { AttachedFile } from './session-chat-input.js';
4
4
  *
5
5
  * - `true` — every in-thread composer. It stays mounted, so it resets in
6
6
  * place and revokes the local object URLs nobody references any more.
7
- * - `'text-only'` — project home. It clears like any other composer, so the
8
- * message visibly LEAVES the box, but it revokes nothing: the same local
9
- * URLs are what the instant shell draws its attachment previews from a
10
- * moment later, on the other side of the navigation.
7
+ * - `'text-only'` — a space composer (`space-view.tsx`). It clears like any
8
+ * other composer, so the message visibly LEAVES the box, but it revokes
9
+ * nothing: the same local URLs are what the new thread draws its
10
+ * attachment previews from a moment later.
11
11
  * - `false` — a composer that must keep the submitted draft on screen
12
- * untouched. Nothing clears and nothing is revoked.
13
- *
14
- * `'text-only'` exists because the two halves of `false` turned out to be
15
- * separate decisions. Project home held BOTH — text on screen and URLs alive —
16
- * for one reason (the URLs), and the text half was the visible cost: Enter left
17
- * the sentence sitting in a locked box under a spinner for the whole create
18
- * round trip (measured 1165ms end to end on localhost, `POST .../sessions`
19
- * alone 908ms; longer over a real network), which reads as a send that did not
20
- * happen. Splitting them lets the box empty at the keypress, like everywhere
21
- * else in the app, with the previews still intact when the shell takes over.
12
+ * untouched. Nothing clears and nothing is revoked. Project home is one:
13
+ * the sent message stays in the locked box under the spinner until the
14
+ * session page opens, so the user sees what is being sent and a refused
15
+ * send leaves the text in place.
22
16
  */
23
17
  export type ComposerSendReset = boolean | 'text-only';
24
18
  /**
@@ -94,6 +94,8 @@ export interface ComposerToolbarProps {
94
94
  leading?: React.ReactNode;
95
95
  /** The `chat_input` control holds model and effort: this toolbar draws neither. */
96
96
  pickersInChatInput?: boolean;
97
+ /** The agent runs a program (`run`), not a model: this toolbar draws neither model nor effort. */
98
+ noModel?: boolean;
97
99
  isSending: boolean;
98
100
  isBusy: boolean;
99
101
  onStop?: () => void;
@@ -121,4 +123,4 @@ export interface ComposerToolbarProps {
121
123
  call?: ComposerCall;
122
124
  onSubmit: () => void;
123
125
  }
124
- export declare function ComposerToolbar({ models, modelsLoading, selectedModel, onModelChange, modelDefaultControls, providers, modelRequired, modelMenuOpen, onModelMenuOpenChange, reasoningMenuOpen, onReasoningMenuOpenChange, variants, selectedVariant, onVariantChange, projectId, toolbarSlot, rewind, leading, pickersInChatInput, 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;
126
+ export declare function ComposerToolbar({ 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;
@@ -9,10 +9,10 @@ import Loading from '../../primitives/loading.js';
9
9
  import { ModelSelector } from '../models/model-selector.js';
10
10
  import { ReasoningEffortSelector } from './reasoning-effort-selector.js';
11
11
  import { SendStopControl } from './send-stop-control.js';
12
- export function ComposerToolbar({ models, modelsLoading, selectedModel, onModelChange, modelDefaultControls, providers, modelRequired, modelMenuOpen, onModelMenuOpenChange, reasoningMenuOpen, onReasoningMenuOpenChange, variants, selectedVariant, onVariantChange, projectId, toolbarSlot, rewind, leading, pickersInChatInput = false, isSending, isBusy, onStop, stopDisabled, canStop, escCount, lockForQuestion, questionButtonLabel, submitLabel, questionCanAct, hasText, canSubmit, submitDisabled, disabled, modelUnavailable, agentUnavailable = false, attachmentFailed = false, attachmentUnsupported = null, call, onSubmit, }) {
12
+ export function ComposerToolbar({ 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
13
  const tI18nComplete = useTranslations('hardcodedUi.i18nComplete');
14
14
  const { modelPickerEnabled } = useUiHostConfig();
15
- const showModel = !pickersInChatInput && modelPickerEnabled && (models.length > 0 || modelRequired) && !!onModelChange;
15
+ const showModel = !noModel && !pickersInChatInput && modelPickerEnabled && (models.length > 0 || modelRequired) && !!onModelChange;
16
16
  // Either `/` palette row opens the one merged popover.
17
17
  const pickerOpen = modelMenuOpen === undefined && reasoningMenuOpen === undefined
18
18
  ? undefined
@@ -22,7 +22,7 @@ export function ComposerToolbar({ models, modelsLoading, selectedModel, onModelC
22
22
  if (!next)
23
23
  onReasoningMenuOpenChange?.(false);
24
24
  };
25
- return (_jsxs("div", { className: "kortix-composer-toolbar flex items-center justify-between gap-1 overflow-visible", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-1 overflow-visible", 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 && modelPickerEnabled && !pickersInChatInput && _jsx(ReasoningEffortSelector, { variants: variants, selectedVariant: selectedVariant, onVariantChange: onVariantChange, open: reasoningMenuOpen, onOpenChange: onReasoningMenuOpenChange })] }), _jsxs("div", { className: "flex shrink-0 items-center gap-1.5", 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
25
+ return (_jsxs("div", { className: "kortix-composer-toolbar flex items-center justify-between gap-1 overflow-visible", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-1 overflow-visible", 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: "flex shrink-0 items-center gap-1.5", 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
26
26
  ? tI18nComplete.raw('text98433e61649a')
27
27
  : 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 })] })] }));
28
28
  }
@@ -205,6 +205,13 @@ export interface SessionChatInputProps {
205
205
  id: number;
206
206
  files?: AttachedFile[];
207
207
  mode?: 'replace' | 'merge';
208
+ /**
209
+ * Restore the saved draft first, then merge this text after it. Only the
210
+ * home typing buffer sets it (`use-home-typing-buffer.ts`): keys typed
211
+ * while the page loaded continue the draft. Any other prefill still wins
212
+ * over the draft.
213
+ */
214
+ restoreDraft?: boolean;
208
215
  /**
209
216
  * Submit the prefill once it has landed, exactly as if the person pressed
210
217
  * Enter. For one-click starters (the first chat's "Update memory"): the
@@ -25,7 +25,7 @@ import { ComposerCard } from './ComposerCard.js';
25
25
  import { handleBillingError } from '../../internal/lib/error-handler.js';
26
26
  import { attachedFileUploadId, attachmentsBlockSend, captureAttachmentSubmission, dispatchLatched, planAttachmentReplacement, refusedFilesToast, runComposerSend, heldTraySizes, splitComposerFiles, stageComposerFiles, takeNewBillingRefusals, } from './attachment-submission.js';
27
27
  import { draftWillRunCommand, planCommandAttachments, planUnresolvedCommandChip, readCommandChipLabel, } from './command-attachments.js';
28
- import { appendComposerQuote, classifyPaste, isUndoKey, popPasteUndo, extractReplyQuotes, nextPastedTextFileName, planDraftSubmission, planFailedSendRecovery, planPrefillMerge, planQuoteRequests, removeComposerQuote, resolveEditorPlaceholder, restoreComposerQuotes, shouldApplyPrefill, shouldSubmitPrefill, shouldSubmitWhenReady, textToDocument, } from './composer-logic.js';
28
+ import { appendComposerQuote, classifyPaste, isUndoKey, popPasteUndo, extractReplyQuotes, nextPastedTextFileName, planDraftSubmission, planFailedSendRecovery, planPrefillMerge, appendTextToDocument, planQuoteRequests, removeComposerQuote, resolveEditorPlaceholder, restoreComposerQuotes, shouldApplyPrefill, shouldSubmitPrefill, shouldSubmitWhenReady, textToDocument, } from './composer-logic.js';
29
29
  import { getContextUsage } from './context-ring.js';
30
30
  import { useComposerFocus } from './hooks/use-composer-focus.js';
31
31
  import { useMenuRevalidation } from './hooks/use-file-search.js';
@@ -310,7 +310,7 @@ function ComposerImpl(props) {
310
310
  quotes: quoteTexts,
311
311
  pastes,
312
312
  uploads: draftUploads,
313
- hasPrefill: !!prefill,
313
+ hasPrefill: !!prefill && !prefill.restoreDraft,
314
314
  onRestore: handleDraftRestore,
315
315
  });
316
316
  /**
@@ -743,11 +743,14 @@ function ComposerImpl(props) {
743
743
  const prefillText = prefill?.text ?? '';
744
744
  const prefillFiles = prefill?.files;
745
745
  const prefillMode = prefill?.mode;
746
+ const prefillRestoreDraft = prefill?.restoreDraft === true;
746
747
  const prefillSubmit = prefill?.submit === true;
747
748
  // `handleSubmit` is declared further down; the prefill effect reaches it
748
749
  // through this ref, bound in an effect right after that declaration.
749
750
  const handleSubmitRef = useRef(() => undefined);
750
751
  const submittedPrefillIdRef = useRef(null);
752
+ // An append is not idempotent: each `restoreDraft` prefill lands once.
753
+ const appendedPrefillIdRef = useRef(null);
751
754
  // The prefill id that landed in the editor: `'when-ready'` submits only after it.
752
755
  const [landedPrefillId, setLandedPrefillId] = useState(null);
753
756
  const onPrefillAppliedRef = useRef(onPrefillApplied);
@@ -774,7 +777,17 @@ function ComposerImpl(props) {
774
777
  const quoted = extractReplyQuotes(prefillText);
775
778
  const pasted = splitPastedContent(quoted.text);
776
779
  const incoming = { quotes: quoted.quotes, text: pasted.text };
777
- if (prefillMode === 'merge') {
780
+ if (prefillRestoreDraft) {
781
+ // Keys typed while the page loaded continue the restored draft, at its
782
+ // end, where the caret lands (`setDocument` focuses the end). The draft
783
+ // is already in the editor: `useComposerDraft`'s restore effect is
784
+ // declared above this one, so it runs first in the same commit.
785
+ if (incoming.text && appendedPrefillIdRef.current !== prefillId) {
786
+ appendedPrefillIdRef.current = prefillId;
787
+ editorRef.current?.setDocument(appendTextToDocument(editorRef.current?.getDocument() ?? EMPTY_DOCUMENT, incoming.text));
788
+ }
789
+ }
790
+ else if (prefillMode === 'merge') {
778
791
  const merged = planPrefillMerge({
779
792
  prefillDoc: textToDocument(incoming.text),
780
793
  prefillIsEmpty: incoming.text.length === 0,
@@ -850,6 +863,7 @@ function ComposerImpl(props) {
850
863
  prefillText,
851
864
  prefillFiles,
852
865
  prefillMode,
866
+ prefillRestoreDraft,
853
867
  prefillSubmit,
854
868
  editorElement,
855
869
  addPromptAttachments,
@@ -354,6 +354,9 @@ export const ComposerEditor = forwardRef(function ComposerEditor({ placeholder,
354
354
  role: 'textbox',
355
355
  'aria-multiline': 'true',
356
356
  'aria-label': t('messageInput'),
357
+ // A locale-free hook for code outside the composer that must know
358
+ // the editor exists (`use-home-typing-buffer.ts` in apps/web).
359
+ 'data-composer-editor': '',
357
360
  /**
358
361
  * `min-h-[3.5em]` — taller than one line by design. History: was
359
362
  * `1.5em` (exactly one line) on the reasoning that a taller floor
@@ -400,10 +403,9 @@ export const ComposerEditor = forwardRef(function ComposerEditor({ placeholder,
400
403
  * dev.kortix.com: clear at T, phantom write at T+406ms, and the next
401
404
  * visit to project home restored "Hi" into the composer.
402
405
  *
403
- * That composer clears now (`clearOnSend="text-only"`), so its phantom
404
- * write would carry an empty document. The guard stays: it is about
405
- * `setEditable`, and every composer that flips `disabled` mid-send is one
406
- * debounce away from the same bug.
406
+ * Project home keeps the sent text in the locked box again, so this
407
+ * guard is what keeps the message out of the saved draft. Every composer
408
+ * that flips `disabled` mid-send is one debounce away from the same bug.
407
409
  *
408
410
  * The view still refreshes — `setOptions` calls `view.updateState`
409
411
  * whether or not the event is emitted.
@@ -7,6 +7,8 @@ interface SessionSiteHeaderProps {
7
7
  parent?: {
8
8
  onOpen: () => void;
9
9
  };
10
+ /** The session works now: its child list polls every 5 s instead of every 30 s. */
11
+ live?: boolean;
10
12
  }
11
- export declare function SessionSiteHeader({ sessionId, sessionTitle, isMobileView, leadingAction, parent, }: SessionSiteHeaderProps): import("react").JSX.Element;
13
+ export declare function SessionSiteHeader({ sessionId, sessionTitle, isMobileView, leadingAction, parent, live, }: SessionSiteHeaderProps): import("react").JSX.Element;
12
14
  export {};
@@ -56,7 +56,7 @@ const DEV_TOOLS = [
56
56
  { view: 'desktop', label: 'Desktop', Icon: MonitorIcon },
57
57
  { view: 'files', label: 'Files', Icon: FolderSimpleIcon },
58
58
  ];
59
- export function SessionSiteHeader({ sessionId, sessionTitle, isMobileView, leadingAction, parent, }) {
59
+ export function SessionSiteHeader({ sessionId, sessionTitle, isMobileView, leadingAction, parent, live = false, }) {
60
60
  const tI18nHardcoded = useTranslations('hardcodedUi');
61
61
  const tHardcodedUi = useTranslations('hardcodedUi');
62
62
  const tPalette = useTranslations('commandPalette');
@@ -185,7 +185,8 @@ export function SessionSiteHeader({ sessionId, sessionTitle, isMobileView, leadi
185
185
  const subsessions = projectSession && !parent ? directSubsessions(projectSession) : [];
186
186
  const childSessions = useSessionChildren(projectId ?? '', projectSessionId ?? '', {
187
187
  enabled: isProjectSession && !parent,
188
- refetchInterval: 5_000,
188
+ // An idle session starts no child: poll every 30 s, every 5 s while it works.
189
+ refetchInterval: live ? 5_000 : 30_000,
189
190
  });
190
191
  const startRename = () => {
191
192
  if (canRename)
@@ -0,0 +1,29 @@
1
+ /** Where "Back to workspaces" goes: the chooser, never the door that reopens this workspace. */
2
+ export declare const CONNECT_MODEL_STEP_BACK_HREF = "/workspaces";
3
+ /**
4
+ * The "Connect a model" step: what every workspace page shows while the viewer
5
+ * can run no model (`useWorkspaceModelGate`). New workspaces land here right
6
+ * after setup, and the workspace opens on its own once a model works: the
7
+ * provider dialog's save refreshes the model list the gate reads.
8
+ *
9
+ * - The two plan tiles first (ChatGPT, Claude): most people already pay for
10
+ * one, and each opens the provider dialog with that provider expanded.
11
+ * - "Add provider key" opens the same dialog on its provider list.
12
+ * - "Upgrade plan" only for a viewer who may change the project's models,
13
+ * when the workspace's plan has no Kortix models
14
+ * (`model_access.requires_provider_key`) and billing is on.
15
+ * - Every member gets the tiles and the key: the gate is per viewer, and a
16
+ * member may connect a login or a key for themselves (the server refuses
17
+ * only a connection shared with everyone, 403). A member who cannot change
18
+ * the project's models also reads who can connect one for everyone.
19
+ *
20
+ * There is no skip: with no model, nothing in the workspace can run. "Back to
21
+ * workspaces" is the way out, to another workspace or to Log out.
22
+ *
23
+ * The host mounts the upgrade dialog (`GlobalUpgradeModal` in `apps/web`):
24
+ * "Upgrade plan" opens it through the upgrade store.
25
+ */
26
+ export declare function ConnectModelStep({ projectId, workspaceName, }: {
27
+ projectId: string;
28
+ workspaceName: string | null | undefined;
29
+ }): import("react").JSX.Element;
@@ -0,0 +1,50 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { CreditCardIcon, KeyIcon } from '@phosphor-icons/react';
4
+ import { useTranslations } from '../../i18n/index.js';
5
+ import { AuthFrame } from '../../internal/auth/auth-card-shell.js';
6
+ import { Rise, StepHeader } from '../../internal/auth/auth-primitives.js';
7
+ import { useAccountState } from '../../internal/billing/use-account-state.js';
8
+ import { Button } from '../../primitives/button.js';
9
+ import { UiLink } from '../../providers/ui-provider.js';
10
+ import { ModelConnectionLayoutContext } from './model-connection-layout.js';
11
+ import { ConnectPlanRows } from './subscription-offer.js';
12
+ import { useModelConnectionGate } from './use-model-connection-gate.js';
13
+ /** Where "Back to workspaces" goes: the chooser, never the door that reopens this workspace. */
14
+ export const CONNECT_MODEL_STEP_BACK_HREF = '/workspaces';
15
+ /**
16
+ * The "Connect a model" step: what every workspace page shows while the viewer
17
+ * can run no model (`useWorkspaceModelGate`). New workspaces land here right
18
+ * after setup, and the workspace opens on its own once a model works: the
19
+ * provider dialog's save refreshes the model list the gate reads.
20
+ *
21
+ * - The two plan tiles first (ChatGPT, Claude): most people already pay for
22
+ * one, and each opens the provider dialog with that provider expanded.
23
+ * - "Add provider key" opens the same dialog on its provider list.
24
+ * - "Upgrade plan" only for a viewer who may change the project's models,
25
+ * when the workspace's plan has no Kortix models
26
+ * (`model_access.requires_provider_key`) and billing is on.
27
+ * - Every member gets the tiles and the key: the gate is per viewer, and a
28
+ * member may connect a login or a key for themselves (the server refuses
29
+ * only a connection shared with everyone, 403). A member who cannot change
30
+ * the project's models also reads who can connect one for everyone.
31
+ *
32
+ * There is no skip: with no model, nothing in the workspace can run. "Back to
33
+ * workspaces" is the way out, to another workspace or to Log out.
34
+ *
35
+ * The host mounts the upgrade dialog (`GlobalUpgradeModal` in `apps/web`):
36
+ * "Upgrade plan" opens it through the upgrade store.
37
+ */
38
+ export function ConnectModelStep({ projectId, workspaceName, }) {
39
+ const t = useTranslations('sessionUi.modelGate');
40
+ const { canWriteProviders, openConnectProvider, openUpgrade, showUpgradeOption, modal } = useModelConnectionGate(undefined, { projectId });
41
+ const accountState = useAccountState();
42
+ const offerUpgrade = canWriteProviders &&
43
+ showUpgradeOption &&
44
+ accountState.data?.model_access?.requires_provider_key === true;
45
+ const name = workspaceName?.trim() || t('stepThisWorkspace');
46
+ const description = canWriteProviders
47
+ ? t(offerUpgrade ? 'stepBodyUpgrade' : 'stepBody', { workspace: name })
48
+ : t('stepBodyMember', { workspace: name });
49
+ return (_jsxs(AuthFrame, { footerVariant: "none", backHref: CONNECT_MODEL_STEP_BACK_HREF, children: [modal, _jsx(Rise, { children: _jsx(StepHeader, { title: t('stepTitle'), description: description }) }, "connect-model-header"), _jsx(Rise, { delay: 0.06, children: _jsxs("div", { className: "flex flex-col gap-5", "data-testid": "connect-model-step", children: [_jsx(ModelConnectionLayoutContext.Provider, { value: "above", children: _jsx(ConnectPlanRows, { projectId: projectId, dismissible: false, className: "sm:grid-cols-1" }) }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsxs(Button, { type: "button", variant: "outline", size: "lg", className: "w-full gap-1.5", onClick: () => openConnectProvider('providers'), children: [_jsx(KeyIcon, { className: "size-4 shrink-0" }), t('noModelAddProviderKey')] }), offerUpgrade ? (_jsxs(Button, { type: "button", variant: "outline", size: "lg", className: "w-full gap-1.5", onClick: openUpgrade, children: [_jsx(CreditCardIcon, { className: "size-4 shrink-0" }), t('noModelUpgradePlan')] })) : null, _jsx(Button, { asChild: true, variant: "ghost", size: "lg", className: "w-full", children: _jsx(UiLink, { href: CONNECT_MODEL_STEP_BACK_HREF, children: t('stepBack') }) })] })] }) }, "connect-model-body")] }));
50
+ }
@@ -0,0 +1,11 @@
1
+ import { type WorkspaceModelGateView } from './workspace-model-gate.js';
2
+ /**
3
+ * Whether `projectId` may open for the signed-in viewer: `'open'`,
4
+ * `'pending'` (no answer yet, and this browser never saw it ready) or
5
+ * `'blocked'` (no model can run). See `workspace-model-gate.ts` for the rules.
6
+ *
7
+ * Reads `/model-picker` through its shared cache entry
8
+ * (`qk.project.modelPicker`), the one the composer, the model picker and the
9
+ * shell prefetch read, so it adds no request to a workspace load.
10
+ */
11
+ export declare function useWorkspaceModelGate(projectId: string): WorkspaceModelGateView;
@@ -0,0 +1,62 @@
1
+ 'use client';
2
+ import { useQuery } from '@tanstack/react-query';
3
+ import { useEffect, useMemo } from 'react';
4
+ import { getWorkspaceModelPicker } from '@kortix/sdk';
5
+ import { contract, flattenModels, projectLlmCatalogToProviderList, qk, useFeatureFlag, } from '@kortix/sdk/react';
6
+ import { useUiViewerId } from '../../providers/ui-provider.js';
7
+ import { isRunnableModel } from './model-availability.js';
8
+ import { readModelReady, resolveWorkspaceModelGate, writeModelReady, } from './workspace-model-gate.js';
9
+ /**
10
+ * While the workspace is blocked, re-read the model list on this cadence, so a
11
+ * connection made elsewhere (another tab, another device, a person who manages
12
+ * the workspace) opens it without a reload. The same cadence as the access
13
+ * gate's approval poll. A connection made on this screen does not wait for
14
+ * it: the provider dialog's save invalidates the same query at once
15
+ * (`refreshWorkspaceProviderState`).
16
+ */
17
+ const BLOCKED_RECHECK_MS = 15_000;
18
+ /**
19
+ * Whether `projectId` may open for the signed-in viewer: `'open'`,
20
+ * `'pending'` (no answer yet, and this browser never saw it ready) or
21
+ * `'blocked'` (no model can run). See `workspace-model-gate.ts` for the rules.
22
+ *
23
+ * Reads `/model-picker` through its shared cache entry
24
+ * (`qk.project.modelPicker`), the one the composer, the model picker and the
25
+ * shell prefetch read, so it adds no request to a workspace load.
26
+ */
27
+ export function useWorkspaceModelGate(projectId) {
28
+ const viewerId = useUiViewerId();
29
+ // A program agent runs code instead of a model (flag `program_agents`), so a
30
+ // project that turned them on may work with no model at all.
31
+ const programAgents = useFeatureFlag(projectId, 'program_agents').enabled;
32
+ const enabled = !!projectId && !programAgents;
33
+ const query = useQuery({
34
+ queryKey: qk.project.modelPicker(projectId),
35
+ queryFn: () => getWorkspaceModelPicker(projectId),
36
+ enabled,
37
+ ...contract('config'),
38
+ retry: false,
39
+ refetchInterval: (current) => current.state.data && !flattenCatalog(current.state.data).some(isRunnableModel)
40
+ ? BLOCKED_RECHECK_MS
41
+ : false,
42
+ });
43
+ const models = useMemo(() => (query.data ? flattenCatalog(query.data) : undefined), [query.data]);
44
+ // Read once per viewer and workspace: the write below must not flip a
45
+ // decision that is already on screen.
46
+ const rememberedReady = useMemo(() => readModelReady(viewerId, projectId), [viewerId, projectId]);
47
+ const view = resolveWorkspaceModelGate({
48
+ enabled,
49
+ models,
50
+ failed: query.isError,
51
+ rememberedReady,
52
+ });
53
+ useEffect(() => {
54
+ // Only a server answer is recorded; a remembered or failed-open verdict is not.
55
+ if (enabled && models)
56
+ writeModelReady(viewerId, projectId, view === 'open');
57
+ }, [enabled, models, projectId, view, viewerId]);
58
+ return view;
59
+ }
60
+ function flattenCatalog(catalog) {
61
+ return flattenModels(projectLlmCatalogToProviderList(catalog));
62
+ }