@kortix/ui 0.15.3 → 0.15.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 (72) hide show
  1. package/dist/_vendor/kortix-shared.js +87 -29
  2. package/dist/_vendor/shared/markdown-math.d.ts +6 -0
  3. package/dist/customize/agents/agent-drives-section.d.ts +1 -3
  4. package/dist/customize/agents/agent-drives-section.js +3 -4
  5. package/dist/customize/agents/agent-page.js +2 -2
  6. package/dist/customize/agents/agent-tabs.d.ts +1 -1
  7. package/dist/customize/agents/agent-tabs.js +1 -2
  8. package/dist/customize/connectors/add-mcp/add-mcp-server-dialog.js +7 -2
  9. package/dist/customize/connectors/add-mcp/add-mcp-server.d.ts +7 -0
  10. package/dist/customize/connectors/add-mcp/add-mcp-server.js +3 -0
  11. package/dist/customize/connectors/connectors-page.d.ts +8 -0
  12. package/dist/customize/connectors/connectors-page.js +34 -1
  13. package/dist/customize/sections/view/agent-editor-access-fields.js +1 -3
  14. package/dist/files/project/components/drive-explorer.js +64 -43
  15. package/dist/files/project/components/drive-upload-tray.d.ts +2 -1
  16. package/dist/files/project/components/drive-upload-tray.js +9 -4
  17. package/dist/files/project/drop-tree.d.ts +16 -0
  18. package/dist/files/project/drop-tree.js +39 -0
  19. package/dist/files/project/upload-batch.d.ts +15 -0
  20. package/dist/files/project/upload-batch.js +12 -0
  21. package/dist/i18n/en.d.ts +16 -6
  22. package/dist/i18n/en.js +29 -19
  23. package/dist/internal/billing/use-cost-explorer.d.ts +19 -1
  24. package/dist/internal/billing/use-cost-explorer.js +27 -1
  25. package/dist/internal/lib/billing/billing-gate-state.d.ts +5 -6
  26. package/dist/internal/lib/billing/billing-gate-state.js +10 -11
  27. package/dist/internal/lib/browser-error-noise.d.ts +1 -1
  28. package/dist/internal/lib/browser-error-noise.js +1 -1
  29. package/dist/internal/lib/browser-noise/rules/injected-scripts.d.ts +5 -1
  30. package/dist/internal/lib/browser-noise/rules/injected-scripts.js +86 -0
  31. package/dist/internal/lib/mermaid-utils.js +2 -24
  32. package/dist/primitives/mermaid-render.js +3 -20
  33. package/dist/session/composer/ComposerCard.d.ts +1 -1
  34. package/dist/session/composer/ComposerCard.js +2 -2
  35. package/dist/session/composer/composer-chat-input.d.ts +14 -1
  36. package/dist/session/composer/composer-chat-input.js +4 -2
  37. package/dist/session/composer/composer-toolbar.d.ts +4 -1
  38. package/dist/session/composer/composer-toolbar.js +2 -2
  39. package/dist/session/composer/composer.d.ts +8 -0
  40. package/dist/session/composer/queue-projection.d.ts +10 -8
  41. package/dist/session/composer/queue-projection.js +10 -9
  42. package/dist/session/composer/send-stop-control.d.ts +15 -1
  43. package/dist/session/composer/send-stop-control.js +30 -5
  44. package/dist/session/composer/use-instant-session-send.js +2 -2
  45. package/dist/session/header/session-embed-menu-item.d.ts +12 -0
  46. package/dist/session/header/session-embed-menu-item.js +30 -0
  47. package/dist/{workspace/sidebar/modal/session-embed-section.d.ts → session/header/session-embed-snippet.d.ts} +2 -11
  48. package/dist/session/header/session-embed-snippet.js +21 -0
  49. package/dist/session/header/session-site-header.js +9 -2
  50. package/dist/session/models/ask-owner-for-credits-button.d.ts +7 -1
  51. package/dist/session/models/ask-owner-for-credits-button.js +3 -2
  52. package/dist/session/thread/session-chat.js +18 -7
  53. package/dist/session/voice/composer-call.d.ts +31 -0
  54. package/dist/session/voice/composer-call.js +46 -0
  55. package/dist/session/voice/voice-call-card.js +2 -0
  56. package/dist/session/voice/voice-call-store.d.ts +8 -0
  57. package/dist/session/voice/voice-call-store.js +5 -0
  58. package/dist/session/voice/voice-call.d.ts +2 -2
  59. package/dist/session/voice/voice-call.js +6 -6
  60. package/dist/test-utils/intl.d.ts +16 -6
  61. package/dist/workspace/home/existing-repo-setup-prompt.js +2 -3
  62. package/dist/workspace/instant-session-shell.js +11 -1
  63. package/dist/workspace/layout/project-home.js +24 -2
  64. package/dist/workspace/layout/use-project-home-call.d.ts +24 -0
  65. package/dist/workspace/layout/use-project-home-call.js +56 -0
  66. package/dist/workspace/new/workspace-name.d.ts +13 -0
  67. package/dist/workspace/new/workspace-name.js +20 -0
  68. package/dist/workspace/sidebar/footer/project-balance-warning.js +9 -6
  69. package/dist/workspace/sidebar/footer/sidebar-alert.d.ts +1 -1
  70. package/dist/workspace/sidebar/modal/share-session-modal.js +2 -3
  71. package/package.json +7 -7
  72. package/dist/workspace/sidebar/modal/session-embed-section.js +0 -71
@@ -203,6 +203,13 @@ var isChannelPlatform = (platform) => CHANNEL_PLATFORM_IDS.includes(platform);
203
203
  // ../manifest-schema/src/constants.ts
204
204
  var EVERY_GRANT = "*";
205
205
  var EVERY_GRANT_KEYS = ["tools", "skills", "subagents", "commands", "extensions", "connectors", "secrets", "apps", "kortix_permissions"];
206
+ function isEveryGrant(value) {
207
+ if (typeof value === "string") {
208
+ const v = value.trim().toLowerCase();
209
+ return v === "*" || v === "all";
210
+ }
211
+ return Array.isArray(value) && value.some((item) => typeof item === "string" && item.trim() === "*");
212
+ }
206
213
  var CHANNEL_PLATFORMS = CHANNEL_PLATFORM_IDS;
207
214
  ({
208
215
  ...Object.fromEntries(CHANNEL_PLATFORMS.map((platform) => [channelConnectorSlug(platform), "channel"]))});
@@ -285,6 +292,21 @@ function everyScalar() {
285
292
  node.type = Scalar.QUOTE_DOUBLE;
286
293
  return node;
287
294
  }
295
+ var REPOSITORY_READ_GRANT = "workspace.gitops.read";
296
+ function grantRepositoryRead(doc, block) {
297
+ const current = block.toJSON().kortix_permissions;
298
+ if (typeof current === "string" && isEveryGrant(current)) return;
299
+ if (typeof current === "string" && current.trim() !== "none") return;
300
+ if (Array.isArray(current)) {
301
+ if (current.some((entry) => entry === REPOSITORY_READ_GRANT || entry === "project.gitops.read")) return;
302
+ const node = block.get("kortix_permissions", true);
303
+ if (isSeq(node)) {
304
+ node.add(doc.createNode(REPOSITORY_READ_GRANT));
305
+ return;
306
+ }
307
+ }
308
+ block.set("kortix_permissions", doc.createNode([REPOSITORY_READ_GRANT]));
309
+ }
288
310
  var DEPRECATIONS = [
289
311
  {
290
312
  id: "drop-kortix-version",
@@ -353,6 +375,40 @@ var DEPRECATIONS = [
353
375
  return [`agents.${name}.workspace`];
354
376
  })
355
377
  },
378
+ {
379
+ id: "agent-workspace",
380
+ since: "2026-11-08",
381
+ summary: "`workspace: { project_repository }`, `workspace: branch | runtime | read` and `repository_access` are obsolete: a session never checks out the repository at boot. `project_repository: true` becomes `workspace.gitops.read` in `kortix_permissions`; clone explicitly with `workspace: { repos: [...] }` or `kortix workspaces clone`.",
382
+ apply: (doc) => {
383
+ const version = doc.get("kortix_version");
384
+ if (version === 1 || version === 2) return [];
385
+ return agentBlocks(doc).flatMap(([name, block]) => {
386
+ const workspace = block.toJSON().workspace;
387
+ const access = block.toJSON().repository_access;
388
+ const legacyString = typeof workspace === "string";
389
+ const legacyMap = typeof workspace === "object" && workspace !== null && !Array.isArray(workspace) && "project_repository" in workspace;
390
+ const hasAccess = block.has("repository_access");
391
+ if (!legacyString && !legacyMap && !hasAccess) return [];
392
+ const repository = workspace === "branch" || legacyMap && workspace.project_repository === true || !legacyString && !legacyMap && access === true;
393
+ if (repository) grantRepositoryRead(doc, block);
394
+ const paths = [];
395
+ if (hasAccess) {
396
+ deleteKeepingComments(block, "repository_access");
397
+ paths.push(`agents.${name}.repository_access`);
398
+ }
399
+ if (legacyString) {
400
+ deleteKeepingComments(block, "workspace");
401
+ paths.push(`agents.${name}.workspace`);
402
+ } else if (legacyMap) {
403
+ const map = block.get("workspace", true);
404
+ if (isMap(map)) map.delete("project_repository");
405
+ if (!isMap(map) || map.items.length === 0) deleteKeepingComments(block, "workspace");
406
+ paths.push(`agents.${name}.workspace`);
407
+ }
408
+ return paths;
409
+ });
410
+ }
411
+ },
356
412
  {
357
413
  id: "sandbox-templates",
358
414
  since: "2026-09-15",
@@ -2707,40 +2763,42 @@ function hasReferenceDefinitionOutsideFences(markdown, definition) {
2707
2763
  return definition.test(markdown.slice(runStart));
2708
2764
  }
2709
2765
  var KATEX_FENCE_LANGUAGES = /* @__PURE__ */ new Set(["katex", "latex", "math", "tex"]);
2766
+ var MERMAID_DIAGRAM_STARTERS = [
2767
+ "graph",
2768
+ "flowchart",
2769
+ "sequencediagram",
2770
+ "classdiagram",
2771
+ "statediagram",
2772
+ "erdiagram",
2773
+ "journey",
2774
+ "gantt",
2775
+ "pie",
2776
+ "gitgraph",
2777
+ "mindmap",
2778
+ "timeline",
2779
+ "sankey",
2780
+ "block",
2781
+ "quadrant",
2782
+ "requirement",
2783
+ "c4context",
2784
+ "c4container",
2785
+ "c4component",
2786
+ "c4dynamic"
2787
+ ];
2788
+ var MERMAID_CODE_STARTERS = [
2789
+ ...MERMAID_DIAGRAM_STARTERS,
2790
+ "commit",
2791
+ "branch",
2792
+ "checkout",
2793
+ "merge"
2794
+ ];
2710
2795
  function isMermaidCode(language, code) {
2711
2796
  if (!code?.trim()) return false;
2712
2797
  if (language === "mermaid") return true;
2713
2798
  if (!language || language === "text" || language === "plain") {
2714
2799
  const trimmed = code.trim();
2715
2800
  const firstLine = trimmed.split("\n")[0]?.toLowerCase().trim();
2716
- const mermaidStarters = [
2717
- "graph",
2718
- "flowchart",
2719
- "sequencediagram",
2720
- "classdiagram",
2721
- "statediagram",
2722
- "erdiagram",
2723
- "journey",
2724
- "gantt",
2725
- "pie",
2726
- "gitgraph",
2727
- "mindmap",
2728
- "timeline",
2729
- "sankey",
2730
- "block",
2731
- "quadrant",
2732
- "requirement",
2733
- "c4context",
2734
- "c4container",
2735
- "c4component",
2736
- "c4dynamic",
2737
- // Git graph specific patterns (gitgraph starts with these commands)
2738
- "commit",
2739
- "branch",
2740
- "checkout",
2741
- "merge"
2742
- ];
2743
- return mermaidStarters.some((starter) => firstLine.startsWith(starter.toLowerCase()));
2801
+ return MERMAID_CODE_STARTERS.some((starter) => firstLine.startsWith(starter.toLowerCase()));
2744
2802
  }
2745
2803
  return false;
2746
2804
  }
@@ -5709,4 +5767,4 @@ function parseWorkspaceSettingsSection(raw) {
5709
5767
  return Object.prototype.hasOwnProperty.call(WORKSPACE_SETTINGS_SECTION_ALIASES, value) ? WORKSPACE_SETTINGS_SECTION_ALIASES[value] : null;
5710
5768
  }
5711
5769
 
5712
- export { ARTIFACT_DOC_CSS, AVATAR_INK, CARD_TEXT_RATIO, CHANNELS, CHANNEL_PLATFORM_IDS, COMMIT_CONFIRM_ATTEMPTS, COMMIT_CONFIRM_DELAY_MS, CREDITS_PER_DOLLAR, CURATED_SECTIONS, HUMAN_ONLY, KATEX_FENCE_LANGUAGES, LANGUAGE_ALIASES, MAX_PROMPT_ATTACHMENTS_BYTES, MAX_PROMPT_ATTACHMENT_BYTES, MAX_PROMPT_ATTACHMENT_FILES, MAX_PROMPT_UPLOAD_FILENAME_BYTES, MY_KORTIX_AGENT_NAME, MY_KORTIX_DISPLAY_NAME, MY_KORTIX_SANDBOX_SLUG, OTHER, PASTED_INLINE_MAX_BYTES, PIXEL_KORTIX_ROWS, POLICY_SETS_UNSUPPORTED_PROVIDERS, POPULAR_SECTION, PREVIEW_BUILDING_STATES, PREVIEW_STATE_MESSAGE, PROJECT_GLYPH_COLORS, PROJECT_GLYPH_GROUPS, SPACE_POST_SUMMARY, UNKNOWN_RATIO, UPLOAD_LIMITS, WORKSPACE_SETTINGS_GROUPS, appAdminsOnly, autoLinkUrls, avatarFill, buildWebhookSampleRequest, capitalizeWords, cardImageShape, cardListLayout, chalkColors, channelPromptTail, confirmCommitted, countInSection, dollarsToCredits, editConfigPrompt, errorCode, escapeCurrencyDollars, expandPastedContent, extractReadableHtml, fileTagBlocks, fixManifestText, fnv1a, formatFileSize, formatRelative, formatUsdAsCredits, gridApps, groupIntoSections, hasReferenceDefinitionOutsideFences, humanizeCategory, indexOfIgnoreCase, isAllowedWebPushHost, isAmbiguousCreateFailure, isChannelFileLabel, isChannelPlatform, isMermaidCode, isMyKortixAgentName, isProjectGlyphColor, isProjectGlyphName, isProjectGlyphPaletteColor, languageLabel, looksLikeMarkdown, masonryColumns, neutralizePastedTags, newConfigPrompt, newPastedContentId, normalizeLanguage, normalizeLatexDelimiters, normalizeProjectGlyphColor, openMarkdownLinkAtEnd, parseBackgroundWorkers, parseBalanceUsd, parseChannelMessage, parseGrepOutput, parseManifestText, parseMemoryEntryOutput, parseMemorySearchOutput, parsePeerMessagePrompt, parseReminderPrompt, parseSessionGetOutput, parseSessionMessagesOutput, parseSessionMetadataOutput, parseSessionSearchHits, parseTriggerEvent, parseTriggerLines, parseWorkspaceSettingsSection, passesPixelMarkGate, peerHandleLabel, pixelMarkShape, policySetNameError, prefersPreviewLink, prepareMarkdownForKatex, prepareMarkdownForMath, promptFileReferenceXml, ptyOutputBlock, ptySpawnedBody, pushTypeOf, referenceHeaders, removeSpans, replaceSpans, resolveRegisteredKey, safeHttpUrl, sandboxMediaPath, sanitizePromptUploadFilename, sectionKeyForCategory, sectionKeysForEntry, sectionTitle, selfClosingTags, serializePromptWithPastes, shouldTilePaste, skillDocumentBody, slackPlainText, slugifySlug, spaceDriveFolders, spaceSlug, splitPastedContent, stripBashMetadata, stripChatMentionMarkup, stripMarkupForToolOutput, tagBlocks, toolRegistryCandidates, trimPastedText, truncateString, utf8Bytes, withoutEdgeQuotes, xmlBlocks };
5770
+ export { ARTIFACT_DOC_CSS, AVATAR_INK, CARD_TEXT_RATIO, CHANNELS, CHANNEL_PLATFORM_IDS, COMMIT_CONFIRM_ATTEMPTS, COMMIT_CONFIRM_DELAY_MS, CREDITS_PER_DOLLAR, CURATED_SECTIONS, HUMAN_ONLY, KATEX_FENCE_LANGUAGES, LANGUAGE_ALIASES, MAX_PROMPT_ATTACHMENTS_BYTES, MAX_PROMPT_ATTACHMENT_BYTES, MAX_PROMPT_ATTACHMENT_FILES, MAX_PROMPT_UPLOAD_FILENAME_BYTES, MERMAID_DIAGRAM_STARTERS, MY_KORTIX_AGENT_NAME, MY_KORTIX_DISPLAY_NAME, MY_KORTIX_SANDBOX_SLUG, OTHER, PASTED_INLINE_MAX_BYTES, PIXEL_KORTIX_ROWS, POLICY_SETS_UNSUPPORTED_PROVIDERS, POPULAR_SECTION, PREVIEW_BUILDING_STATES, PREVIEW_STATE_MESSAGE, PROJECT_GLYPH_COLORS, PROJECT_GLYPH_GROUPS, SPACE_POST_SUMMARY, UNKNOWN_RATIO, UPLOAD_LIMITS, WORKSPACE_SETTINGS_GROUPS, appAdminsOnly, autoLinkUrls, avatarFill, buildWebhookSampleRequest, capitalizeWords, cardImageShape, cardListLayout, chalkColors, channelPromptTail, confirmCommitted, countInSection, dollarsToCredits, editConfigPrompt, errorCode, escapeCurrencyDollars, expandPastedContent, extractReadableHtml, fileTagBlocks, fixManifestText, fnv1a, formatFileSize, formatRelative, formatUsdAsCredits, gridApps, groupIntoSections, hasReferenceDefinitionOutsideFences, humanizeCategory, indexOfIgnoreCase, isAllowedWebPushHost, isAmbiguousCreateFailure, isChannelFileLabel, isChannelPlatform, isMermaidCode, isMyKortixAgentName, isProjectGlyphColor, isProjectGlyphName, isProjectGlyphPaletteColor, languageLabel, looksLikeMarkdown, masonryColumns, neutralizePastedTags, newConfigPrompt, newPastedContentId, normalizeLanguage, normalizeLatexDelimiters, normalizeProjectGlyphColor, openMarkdownLinkAtEnd, parseBackgroundWorkers, parseBalanceUsd, parseChannelMessage, parseGrepOutput, parseManifestText, parseMemoryEntryOutput, parseMemorySearchOutput, parsePeerMessagePrompt, parseReminderPrompt, parseSessionGetOutput, parseSessionMessagesOutput, parseSessionMetadataOutput, parseSessionSearchHits, parseTriggerEvent, parseTriggerLines, parseWorkspaceSettingsSection, passesPixelMarkGate, peerHandleLabel, pixelMarkShape, policySetNameError, prefersPreviewLink, prepareMarkdownForKatex, prepareMarkdownForMath, promptFileReferenceXml, ptyOutputBlock, ptySpawnedBody, pushTypeOf, referenceHeaders, removeSpans, replaceSpans, resolveRegisteredKey, safeHttpUrl, sandboxMediaPath, sanitizePromptUploadFilename, sectionKeyForCategory, sectionKeysForEntry, sectionTitle, selfClosingTags, serializePromptWithPastes, shouldTilePaste, skillDocumentBody, slackPlainText, slugifySlug, spaceDriveFolders, spaceSlug, splitPastedContent, stripBashMetadata, stripChatMentionMarkup, stripMarkupForToolOutput, tagBlocks, toolRegistryCandidates, trimPastedText, truncateString, utf8Bytes, withoutEdgeQuotes, xmlBlocks };
@@ -40,6 +40,12 @@ export declare function hasReferenceDefinitionOutsideFences(markdown: string, de
40
40
  export declare const KATEX_FENCE_LANGUAGES: ReadonlySet<string>;
41
41
  /** True when a fence language renders as display math. Case-insensitive, as on web. */
42
42
  export declare function isMathFenceLanguage(language: string): boolean;
43
+ /**
44
+ * Mermaid diagram types: a fence whose first line starts with one of these
45
+ * renders as a Mermaid diagram. The web renderer's validators in `packages/ui`
46
+ * share this list.
47
+ */
48
+ export declare const MERMAID_DIAGRAM_STARTERS: readonly string[];
43
49
  /**
44
50
  * Detects if a code block contains Mermaid syntax
45
51
  */
@@ -18,10 +18,8 @@
18
18
  * wait for the page's Save. A folder that comes through the project is
19
19
  * changed in Files, where its sharing lives.
20
20
  */
21
- export declare function AgentDrivesSection({ projectId, agentName, repositoryAccess, }: {
21
+ export declare function AgentDrivesSection({ projectId, agentName, }: {
22
22
  projectId: string;
23
23
  /** Absent: the project's mounts (Project admin). */
24
24
  agentName?: string;
25
- /** Whether sessions of the agent get the project repository at /workspace. Agent mode only. */
26
- repositoryAccess?: boolean;
27
25
  }): import("react").JSX.Element;
@@ -40,14 +40,13 @@ import { CapabilityPageShell } from '../shared/capability-page-shell.js';
40
40
  * wait for the page's Save. A folder that comes through the project is
41
41
  * changed in Files, where its sharing lives.
42
42
  */
43
- export function AgentDrivesSection({ projectId, agentName, repositoryAccess = true, }) {
43
+ export function AgentDrivesSection({ projectId, agentName, }) {
44
44
  const t = useTranslations('agentMounts');
45
45
  const drive = useProjectDrive(projectId);
46
46
  const driveId = drive.data?.driveId ?? null;
47
47
  const agentPlan = useAgentMounts(agentName ? driveId : null, agentName ?? '');
48
48
  const projectPlan = useProjectMounts(agentName ? null : driveId);
49
49
  const plan = agentName ? agentPlan : projectPlan;
50
- const showRepository = !!agentName && repositoryAccess;
51
50
  const root = useFolderAccess(driveId, '/');
52
51
  // Mounting needs `manage` on the folder; someone who holds it at the top holds it below.
53
52
  const canMount = root.data?.access === 'manage';
@@ -59,11 +58,11 @@ export function AgentDrivesSection({ projectId, agentName, repositoryAccess = tr
59
58
  else if (drive.isError || plan.isError || !driveId || !plan.data) {
60
59
  body = (_jsx(ErrorState, { size: "sm", title: agentName ? t('loadError') : t('projectLoadError'), action: _jsx(Button, { variant: "outline", size: "sm", onClick: () => void plan.refetch(), children: t('retry') }) }));
61
60
  }
62
- else if (plan.data.mounts.length === 0 && !showRepository) {
61
+ else if (plan.data.mounts.length === 0) {
63
62
  body = (_jsx(EmptyState, { media: _jsx(EmptyArt, { icon: HardDrivesIcon }), title: t('emptyTitle'), description: agentName ? t('emptyDescription') : t('projectEmptyDescription') }));
64
63
  }
65
64
  else {
66
- body = (_jsxs("div", { className: "space-y-3", children: [_jsxs(EditorList, { children: [showRepository ? (_jsxs("li", { className: "flex min-h-12 items-center gap-3 px-4 py-2", children: [_jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("code", { className: "text-foreground block truncate font-mono text-sm", children: "/workspace" }), _jsx("span", { className: "text-muted-foreground block truncate text-xs", children: t('repository') })] }), _jsx("span", { className: "text-muted-foreground shrink-0 text-xs", children: t('readWrite') })] })) : null, plan.data.mounts.map((mount) => (_jsx(MountRow, { driveId: driveId, agentName: agentName, mount: mount }, mount.path)))] }), plan.data.skipped.length > 0 ? (_jsx("p", { className: "text-muted-foreground text-xs text-pretty", children: t('skipped', { slots: plan.data.slots, list: plan.data.skipped.join(', ') }) })) : null] }));
65
+ body = (_jsxs("div", { className: "space-y-3", children: [_jsx(EditorList, { children: plan.data.mounts.map((mount) => (_jsx(MountRow, { driveId: driveId, agentName: agentName, mount: mount }, mount.path))) }), plan.data.skipped.length > 0 ? (_jsx("p", { className: "text-muted-foreground text-xs text-pretty", children: t('skipped', { slots: plan.data.slots, list: plan.data.skipped.join(', ') }) })) : null] }));
67
66
  }
68
67
  return (_jsxs(CapabilityPageShell, { title: t('title'), description: agentName ? t('lead') : t('projectLead'), action: _jsxs(_Fragment, { children: [canMount && driveId ? (_jsxs(Button, { variant: "secondary", size: "sm", className: "gap-1.5", onClick: () => setPicking(true), children: [_jsx(PlusIcon, { className: "size-3.5 shrink-0" }), t('mount')] })) : null, _jsx(ManageButton, { href: (id) => uiRoutes().drive(id) })] }), children: [_jsx("div", { "data-testid": "drive-mounts", children: body }), driveId ? (_jsx(FolderPicker, { open: picking, onOpenChange: setPicking, driveId: driveId, agentName: agentName, mounted: new Set(plan.data?.mounts.map((m) => m.path)) })) : null] }));
69
68
  }
@@ -448,7 +448,7 @@ function EditableAgentPage({ projectId, agent, config, initial, renderApps, }) {
448
448
  const railItems = railGroups.flatMap((group) => group.items);
449
449
  const dirtyItems = useMemo(() => changedItems(editor.draft, editor.baseline), [editor.draft, editor.baseline]);
450
450
  const changed = new Intl.ListFormat(locale, { type: 'conjunction' }).format(dirtyItems.map((key) => railItems.find((item) => item.key === key)?.label ?? key));
451
- const editorSection = (view) => (_jsx(AgentConfigSections, { section: view, editor: editor, options: options, skillsOptions: skillsOptions, registryOptions: registryOptions, apps: null, drives: _jsx(AgentDrivesSection, { projectId: projectId, agentName: agent.name, repositoryAccess: draft.repository_access !== false }), sectionStyle: "tab" }));
451
+ const editorSection = (view) => (_jsx(AgentConfigSections, { section: view, editor: editor, options: options, skillsOptions: skillsOptions, registryOptions: registryOptions, apps: null, drives: _jsx(AgentDrivesSection, { projectId: projectId, agentName: agent.name }), sectionStyle: "tab" }));
452
452
  const body = (() => {
453
453
  const view = location.view;
454
454
  switch (location.tab) {
@@ -474,7 +474,7 @@ function EditableAgentPage({ projectId, agent, config, initial, renderApps, }) {
474
474
  if (view === 'apps' && renderApps)
475
475
  return (_jsx(Embedded, { agentName: agent.name, column: RAIL_COLUMN, children: renderApps({ agentName: agent.name, grant: appsGrant, needsAppRead: !grantsAppRead(draft.kortix_permissions ?? draft.kortix_cli) }) }));
476
476
  if (view === 'drives')
477
- return (_jsx(Embedded, { agentName: agent.name, column: RAIL_COLUMN, children: _jsx(AgentDrivesSection, { projectId: projectId, agentName: agent.name, repositoryAccess: draft.repository_access !== false }) }));
477
+ return (_jsx(Embedded, { agentName: agent.name, column: RAIL_COLUMN, children: _jsx(AgentDrivesSection, { projectId: projectId, agentName: agent.name }) }));
478
478
  // Model is this agent's model only. The project-wide gateway screens
479
479
  // (providers, routing, costs, logs) live once, in Project admin.
480
480
  if (view === 'model')
@@ -79,8 +79,8 @@ export declare const YAML_KEY_ROW: {
79
79
  readonly secrets: "secrets";
80
80
  readonly apps: "apps";
81
81
  readonly kortix_permissions: "actions";
82
- readonly workspace: "workspace";
83
82
  readonly sandbox: "workspace";
83
+ readonly workspace: "workspace";
84
84
  readonly network_egress: "workspace";
85
85
  };
86
86
  /** One row of the agent page's rail: a tab with no views, or a view. */
@@ -131,14 +131,13 @@ export const YAML_KEY_ROW = {
131
131
  secrets: 'secrets',
132
132
  apps: 'apps',
133
133
  kortix_permissions: 'actions',
134
- workspace: 'workspace',
135
134
  sandbox: 'workspace',
135
+ workspace: 'workspace',
136
136
  network_egress: 'workspace',
137
137
  };
138
138
  /** The editor draft's wire names for a kortix.yaml key (v2 aliases included). */
139
139
  const WIRE_KEY = {
140
140
  file: 'prompt_file',
141
- repository_access: 'workspace',
142
141
  kortix_cli: 'kortix_permissions',
143
142
  connectors_personal: 'connectors_required',
144
143
  };
@@ -48,6 +48,10 @@ export function AddMcpServerDialog({ projectId, open, onOpenChange, takenSlugs,
48
48
  : tSharing('visibilityEveryone');
49
49
  const [url, setUrl] = useState(app?.url ?? initial?.url ?? '');
50
50
  const [audience, setAudience] = useState({ audience: 'private', picked: NO_PICKS });
51
+ // The phase running while Connect is pending: a slow server can stretch the
52
+ // serial phases to minutes, and the wait must say what it is waiting on
53
+ // (KRTX-4640).
54
+ const [stage, setStage] = useState(null);
51
55
  // The catalogue app's own server, unchanged: named after the app, and its
52
56
  // sign-in is known to be one click (`mcpServerFor`).
53
57
  const appServer = app !== null && url.trim() === app.url;
@@ -69,7 +73,7 @@ export function AddMcpServerDialog({ projectId, open, onOpenChange, takenSlugs,
69
73
  grantees: newAccountGrantees(audience.picked),
70
74
  takenSlugs,
71
75
  returnUrl: (slug) => `${window.location.origin}${connectorHref(projectId, slug)}`,
72
- }, sdkAddMcpServerDeps(accountId)),
76
+ }, { ...sdkAddMcpServerDeps(accountId), onStage: setStage }),
73
77
  onSuccess: (result) => {
74
78
  onAdded();
75
79
  if (result.signInUrl) {
@@ -110,11 +114,12 @@ export function AddMcpServerDialog({ projectId, open, onOpenChange, takenSlugs,
110
114
  setUrl(app?.url ?? '');
111
115
  setNameEdit(null);
112
116
  setAudience({ audience: 'private', picked: NO_PICKS });
117
+ setStage(null);
113
118
  }
114
119
  };
115
120
  return (_jsx(Modal, { open: open, onOpenChange: close, children: _jsxs(ModalContent, { className: "lg:max-w-md", children: [_jsxs(ModalHeader, { children: [_jsx(ModalTitle, { children: app ? t('addMcpAppTitle', { name: app.name }) : t('addMcpTitle') }), _jsx(ModalDescription, { children: app ? t('addMcpAppDescription', { name: app.name }) : t('addMcpDescription') })] }), _jsxs("form", { onSubmit: (event) => {
116
121
  event.preventDefault();
117
122
  if (canSubmit)
118
123
  add.mutate();
119
- }, children: [_jsxs(ModalBody, { className: "max-h-[60vh] space-y-4 overflow-y-auto", children: [app ? null : (_jsxs(Field, { children: [_jsx(FieldLabel, { htmlFor: `${id}-url`, children: t('addMcpUrlLabel') }), _jsx(Input, { id: `${id}-url`, type: "url", inputMode: "url", autoComplete: "off", spellCheck: false, value: url, onChange: (event) => setUrl(event.target.value), placeholder: "https://mcp.example.com/mcp", "aria-invalid": urlInvalid || undefined, disabled: add.isPending, autoFocus: !app }), urlInvalid ? (_jsx(FieldDescription, { className: "text-destructive", role: "alert", children: t('addMcpUrlInvalid') })) : (_jsx(FieldDescription, { children: t('addMcpUrlHint') }))] })), app && nameEdit === null ? null : (_jsxs(Field, { children: [_jsx(FieldLabel, { htmlFor: `${id}-name`, children: t('installNameLabel') }), _jsx(Input, { id: `${id}-name`, value: nameEdit ?? identity?.name ?? '', onChange: (event) => setNameEdit(event.target.value), autoComplete: "off", disabled: add.isPending || identity === null }), _jsx(FieldDescription, { children: t('installProfileHint') })] })), _jsx(AudienceFields, { projectId: projectId, value: audience, onChange: setAudience, canShare: canManageConnections, accountId: accountId, everyoneLabel: everyoneLabel, shareRequiresLabel: tSharing('shareRequiresManage'), disabled: add.isPending })] }), _jsxs(ModalFooter, { className: "sm:justify-between", children: [app && nameEdit === null ? (_jsx(Button, { type: "button", variant: "text", size: "sm", className: "px-0", onClick: () => setNameEdit(identity?.name ?? app.name), disabled: add.isPending, children: t('installRename') })) : null, _jsx(Button, { type: "button", variant: "outline-ghost", className: app && nameEdit === null ? 'sm:ml-auto' : undefined, onClick: () => close(false), disabled: add.isPending, children: tI18nComplete.raw('text19766ed6ccb2') }), _jsxs(Button, { type: "submit", disabled: !canSubmit, children: [add.isPending ? _jsx(Loading, { className: "size-4 shrink-0" }) : null, t('addMcpConnect')] })] })] })] }) }));
124
+ }, children: [_jsxs(ModalBody, { className: "max-h-[60vh] space-y-4 overflow-y-auto", children: [app ? null : (_jsxs(Field, { children: [_jsx(FieldLabel, { htmlFor: `${id}-url`, children: t('addMcpUrlLabel') }), _jsx(Input, { id: `${id}-url`, type: "url", inputMode: "url", autoComplete: "off", spellCheck: false, value: url, onChange: (event) => setUrl(event.target.value), placeholder: "https://mcp.example.com/mcp", "aria-invalid": urlInvalid || undefined, disabled: add.isPending, autoFocus: !app }), urlInvalid ? (_jsx(FieldDescription, { className: "text-destructive", role: "alert", children: t('addMcpUrlInvalid') })) : (_jsx(FieldDescription, { children: t('addMcpUrlHint') }))] })), app && nameEdit === null ? null : (_jsxs(Field, { children: [_jsx(FieldLabel, { htmlFor: `${id}-name`, children: t('installNameLabel') }), _jsx(Input, { id: `${id}-name`, value: nameEdit ?? identity?.name ?? '', onChange: (event) => setNameEdit(event.target.value), autoComplete: "off", disabled: add.isPending || identity === null }), _jsx(FieldDescription, { children: t('installProfileHint') })] })), _jsx(AudienceFields, { projectId: projectId, value: audience, onChange: setAudience, canShare: canManageConnections, accountId: accountId, everyoneLabel: everyoneLabel, shareRequiresLabel: tSharing('shareRequiresManage'), disabled: add.isPending }), add.isPending && stage ? (_jsx(FieldDescription, { role: "status", "aria-live": "polite", children: t(stage === 'connector' ? 'addMcpStageConnector' : stage === 'account' ? 'addMcpStageAccount' : 'addMcpStageSignIn') })) : null] }), _jsxs(ModalFooter, { className: "sm:justify-between", children: [app && nameEdit === null ? (_jsx(Button, { type: "button", variant: "text", size: "sm", className: "px-0", onClick: () => setNameEdit(identity?.name ?? app.name), disabled: add.isPending, children: t('installRename') })) : null, _jsx(Button, { type: "button", variant: "outline-ghost", className: app && nameEdit === null ? 'sm:ml-auto' : undefined, onClick: () => close(false), disabled: add.isPending, children: tI18nComplete.raw('text19766ed6ccb2') }), _jsxs(Button, { type: "submit", disabled: !canSubmit, children: [add.isPending ? _jsx(Loading, { className: "size-4 shrink-0" }) : null, t('addMcpConnect')] })] })] })] }) }));
120
125
  }
@@ -20,7 +20,14 @@ export type Grantee = {
20
20
  type: 'user' | 'group' | 'service_account';
21
21
  id: string;
22
22
  };
23
+ /** What `addMcpServer` is doing while the Connect press runs. Each stage is a
24
+ * serial network phase (create+sync, account, sign-in discovery) that a slow
25
+ * server can stretch to minutes — the dialog shows it instead of a spinner
26
+ * alone (KRTX-4640). */
27
+ export type AddMcpStage = 'connector' | 'account' | 'sign-in';
23
28
  export interface AddMcpServerDeps {
29
+ /** Surfaces the current phase while the mutation is pending. */
30
+ onStage?: (stage: AddMcpStage) => void;
24
31
  /** Creates the connector and runs its first sync (`createConnectorWithOptionalOAuth2`). */
25
32
  createConnector: (projectId: string, draft: ConnectorDraftInput) => Promise<{
26
33
  syncError: string | null;
@@ -60,6 +60,7 @@ export async function addMcpServer(projectId, input, deps) {
60
60
  if (!identity)
61
61
  throw new Error('Enter the MCP server URL, starting with https://');
62
62
  const { slug, name } = identity;
63
+ deps.onStage?.('connector');
63
64
  const created = await deps.createConnector(projectId, {
64
65
  slug,
65
66
  name,
@@ -70,6 +71,7 @@ export async function addMcpServer(projectId, input, deps) {
70
71
  // A slug another connector already has answers 409; it never replaces that connector.
71
72
  create_only: true,
72
73
  });
74
+ deps.onStage?.('account');
73
75
  const account = input.audience === 'private'
74
76
  ? await deps.createMemberAccount(projectId, { connector_alias: slug, label: name })
75
77
  : await deps.projectAccount(projectId, slug, name);
@@ -87,6 +89,7 @@ export async function addMcpServer(projectId, input, deps) {
87
89
  // The connector and its account exist either way: a sign-in that cannot
88
90
  // start says why, and the connector page retries it.
89
91
  try {
92
+ deps.onStage?.('sign-in');
90
93
  const signInUrl = await deps.startSignIn(projectId, connectionId, input.returnUrl(slug));
91
94
  // No one-click sign-in: the 401 stays, and the connector page asks for a credential.
92
95
  const syncError = signInUrl ? null : created.syncError;
@@ -51,3 +51,11 @@ export declare function ConnectorsPage({ projectId, surface, grant, agentPanel,
51
51
  /** Agent scope only: a granted connector's own rule control (its policy-set picker), in its row. */
52
52
  rowControl?: (slug: string) => ReactNode | undefined;
53
53
  }): import("react").JSX.Element;
54
+ /** The server an agent's `setup_url` asks a person to approve, or null. */
55
+ export declare function setupLinkFromParams(search: {
56
+ get(key: string): string | null;
57
+ } | null | undefined): {
58
+ provider: string;
59
+ url: string | null;
60
+ name: string | null;
61
+ } | null;
@@ -204,6 +204,27 @@ export function ConnectorsPage({ projectId, surface = { kind: 'global' }, grant,
204
204
  // The catalogue app whose own MCP server the MCP dialog connects. Null for
205
205
  // a server the user pastes (New → MCP server).
206
206
  const [mcpApp, setMcpApp] = useState(null);
207
+ // An agent's `setup_url` (`?custom=1&provider=mcp&url=…&name=…`): the one
208
+ // approval of an exact server. The MCP dialog opens prefilled; adding it is
209
+ // the approval. Read once, then dropped from the URL so closing the dialog
210
+ // does not reopen it.
211
+ const [setupLink, setSetupLink] = useState(null);
212
+ useEffect(() => {
213
+ const link = setupLinkFromParams(search);
214
+ if (!link)
215
+ return;
216
+ if (link.provider === 'mcp') {
217
+ setMcpApp(null);
218
+ setSetupLink({ url: link.url ?? '', ...(link.name ? { name: link.name } : {}) });
219
+ setPanel('mcp');
220
+ }
221
+ else
222
+ setPanel('custom');
223
+ replaceParams((params) => {
224
+ for (const key of SETUP_LINK_PARAMS)
225
+ params.delete(key);
226
+ });
227
+ }, [search, replaceParams]);
207
228
  // The catalogue opens on the apps that connect in one click.
208
229
  const [oneClick, setOneClick] = useState(true);
209
230
  const [kindFilter, setKindFilter] = useState('all');
@@ -403,7 +424,11 @@ export function ConnectorsPage({ projectId, surface = { kind: 'global' }, grant,
403
424
  /* The whole of what used to be `/workspaces/<id>/channels`, minus the
404
425
  shell it used to bring — this page's `CapabilityPageShell` is the
405
426
  one column, the one heading and the one scroll container now. */
406
- _jsx(ChannelsSection, { projectId: projectId })) : catalogActive ? (catalogSection) : (_jsxs(_Fragment, { children: [_jsx(ConnectorMovesBanner, { projectId: projectId }), listBody(filtered)] })), _jsx(AddMcpServerDialog, { projectId: projectId, app: mcpApp, open: panel === 'mcp', onOpenChange: (open) => setPanel(open ? 'mcp' : null), takenSlugs: connectors.map((connector) => connector.slug), onAdded: invalidate }, mcpApp?.url ?? 'paste'), installRequest ? (_jsx(InstallDialog, { appName: installRequest.target.appName, way: installRequest.way, open: true, pending: false, onOpenChange: (open) => !open && setInstallRequest(null), onConfirm: confirmInstall }, installRequest.target.appName)) : null, _jsx(Modal, { open: panel === 'custom', onOpenChange: (open) => !open && setPanel(null), children: _jsxs(ModalContent, { className: "lg:max-w-3xl", children: [_jsxs(ModalHeader, { children: [_jsx(ModalTitle, { children: tI18nComplete.raw('text90ccaee30bdc') }), _jsx(ModalDescription, { children: tI18nComplete.raw('textd2f3be0047c4') })] }), _jsx(ModalBody, { className: "max-h-[75vh] overflow-y-auto", children: _jsx(CustomConnectorForm, { projectId: projectId, onAdded: (slug, { addAccount }) => {
427
+ _jsx(ChannelsSection, { projectId: projectId })) : catalogActive ? (catalogSection) : (_jsxs(_Fragment, { children: [_jsx(ConnectorMovesBanner, { projectId: projectId }), listBody(filtered)] })), _jsx(AddMcpServerDialog, { projectId: projectId, app: mcpApp, initial: mcpApp ? null : setupLink, open: panel === 'mcp', onOpenChange: (open) => {
428
+ setPanel(open ? 'mcp' : null);
429
+ if (!open)
430
+ setSetupLink(null);
431
+ }, takenSlugs: connectors.map((connector) => connector.slug), onAdded: invalidate }, mcpApp?.url ?? setupLink?.url ?? 'paste'), installRequest ? (_jsx(InstallDialog, { appName: installRequest.target.appName, way: installRequest.way, open: true, pending: false, onOpenChange: (open) => !open && setInstallRequest(null), onConfirm: confirmInstall }, installRequest.target.appName)) : null, _jsx(Modal, { open: panel === 'custom', onOpenChange: (open) => !open && setPanel(null), children: _jsxs(ModalContent, { className: "lg:max-w-3xl", children: [_jsxs(ModalHeader, { children: [_jsx(ModalTitle, { children: tI18nComplete.raw('text90ccaee30bdc') }), _jsx(ModalDescription, { children: tI18nComplete.raw('textd2f3be0047c4') })] }), _jsx(ModalBody, { className: "max-h-[75vh] overflow-y-auto", children: _jsx(CustomConnectorForm, { projectId: projectId, onAdded: (slug, { addAccount }) => {
407
432
  invalidate();
408
433
  setPanel(null);
409
434
  router.push(connectorHref(projectId, slug, { addAccount }));
@@ -424,6 +449,14 @@ function useSearchInUrl(query, search, pathname) {
424
449
  shallowNavigate(suffix ? `${pathname}?${suffix}` : pathname, { replace: true });
425
450
  }, [debouncedValue, search, pathname, shallowNavigate]);
426
451
  }
452
+ /** The query keys of an agent's `setup_url` (`customConnectorSetupUrl` in the API). */
453
+ const SETUP_LINK_PARAMS = ['custom', 'provider', 'url', 'transport', 'endpoint', 'spec', 'base_url', 'name'];
454
+ /** The server an agent's `setup_url` asks a person to approve, or null. */
455
+ export function setupLinkFromParams(search) {
456
+ if (search?.get('custom') !== '1')
457
+ return null;
458
+ return { provider: search.get('provider') ?? 'mcp', url: search.get('url'), name: search.get('name') };
459
+ }
427
460
  function useConnectorNavigation(projectId) {
428
461
  const search = useUiSearchParams();
429
462
  const router = useUiRouter();
@@ -11,7 +11,6 @@ import { useTranslations as useI18nTranslations } from '../../../i18n/index.js';
11
11
  */
12
12
  import { Button } from '../../../primitives/button.js';
13
13
  import Hint from '../../../primitives/hint.js';
14
- import { Switch } from '../../../primitives/switch.js';
15
14
  import { capabilityTabHref } from '../../../internal/lib/capability-tab-routes.js';
16
15
  import { SandboxTemplateMenu, describeSandboxTemplate, } from '../../../access/sandbox-template-menu.js';
17
16
  import { cn } from '../../../internal/lib/utils.js';
@@ -107,7 +106,6 @@ export function ProjectActionsSection({ draft, set }) {
107
106
  }
108
107
  export function WorkspaceSection({ draft, set, sandboxTemplates, defaultSandboxSlug, }) {
109
108
  const tI18nComplete = useI18nTranslations('hardcodedUi.i18nComplete');
110
- const tRepository = useI18nTranslations('repositoryAccess');
111
109
  const tTabs = useI18nTranslations('agentEditor.tabs');
112
110
  const pinned = draft.sandbox ? sandboxTemplates.find((t) => t.slug === draft.sandbox) : undefined;
113
111
  const projectDefault = defaultSandboxSlug
@@ -127,7 +125,7 @@ export function WorkspaceSection({ draft, set, sandboxTemplates, defaultSandboxS
127
125
  : tI18nComplete.raw('text64f405e80a8d'), children: _jsx(SandboxTemplateMenu, { items: sandboxTemplates, selectedSlug: draft.sandbox ?? null, resolvedSlug: defaultSandboxSlug, inherit: {
128
126
  label: tI18nComplete.raw('texte8cb80e5c5cb'),
129
127
  description: tI18nComplete.raw('textb23625948eee'),
130
- }, onSelect: (slug) => set('sandbox', slug ?? undefined), align: "end", trigger: _jsxs(Button, { type: "button", variant: "outline", size: "sm", "aria-label": tI18nComplete.raw('text9e471951a1b4'), className: "w-full justify-between gap-2 font-normal", children: [_jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [_jsx(PinnedIcon, { className: "text-muted-foreground size-3.5 shrink-0" }), _jsx("span", { className: cn('truncate', stalePin && 'text-kortix-orange font-mono'), children: pinned ? pinned.name : (stalePin ?? tI18nComplete.raw('texte8cb80e5c5cb')) })] }), _jsx(CaretDownIcon, { className: "text-muted-foreground size-3.5 shrink-0" })] }) }) }), _jsx(SettingRow, { label: tRepository('label'), help: tRepository(draft.repository_access === false ? 'disabled' : 'enabled'), children: _jsx(Switch, { "aria-label": tRepository('label'), checked: draft.repository_access ?? true, onCheckedChange: (enabled) => set('repository_access', enabled) }) }), _jsx(SettingRow, { label: tTabs('networkEgress'), children: _jsx("span", { className: "text-muted-foreground text-sm text-pretty sm:text-right", children: draft.network_egress
128
+ }, onSelect: (slug) => set('sandbox', slug ?? undefined), align: "end", trigger: _jsxs(Button, { type: "button", variant: "outline", size: "sm", "aria-label": tI18nComplete.raw('text9e471951a1b4'), className: "w-full justify-between gap-2 font-normal", children: [_jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [_jsx(PinnedIcon, { className: "text-muted-foreground size-3.5 shrink-0" }), _jsx("span", { className: cn('truncate', stalePin && 'text-kortix-orange font-mono'), children: pinned ? pinned.name : (stalePin ?? tI18nComplete.raw('texte8cb80e5c5cb')) })] }), _jsx(CaretDownIcon, { className: "text-muted-foreground size-3.5 shrink-0" })] }) }) }), _jsx(SettingRow, { label: tTabs('networkEgress'), children: _jsx("span", { className: "text-muted-foreground text-sm text-pretty sm:text-right", children: draft.network_egress
131
129
  ? tTabs('networkEgressDeclared')
132
130
  : tTabs('networkEgressNone') }) })] }));
133
131
  }
@@ -21,7 +21,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore
21
21
  import { useFileExplorerSource } from '../explorer-source.js';
22
22
  import { buildGitStatusMap } from '../hooks/index.js';
23
23
  import { forEachLimit, MAX_UPLOAD_BYTES, partitionUploadBatch, resolveUploadTarget, UPLOAD_CONCURRENCY, } from '../upload-batch.js';
24
- import { droppedEntries, hasFolder, readDroppedTree, treeLevels, } from '../drop-tree.js';
24
+ import { droppedEntries, folderMaker, hasFolder, readDroppedTree, treeLevels, } from '../drop-tree.js';
25
25
  import { DriveCreateDialog, } from './drive-create-dialog.js';
26
26
  import { DriveGridView } from './drive-grid-view.js';
27
27
  import { DriveListView } from './drive-list-view.js';
@@ -393,19 +393,27 @@ export function DriveExplorer({ embedded = false, shareContext, leading, trailin
393
393
  folderPickerRef.current?.click();
394
394
  }, []);
395
395
  /**
396
- * Send one file and track it in the tray. The mutation settles after its
397
- * listing refetch, so the pending row hands over to the real one in place.
396
+ * Send one file and track it in the tray. `before` makes the file's folder
397
+ * first (a folder upload); a failure there fails the row like a failed send,
398
+ * and Retry runs it again. The mutation settles after its listing refetch,
399
+ * so the pending row hands over to the real one in place.
398
400
  */
399
401
  const uploadAsync = uploadMutation.mutateAsync;
400
- const runUpload = useCallback(async (upload, shownIn) => {
402
+ const runUpload = useCallback(async (upload, shownIn, before) => {
401
403
  const patch = (next) => useDriveUploads.getState().patch(upload.id, next);
402
404
  patch({ status: 'uploading', sent: 0, error: undefined });
403
405
  let ok = false;
404
406
  try {
407
+ await before?.();
405
408
  await uploadAsync({
406
409
  file: upload.file,
407
410
  targetPath: upload.targetPath,
408
- onProgress: (sent) => patch({ sent }),
411
+ // The SDK resends a busy-server failure from byte 0: the bar holds its high mark.
412
+ onProgress: (sent) => {
413
+ const prev = useDriveUploads.getState().uploads.find((u) => u.id === upload.id)?.sent ?? 0;
414
+ if (sent > prev)
415
+ patch({ sent });
416
+ },
409
417
  });
410
418
  ok = true;
411
419
  patch({ status: 'done', sent: upload.file.size });
@@ -435,23 +443,26 @@ export function DriveExplorer({ embedded = false, shareContext, leading, trailin
435
443
  }, [navigateToPath, onOpenFolder]);
436
444
  /**
437
445
  * Put files in the tray with their previews, then send them, 4 at a time.
446
+ * Each item names the folder view its pending row is in (`shownIn`, or
447
+ * `null` for none) and, for a folder upload, the folder to make first.
438
448
  * `landedIn` is the folder the batch lands in, for the toast's "Open folder".
439
449
  */
440
- const startBatch = useCallback(async (items, shownIn, landedIn) => {
441
- const batch = items.map(({ file, targetPath }) => {
450
+ const startBatch = useCallback(async (items, landedIn) => {
451
+ const batch = items.map(({ file, targetPath, shownIn, before, reset }) => {
442
452
  const upload = { id: crypto.randomUUID(), file, targetPath, status: 'queued' };
443
453
  upload.retry = () => {
454
+ reset?.();
444
455
  previewUpload?.(file, targetPath);
445
- void runUpload(upload, null);
456
+ void runUpload(upload, null, before);
446
457
  };
447
- return upload;
458
+ return { upload, shownIn, before };
448
459
  });
449
- useDriveUploads.getState().add(batch);
450
- for (const u of batch)
451
- previewUpload?.(u.file, u.targetPath);
460
+ useDriveUploads.getState().add(batch.map((b) => b.upload));
461
+ for (const { upload } of batch)
462
+ previewUpload?.(upload.file, upload.targetPath);
452
463
  let failed = 0;
453
- await forEachLimit(batch, UPLOAD_CONCURRENCY, async (u) => {
454
- if (!(await runUpload(u, shownIn)))
464
+ await forEachLimit(batch, UPLOAD_CONCURRENCY, async ({ upload, shownIn, before }) => {
465
+ if (!(await runUpload(upload, shownIn, before)))
455
466
  failed++;
456
467
  });
457
468
  // One toast for the whole batch; a failure stays in the tray with Retry.
@@ -488,12 +499,15 @@ export function DriveExplorer({ embedded = false, shareContext, leading, trailin
488
499
  ...accepted.map((file) => ({ dir: shownIn, node: pendingNode(file.name, 'file') })),
489
500
  ]);
490
501
  }
491
- await startBatch(accepted.map((file) => ({ file, targetPath })), shownIn, targetDirPath ?? currentPath);
502
+ await startBatch(accepted.map((file) => ({ file, targetPath, shownIn })), targetDirPath ?? currentPath);
492
503
  }, [currentPath, isRootPath, pendingNode, startBatch, uploadLimit, describeRejection]);
493
504
  /**
494
- * Upload a tree (a picked or dropped folder) into `base`: its folders are
495
- * made first, one depth at a time (a level in parallel), then its files go
496
- * up into them. Top folders landing in the folder in view show at once.
505
+ * Upload a tree (a picked or dropped folder, or several) into `base`. Every
506
+ * file enters the tray at once, so progress shows from the first click; each
507
+ * file then makes its own folder chain on demand (`folderMaker`: each folder
508
+ * once, parents first) and goes up. A folder that fails to make fails only
509
+ * the files inside it, each with Retry. Top folders landing in the folder in
510
+ * view show at once.
497
511
  */
498
512
  const uploadTree = useCallback(async (tree, base) => {
499
513
  const { accepted, rejected } = partitionUploadBatch(tree.map((t) => t.file), uploadLimit, describeRejection);
@@ -505,40 +519,47 @@ export function DriveExplorer({ embedded = false, shareContext, leading, trailin
505
519
  return;
506
520
  const root = base === '/' ? '' : base.replace(/\/+$/, '');
507
521
  const at = (rel) => (root && rel ? `${root}/${rel}` : root || rel);
508
- const levels = treeLevels(items);
509
- const tops = levels[0] ?? [];
522
+ const tops = treeLevels(items)[0] ?? [];
510
523
  const dir = currentPath;
511
524
  const inView = root === normalizedCurrentPath;
525
+ const unsettled = new Set(inView ? tops : []);
512
526
  if (inView) {
513
527
  setPending((prev) => [...prev, ...tops.map((top) => ({ dir, node: pendingNode(top, 'directory') }))]);
514
528
  }
515
- let ok = true;
516
- try {
517
- for (const level of levels) {
518
- await Promise.all(level.map((d) => mkdirMutation.mutateAsync({ dirPath: at(d) }).catch((err) => {
519
- // Already there (an earlier upload of the same folder): reuse it.
520
- if (err?.status !== 409)
521
- throw err;
522
- })));
529
+ const ensure = folderMaker(async (rel) => {
530
+ const settle = () => {
531
+ // A top folder's pending row hands over once the server has it.
532
+ if (unsettled.delete(rel))
533
+ settlePending(dir, rel, true);
534
+ };
535
+ try {
536
+ await mkdirMutation.mutateAsync({ dirPath: at(rel) });
537
+ settle();
523
538
  }
524
- }
525
- catch (err) {
526
- ok = false;
527
- errorToast(tHardcodedUi('i18nComplete.text5334297c9387', {
528
- value0: err instanceof Error ? err.message : tHardcodedUi.raw('i18nComplete.text27c2ccd962c2'),
529
- }));
539
+ catch (err) {
540
+ // Already there (an earlier upload of the same folder): reuse it.
541
+ if (err?.status === 409)
542
+ settle();
543
+ throw err;
544
+ }
545
+ });
546
+ try {
547
+ await startBatch(items.map(({ file, dir: rel }) => ({
548
+ file,
549
+ targetPath: at(rel) || undefined,
550
+ // Loose files dropped beside the folders land in the view.
551
+ shownIn: inView && !rel ? currentPath : null,
552
+ before: rel ? () => ensure(rel) : undefined,
553
+ reset: rel ? () => ensure.forget(rel) : undefined,
554
+ })), tops.length === 1 ? at(tops[0]) : root || '/');
530
555
  }
531
556
  finally {
532
- if (inView)
533
- for (const top of tops)
534
- settlePending(dir, top, ok);
557
+ // A top folder that never got made drops its pending row.
558
+ for (const top of unsettled)
559
+ settlePending(dir, top, false);
560
+ unsettled.clear();
535
561
  }
536
- if (!ok)
537
- return;
538
- await startBatch(items.map(({ file, dir: rel }) => ({ file, targetPath: at(rel) || undefined })),
539
- // Loose files dropped beside the folders land in the view.
540
- inView ? currentPath : null, tops.length === 1 ? at(tops[0]) : root || '/');
541
- }, [currentPath, normalizedCurrentPath, pendingNode, settlePending, mkdirMutation, startBatch, tHardcodedUi, uploadLimit, describeRejection]);
562
+ }, [currentPath, normalizedCurrentPath, pendingNode, settlePending, mkdirMutation, startBatch, uploadLimit, describeRejection]);
542
563
  /** The folder picker (`webkitRelativePath` is `Picked/sub/file.png`). The browser already asked. */
543
564
  const handleUploadFolder = useCallback((fileList) => uploadTree(Array.from(fileList).map((file) => ({
544
565
  file,