@arbidocs/blocks 0.5.75 → 0.5.76
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.
- package/README.md +23 -0
- package/dist/{ConnectedDocumentViewer-U5TQ4LFJ.js → ConnectedDocumentViewer-4LRZ5N3L.js} +6 -6
- package/dist/{ConnectedDocumentViewer-U5TQ4LFJ.js.map → ConnectedDocumentViewer-4LRZ5N3L.js.map} +1 -1
- package/dist/{ConnectedDocumentViewer-ID2RG5MF.cjs → ConnectedDocumentViewer-FREQM2ES.cjs} +7 -7
- package/dist/{ConnectedDocumentViewer-ID2RG5MF.cjs.map → ConnectedDocumentViewer-FREQM2ES.cjs.map} +1 -1
- package/dist/{ConnectedNativeDocxComparison-PBMS77ZP.js → ConnectedNativeDocxComparison-P7OJ3UVK.js} +6 -6
- package/dist/{ConnectedNativeDocxComparison-PBMS77ZP.js.map → ConnectedNativeDocxComparison-P7OJ3UVK.js.map} +1 -1
- package/dist/{ConnectedNativeDocxComparison-R4OFGVHY.cjs → ConnectedNativeDocxComparison-RQIKQM5O.cjs} +7 -7
- package/dist/{ConnectedNativeDocxComparison-R4OFGVHY.cjs.map → ConnectedNativeDocxComparison-RQIKQM5O.cjs.map} +1 -1
- package/dist/{ConnectedNativeDocxEditor-27JZI2D5.js → ConnectedNativeDocxEditor-HX3FDJ2T.js} +5 -5
- package/dist/{ConnectedNativeDocxEditor-27JZI2D5.js.map → ConnectedNativeDocxEditor-HX3FDJ2T.js.map} +1 -1
- package/dist/{ConnectedNativeDocxEditor-774XRIP3.cjs → ConnectedNativeDocxEditor-XKQV7A37.cjs} +7 -7
- package/dist/{ConnectedNativeDocxEditor-774XRIP3.cjs.map → ConnectedNativeDocxEditor-XKQV7A37.cjs.map} +1 -1
- package/dist/{ConnectedStreamedWordArtifact-7TNIQTVE.cjs → ConnectedStreamedWordArtifact-CSRL4SCO.cjs} +7 -7
- package/dist/ConnectedStreamedWordArtifact-CSRL4SCO.cjs.map +1 -0
- package/dist/{ConnectedStreamedWordArtifact-XEFXYMKS.js → ConnectedStreamedWordArtifact-SSH6M5LN.js} +6 -6
- package/dist/ConnectedStreamedWordArtifact-SSH6M5LN.js.map +1 -0
- package/dist/{DocumentReviewCard-7OPL6PWG.cjs → DocumentReviewCard-3PZJPVQC.cjs} +14 -14
- package/dist/{DocumentReviewCard-7OPL6PWG.cjs.map → DocumentReviewCard-3PZJPVQC.cjs.map} +1 -1
- package/dist/{DocumentReviewCard-NDHCFYYT.js → DocumentReviewCard-KHMHG7A5.js} +9 -9
- package/dist/{DocumentReviewCard-NDHCFYYT.js.map → DocumentReviewCard-KHMHG7A5.js.map} +1 -1
- package/dist/{WorkspaceTableView-4INHJ7QK.js → WorkspaceTableView-4VMCTOFT.js} +5 -5
- package/dist/{WorkspaceTableView-4INHJ7QK.js.map → WorkspaceTableView-4VMCTOFT.js.map} +1 -1
- package/dist/{WorkspaceTableView-BTUSU3N3.cjs → WorkspaceTableView-Q44KNO3Z.cjs} +7 -7
- package/dist/{WorkspaceTableView-BTUSU3N3.cjs.map → WorkspaceTableView-Q44KNO3Z.cjs.map} +1 -1
- package/dist/agents/index.cjs +281 -281
- package/dist/agents/index.js +4 -4
- package/dist/{chunk-E3ILJRG4.cjs → chunk-2HECOUXC.cjs} +4 -3
- package/dist/chunk-2HECOUXC.cjs.map +1 -0
- package/dist/{chunk-AQPZ4QMV.cjs → chunk-3J2ASIM7.cjs} +3 -3
- package/dist/chunk-3J2ASIM7.cjs.map +1 -0
- package/dist/{chunk-QCFNPQWS.cjs → chunk-3LJUTIS6.cjs} +44 -44
- package/dist/{chunk-QCFNPQWS.cjs.map → chunk-3LJUTIS6.cjs.map} +1 -1
- package/dist/chunk-4B6HYQTW.cjs +20 -0
- package/dist/chunk-4B6HYQTW.cjs.map +1 -0
- package/dist/{chunk-4UMVAJJZ.js → chunk-6NEBHZIF.js} +4 -4
- package/dist/{chunk-4UMVAJJZ.js.map → chunk-6NEBHZIF.js.map} +1 -1
- package/dist/{chunk-IMIE5NOQ.js → chunk-7E5GV4R7.js} +4 -4
- package/dist/{chunk-IMIE5NOQ.js.map → chunk-7E5GV4R7.js.map} +1 -1
- package/dist/{chunk-LNXMSIKU.js → chunk-AWFEB4YJ.js} +8 -8
- package/dist/{chunk-LNXMSIKU.js.map → chunk-AWFEB4YJ.js.map} +1 -1
- package/dist/{chunk-JMQLTMJ7.js → chunk-B3BD5IJR.js} +16 -20
- package/dist/chunk-B3BD5IJR.js.map +1 -0
- package/dist/{chunk-5Q2U7GLI.cjs → chunk-CDW3W5U5.cjs} +4 -4
- package/dist/{chunk-5Q2U7GLI.cjs.map → chunk-CDW3W5U5.cjs.map} +1 -1
- package/dist/{chunk-SK5TP4DP.js → chunk-DBPPOJQM.js} +3 -3
- package/dist/{chunk-SK5TP4DP.js.map → chunk-DBPPOJQM.js.map} +1 -1
- package/dist/{chunk-NJ3YV3VM.cjs → chunk-DMYBHKNQ.cjs} +27 -27
- package/dist/{chunk-NJ3YV3VM.cjs.map → chunk-DMYBHKNQ.cjs.map} +1 -1
- package/dist/{chunk-563BHHHO.cjs → chunk-E6S6WHXL.cjs} +9 -9
- package/dist/{chunk-563BHHHO.cjs.map → chunk-E6S6WHXL.cjs.map} +1 -1
- package/dist/{chunk-BV34QPKE.js → chunk-EASXRDYQ.js} +3 -3
- package/dist/{chunk-BV34QPKE.js.map → chunk-EASXRDYQ.js.map} +1 -1
- package/dist/{chunk-JOFUAQTV.js → chunk-HWNVAQBX.js} +3 -3
- package/dist/{chunk-JOFUAQTV.js.map → chunk-HWNVAQBX.js.map} +1 -1
- package/dist/{chunk-PNWSEIWS.cjs → chunk-I3HK46DH.cjs} +4 -4
- package/dist/{chunk-PNWSEIWS.cjs.map → chunk-I3HK46DH.cjs.map} +1 -1
- package/dist/{chunk-GJKXYX47.js → chunk-IJ2CTMA7.js} +3 -3
- package/dist/{chunk-GJKXYX47.js.map → chunk-IJ2CTMA7.js.map} +1 -1
- package/dist/{chunk-7ZL6OVGO.cjs → chunk-IQFHOKQH.cjs} +23 -46
- package/dist/chunk-IQFHOKQH.cjs.map +1 -0
- package/dist/{chunk-7ZCM2GR2.js → chunk-IRCGXKLB.js} +3 -3
- package/dist/{chunk-7ZCM2GR2.js.map → chunk-IRCGXKLB.js.map} +1 -1
- package/dist/{chunk-G4GLDQLY.js → chunk-KG3W76BB.js} +3 -3
- package/dist/chunk-KG3W76BB.js.map +1 -0
- package/dist/{chunk-B66CICTP.cjs → chunk-KHLPBCRZ.cjs} +52 -52
- package/dist/{chunk-B66CICTP.cjs.map → chunk-KHLPBCRZ.cjs.map} +1 -1
- package/dist/{chunk-J4SEJSSV.js → chunk-KPIR4MJV.js} +6 -6
- package/dist/{chunk-J4SEJSSV.js.map → chunk-KPIR4MJV.js.map} +1 -1
- package/dist/{chunk-PA4EGGCI.js → chunk-KSHTODQZ.js} +3 -3
- package/dist/{chunk-PA4EGGCI.js.map → chunk-KSHTODQZ.js.map} +1 -1
- package/dist/{chunk-PT6D5B6L.cjs → chunk-MAUJVVFJ.cjs} +360 -410
- package/dist/chunk-MAUJVVFJ.cjs.map +1 -0
- package/dist/{chunk-MP7XCRHV.js → chunk-NRI5DKJE.js} +4 -3
- package/dist/chunk-NRI5DKJE.js.map +1 -0
- package/dist/{chunk-XXPDAENX.cjs → chunk-PGTDQBMX.cjs} +7 -7
- package/dist/{chunk-XXPDAENX.cjs.map → chunk-PGTDQBMX.cjs.map} +1 -1
- package/dist/{chunk-4JKK6S7U.cjs → chunk-S7G3A52F.cjs} +5 -5
- package/dist/{chunk-4JKK6S7U.cjs.map → chunk-S7G3A52F.cjs.map} +1 -1
- package/dist/{chunk-OUCWTKQT.js → chunk-SBFQF3BU.js} +4 -4
- package/dist/{chunk-OUCWTKQT.js.map → chunk-SBFQF3BU.js.map} +1 -1
- package/dist/{chunk-52VME6ZS.cjs → chunk-SIOBGNRY.cjs} +18 -18
- package/dist/{chunk-52VME6ZS.cjs.map → chunk-SIOBGNRY.cjs.map} +1 -1
- package/dist/chunk-SK3GBHPJ.js +15 -0
- package/dist/chunk-SK3GBHPJ.js.map +1 -0
- package/dist/{chunk-RADE22SM.cjs → chunk-T2OG3CPR.cjs} +4 -4
- package/dist/{chunk-RADE22SM.cjs.map → chunk-T2OG3CPR.cjs.map} +1 -1
- package/dist/{chunk-IGQJ6ET3.js → chunk-TWSOU6SE.js} +421 -501
- package/dist/chunk-TWSOU6SE.js.map +1 -0
- package/dist/{chunk-QRV4XYFJ.js → chunk-UCD7644N.js} +3 -3
- package/dist/{chunk-QRV4XYFJ.js.map → chunk-UCD7644N.js.map} +1 -1
- package/dist/{chunk-TQ4VGQHG.js → chunk-ULUCGL24.js} +3 -3
- package/dist/{chunk-TQ4VGQHG.js.map → chunk-ULUCGL24.js.map} +1 -1
- package/dist/{chunk-IRI6LPDX.cjs → chunk-UR4OSH2Q.cjs} +4 -4
- package/dist/{chunk-IRI6LPDX.cjs.map → chunk-UR4OSH2Q.cjs.map} +1 -1
- package/dist/{chunk-66QN6ZJR.cjs → chunk-URZAK3A3.cjs} +36 -36
- package/dist/{chunk-66QN6ZJR.cjs.map → chunk-URZAK3A3.cjs.map} +1 -1
- package/dist/{chunk-57S2PLCM.js → chunk-V2QWATXQ.js} +3 -3
- package/dist/{chunk-57S2PLCM.js.map → chunk-V2QWATXQ.js.map} +1 -1
- package/dist/{chunk-55JI2IGZ.cjs → chunk-VBLJNOVP.cjs} +4 -4
- package/dist/{chunk-55JI2IGZ.cjs.map → chunk-VBLJNOVP.cjs.map} +1 -1
- package/dist/{chunk-KFAFWPZK.cjs → chunk-VRMACPJR.cjs} +7 -7
- package/dist/{chunk-KFAFWPZK.cjs.map → chunk-VRMACPJR.cjs.map} +1 -1
- package/dist/{chunk-5Y6V7F6W.cjs → chunk-VWUNPAR2.cjs} +15 -19
- package/dist/chunk-VWUNPAR2.cjs.map +1 -0
- package/dist/{chunk-T3GTQXGP.js → chunk-W7CQ5MLR.js} +3 -3
- package/dist/{chunk-T3GTQXGP.js.map → chunk-W7CQ5MLR.js.map} +1 -1
- package/dist/{chunk-AOBNXZLS.cjs → chunk-Y3VXKSW7.cjs} +594 -674
- package/dist/chunk-Y3VXKSW7.cjs.map +1 -0
- package/dist/{chunk-RTYU6ZGO.cjs → chunk-YCABQ5W4.cjs} +4 -4
- package/dist/{chunk-RTYU6ZGO.cjs.map → chunk-YCABQ5W4.cjs.map} +1 -1
- package/dist/{chunk-EWHD3BY5.js → chunk-ZHHUEYSB.js} +25 -48
- package/dist/chunk-ZHHUEYSB.js.map +1 -0
- package/dist/{chunk-5PKIDR2Q.js → chunk-ZHJVABQ6.js} +361 -406
- package/dist/chunk-ZHJVABQ6.js.map +1 -0
- package/dist/connect/docx.cjs +11 -11
- package/dist/connect/docx.js +7 -7
- package/dist/connect/index.cjs +1448 -1367
- package/dist/connect/index.cjs.map +1 -1
- package/dist/connect/index.d.ts +2 -0
- package/dist/connect/index.js +545 -466
- package/dist/connect/index.js.map +1 -1
- package/dist/connect/viewer.cjs +5 -5
- package/dist/connect/viewer.js +4 -4
- package/dist/connection/account-cluster/ConnectedAccountCluster.d.ts +2 -1
- package/dist/connection/facts/useFactFilters.d.ts +46 -0
- package/dist/connection/files/fields/ConnectedTagForm.d.ts +1 -1
- package/dist/connection/report-problem/ReportProblemDialog.d.ts +10 -8
- package/dist/connection/report-problem/useReportProblem.d.ts +2 -6
- package/dist/connection/tags/ConnectedTagTable.d.ts +1 -1
- package/dist/connection/tags/ConnectedTagsPage.d.ts +3 -1
- package/dist/connection/tags/TagsPageSections.d.ts +5 -3
- package/dist/connection/tags/tagged-content.d.ts +10 -0
- package/dist/connection/threads/useThreadTagFilter.d.ts +10 -0
- package/dist/connection/tips/ConnectedTipBar.d.ts +2 -1
- package/dist/connection/tips/useContextualHints.d.ts +6 -1
- package/dist/embed/index.cjs +13 -12
- package/dist/embed/index.js +8 -7
- package/dist/facts/index.cjs +45 -45
- package/dist/facts/index.js +2 -2
- package/dist/files/index.cjs +226 -226
- package/dist/files/index.js +2 -2
- package/dist/index.cjs +423 -367
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +76 -16
- package/dist/index.js.map +1 -1
- package/dist/settings/FilterChip.d.ts +2 -1
- package/dist/settings/TriStateFilterMenu.d.ts +1 -0
- package/dist/settings/index.cjs +158 -158
- package/dist/settings/index.js +2 -2
- package/dist/shell/index.cjs +14 -14
- package/dist/shell/index.js +1 -1
- package/dist/styles.css +1 -1
- package/dist/tags/TagDetail.d.ts +2 -2
- package/dist/tags/TagTable.d.ts +17 -3
- package/dist/tags/index.d.ts +1 -1
- package/dist/workflow-canvas/index.cjs +29 -29
- package/dist/workflow-canvas/index.js +12 -12
- package/node_modules/@arbidocs/coedit/package.json +1 -1
- package/package.json +5 -5
- package/dist/ConnectedStreamedWordArtifact-7TNIQTVE.cjs.map +0 -1
- package/dist/ConnectedStreamedWordArtifact-XEFXYMKS.js.map +0 -1
- package/dist/chunk-5PKIDR2Q.js.map +0 -1
- package/dist/chunk-5Y6V7F6W.cjs.map +0 -1
- package/dist/chunk-7ZL6OVGO.cjs.map +0 -1
- package/dist/chunk-AOBNXZLS.cjs.map +0 -1
- package/dist/chunk-AQPZ4QMV.cjs.map +0 -1
- package/dist/chunk-E3ILJRG4.cjs.map +0 -1
- package/dist/chunk-EWHD3BY5.js.map +0 -1
- package/dist/chunk-G4GLDQLY.js.map +0 -1
- package/dist/chunk-IGQJ6ET3.js.map +0 -1
- package/dist/chunk-JMQLTMJ7.js.map +0 -1
- package/dist/chunk-MP7XCRHV.js.map +0 -1
- package/dist/chunk-PT6D5B6L.cjs.map +0 -1
- package/dist/connection/tags/TagPlacement.d.ts +0 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/connection/workflows/useSkillsEnabled.ts","../src/connection/workflows/useWorkflowDefinitions.ts","../src/connection/workflows/useWorkflowTasks.ts","../src/connection/tasks/ConnectedTaskComposer.tsx","../src/connection/ConnectedWorkflowHistory.tsx","../src/connection/tasks/useTaskPeople.tsx","../src/connection/tasks/ConnectedThreadTaskBar.tsx","../src/connection/workflows/useRequiredLabels.ts","../src/connection/projects/useProjectSummaries.ts","../src/connection/workflows/WorkflowRunPage.tsx","../src/connection/WorkflowRunThread.tsx","../src/connection/useWorkflowThread.ts","../src/connection/WorkflowRunnerDialogs.tsx","../src/connection/ConnectedWorkflowRunner.tsx","../src/connection/workflows/useWorkflowsPageState.ts"],"names":["useMemo","useDocuments","useArbiSessionState","jsx","useAgents","useCallback","useUpdateConversation","useState","useWorkspaceUsers","useArbiSession","getUserDisplayName","getDocumentTitle","jsxs","Button","useEffect","useWorkspaces","useRef","useArbi","useCreateWork","useActOnStep","useConversationActivity","Fragment","Loader2","useTags","page","useArbiSessionStore","files","useWorkflows"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,MAAM,EAAE,IAAA,EAAM,YAAA,EAAa,GAAI,eAAA,EAAgB;AAC/C,EAAA,OAAO,cAAc,WAAA,IAAe,KAAA;AACtC;ACwBO,SAAS,sBAAA,GAAuD;AACrE,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAS,GAAI,SAAA,EAAU;AACrC,EAAA,MAAM,QAAQ,gBAAA,EAAiB;AAC/B,EAAA,MAAM,gBAAgB,gBAAA,EAAiB;AACvC,EAAA,OAAO,QAAQ,MAAM;AAEnB,IAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAU,MAAA,EAAQ,YAAW,GAAI,mBAAA;AAAA,MAC7C,aAAA;AAAA,MACA,YAAY;AAAC,KACf;AACA,IAAA,MAAM,GAAA,GAAM,CAAC,GAAG,QAAA,EAAU,GAAG,UAAU,CAAA;AACvC,IAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,GAAA,CAAI,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,EAAA,EAAI,CAAC,CAAC,CAAC,CAAA;AAC9C,IAAA,MAAM,MAAA,GAAS,gBA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A,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,gBAAA,EAAkB;AAAA,GACpB;AACF","file":"chunk-LNXMSIKU.js","sourcesContent":["/**\n * The one gate for everything skill-shaped in the app: the empty chat's Start list, the skill\n * entries of the slash menu, the sidebar's Skills item, the Skills browser's entry points and the\n * typed `/skill` interception. It is the personal `show_skills` user setting, default off; the\n * switch lives in Settings, Experimental (developers only), so today only developers have it.\n */\n\nimport { useUserSettings } from '@arbidocs/react'\n\nexport function useSkillsEnabled(): boolean {\n const { data: userSettings } = useUserSettings()\n return userSettings?.show_skills ?? false\n}\n","/**\n * The one list of workflows: the seeded ones plus every skill the user can invoke (each degraded\n * to a single-field form from its `arg_hint`). The dashboard tiles, the slash menu, tasks and\n * agents all read this.\n */\n\nimport { useMemo } from 'react'\nimport { useSkills } from '@arbidocs/react'\nimport { mergeSkillWorkflows } from '../../agents/workflows/workflow'\nimport { type WorkflowDefinition } from '../../agents/workflows/types'\nimport {\n CUSTOM_TASK,\n DASHBOARD_OPERATIONS,\n DASHBOARD_PINNED,\n REMIND_TASK,\n} from '../../agents/workflows/catalogue/seed'\nimport { useSkillsEnabled } from './useSkillsEnabled'\nimport { sortByRecentUse, useWorkflowUsage } from '../../agents/workflows/catalogue/workflow-usage'\nimport { WEB_WORKFLOWS } from '../../agents/workflows/catalogue/registry'\n\nexport interface UseWorkflowDefinitionsResult {\n /** Every skill workflow of this host: built-ins plus the user's and the marketplace's (one list). */\n skills: WorkflowDefinition[]\n /** The user has skills switched on (`show_skills`): the gate of every skill-shaped surface. */\n skillsEnabled: boolean\n /**\n * The empty chat's Start section: built-ins first (their own order), then the user's own and\n * marketplace skills by recent use, then name. EMPTY for users without skills enabled.\n */\n start: WorkflowDefinition[]\n /** The dashboard Start band: pinned skills in order, then the operation launchers. */\n dashboard: WorkflowDefinition[]\n /** What a task can run: schedulable skills plus a free instruction and a reminder. */\n forTasks: WorkflowDefinition[]\n}\n\nexport function useWorkflowDefinitions(): UseWorkflowDefinitionsResult {\n const { data: listings } = useSkills()\n const usage = useWorkflowUsage()\n const skillsEnabled = useSkillsEnabled()\n return useMemo(() => {\n // An uploaded skill of a built-in's slug is used instead of it.\n const { host: builtins, skills: fromServer } = mergeSkillWorkflows(\n WEB_WORKFLOWS,\n listings ?? []\n )\n const all = [...builtins, ...fromServer]\n const byId = new Map(all.map((w) => [w.id, w]))\n const pinned = DASHBOARD_PINNED.flatMap((id) => {\n const w = byId.get(id)\n return w ? [w] : []\n })\n return {\n skills: all,\n skillsEnabled,\n start: skillsEnabled ? [...builtins, ...sortByRecentUse(fromServer, usage)] : [],\n dashboard: [...pinned, ...DASHBOARD_OPERATIONS],\n forTasks: [CUSTOM_TASK, ...all.filter((w) => w.schedulable), REMIND_TASK],\n }\n }, [listings, usage, skillsEnabled])\n}\n","/**\n * Creating and updating work and workflows from the composer, in one place.\n *\n * \"Now\" is an assistant query with task options (the person's own run: the thread becomes a task); a plain\n * to-do creates work with no run. Any other start (a date, a repeat, an event, after another task) saves a workflow\n * that creates the work when it fires. The request mapping is shared with every host (and tested in\n * blocks): `taskComposerToCreateRequest` decides which.\n *\n * Workspace authorization is a per-run, least-privilege choice (`auth_mode`) composed over the shipped\n * workspace-access-request + grant machinery:\n * - Now -> no tier: the query runs as the person asking, with their own access.\n * - Workflow -> `scheduled_require_auth` by default (asks at run time), or `scheduled_permanent`\n * (\"keep access\"): standing membership so unattended runs can decrypt while the owner\n * is away. Only this tier grants membership.\n */\n\nimport {\n useCreateWorkflow,\n useGrantAgentAccess,\n useRunWorkflow,\n useUpdateWorkflow,\n useDocuments,\n useArbiSessionState,\n useCreateWork,\n useStartTaskQuery,\n useUpdateConversation,\n} from '@arbidocs/react'\nimport { getDocumentTitle } from '@arbidocs/react/ui'\nimport type { components } from '@arbidocs/client'\nimport { useCallback, useMemo } from 'react'\nimport {\n composerToWorkflowUpdate,\n taskComposerToCreateRequest,\n taskComposerToUpdateRequest,\n} from '../../agents/tasks/taskRequest'\nimport { type TaskComposerValues } from '../../agents/tasks/taskComposerTypes'\nimport { type WorkflowDefinition } from '../../agents/workflows/types'\nimport type { TaskPlan } from '../../agents/workflows/planSteps'\nimport { useBlocksEnvironment } from '../../provider/environment'\n\ntype Task = components['schemas']['ConversationResponse']\ntype Workflow = components['schemas']['WorkflowResponse']\n\nexport interface TaskSubmitContext {\n workflow: WorkflowDefinition\n values: TaskComposerValues\n /** Goal checklist for agent work, if one was drafted. */\n plan?: TaskPlan | null\n}\n\n/** What a composer submission created. `ran` is null for work no agent runs. */\nexport type CreateOutcome =\n | { kind: 'work'; task: Pick<Task, 'title'> & { external_id?: string }; ran: boolean | null }\n | { kind: 'workflow'; workflow: Workflow }\n\nexport function useWorkflowTasks() {\n const createWork = useCreateWork()\n const runWorkflow = useRunWorkflow()\n const startQuery = useStartTaskQuery()\n const createWorkflow = useCreateWorkflow()\n const updateConversation = useUpdateConversation()\n const updateWorkflowMutation = useUpdateWorkflow()\n const activeWorkspaceId = useArbiSessionState((s) => s.workspaceId)\n const { openFiles } = useBlocksEnvironment()\n\n // Standing access for a workflow's agent, so its unattended runs can read the workspace. An agent\n // that is already a member makes the server refuse the re-grant: that is no failure here.\n const { mutateAsync: grant } = useGrantAgentAccess()\n const grantAgentAccess = useCallback(\n (agentExtId: string, workspaceId: string) =>\n grant({ agentExtId, workspaceId }).then(\n () => undefined,\n () => undefined\n ),\n [grant]\n )\n // File names for the prompt's wording (\"the document <name>\"): the server is told the ids as well.\n const { data: documents = [] } = useDocuments()\n const documentTitles = useMemo(\n () =>\n Object.fromEntries(documents.map((d) => [d.external_id, getDocumentTitle(d, d.external_id)])),\n [documents]\n )\n\n /**\n * Create work or a workflow. `forceWorkflow` is for the workflow dialog, where even a reminder is\n * saved as a workflow.\n */\n const create = useCallback(\n async (ctx: TaskSubmitContext, forceWorkflow = false): Promise<CreateOutcome> => {\n const request = taskComposerToCreateRequest(\n { ...ctx, documentTitles, plan: ctx.plan ?? null },\n activeWorkspaceId ?? undefined,\n forceWorkflow\n )\n if (request.kind === 'workflow') {\n const workflow = await createWorkflow.mutateAsync(request.body)\n // Keep access: deposit the key for the agent the server assigned (the Assistant when none was\n // picked), while the owner is here, so unattended runs start on their own.\n const workspaceId = workflow.workspace_ext_id ?? request.body.workspace_ext_id\n if (\n workflow.auth_mode === 'scheduled_permanent' &&\n !workflow.on_demand &&\n workflow.agent_ext_id &&\n workspaceId\n ) {\n await grantAgentAccess(workflow.agent_ext_id, workspaceId)\n }\n if (ctx.workflow.documentAction && ctx.values.when === 'now' && !forceWorkflow) {\n const result = await runWorkflow.mutateAsync(workflow.external_id)\n if (result.error) throw new Error(result.error)\n openFiles()\n }\n return { kind: 'workflow', workflow }\n }\n if (request.kind === 'query') {\n // Run now is the person's own assistant query: it makes the thread a task and runs it.\n const { conversationId } = await startQuery.start(request.query)\n return {\n kind: 'work',\n task: { external_id: conversationId, title: request.query.task.title ?? null },\n ran: true,\n }\n }\n // A plain to-do (or reminder): a task with no run.\n const task = await createWork.mutateAsync(request.body)\n return { kind: 'work', task, ran: null }\n },\n [\n activeWorkspaceId,\n createWork,\n createWorkflow,\n documentTitles,\n grantAgentAccess,\n startQuery,\n runWorkflow,\n openFiles,\n ]\n )\n\n /** PATCH the editable fields of a task (the instruction, workspace and agent stay as created). */\n const update = useCallback(\n async (task: Pick<Task, 'external_id'> & { is_owner?: boolean }, ctx: TaskSubmitContext) => {\n const patch = taskComposerToUpdateRequest({ ...ctx, plan: ctx.plan ?? null })\n // Who can see a task is its owner's to change: an editor's save leaves it out.\n if (task.is_owner === false) delete patch.shared\n await updateConversation.mutateAsync({ conversationId: task.external_id, patch })\n },\n [updateConversation]\n )\n\n /** PATCH a workflow: its name, trigger and action. */\n const updateWorkflow = useCallback(\n async (\n workflow: Pick<Workflow, 'external_id' | 'agent_ext_id' | 'workspace_ext_id'> & {\n is_owner?: boolean\n },\n ctx: TaskSubmitContext\n ) => {\n const patch = composerToWorkflowUpdate({ ...ctx, documentTitles, plan: ctx.plan ?? null })\n // Sharing a workflow is its owner's: an editor's save leaves it out.\n if (workflow.is_owner === false) delete patch.shared\n const workspaceId = workflow.workspace_ext_id ?? activeWorkspaceId\n const updated = await updateWorkflowMutation.mutateAsync({\n workflowId: workflow.external_id,\n patch,\n })\n // The agent the server keeps (the Assistant when none was picked) gets the key for unattended runs.\n const agentId = updated.agent_ext_id ?? patch.agent_ext_id ?? workflow.agent_ext_id\n if (\n updated.auth_mode === 'scheduled_permanent' &&\n !updated.on_demand &&\n agentId &&\n workspaceId\n ) {\n await grantAgentAccess(agentId, workspaceId)\n }\n },\n [activeWorkspaceId, documentTitles, grantAgentAccess, updateWorkflowMutation]\n )\n\n return {\n create,\n update,\n updateWorkflow,\n isPending:\n createWork.isPending ||\n startQuery.isPending ||\n createWorkflow.isPending ||\n updateConversation.isPending ||\n updateWorkflowMutation.isPending,\n }\n}\n","/**\n * Create / edit a task, or create / edit a workflow: the `TaskComposer` block, connected.\n *\n * A task is a conversation with a status. \"Now\" (or a plain to-do) creates it; any other start (at a\n * time, on an event, after another task) saves a workflow that creates it when it fires. Pick the\n * workflow definition (or write your own instruction), fill its form, choose when, and who does it.\n * Everything the backend needs beyond that (authorization tier, name, notification, goal checklist)\n * is derived or folded under \"More options\". The API mapping lives in `useWorkflowTasks`, shared with\n * \"launch as another agent\". With `kind=\"workflow\"` it is the workflow dialog the Workflows page uses.\n */\n\nimport {\n useAgents,\n useAgentWorkspaces,\n useArbiSessionState,\n useDocuments,\n usePlanWork,\n useTags,\n useWorkflows,\n useWorkItems,\n useWorkspaces,\n} from '@arbidocs/react'\nimport type { components } from '@arbidocs/client'\nimport { useEffect, useMemo, useState } from 'react'\nimport { Button } from '@arbidocs/react/ui'\nimport { TaskComposer } from '../../agents/tasks/TaskComposer'\nimport { TaskPlan as TaskPlanForm } from '../../agents/tasks/TaskPlan'\nimport type { TaskPlan } from '../../agents/workflows/planSteps'\nimport { moveTargets, type TaskListRow } from '../../agents/tasks/taskRows'\nimport { taskToComposerValues, workflowToComposerValues } from '../../agents/tasks/taskRequest'\nimport { type AgentOption } from '../../agents/workflows/AgentSelect'\nimport { type TaskComposerValues } from '../../agents/tasks/taskComposerTypes'\nimport { ArbiApiError } from '@arbidocs/sdk/browser'\nimport { detectTimeZone, listTimeZones } from '../../calendar/zone'\nimport { useBlocksEnvironment } from '../../provider/environment'\nimport { useOpenWorkflow } from '../workflows/useOpenWorkflow'\n\ntype Task = components['schemas']['ConversationResponse']\ntype Workflow = components['schemas']['WorkflowResponse']\nimport {\n CUSTOM_TASK_ID,\n REMIND_TASK_ID,\n renderWorkflowIcon,\n} from '../../agents/workflows/catalogue/seed'\nimport { useWorkflowDefinitions } from '../workflows/useWorkflowDefinitions'\nimport { useWorkflowTasks } from '../workflows/useWorkflowTasks'\nimport { AUTOMATION_EVENTS } from '../../agents/tasks/taskHelpers'\nimport {\n ConnectedWorkflowDocumentsField,\n useConnectedWorkflowScopeSource,\n} from '../ConnectedWorkflowLauncher'\n\nexport interface ConnectedTaskComposerProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** `workflow` is the workflow dialog (new, or `workflow` to edit); the default adds a task. */\n kind?: 'work' | 'workflow'\n /** Save an on-demand recipe instead of running immediately. */\n saveOnly?: boolean\n /** Present -> edit this task; absent -> create. */\n task?: Task | null\n /** `kind=\"workflow\"` only: present -> edit this workflow. */\n workflow?: Workflow | null\n /** Create-mode default assignee (the Agents page's \"Assign task\"). */\n initialAgentExtId?: string\n /** `kind=\"workflow\"` create-mode template: opens with this workflow definition (a skill's) selected. */\n initialWorkflowId?: string\n /** `kind=\"workflow\"` create-mode: open on the Run later view (when, which agent, access). */\n startLater?: boolean\n /** A prompt carried from the quick task launcher into scheduling. */\n initialShared?: boolean\n initialPrompt?: string\n /** A saved recipe copied into a new schedule; the original is not edited. */\n launchWorkflow?: Workflow\n /** Create-mode parent: opens as \"Add sub-task\" under this task. */\n initialParentTaskExtId?: string\n}\n\n/** What \"always allowed\" means: the workspaces the agent will hold standing access to. */\nfunction StandingAccessNote({\n agentId,\n activeWorkspaceName,\n}: {\n agentId: string\n activeWorkspaceName: string | null\n}) {\n const { data: held = [] } = useAgentWorkspaces(agentId, { enabled: agentId !== '' })\n const names = new Set(held.map((w) => w.name))\n if (activeWorkspaceName) names.add(activeWorkspaceName)\n return (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"task-standing-access\">\n {agentId === '' ? 'Your own assistant needs no grant.' : 'It will hold standing access to: '}\n {agentId !== '' && (\n <span className=\"font-medium text-foreground\">\n {[...names].join(', ') || 'no workspace yet'}\n </span>\n )}\n </p>\n )\n}\n\nexport function ConnectedTaskComposer({\n open,\n onOpenChange,\n kind = 'work',\n saveOnly = false,\n task,\n workflow: editingWorkflow,\n initialWorkflowId,\n startLater: startLaterProp,\n initialPrompt,\n initialShared,\n launchWorkflow,\n initialAgentExtId,\n initialParentTaskExtId,\n}: ConnectedTaskComposerProps) {\n const { notify, openConversation, openUpload } = useBlocksEnvironment()\n // Scheduling (\"Run later\") belongs to Workflows: offered while the host has its page.\n const openWorkflow = useOpenWorkflow()\n const automationsEnabled = openWorkflow !== undefined\n const startLater = startLaterProp && automationsEnabled\n const isWorkflow = kind === 'workflow'\n const isEdit = isWorkflow ? !!editingWorkflow : !!task\n const { forTasks: baseSkills, skills } = useWorkflowDefinitions()\n const { data: reviewFields = [] } = useTags()\n const scheduledSkills = useMemo(\n () => [\n ...baseSkills,\n {\n id: '__document_review__',\n title: 'AI Review',\n description: 'Write answers and citations into document fields.',\n documentAction: 'annotate_documents' as const,\n run: { kind: 'operation' as const },\n landing: 'files' as const,\n inputs: [\n { name: 'scope', type: 'scope' as const, label: 'Documents', by: ['labels' as const] },\n {\n name: 'output',\n type: 'select' as const,\n label: 'Review field',\n required: true,\n description:\n 'Choose a field with saved AI instructions. Create one using AI Review in Files.',\n options: reviewFields\n .filter((field) => field.instruction)\n .map((field) => ({ value: field.external_id, label: field.name })),\n },\n {\n name: 'overwrite',\n type: 'boolean' as const,\n label: 'Regenerate existing answers',\n default: false,\n },\n ],\n },\n {\n id: '__document_email__',\n title: 'Email latest documents',\n description: 'Email me links to documents added since the previous successful digest.',\n documentAction: 'email_documents' as const,\n run: { kind: 'operation' as const },\n landing: 'files' as const,\n inputs: [\n { name: 'scope', type: 'scope' as const, label: 'Documents', by: ['labels' as const] },\n {\n name: 'latest',\n type: 'boolean' as const,\n label: 'Only documents added since the last digest',\n default: true,\n },\n ],\n },\n ],\n [baseSkills, reviewFields]\n )\n // A skill opened from the library runs now even if it cannot be scheduled: offer it as a template too.\n const forTasks = useMemo(() => {\n const picked = initialWorkflowId ? skills.find((w) => w.id === initialWorkflowId) : undefined\n return picked &&\n !scheduledSkills.some((w) => w.id === picked.id) &&\n picked.run.kind === 'prompt'\n ? [...scheduledSkills, picked]\n : scheduledSkills\n }, [scheduledSkills, skills, initialWorkflowId])\n const { data: workspaceAutomations = [] } = useWorkflows()\n const { data: agents = [] } = useAgents()\n const { data: workspaces = [] } = useWorkspaces()\n const planWork = usePlanWork()\n const { tasks: allTasks } = useWorkItems()\n const { data: documents = [] } = useDocuments()\n const { create, update, updateWorkflow, isPending } = useWorkflowTasks()\n // The files behind a template's file fields: the same pieces the skill launcher wires.\n const scopeSource = useConnectedWorkflowScopeSource()\n const activeWorkspaceId = useArbiSessionState((s) => s.workspaceId)\n const activeWorkspace = useMemo(\n () => workspaces.find((w) => w.external_id === activeWorkspaceId) ?? null,\n [workspaces, activeWorkspaceId]\n )\n const timezones = useMemo(() => listTimeZones(), [])\n // The plan lists documents by id; show their names.\n const documentNames = useMemo(\n () =>\n Object.fromEntries(\n documents.flatMap((d) => (d.file_name ? [[d.external_id, d.file_name]] : []))\n ),\n [documents]\n )\n // Tasks a new task can be part of: any other task that keeps the sub-task tree within its maximum\n // depth and (when editing) is not the task itself or one of its descendants. A workflow can wait on\n // any task, finished ones included (they re-open and finish again).\n const taskOptions = useMemo(() => {\n const label = (t: TaskListRow) => t.title?.trim() || 'Untitled task'\n if (isWorkflow) return allTasks.map((t) => ({ id: t.external_id, name: label(t) }))\n const subject: TaskListRow = task ?? { external_id: '__new__' }\n return moveTargets<TaskListRow>(\n [...allTasks.filter((t) => t.external_id !== subject.external_id), subject],\n subject\n ).map((t) => ({ id: t.external_id, name: label(t) }))\n }, [allTasks, task, isWorkflow])\n // The owner's main agent: what a scheduled workflow runs as unless another is picked.\n const defaultAgentId = useMemo(\n () => (agents.find((a) => a.given_name === 'Assistant') ?? agents[0])?.external_id,\n [agents]\n )\n const agentOptions = useMemo<AgentOption[]>(\n () => agents.map((a) => ({ id: a.external_id, label: a.given_name || a.email })),\n [agents]\n )\n\n // What the composer opens with: the edit target, or (create) the preset assignee.\n const initialValues = useMemo(() => {\n const ids = {\n customWorkflowId: CUSTOM_TASK_ID,\n reminderWorkflowId: REMIND_TASK_ID,\n definitions: forTasks,\n }\n const base = launchWorkflow\n ? {\n ...workflowToComposerValues(launchWorkflow, ids),\n when: 'once' as const,\n runAt: '',\n rrule: '',\n eventKind: '',\n afterTaskId: '',\n name: '',\n }\n : editingWorkflow\n ? workflowToComposerValues(editingWorkflow, ids)\n : task\n ? taskToComposerValues(task, ids)\n : isWorkflow\n ? {\n // Run now is the default start; scheduling is the fallback in the same field.\n assignee: 'agent' as const,\n workflowId: initialWorkflowId ?? CUSTOM_TASK_ID,\n when: startLater ? ('once' as const) : ('now' as const),\n ...(initialPrompt\n ? {\n inputs: {\n [initialWorkflowId === REMIND_TASK_ID ? 'message' : 'instruction']:\n initialPrompt,\n },\n }\n : {}),\n // A scheduled run needs an agent: the owner's Assistant unless another is picked.\n ...(startLater && defaultAgentId ? { agentId: defaultAgentId } : {}),\n }\n : initialAgentExtId\n ? // Assigning an agent means agentic work: the free instruction, and tell me when done.\n { agentId: initialAgentExtId, workflowId: CUSTOM_TASK_ID, notifyOnComplete: true }\n : {}\n return {\n timezone: detectTimeZone(),\n ...base,\n ...(initialShared !== undefined && !task && !editingWorkflow\n ? { shared: initialShared }\n : {}),\n ...(!task && !isWorkflow && initialParentTaskExtId\n ? { parentTaskId: initialParentTaskExtId }\n : {}),\n }\n }, [\n forTasks,\n task,\n editingWorkflow,\n isWorkflow,\n initialWorkflowId,\n startLater,\n initialPrompt,\n initialShared,\n launchWorkflow,\n defaultAgentId,\n initialAgentExtId,\n initialParentTaskExtId,\n ])\n\n const [plan, setPlan] = useState<TaskPlan | null>(null)\n useEffect(() => {\n if (open) setPlan(task?.plan ?? editingWorkflow?.plan ?? launchWorkflow?.plan ?? null) // the stored plan when editing agent work\n }, [open, task, editingWorkflow, launchWorkflow])\n\n const handleGeneratePlan = async (values: TaskComposerValues) => {\n if (!activeWorkspace) {\n notify('Open a workspace first — the plan is scoped to it', 'warning')\n return\n }\n const objective = String(values.inputs.instruction ?? '').trim()\n if (!objective) {\n notify('Write the instruction first — it’s the planner’s objective', 'warning')\n return\n }\n try {\n const drafted = await planWork.mutateAsync({\n objective,\n max_passes: plan?.max_passes ?? 3,\n })\n setPlan(drafted)\n notify('Drafted a plan — review the checklist', 'success')\n } catch {\n notify('Could not draft a plan', 'error')\n }\n }\n\n const submit = async (submitted: TaskComposerValues, options?: { runOnce?: boolean }) => {\n // A task for me is a plain to-do and runs no workflow.\n const chosen =\n forTasks.find((w) => w.id === submitted.workflowId) ??\n (submitted.assignee === 'me' ? forTasks[0] : undefined)\n if (!chosen) return\n if (plan && !plan.goal.trim()) {\n notify('The plan needs a goal', 'warning')\n return\n }\n if (plan && plan.criteria.some((c) => !c.text.trim())) {\n notify('Every checklist criterion needs text (or remove it)', 'warning')\n return\n }\n const ctx = {\n workflow: chosen,\n values: submitted,\n plan: chosen.id === CUSTOM_TASK_ID ? plan : null,\n }\n try {\n if (isWorkflow && editingWorkflow && !options?.runOnce) {\n await updateWorkflow(editingWorkflow, ctx)\n notify(`Updated “${editingWorkflow.name}”`, 'success')\n } else if (isEdit && task) {\n await update(task, ctx)\n notify(`Updated “${task.title ?? 'task'}”`, 'success')\n } else {\n const created = await create(ctx, saveOnly && !options?.runOnce)\n if (created.kind === 'workflow') {\n notify(`Saved “${created.workflow.name}”.`, 'success')\n // The saved workflow, on the Workflows page.\n openWorkflow?.()\n } else {\n const name = created.task.title ?? 'task'\n if ((created.ran || options?.runOnce) && created.task.external_id) {\n // The run is a thread: go and watch it, rather than leave a toast to say it started.\n openConversation(created.task.external_id)\n } else {\n notify(\n created.ran === null\n ? `Added “${name}”`\n : 'Task created, but the run could not start',\n created.ran === false ? 'warning' : 'success'\n )\n }\n }\n }\n onOpenChange(false)\n } catch (error) {\n const what = `Failed to ${isEdit ? 'update' : 'create'} the ${isWorkflow ? 'workflow' : 'task'}`\n notify(\n error instanceof Error && error.message.startsWith('Open a workspace')\n ? error.message\n : error instanceof ArbiApiError && error.detail\n ? `${what}: ${error.detail}`\n : what,\n 'error'\n )\n }\n }\n\n return (\n <TaskComposer\n key={editingWorkflow?.external_id ?? task?.external_id ?? 'new'}\n open={open}\n onOpenChange={onOpenChange}\n kind={kind}\n saveOnly={saveOnly}\n hideRunLater={!automationsEnabled}\n defaultAgentId={defaultAgentId}\n isEdit={isEdit}\n workflows={forTasks}\n agents={agentOptions}\n tasks={taskOptions}\n initialValues={initialValues}\n timezones={timezones}\n eventOptions={AUTOMATION_EVENTS}\n eventWorkflowOptions={workspaceAutomations\n .filter((item) => item.external_id !== editingWorkflow?.external_id)\n .map((item) => ({ id: item.external_id, label: item.name }))}\n isPending={isPending}\n planDrafting={planWork.isPending}\n hasPlan={plan !== null}\n renderIcon={renderWorkflowIcon}\n scopeSource={scopeSource}\n renderDocuments={(field, value, onChange) => (\n <ConnectedWorkflowDocumentsField\n field={field}\n value={value}\n onChange={onChange}\n onAddFiles={openUpload}\n />\n )}\n addFilesAction={\n openUpload && (\n <Button size=\"sm\" onClick={() => openUpload()} data-testid=\"workflow-add-files-first\">\n Add files\n </Button>\n )\n }\n onDropFiles={openUpload && ((files) => openUpload(files))}\n standingAccess={(values) => (\n <StandingAccessNote\n agentId={values.agentId}\n activeWorkspaceName={activeWorkspace?.name ?? null}\n />\n )}\n labels={{\n ...(isWorkflow\n ? {\n titleNewWorkflow: 'New workflow',\n titleEditWorkflow: 'Edit workflow',\n workflowNamePlaceholder: 'Name this workflow',\n createWorkflow: 'Create workflow',\n saveWorkflow: 'Save workflow',\n descriptionWorkflow: 'Choose what happens and when this workflow starts.',\n eventHint: 'Choose the workspace event that starts this workflow.',\n runAsAgentHint: 'Scheduled AI work runs as your chosen assistant when you are away.',\n }\n : {}),\n ...(plan\n ? { addAndStart: 'Approve plan and start', addAndSchedule: 'Approve plan and schedule' }\n : {}),\n }}\n onSubmit={submit}\n goal={(values) =>\n values.workflowId === CUSTOM_TASK_ID ? (\n <TaskPlanForm\n plan={plan}\n onChange={setPlan}\n onGenerate={() => handleGeneratePlan(values)}\n isGenerating={planWork.isPending}\n workspaceName={activeWorkspace?.name ?? null}\n documentNames={documentNames}\n objective={String(values.inputs.instruction ?? '')}\n />\n ) : null\n }\n />\n )\n}\n","/**\n * A saved workflow's history and a task's activity, bound to the connection.\n *\n * - `ConnectedWorkflowHistory`: every run of a workflow (re-read while shown), each with when, what\n * it was (a thread, an email, an AI review, a reminder) and how it went; a run's thread opens\n * through the environment's `openConversation`, a document action's result through the host.\n * - `ConnectedTaskActivityDialog`: a task's timeline (re-read while it runs), with who did what.\n */\n\nimport { useCallback, type ReactNode } from 'react'\nimport { useAgents, useConversationActivity, useWorkflowRuns } from '@arbidocs/react'\nimport { formatRelativeTime } from '@arbidocs/react/ui'\nimport {\n TaskRunsDialog,\n type TaskRunView,\n type TaskRunsDialogLabels,\n} from '../agents/tasks/TaskRunsDialog'\nimport { TaskActivityDialog } from '../agents/tasks/TaskActivityDialog'\nimport type { TaskActivityEvent } from '../agents/tasks/TaskActivityTimeline'\nimport { PersonPill } from '../agents/tasks/PersonPill'\nimport { fmtDate } from '../lib/format'\nimport { useBlocksEnvironment } from '../provider/environment'\nimport { useConnectedWorkspace } from './ConnectionProvider'\nimport { useConnectedWorkspaceRole } from './ConnectedWorkflowsTable'\n\ntype WorkflowRun = NonNullable<ReturnType<typeof useWorkflowRuns>['data']>[number]\n\n/** What a run was, in a word. */\nconst RUN_KIND: Record<string, string> = {\n email_documents: 'Email',\n annotate_documents: 'AI Review',\n reminder: 'Reminder',\n}\nconst DOCUMENT_ACTIONS = new Set(['email_documents', 'annotate_documents'])\n\n/** A run as the history lists it: when, what, on how many documents. */\nexport function workflowRunView(\n run: WorkflowRun,\n formatDate: (iso: string) => string\n): TaskRunView {\n const documents = DOCUMENT_ACTIONS.has(run.action_type)\n ? ` · ${run.document_ext_ids.length} documents`\n : ''\n return {\n id: `execution-${run.id}`,\n // An AI review that finished has a result to open (its fields over its documents).\n resultId:\n run.action_type === 'annotate_documents' && run.status === 'completed'\n ? String(run.id)\n : undefined,\n status: run.status,\n when: `${formatDate(run.created_at)} · ${RUN_KIND[run.action_type] ?? 'Thread'}${documents}`,\n error: run.error,\n conversationId: run.conversation_ext_id ?? undefined,\n }\n}\n\nexport interface ConnectedWorkflowHistoryProps {\n /** The workflow (`null`: closed). */\n workflow: { external_id: string; name: string } | null\n onOpenChange: (open: boolean) => void\n /** In the page rather than a dialog. */\n inline?: boolean\n hideHeader?: boolean\n formatDate?: (iso: string) => string\n /** Open a document action's result (an AI review's fields): the host's. Absent: no Open. */\n onOpenResult?: (run: WorkflowRun) => void\n /** Under a failed run: e.g. a way to report it. */\n renderErrorReport?: (run: TaskRunView) => ReactNode\n labels?: Partial<TaskRunsDialogLabels>\n}\n\nexport function ConnectedWorkflowHistory({\n workflow,\n onOpenChange,\n inline,\n hideHeader,\n formatDate = fmtDate,\n onOpenResult,\n renderErrorReport,\n labels,\n}: ConnectedWorkflowHistoryProps) {\n const { openConversation } = useBlocksEnvironment()\n const { data: runs = [], isLoading } = useWorkflowRuns(workflow?.external_id)\n return (\n <TaskRunsDialog\n inline={inline}\n hideHeader={hideHeader}\n open={!!workflow}\n onOpenChange={onOpenChange}\n taskName={workflow?.name}\n renderErrorReport={renderErrorReport}\n isLoading={isLoading}\n labels={{\n title: (name) => `History — ${name}`,\n description: 'Executions and results of this workflow.',\n empty: 'This workflow hasn’t run yet.',\n ...labels,\n }}\n runs={runs.map((run) => workflowRunView(run, formatDate))}\n onOpenResult={\n onOpenResult &&\n ((id) => {\n const run = runs.find((r) => String(r.id) === id)\n if (run) onOpenResult(run)\n })\n }\n onOpenRun={(conversationId) => openConversation(conversationId)}\n />\n )\n}\n\n/** Relative time, compact for list rows. */\nconst relativeTime = (iso: string) => formatRelativeTime(iso, { style: 'short' })\n\nexport interface ConnectedTaskActivityDialogProps {\n conversationId: string\n taskName: string\n /** The run is generating right now: the timeline then re-reads itself every few seconds. */\n live?: boolean\n onClose: () => void\n formatExact?: (iso: string) => string\n}\n\nexport function ConnectedTaskActivityDialog({\n conversationId,\n taskName,\n live,\n onClose,\n formatExact = fmtDate,\n}: ConnectedTaskActivityDialogProps) {\n const activity = useConversationActivity(conversationId, { live })\n const { data: agents = [] } = useAgents()\n const { userId } = useConnectedWorkspace()\n const { members } = useConnectedWorkspaceRole()\n const renderPerson = useCallback(\n (id: string | null | undefined) => {\n const isMe = !!id && id === userId\n const member = members.find((m) => m.user.external_id === id)?.user\n const name =\n (member && [member.given_name, member.family_name].filter(Boolean).join(' ')) ||\n member?.email\n const person = { id, label: isMe ? 'You' : name || 'Someone', isMe }\n return <PersonPill person={person} />\n },\n [userId, members]\n )\n const agentName = useCallback(\n (agentId: string) => agents.find((a) => a.external_id === agentId)?.given_name ?? undefined,\n [agents]\n )\n return (\n <TaskActivityDialog\n open\n onOpenChange={(open) => !open && onClose()}\n taskName={taskName}\n events={activity.data as TaskActivityEvent[] | undefined}\n isLoading={activity.isLoading}\n isError={activity.isError}\n renderPerson={renderPerson}\n agentName={agentName}\n formatRelative={relativeTime}\n formatExact={formatExact}\n />\n )\n}\n","import { useCallback, useMemo, type ReactNode } from 'react'\nimport { useAgents, useArbiSession, useWorkspaceUsers } from '@arbidocs/react'\nimport { getUserDisplayName, isAgent } from '@arbidocs/react/ui'\nimport { PersonPill, type TaskPerson } from '../../agents/tasks/PersonPill'\nimport { DocumentUser } from '../files/fields/DocumentUser'\n\n/** The workspace roles that can edit it. */\nconst EDITOR_ROLES: readonly string[] = ['owner', 'collaborator']\n\n/**\n * People who can own tasks here: humans (never agents) who can edit the workspace, other than me\n * (the task list shows me as \"Me\"). They name each task's owner.\n */\nexport function useTaskPeople(): { id: string; label: string }[] {\n const { data: members = [] } = useWorkspaceUsers()\n const currentUserExtId = useArbiSession().user?.external_id\n return useMemo(\n () =>\n members\n .filter(\n (m) =>\n !isAgent(m.user) &&\n m.user.external_id !== currentUserExtId &&\n EDITOR_ROLES.includes(m.role)\n )\n .map((m) => ({ id: m.user.external_id, label: getUserDisplayName(m.user) })),\n [members, currentUserExtId]\n )\n}\n\n/**\n * How the Tasks table draws a person: the host's own user pill (presence, a click to message, the\n * rich tooltip) when the person is a member or agent we know, else the plain shared pill.\n */\nexport function useRenderTaskPerson(): (person: TaskPerson) => ReactNode {\n const { data: members = [] } = useWorkspaceUsers()\n const { data: agents = [] } = useAgents()\n const byId = useMemo(() => {\n const map = new Map(members.map((m) => [m.user.external_id, m.user]))\n for (const agent of agents) if (!map.has(agent.external_id)) map.set(agent.external_id, agent)\n return map\n }, [members, agents])\n return useCallback(\n (person: TaskPerson) => {\n const user = person.id ? byId.get(person.id) : undefined\n return user ? <DocumentUser user={user} variant=\"pill\" /> : <PersonPill person={person} />\n },\n [byId]\n )\n}\n","import { useState, type ReactNode } from 'react'\nimport type { components } from '@arbidocs/client'\nimport { useConnectedThreadActivity } from './useConnectedThreadActivity'\nimport { MoreHorizontal } from 'lucide-react'\nimport {\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from '@arbidocs/react/ui'\nimport { TaskFlow } from '../../agents/tasks/TaskFlow'\nimport {\n WorkflowThreadStartedBy,\n WorkflowThreadStrip,\n} from '../../agents/tasks/WorkflowThreadStrip'\nimport { ThreadFollowMenuItem } from '../../activity/NotificationRelevanceControls'\nimport {\n assigneeName,\n canAssign,\n runFieldsOf,\n splitDocRef,\n stepStatesFromActivity,\n type WorkflowActivityEvent,\n} from '../../agents/workflows/run'\nimport { fromPlanSteps, type TaskPlanStep } from '../../agents/workflows/planSteps'\nimport { type WorkflowInputs } from '../../agents/workflows/types'\nimport { RenameDialog } from '../../settings/Projects'\nimport { getEntityLabel, getDocumentTitle, getUserDisplayName } from '@arbidocs/react/ui'\nimport {\n useActOnStep,\n useArbiSession,\n useCanEditShared,\n useConversationItems,\n useDocuments,\n useFollowThread,\n useUpdateConversation,\n useWorkspaceUsers,\n} from '@arbidocs/react'\nimport { WorkflowStepAction } from '../../agents/workflows/WorkflowStepAction'\nimport { useBlocksEnvironment } from '../../provider/environment'\n\nexport interface ConnectedThreadTaskBarProps {\n conversationId: string | null | undefined\n /**\n * `bar` (default): the thread's whole top bar — a run's steps (as many as fit) or what happened,\n * linked threads and the thread's options. `steps`: only a run's steps on the chevron bar,\n * previous, current and next, the rest behind \"…N\" (a run page's step bar, under its own header).\n */\n variant?: 'bar' | 'steps'\n /** `steps`: the step in view, when the host keeps it (its runner's current step). */\n currentStepId?: string | null\n /** `steps`: a step was gone to on the bar. */\n onSelectStep?: (stepId: string) => void\n /** Draws a step's icon name. Absent: its kind's icon. */\n renderIcon?: (icon: string) => ReactNode\n}\n\n/**\n * A thread's top bar: a workflow run's steps (each person's step done from here), or what\n * happened in the thread, the threads linked to it, and its options (follow, mark done, rename).\n * One shared, persisted history for tasks and ordinary conversations.\n */\nexport function ConnectedThreadTaskBar({\n conversationId,\n variant = 'bar',\n currentStepId,\n onSelectStep,\n renderIcon,\n}: ConnectedThreadTaskBarProps) {\n const { conversations } = useConversationItems()\n const { activity, items, related, signals, startedBy } =\n useConnectedThreadActivity(conversationId)\n const canEditShared = useCanEditShared()\n const update = useUpdateConversation()\n const actOnStep = useActOnStep()\n const [error, setError] = useState<string | null>(null)\n const [busy, setBusy] = useState(false)\n const [renameOpen, setRenameOpen] = useState(false)\n const follow = useFollowThread(conversationId)\n const [newTitle, setNewTitle] = useState('')\n const { data: members = [] } = useWorkspaceUsers()\n const { data: documents = [] } = useDocuments()\n const me = useArbiSession().user?.external_id\n const { notify, openDocument, openFiles, openMail } = useBlocksEnvironment()\n const task = conversations.find((c) => c.external_id === conversationId)\n if (!conversationId) return null\n const nameOf = (id: string) => {\n const person = members.find((m) => m.user.external_id === id)?.user\n return person ? getUserDisplayName(person) : undefined\n }\n const steps = fromPlanSteps((task?.plan?.steps ?? []) as TaskPlanStep[])\n const states = stepStatesFromActivity((activity.data ?? []) as WorkflowActivityEvent[])\n const runInputs = (task?.skill_inputs ?? {}) as WorkflowInputs\n const stepCall = (body: components['schemas']['StepActionRequest']) =>\n actOnStep.mutateAsync({ conversationId, body })\n const canEdit = Boolean(task?.is_owner || (task?.is_shared && canEditShared))\n const renameThread = () => {\n const title = newTitle.trim()\n if (!title) return\n setBusy(true)\n setError(null)\n update\n .mutateAsync({ conversationId, patch: { title } })\n .then(() => {\n setRenameOpen(false)\n notify(`${getEntityLabel('CONVERSATION')} renamed successfully`, 'success')\n })\n .catch((e: unknown) =>\n setError(e instanceof Error ? e.message : 'Could not rename the thread')\n )\n .finally(() => setBusy(false))\n }\n const strip = (\n <WorkflowThreadStrip\n renderIcon={renderIcon}\n {...(variant === 'steps' ? { maxSpan: 3, current: currentStepId, onSelectStep } : {})}\n steps={steps}\n states={states}\n items={items}\n assigneeOf={(step) =>\n canAssign(step)\n ? assigneeName(step.assignee, {\n // A step that is the viewer's own reads \"Waiting for you\".\n nameOf: (id) => (id === me ? 'you' : nameOf(id)),\n inputs: runInputs,\n fields: runFieldsOf(steps),\n announcedTo: states[step.id]?.announcedTo,\n })\n : undefined\n }\n signals={signals}\n startedBy={startedBy}\n // The documents first: what a step drafted, what an approval approves.\n nameOfDoc={(id) => {\n const doc = documents.find((d) => d.external_id === id)\n return doc ? getDocumentTitle(doc) : undefined\n }}\n onOpenDocument={(ref) => openDocument(splitDocRef(ref).id)}\n inputs={runInputs}\n nameOf={(id) => (id === me ? 'you' : nameOf(id))}\n onSkip={\n canEdit\n ? (step) =>\n void actOnStep\n .mutateAsync({ conversationId, body: { step, action: 'skip' } })\n .catch((e: unknown) =>\n notify(e instanceof Error ? e.message : 'Could not skip the step', 'error')\n )\n : undefined\n }\n renderStepAction={(step, phase) =>\n // A signer or a draft's person acts on their step even on a thread they cannot edit.\n canEdit || phase === 'waiting' || phase === 'done' ? (\n <WorkflowStepAction\n step={step}\n phase={phase}\n steps={steps}\n states={states}\n inputs={runInputs}\n me={me}\n nameOf={nameOf}\n onComplete={(inputs) => stepCall({ step: step.id, action: 'complete', inputs })}\n onSendBack={(to, note) =>\n stepCall({ step: step.id, action: 'send_back', to, ...(note ? { note } : {}) })\n }\n onDecline={(note) =>\n stepCall({ step: step.id, action: 'decline', ...(note ? { note } : {}) })\n }\n onOpenDocument={(id) => openDocument(id)}\n onOpenDraft={openMail && ((draftId) => openMail({ draftId }))}\n onOpenReview={() => openFiles()}\n />\n ) : null\n }\n />\n )\n if (variant === 'steps')\n return task?.plan?.steps?.length ? (\n <div className=\"flex min-w-0 items-center\" data-testid=\"thread-task-bar-steps\">\n {strip}\n </div>\n ) : null\n return (\n <div\n className=\"flex min-w-0 items-center gap-2 border-b border-border px-2 py-1\"\n data-testid=\"thread-task-bar\"\n >\n {task?.plan?.steps?.length ? (\n // A workflow run: its named steps, with what happened in the thread under each.\n strip\n ) : items.length || startedBy ? (\n <>\n {/* A linked run without steps of its own still says what started it. */}\n {startedBy && <WorkflowThreadStartedBy origin={startedBy} />}\n <TaskFlow items={items.filter((item) => !item.step)} />\n </>\n ) : (\n // Ordinary chats record no activity events, so an empty ribbon says nothing rather than\n // \"No recorded activity yet\" while the answer and its steps are right there in the thread.\n <span className=\"min-w-0 flex-1 px-2 text-xs text-muted-foreground\">\n {activity.isLoading\n ? 'Loading activity…'\n : activity.isError\n ? 'Could not load activity'\n : null}\n </span>\n )}\n {related.map((link) => (\n <button\n key={link.id}\n onClick={link.onSelect}\n title={link.title}\n className=\"max-w-36 truncate text-[10px] text-muted-foreground hover:text-primary hover:underline\"\n data-testid={`thread-related-${link.id}`}\n >\n ↗ {link.label}\n </button>\n ))}\n {activity.isError && (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => void activity.refetch()}>\n Retry\n </Button>\n )}\n {/* Completion is a human decision: any editor can mark it done. */}\n {/* Rename is offered on every editable thread, tasks and ordinary chats alike. */}\n {/* Following is anyone's own choice: it is on every thread they can see. */}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n size=\"icon\"\n variant=\"ghost\"\n className=\"size-8 shrink-0\"\n aria-label=\"Thread options\"\n >\n <MoreHorizontal className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <ThreadFollowMenuItem\n following={follow.following}\n onFollowingChange={(on) =>\n // Following changes nothing on screen: say what it does.\n follow.setFollowing(on, {\n onSuccess: () =>\n notify(\n on\n ? 'Following this thread: you’ll be notified of everything in it'\n : 'Unfollowed this thread',\n 'success'\n ),\n onError: () =>\n notify(\n on ? 'Could not follow this thread' : 'Could not unfollow this thread',\n 'error'\n ),\n })\n }\n disabled={follow.isLoading || follow.isSaving}\n />\n {canEdit && task?.status && (\n <DropdownMenuItem\n disabled={busy}\n onSelect={() => {\n setBusy(true)\n void update\n .mutateAsync({\n conversationId,\n patch: { status: task.status === 'done' ? 'todo' : 'done' },\n })\n .catch((e: unknown) =>\n setError(e instanceof Error ? e.message : 'Could not update the thread')\n )\n .finally(() => setBusy(false))\n }}\n >\n {task.status === 'done' ? 'Reopen thread' : 'Mark done'}\n </DropdownMenuItem>\n )}\n {canEdit && (\n <DropdownMenuItem\n disabled={busy}\n onSelect={() => {\n setNewTitle(task?.title ?? '')\n setRenameOpen(true)\n }}\n data-testid=\"rename-thread-item\"\n >\n Rename\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n {error && (\n <span role=\"alert\" className=\"text-xs text-destructive\">\n {error}\n </span>\n )}\n <RenameDialog\n open={renameOpen}\n onClose={() => setRenameOpen(false)}\n title={`Rename ${getEntityLabel('CONVERSATION')}`}\n labels={{ description: 'Rename the conversation title' }}\n fieldLabel={`${getEntityLabel('CONVERSATION')} Title`}\n placeholder=\"Enter title\"\n value={newTitle}\n onChange={setNewTitle}\n onSave={renameThread}\n isSaving={busy}\n canSave={!!newTitle.trim()}\n dialogTestId=\"rename-thread-modal\"\n />\n </div>\n )\n}\n","/**\n * A workflow's required labels (`requiredLabels`), made to exist in the workspace a run works in.\n * The workspace is always named on the requests (`tags.list({ workspaceId })`,\n * `useCreateTag` with `workspaceId`), never taken from whichever workspace is open when they are\n * sent: a switch while the labels are being set up cannot put them in the wrong workspace.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useArbi, useCreateTag } from '@arbidocs/react'\nimport { matchRequiredLabels } from '../../agents/workflows/requiredLabels'\nimport type { WorkflowRequiredLabel } from '../../agents/workflows/types'\n\n/** Label ids by key. */\nexport type RequiredLabelIds = Record<string, string>\n\n/**\n * `ensure(labels, workspaceId)`: the labels' ids in that workspace, by key, creating the ones it\n * does not have (an existing label of the same name, in any case, is used). One set-up per\n * workspace at a time: a second call while one is under way waits for it; a finished one is kept.\n */\nexport function useEnsureRequiredLabels(): (\n labels: readonly WorkflowRequiredLabel[],\n workspaceId: string\n) => Promise<RequiredLabelIds> {\n const arbi = useArbi()\n const { mutateAsync: createTag } = useCreateTag()\n const done = useRef(new Map<string, Promise<RequiredLabelIds>>())\n return useCallback(\n (labels, workspaceId) => {\n if (!labels.length) return Promise.resolve({})\n const key = `${workspaceId}\\n${labels.map((l) => `${l.key}=${l.name}`).join('\\n')}`\n const known = done.current.get(key)\n if (known) return known\n const setUp = (async () => {\n const existing = await arbi.tags.list({ workspaceId })\n const { ids, missing } = matchRequiredLabels(labels, existing)\n for (const label of missing) {\n const tag = await createTag({\n name: label.name,\n instruction: label.instruction ?? null,\n shared: label.shared ?? true,\n tagType: {\n type: label.format?.type ?? 'checkbox',\n options: label.format?.options ?? [],\n },\n workspaceId,\n })\n ids[label.key] = tag.external_id\n }\n return ids\n })()\n done.current.set(key, setUp)\n // A failed set-up is tried again next time.\n setUp.catch(() => done.current.delete(key))\n return setUp\n },\n [arbi, createTag]\n )\n}\n\nexport interface RequiredLabelsState {\n /** `idle`: nothing to set up (no labels, or no workspace yet). */\n status: 'idle' | 'preparing' | 'ready' | 'failed'\n /** The labels' ids in the workspace, by key, once ready. */\n ids: RequiredLabelIds\n error: string | null\n retry: () => void\n}\n\n/**\n * Set the labels up in `workspaceId` as soon as it is known (`enabled`), for a page that shows the\n * set-up before the run. A new workspace starts over; what an earlier workspace's set-up returns\n * late is dropped.\n */\nexport function useRequiredLabels(\n labels: readonly WorkflowRequiredLabel[],\n workspaceId: string | undefined,\n ensure: ReturnType<typeof useEnsureRequiredLabels>,\n enabled = true\n): RequiredLabelsState {\n const [state, setState] = useState<Omit<RequiredLabelsState, 'retry'> & { for?: string }>({\n status: 'idle',\n ids: {},\n error: null,\n })\n const [attempt, setAttempt] = useState(0)\n const active = enabled && !!workspaceId && labels.length > 0\n const signature = labels.map((l) => `${l.key}=${l.name}`).join('\\n')\n const latest = useRef({ labels, ensure })\n latest.current = { labels, ensure }\n useEffect(() => {\n if (!active || !workspaceId) return\n let live = true\n setState({ status: 'preparing', ids: {}, error: null, for: workspaceId })\n latest.current.ensure(latest.current.labels, workspaceId).then(\n (ids) => live && setState({ status: 'ready', ids, error: null, for: workspaceId }),\n (e: unknown) =>\n live &&\n setState({\n status: 'failed',\n ids: {},\n error: e instanceof Error && e.message ? e.message : String(e),\n for: workspaceId,\n })\n )\n return () => {\n live = false\n }\n }, [active, workspaceId, signature, attempt])\n const retry = useCallback(() => setAttempt((a) => a + 1), [])\n if (!active) return { status: 'idle', ids: {}, error: null, retry }\n // Until the effect has started for this workspace, it is being prepared.\n if (state.for !== workspaceId) return { status: 'preparing', ids: {}, error: null, retry }\n return { status: state.status, ids: state.ids, error: state.error, retry }\n}\n","/**\n * Projects joined with their workspaces: what a project list or a project page shows of each\n * project (its details, workspaces, documents, threads, people, storage and AI quota), from the\n * shared `useProjects` and `useWorkspaces` lists (no request of its own). A project is created with\n * `useCreateProject` (`@arbidocs/react`).\n *\n * Generic: a site's words for a project (\"matter\", \"engagement\"…) and for its fields live in its\n * own config; these are the backend's project and its `client`, `client_ref`, `stage`,\n * `lead_user`, `budget` and host `fields`.\n */\n\nimport { useMemo } from 'react'\nimport type { components } from '@arbidocs/client'\nimport { useProjects, useProjectUsage, useWorkspaces } from '@arbidocs/react'\nimport {\n isAgentAccount,\n workspaceConversationCount,\n workspaceDocumentCount,\n workspaceGroupStats,\n type GroupedWorkspace,\n} from '../../workspaces/workspace-groups'\n\ntype ProjectResponse = components['schemas']['ProjectResponse']\ntype ProjectBudget = components['schemas']['ProjectBudget']\n\n/** A workspace of a project, with its counts. */\nexport interface ProjectWorkspaceSummary {\n id: string\n name: string\n description?: string\n isPublic: boolean\n documentCount: number\n conversationCount: number\n memberCount: number\n filesMb: number\n updatedAt: string\n}\n\n/** A member of any of the project's workspaces; possibly an agent (`agt-…`). */\nexport interface ProjectMemberSummary {\n id: string\n name: string\n email: string\n role: string\n isAgent: boolean\n}\n\n/** A project and the work it groups. */\nexport interface ProjectSummary {\n id: string\n name: string\n createdAt: string\n subscription: string\n workspaces: ProjectWorkspaceSummary[]\n workspaceCount: number\n documentCount: number\n conversationCount: number\n /** Everyone in the project's workspaces, agents included (`isAgent`). */\n members: ProjectMemberSummary[]\n /** The people (no agents). */\n memberCount: number\n filesMb: number\n storageUsedGb: number\n storageLimitGb: number\n /** AI usage this period against the project's limit (the quota's units). */\n aiUsageUsed: number\n aiUsageLimit: number\n client: string | null\n clientRef: string | null\n stage: string | null\n /** The project's lead (`usr-…`). */\n leadUser: string | null\n budget: ProjectBudget | null\n /** The host's own fields on the project. */\n fields: Record<string, unknown>\n}\n\nfunction workspaceSummary(w: GroupedWorkspace): ProjectWorkspaceSummary {\n return {\n id: w.external_id,\n name: w.name,\n description: w.description ?? undefined,\n isPublic: !!w.is_public,\n documentCount: workspaceDocumentCount(w),\n conversationCount: workspaceConversationCount(w),\n memberCount: w.users?.length ?? 0,\n filesMb: w.user_files_mb ?? 0,\n updatedAt: w.updated_at,\n }\n}\n\nfunction distinctMembers(workspaces: readonly GroupedWorkspace[]): ProjectMemberSummary[] {\n const byId = new Map<string, ProjectMemberSummary>()\n for (const w of workspaces) {\n for (const member of w.users ?? []) {\n const user = member.user\n const id = user?.external_id\n if (!id || byId.has(id)) continue\n const name = [user.given_name, user.family_name].filter(Boolean).join(' ').trim()\n byId.set(id, {\n id,\n name: name || user.email || 'Unknown',\n email: user.email ?? '',\n role: member.role ?? 'member',\n isAgent:\n Boolean((member as { agent_ext_id?: string | null }).agent_ext_id) ||\n isAgentAccount(user),\n })\n }\n }\n return [...byId.values()]\n}\n\n/** Join projects with their workspaces; the projects with the most work first. */\nexport function buildProjectSummaries(\n projects: readonly ProjectResponse[] | undefined,\n workspaces: readonly GroupedWorkspace[] | undefined\n): ProjectSummary[] {\n const byProject = new Map<string, GroupedWorkspace[]>()\n for (const w of workspaces ?? []) {\n const id = w.project_ext_id\n if (!id) continue\n byProject.set(id, [...(byProject.get(id) ?? []), w])\n }\n const summaries = (projects ?? []).map((p): ProjectSummary => {\n const own = byProject.get(p.external_id) ?? []\n const storage = p.quotas?.storage_gb\n const aiUsage = p.quotas?.ai_usage\n const stats = workspaceGroupStats(own)\n return {\n id: p.external_id,\n name: p.name,\n createdAt: p.created_at,\n subscription: p.subscription ?? 'none',\n workspaces: own.map(workspaceSummary),\n workspaceCount: own.length,\n documentCount: stats.documents,\n conversationCount: stats.conversations,\n members: distinctMembers(own),\n memberCount: stats.members,\n filesMb: own.reduce((sum, w) => sum + (w.user_files_mb ?? 0), 0),\n storageUsedGb: storage?.used ?? 0,\n storageLimitGb: storage?.limit ?? 0,\n aiUsageUsed: aiUsage?.used ?? 0,\n aiUsageLimit: aiUsage?.limit ?? 0,\n client: p.client ?? null,\n clientRef: p.client_ref ?? null,\n stage: p.stage ?? null,\n leadUser: p.lead_user ?? null,\n budget: p.budget ?? null,\n fields: p.fields ?? {},\n }\n })\n const work = (s: ProjectSummary) => s.documentCount + s.conversationCount\n return summaries.sort((a, b) => work(b) - work(a))\n}\n\n/** Every project the caller has, joined with its workspaces. */\nexport function useProjectSummaries() {\n const projects = useProjects()\n const workspaces = useWorkspaces()\n const summaries = useMemo(\n () =>\n buildProjectSummaries(\n projects.data as ProjectResponse[] | undefined,\n workspaces.data as GroupedWorkspace[] | undefined\n ),\n [projects.data, workspaces.data]\n )\n return {\n projects: summaries,\n isLoading: projects.isLoading || workspaces.isLoading,\n isError: projects.isError || workspaces.isError,\n error: projects.error ?? workspaces.error,\n }\n}\n\n/** One project's summary, with its AI usage this period. */\nexport function useProjectSummary(projectId: string | undefined) {\n const { projects, isLoading, isError } = useProjectSummaries()\n const project = useMemo(() => projects.find((p) => p.id === projectId), [projects, projectId])\n const usage = useProjectUsage(projectId, 0, { enabled: !!projectId })\n return { project, usage: usage.data, usageLoading: usage.isLoading, isLoading, isError }\n}\n\n/** The workspace a project's work runs in: the one with the most work. */\nexport function primaryProjectWorkspace(\n project: Pick<ProjectSummary, 'workspaces'>\n): ProjectWorkspaceSummary | undefined {\n const work = (w: ProjectWorkspaceSummary) => w.documentCount + w.conversationCount\n return [...project.workspaces].sort((a, b) => work(b) - work(a))[0]\n}\n","/**\n * The parts of a workflow run as a page (`ConnectedWorkflowRunner layout=\"page\"`): where the run\n * works (a project, chosen on the page with `ProjectPicker variant=\"run\"` or created by one of the\n * run's own steps, else the open workspace), opening that workspace, setting up the labels the\n * workflow needs there (`requiredLabels`), and saying so when another workspace has been opened\n * meanwhile. The runner composes them around its usual parts.\n *\n * The run's workspace is decided here and named on every request that sets it up, so nothing the\n * person does in another tab or panel (opening another workspace) moves the run.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react'\nimport {\n useArbiSessionStore,\n useCreateProject,\n useWorkspaces,\n type CreatedProject,\n type CreateProjectVars,\n} from '@arbidocs/react'\nimport { Button, Card, Input, Label, entityNoun } from '@arbidocs/react/ui'\nimport { AlertTriangle, Check, FolderKanban, Loader2, Plus } from 'lucide-react'\nimport type { WorkflowInputs, WorkflowRequiredLabel } from '../../agents/workflows/types'\nimport { ProjectOptionRow, ProjectPicker } from '../../workspaces/WorkspaceFormParts'\nimport { useConnectedWorkspace } from '../ConnectionProvider'\nimport {\n primaryProjectWorkspace,\n useProjectSummaries,\n type ProjectSummary,\n} from '../projects/useProjectSummaries'\nimport { useSelectWorkspace } from '../useSelectWorkspace'\n\n/**\n * Where a run's project comes from:\n * - `pick`: the person chooses one on the page (or makes a new one) before the run;\n * - `{ step, project }`: the run's own form step `step` makes it from what was filled in\n * (`project(inputs)`), and the rest of the run works in its new workspace.\n */\nexport type WorkflowRunProjectFrom =\n | 'pick'\n | {\n step: string\n project: (inputs: WorkflowInputs) => Omit<CreateProjectVars, 'workspace'>\n }\n\nexport interface WorkflowRunPageLabels {\n /** The target line's lead-in (\"Runs in\"). */\n runsIn: string\n /** The project chooser's heading. */\n chooseProject: string\n chooseProjectHint: string\n pickPlaceholder: string\n newProject: string\n newProjectName: string\n createProject: string\n /** Before a project step has made the project. */\n projectFromStep: string\n /** `{name}` is replaced. */\n opening: string\n /** `{name}` is replaced. */\n wrongWorkspace: string\n /** `{name}` is replaced. */\n openWorkspace: string\n preparingLabels: string\n labelsFailed: string\n retry: string\n openProject: string\n /** The run's workspace, before its name has loaded. */\n thisWorkspace: string\n /** The run would start before it has a workspace (a project step not done yet). */\n noWorkspace: string\n noProjects: string\n}\n\nexport const DEFAULT_WORKFLOW_RUN_PAGE_LABELS: WorkflowRunPageLabels = {\n runsIn: 'Runs in',\n chooseProject: `Choose the ${entityNoun('PROJECT')} to run it on`,\n chooseProjectHint: `The run, its documents and its results stay in the ${entityNoun('PROJECT')}.`,\n pickPlaceholder: `Select ${entityNoun('PROJECT')}`,\n newProject: `New ${entityNoun('PROJECT')}`,\n newProjectName: 'Name',\n createProject: 'Create and continue',\n projectFromStep: `A new ${entityNoun('PROJECT')}, from the first step`,\n opening: 'Opening {name}…',\n wrongWorkspace: 'This run works in {name}, which is not the workspace open now.',\n openWorkspace: 'Open {name}',\n preparingLabels: 'Setting up the review columns',\n labelsFailed: 'The review columns could not be set up.',\n retry: 'Try again',\n openProject: `Open the ${entityNoun('PROJECT')}`,\n thisWorkspace: 'this workspace',\n noWorkspace: 'There is no workspace for this run yet.',\n noProjects: `No ${entityNoun('PROJECT', 'PLURAL')} yet.`,\n}\n\n/** The run's workspace has been left while its run was being started. */\nexport class WorkflowRunWorkspaceChangedError extends Error {\n constructor(readonly workspaceId: string) {\n super('The workspace this run works in is no longer open.')\n this.name = 'WorkflowRunWorkspaceChangedError'\n }\n}\n\nexport interface WorkflowRunTargetOptions {\n projectFrom?: WorkflowRunProjectFrom\n /** The project, kept by the host (e.g. in its address). Absent: kept here. */\n projectId?: string | null\n onProjectChange?: (projectId: string) => void\n /** Without a project: the workspace the run works in. Absent: the open one. */\n workspaceId?: string\n /** A new project, made on the page or by the run's step (the host's own follow-up). */\n onProjectCreated?: (\n project: CreatedProject,\n inputs: WorkflowInputs\n ) => Promise<WorkflowInputs | void> | WorkflowInputs | void\n}\n\nexport type WorkflowRunStage = 'pick' | 'loading' | 'opening' | 'switch' | 'ready'\n\n/**\n * Where a page's run works and how far it is from ready: `pick` (no project yet), `loading` (the\n * project is being read), `opening` (its workspace is being opened), `switch` (another workspace\n * is open), `ready`.\n */\nexport function useWorkflowRunTarget({\n projectFrom,\n projectId: controlled,\n onProjectChange,\n workspaceId: fixedWorkspace,\n onProjectCreated,\n}: WorkflowRunTargetOptions) {\n const { workspaceId: open } = useConnectedWorkspace()\n const session = useArbiSessionStore()\n const selectWorkspace = useSelectWorkspace()\n const createProject = useCreateProject()\n const { projects, isLoading: projectsLoading } = useProjectSummaries()\n const { data: workspaces } = useWorkspaces()\n const [own, setOwn] = useState<string | null>(null)\n const projectId = controlled !== undefined ? controlled : own\n // A project the run made (its workspace before the lists have it).\n const [created, setCreated] = useState<{ projectId: string; workspaceId: string } | null>(null)\n // The workspace the run started in: from then on it is the run's, whatever is opened later.\n const [startedIn, setStartedIn] = useState<string | null>(null)\n const project = projectId ? projects.find((p) => p.id === projectId) : undefined\n const projectWorkspace =\n created && created.projectId === projectId\n ? created.workspaceId\n : project\n ? primaryProjectWorkspace(project)?.id\n : undefined\n\n // A run on a project works in the project's workspace (none until there is one); otherwise in\n // the host's workspace, else the open one.\n const target: string | undefined =\n startedIn ?? (projectFrom ? projectWorkspace : (fixedWorkspace ?? open ?? undefined))\n const targetRef = useRef(target)\n targetRef.current = target\n\n // The workspace open now, as of this moment (not of the last render).\n const openNow = useCallback(() => session.getState().workspaceId ?? open ?? null, [session, open])\n\n // A chosen project's workspace is opened once; leaving it later is the person's choice, and the\n // page says so instead of pulling them back.\n const [opening, setOpening] = useState<string | null>(null)\n const tried = useRef(new Set<string>())\n useEffect(() => {\n if (!target || target === open || startedIn || tried.current.has(target)) return\n tried.current.add(target)\n setOpening(target)\n selectWorkspace(target)\n .catch(() => {})\n .finally(() => setOpening((o) => (o === target ? null : o)))\n }, [target, open, startedIn, selectWorkspace])\n\n const pick = useCallback(\n (id: string) => {\n setOwn(id)\n onProjectChange?.(id)\n },\n [onProjectChange]\n )\n\n /** Make a project with its first workspace, open that, and run there. */\n const makeProject = useCallback(\n async (vars: Omit<CreateProjectVars, 'workspace'>, inputs: WorkflowInputs = {}) => {\n const made = await createProject.mutateAsync({ plan: 'free', ...vars, workspace: {} })\n const ws = made.workspace?.external_id\n if (!ws) throw new Error(`The ${entityNoun('PROJECT')} has no workspace`)\n setCreated({ projectId: made.external_id, workspaceId: ws })\n targetRef.current = ws\n setOwn(made.external_id)\n onProjectChange?.(made.external_id)\n tried.current.add(ws)\n await selectWorkspace(ws)\n const extra = await onProjectCreated?.(made, inputs)\n return { project: made, workspaceId: ws, inputs: extra ?? undefined }\n },\n [createProject, onProjectChange, selectWorkspace, onProjectCreated]\n )\n\n const nameOf = (id: string | undefined) =>\n id\n ? (project?.workspaces.find((w) => w.id === id)?.name ??\n (workspaces as Array<{ external_id: string; name: string }> | undefined)?.find(\n (w) => w.external_id === id\n )?.name)\n : undefined\n\n const stage: WorkflowRunStage =\n projectFrom === 'pick' && !projectId && !startedIn\n ? 'pick'\n : projectFrom && projectId && !target\n ? 'loading'\n : target && target !== open\n ? opening === target\n ? 'opening'\n : 'switch'\n : 'ready'\n\n return {\n stage,\n target,\n targetRef,\n targetName: nameOf(target),\n openNow,\n project,\n projectId,\n projects,\n projectsLoading,\n pick,\n makeProject,\n creating: createProject.isPending,\n /** The run started in `workspaceId`: it stays the run's. */\n pin: setStartedIn,\n openTarget: () => (target ? selectWorkspace(target) : Promise.resolve()),\n }\n}\n\nexport type WorkflowRunTarget = ReturnType<typeof useWorkflowRunTarget>\n\n/** Choose a project for the run, or make a new one. */\nexport function WorkflowRunProjectChooser({\n projects,\n loading,\n onPick,\n onCreate,\n creating,\n labels,\n testId,\n}: {\n projects: ProjectSummary[]\n loading?: boolean\n onPick: (projectId: string) => void\n onCreate: (name: string) => Promise<unknown>\n creating?: boolean\n labels: WorkflowRunPageLabels\n testId: string\n}) {\n const [adding, setAdding] = useState(false)\n const [name, setName] = useState('')\n const [error, setError] = useState<string | null>(null)\n const options = useMemo(\n () =>\n projects.map((p) => ({\n id: p.id,\n content: (\n <ProjectOptionRow\n identity={<span className=\"truncate\">{p.name}</span>}\n meta={p.client ?? undefined}\n />\n ),\n })),\n [projects]\n )\n const submit = (e: FormEvent) => {\n e.preventDefault()\n const n = name.trim()\n if (!n) return\n setError(null)\n onCreate(n).catch((err: unknown) =>\n setError(err instanceof Error && err.message ? err.message : String(err))\n )\n }\n return (\n <Card className=\"max-w-2xl space-y-4 p-5 sm:p-6\" data-testid={`${testId}-choose-project`}>\n <div className=\"space-y-1\">\n <h2 className=\"text-base font-semibold\">{labels.chooseProject}</h2>\n <p className=\"text-sm text-muted-foreground\">{labels.chooseProjectHint}</p>\n </div>\n {loading ? (\n <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n ) : projects.length ? (\n <ProjectPicker\n variant=\"run\"\n options={options}\n onChange={onPick}\n onCreate={() => setAdding(true)}\n labels={{ placeholder: labels.pickPlaceholder, create: labels.newProject }}\n testId={`${testId}-project-select`}\n />\n ) : (\n <p className=\"text-sm text-muted-foreground\">{labels.noProjects}</p>\n )}\n {adding || (!loading && !projects.length) ? (\n <form\n onSubmit={submit}\n className=\"space-y-2 border-t border-border pt-4\"\n data-testid={`${testId}-new-project`}\n >\n <Label htmlFor={`${testId}-new-project-name`}>{labels.newProjectName}</Label>\n <div className=\"flex flex-col gap-2 sm:flex-row\">\n <Input\n id={`${testId}-new-project-name`}\n value={name}\n onChange={(e) => setName(e.target.value)}\n autoFocus={adding}\n className=\"sm:max-w-md\"\n data-testid={`${testId}-new-project-name`}\n />\n <Button\n type=\"submit\"\n disabled={!name.trim() || creating}\n data-testid={`${testId}-new-project-create`}\n >\n {creating ? <Loader2 className=\"size-4 animate-spin\" /> : <Plus className=\"size-4\" />}\n {labels.createProject}\n </Button>\n </div>\n {error && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n )}\n </form>\n ) : null}\n </Card>\n )\n}\n\n/** \"Runs in <project> · <workspace>\": where the run works, and a way to the project. */\nexport function WorkflowRunTargetLine({\n project,\n workspaceName,\n fromStep,\n onOpenProject,\n labels,\n testId,\n}: {\n project?: Pick<ProjectSummary, 'id' | 'name'>\n workspaceName?: string\n fromStep?: boolean\n onOpenProject?: (projectId: string) => void\n labels: WorkflowRunPageLabels\n testId: string\n}) {\n const where = project?.name ?? (fromStep ? labels.projectFromStep : undefined)\n if (!where && !workspaceName) return null\n return (\n <div\n className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-sm\"\n data-testid={`${testId}-target`}\n >\n <span className=\"text-muted-foreground\">{labels.runsIn}</span>\n <span className=\"flex min-w-0 items-center gap-1.5 font-medium\">\n <FolderKanban className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden />\n <span className=\"truncate\">{where ?? workspaceName}</span>\n {where && workspaceName && project?.name !== workspaceName && (\n <span className=\"truncate font-normal text-muted-foreground\">· {workspaceName}</span>\n )}\n </span>\n {project && onOpenProject && (\n <Button\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0\"\n onClick={() => onOpenProject(project.id)}\n data-testid={`${testId}-open-project`}\n >\n {labels.openProject}\n </Button>\n )}\n </div>\n )\n}\n\n/** Opening the run's workspace, or setting up its labels: what is being done, and a retry. */\nexport function WorkflowRunPreparing({\n stage,\n workspaceName,\n labels: required,\n failed,\n error,\n onRetry,\n l,\n testId,\n}: {\n stage: 'loading' | 'opening' | 'labels'\n workspaceName: string\n labels: readonly WorkflowRequiredLabel[]\n failed?: boolean\n error?: string | null\n onRetry?: () => void\n l: WorkflowRunPageLabels\n testId: string\n}) {\n if (stage !== 'labels')\n return (\n <p\n className=\"flex items-center gap-2 text-sm text-muted-foreground\"\n data-testid={`${testId}-preparing`}\n >\n <Loader2 className=\"size-4 animate-spin\" />\n {l.opening.replace('{name}', workspaceName)}\n </p>\n )\n return (\n <Card className=\"max-w-2xl space-y-3 p-5\" data-testid={`${testId}-preparing`}>\n <h2 className=\"flex items-center gap-2 text-sm font-semibold\">\n {failed ? (\n <AlertTriangle className=\"size-4 text-destructive\" />\n ) : (\n <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n )}\n {failed ? l.labelsFailed : l.preparingLabels}\n </h2>\n <ul className=\"flex flex-wrap gap-1.5\">\n {required.map((label) => (\n <li\n key={label.key}\n className=\"rounded-full border border-border px-2.5 py-0.5 text-xs text-muted-foreground\"\n >\n {label.name}\n </li>\n ))}\n </ul>\n {failed && (\n <div className=\"flex flex-wrap items-center gap-3\">\n {error && <p className=\"text-sm text-muted-foreground\">{error}</p>}\n <Button size=\"sm\" variant=\"outline\" onClick={onRetry} data-testid={`${testId}-retry`}>\n {l.retry}\n </Button>\n </div>\n )}\n </Card>\n )\n}\n\n/** Another workspace is open than the run's: open the run's to go on. */\nexport function WorkflowRunWorkspaceNotice({\n workspaceName,\n onOpen,\n labels,\n testId,\n}: {\n workspaceName: string\n onOpen: () => Promise<unknown>\n labels: WorkflowRunPageLabels\n testId: string\n}) {\n const [busy, setBusy] = useState(false)\n return (\n <div\n role=\"status\"\n className=\"flex flex-col gap-3 rounded-lg border border-warning/40 bg-warning/10 p-4 sm:flex-row sm:items-center\"\n data-testid={`${testId}-switch`}\n >\n <AlertTriangle className=\"size-5 shrink-0 text-warning\" aria-hidden />\n <p className=\"min-w-0 flex-1 text-sm\">\n {labels.wrongWorkspace.replace('{name}', workspaceName)}\n </p>\n <Button\n size=\"sm\"\n disabled={busy}\n onClick={() => {\n setBusy(true)\n void onOpen().finally(() => setBusy(false))\n }}\n data-testid={`${testId}-open-workspace`}\n >\n {busy ? <Loader2 className=\"size-4 animate-spin\" /> : <Check className=\"size-4\" />}\n {labels.openWorkspace.replace('{name}', workspaceName)}\n </Button>\n </div>\n )\n}\n","/**\n * A workflow run's thread, live and interactive: the blocks `ChatPage` held to the run's one\n * conversation (people ask follow-ups, see the answers and their sources, open documents), with\n * the current step's panel beside it (`aside`). Step messages show as their step's chip.\n */\n\nimport type { ReactNode } from 'react'\nimport { ConversationScope, useConversation } from '@arbidocs/react'\nimport { ChatPage } from '../chat/ChatPage'\nimport type { ChatCitationTarget, ChatPageLabels, WorkflowStepView } from '../chat/chat-page-types'\n\nexport interface WorkflowRunThreadProps {\n conversationId: string\n workspaceId: string | undefined\n /** The current step's panel. */\n aside?: ReactNode\n /** A step by id: its title, kind and phase (step messages show as its chip). */\n stepOf?: (stepId: string) => WorkflowStepView | undefined\n /** Scroll to and mark this message (a step's answer). */\n targetMessageId?: string\n onOpenCitation?: (target: ChatCitationTarget) => void\n labels?: Partial<ChatPageLabels>\n className?: string\n}\n\nexport function WorkflowRunThread(props: WorkflowRunThreadProps) {\n // The run's conversation, in a scope of its own: the page's chat stays where it is.\n return (\n <ConversationScope workspaceId={props.workspaceId} conversationId={props.conversationId}>\n <RunThread {...props} />\n </ConversationScope>\n )\n}\n\nfunction RunThread({\n conversationId,\n workspaceId,\n aside,\n stepOf,\n targetMessageId,\n onOpenCitation,\n labels,\n className,\n}: WorkflowRunThreadProps) {\n const chat = useConversation({ workspaceId })\n return (\n <ChatPage\n chat={{ ...chat, threads: chat.threads.filter((t) => t.id === conversationId) }}\n singleThread\n documentsRequired={false}\n aside={aside}\n asideBreakpoint={52}\n workflowStepOf={stepOf}\n targetMessageId={targetMessageId}\n onOpenCitation={onOpenCitation}\n labels={labels}\n className={className ?? 'h-[min(78dvh,860px)] min-h-[480px] rounded-xl border border-border'}\n />\n )\n}\n","/**\n * A stepped workflow run that lives in a work thread on the server. The thread's plan carries the\n * steps; its activity log says where each step is; the work runner starts each agent step as a\n * turn in the thread. This hook reads all of that and does the person's part: it starts the thread\n * (with the run's inputs and the steps' prompts composed from them), completes forms, uploads and\n * reviews, skips, and retries a failed step. A run whose first open step is an agent or action\n * step starts when the person presses Start: the thread is created and the server starts that\n * step. `WorkflowRunner` shows the result.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n useActOnStep,\n useArbi,\n useConversationActivity,\n useConversationThreads,\n useConversations,\n useCreateWork,\n useWorkspaceUsers,\n type ConversationResponse,\n} from '@arbidocs/react'\nimport { fromPlanSteps, toPlanSteps, type TaskPlanStep } from '../agents/workflows/planSteps'\nimport {\n initialRunInputs,\n runThreadTitle,\n stepFields,\n stepStatesFromActivity,\n workflowSteps,\n type StepComposeOptions,\n type WorkflowActivityEvent,\n} from '../agents/workflows/run'\nimport { useWorkflowView, type WorkflowRunView } from '../agents/workflows/useWorkflowView'\nimport { withLabelIds } from '../agents/workflows/requiredLabels'\nimport type {\n WorkflowDefinition,\n WorkflowInputs,\n WorkflowStep,\n WorkflowStepState,\n} from '../agents/workflows/types'\nimport { useConnectedWorkspace } from './ConnectionProvider'\n\nexport interface UseWorkflowThreadOptions extends StepComposeOptions {\n /**\n * An existing run to show (its thread). Absent: a new run starts when its first step is done,\n * or, when that is an agent or action step, when the person starts it.\n */\n conversationId?: string\n /** The thread was created (store its id to come back to the run). */\n onStarted?: (conversationId: string) => void\n /**\n * The host's commits, by step id (`commit: true` steps): done before the step is recorded, e.g.\n * create and open the matter the run belongs in (the thread is created in the open workspace).\n * May return inputs to merge into the run.\n */\n commit?: Record<string, (inputs: WorkflowInputs) => Promise<WorkflowInputs | void>>\n /** Prefills for a new run. */\n initialInputs?: WorkflowInputs\n /** The agent that runs the agent steps (`agt-…`); absent = the person's own assistant. */\n agentId?: string\n /**\n * The files added on an upload step in this run (doc ids): sent when it is completed, so the\n * step records exactly them.\n */\n documentsFor?: (stepId: string) => string[]\n /**\n * Called as the run's thread is about to be created, after any commit: the host makes the run's\n * workspace ready (its required labels, `requiredLabels`) and may refuse (throw), e.g. when the\n * open workspace is no longer the run's. The label ids it returns go into the steps\n * (`withLabelIds`).\n */\n beforeStart?: () => Promise<{ labelIds?: Record<string, string> } | void>\n}\n\nexport interface WorkflowThread {\n view: WorkflowRunView\n /** The run's thread, once it exists. */\n conversationId: string | undefined\n conversation: ConversationResponse | undefined\n /** A workspace member's name by id. */\n nameOf: (id: string) => string | undefined\n /** The workspace's people (not agents): what a person field offers. */\n people: Array<{ value: string; label: string }>\n}\n\nconst STARTING = new Set(['pending', 'running'])\n\n/**\n * The values a form or a fielded review collected (what is recorded with it on the thread). A\n * review's blank optional fields are left out: the server checks each one given.\n */\nfunction formValues(step: WorkflowStep, inputs: WorkflowInputs): WorkflowInputs | undefined {\n const fields = stepFields(step)\n if (!fields.length) return undefined\n if (step.kind === 'form')\n return Object.fromEntries(fields.map((f) => [f.name, inputs[f.name] ?? '']))\n const given = fields.flatMap((f) => {\n const v = inputs[f.name]\n return v === undefined || v === '' ? [] : [[f.name, v] as const]\n })\n return given.length ? Object.fromEntries(given) : undefined\n}\n\n/** How many times missing answers are fetched again before giving up (about three minutes). */\nexport const ANSWER_RETRY_CAP = 16\n\n/** The wait before the `attempt`th fetch of missing answers: at once, then 1s doubling to 15s. */\nexport function answerRetryDelay(attempt: number): number {\n return attempt === 0 ? 0 : Math.min(1000 * 2 ** (attempt - 1), 15_000)\n}\n\n/**\n * Fetch again, with backoff and a cap, while `missing` (the ids of finished steps' answers not\n * read yet) is not empty. A change in what is missing starts the count again.\n */\nfunction useAnswerRetry(missing: string, refetch: () => Promise<unknown>) {\n const [attempt, setAttempt] = useState(0)\n const [prev, setPrev] = useState(missing)\n if (prev !== missing) {\n setPrev(missing)\n setAttempt(0)\n }\n const refetchRef = useRef(refetch)\n refetchRef.current = refetch\n useEffect(() => {\n if (!missing || attempt >= ANSWER_RETRY_CAP) return\n const t = setTimeout(() => {\n void refetchRef.current()\n setAttempt((a) => a + 1)\n }, answerRetryDelay(attempt))\n return () => clearTimeout(t)\n }, [missing, attempt])\n}\n\nexport function useWorkflowThread(\n workflow: WorkflowDefinition,\n options: UseWorkflowThreadOptions = {}\n): WorkflowThread {\n const arbi = useArbi()\n const { ensureWorkspaceOpen, live, workspaceId } = useConnectedWorkspace()\n const wsId = workspaceId ?? undefined\n const [threadId, setThreadId] = useState(options.conversationId)\n const [localInputs, setLocalInputs] = useState<WorkflowInputs>(() =>\n initialRunInputs(workflow, options.initialInputs)\n )\n // What the person typed: it wins over the thread's copy, which only learns a form's values when\n // that step is completed (until then it holds them blank).\n const [edits, setEdits] = useState<WorkflowInputs>({})\n const [localStates, setLocalStates] = useState<Record<string, WorkflowStepState>>({})\n const createWork = useCreateWork()\n const actOnStep = useActOnStep()\n\n const conversations = useConversations(wsId, { enabled: !!threadId, live: true })\n const members = useWorkspaceUsers(wsId, {\n enabled: live && !!wsId,\n beforeFetch: ensureWorkspaceOpen,\n })\n const nameOf = useCallback(\n (id: string) => {\n const u = members.data?.find((m) => m.user.external_id === id)?.user\n return u ? [u.given_name, u.family_name].filter(Boolean).join(' ') || u.email : undefined\n },\n [members.data]\n )\n const conversation = conversations.data?.find((c) => c.external_id === threadId)\n const steps = useMemo(\n () =>\n workflowSteps(workflow).length > 0\n ? workflowSteps(workflow)\n : fromPlanSteps((conversation?.plan?.steps ?? []) as TaskPlanStep[]),\n [workflow, conversation?.plan?.steps]\n )\n\n // Poll while an agent step is on its way (the server starts it, then runs it).\n const activity = useConversationActivity(threadId, { live: !!threadId })\n const serverStates = useMemo(\n () => stepStatesFromActivity((activity.data ?? []) as WorkflowActivityEvent[]),\n [activity.data]\n )\n const working = steps.some(\n (s) =>\n (s.kind === 'agent' || s.kind === 'action') &&\n STARTING.has(serverStates[s.id]?.status ?? 'pending')\n )\n const threads = useConversationThreads(threadId, { enabled: !!threadId, live: working })\n // Only answers with text: the assistant's message exists (empty) from the moment its turn\n // starts and is filled when the turn ends, which can be after the step is recorded done.\n const answers = useMemo(() => {\n const byId = new Map<string, string>()\n for (const t of threads.data?.threads ?? [])\n for (const m of t.history)\n if (m.role === 'assistant' && m.content?.trim()) byId.set(m.external_id, m.content)\n return byId\n }, [threads.data])\n\n // A step can finish as the run stops (the last one always does): nothing is polled then, and\n // the activity log no longer changes. Fetch the messages again, backing off, until every\n // finished step's answer is in (or the cap is reached; a new missing answer starts again).\n const missing = Object.values(serverStates)\n .flatMap((st) =>\n st.status === 'done' && st.responseId && !answers.has(st.responseId) ? [st.responseId] : []\n )\n .sort()\n .join(' ')\n useAnswerRetry(missing, threads.refetch)\n\n const states = useMemo(() => {\n if (!threadId) return localStates\n const out: Record<string, WorkflowStepState> = {}\n for (const [id, s] of Object.entries(serverStates))\n out[id] = { ...s, text: s.responseId ? answers.get(s.responseId) : undefined }\n return out\n }, [threadId, localStates, serverStates, answers])\n\n const inputs = useMemo(\n () =>\n threadId\n ? { ...localInputs, ...(conversation?.skill_inputs ?? {}), ...edits }\n : { ...localInputs, ...edits },\n [threadId, localInputs, conversation?.skill_inputs, edits]\n ) as WorkflowInputs\n\n const refresh = useCallback(async () => {\n await Promise.all([activity.refetch(), conversations.refetch()])\n }, [activity, conversations])\n\n const act = useCallback(\n async (\n id: string,\n body: {\n step: string\n action: 'complete' | 'skip' | 'send_back' | 'decline'\n inputs?: WorkflowInputs\n documents?: string[]\n to?: string\n note?: string\n }\n ) => {\n await actOnStep.mutateAsync({ conversationId: id, body })\n await refresh()\n },\n [actOnStep, refresh]\n )\n\n // The run starts: its thread, in the workspace now open, with the steps and the inputs so far.\n // Creating it starts the first ready agent step on the server; the steps skipped before it existed\n // are then recorded (which starts what they made ready).\n const createThread = useCallback(\n async (values: WorkflowInputs, done?: string): Promise<string> => {\n const prepared = await options.beforeStart?.()\n const planned = prepared?.labelIds ? withLabelIds(workflow, prepared.labelIds) : workflow\n await ensureWorkspaceOpen()\n const created = await createWork.mutateAsync({\n title: runThreadTitle(workflow, values).slice(0, 60),\n description: workflow.description || null,\n prompt: null,\n skill_ref: null,\n skill_inputs: values as Record<string, unknown>,\n agent_ext_id: options.agentId ?? null,\n auth_mode: 'run_now_temp',\n plan: {\n goal: '',\n criteria: [],\n max_passes: 3,\n documents: [],\n steps: toPlanSteps(planned, {\n inputs: values,\n resolveWorkflow: options.resolveWorkflow,\n compose: options.compose,\n }),\n },\n })\n const id = created.external_id\n setThreadId(id)\n if (done) setLocalStates((s) => ({ ...s, [done]: { status: 'done' } }))\n options.onStarted?.(id)\n for (const [stepId, st] of Object.entries(localStates))\n if (st.status === 'skipped')\n await actOnStep.mutateAsync({\n conversationId: id,\n body: { step: stepId, action: 'skip' },\n })\n return id\n },\n [ensureWorkspaceOpen, createWork, workflow, options, localStates, actOnStep]\n )\n\n const complete = useCallback(\n async (step: WorkflowStep) => {\n let values = inputs\n const commit = step.commit ? options.commit?.[step.id] : undefined\n if (commit && localStates[step.id]?.status !== 'done') {\n values = { ...values, ...((await commit(values)) ?? {}) }\n setLocalInputs(values)\n setEdits({})\n }\n const id = threadId ?? (await createThread(values, step.id))\n const documents = step.kind === 'upload' ? options.documentsFor?.(step.id) : undefined\n await act(id, {\n step: step.id,\n action: 'complete',\n inputs: formValues(step, values),\n ...(documents?.length ? { documents } : {}),\n })\n },\n [inputs, options, localStates, threadId, createThread, act]\n )\n\n // Start the ready agent or action step nothing else will start: create the run's thread (the\n // server starts the step), or run the thread again (the server could not start it before).\n const start = useCallback(async () => {\n if (!threadId) {\n await createThread(inputs)\n await refresh()\n return\n }\n await arbi.conversations.runWithAuth(threadId)\n await refresh()\n }, [threadId, createThread, inputs, arbi, refresh])\n\n const skip = useCallback(\n async (stepId: string) => {\n if (!threadId) {\n setLocalStates((s) => ({ ...s, [stepId]: { status: 'skipped' } }))\n return\n }\n await act(threadId, { step: stepId, action: 'skip' })\n },\n [threadId, act]\n )\n\n const retry = useCallback(\n async (_stepId: string) => {\n if (!threadId) return\n // Running the thread again retries its failed step.\n await arbi.conversations.runWithAuth(threadId)\n await refresh()\n },\n [arbi, threadId, refresh]\n )\n\n const sendBack = useCallback(\n async (stepId: string, to: string, note?: string) => {\n if (!threadId) return\n await act(threadId, { step: stepId, action: 'send_back', to, ...(note ? { note } : {}) })\n },\n [threadId, act]\n )\n\n const decline = useCallback(\n async (stepId: string, note?: string) => {\n if (!threadId) return\n await act(threadId, { step: stepId, action: 'decline', ...(note ? { note } : {}) })\n },\n [threadId, act]\n )\n\n // A run opened later opens where it is once its log has arrived (not at its first step).\n const loaded = !options.conversationId || activity.isSuccess || activity.isError\n\n // Nothing will start a ready agent or action step unless the person does: there is no thread\n // yet, or the thread's run is not under way (it could not start: `last_error` says why).\n const idle = !!conversation && !conversation.in_progress\n const anyRunning = Object.values(states).some((s) => s.status === 'running')\n const needsStart = !threadId || (idle && !anyRunning)\n const runError = idle ? (conversation?.last_error ?? null) : null\n\n const view = useWorkflowView({\n steps,\n states,\n inputs,\n setInput: (name, value) => setEdits((i) => ({ ...i, [name]: value })),\n complete,\n skip,\n retry,\n start,\n needsStart,\n runError,\n sendBack,\n decline,\n nameOf,\n loaded,\n isLocked: (id) => states[id]?.status === 'done',\n })\n\n const people = useMemo(\n () =>\n (members.data ?? [])\n .filter((m) => !m.user.external_id.startsWith('agt-'))\n .map((m) => ({\n value: m.user.external_id,\n label: nameOf(m.user.external_id) ?? m.user.external_id,\n })),\n [members.data, nameOf]\n )\n\n return { view, conversationId: threadId, conversation, nameOf, people }\n}\n","/**\n * What the connected runner opens itself when the host does not take over: the sign flow for a\n * signature step (the blocks `SignDocumentDialog` on the document's PDF), the native Word editor\n * for a tracked-changes version, and a tabular review's grid (its documents by its columns).\n */\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport { useArbi, useDocuments, useTags } from '@arbidocs/react'\nimport {\n DocumentToolsProvider,\n fetchDocumentPdf,\n useOptionalDocumentTools,\n} from '@arbidocs/react/document-tools'\nimport { Loader2 } from 'lucide-react'\nimport { SignDocumentDialog } from '../document-tools/SignDocumentDialog'\nimport { ModalScaffold } from '../settings/ModalScaffold'\nimport { splitDocRef } from '../agents/workflows/run'\nimport { ConnectedNativeDocxEditor } from './docx/ConnectedNativeDocxEditor'\nimport { useConnectedWorkspace } from './ConnectionProvider'\n\nexport interface WorkflowRunnerDialogLabels {\n loadingDocument: string\n preparingDocument: string\n documentFailed: string\n reviewTitle: string\n reviewDescription: string\n document: string\n empty: string\n showMore: string\n showLess: string\n wordTitle: string\n}\n\nexport const DEFAULT_WORKFLOW_RUNNER_DIALOG_LABELS: WorkflowRunnerDialogLabels = {\n loadingDocument: 'Opening the document…',\n preparingDocument: 'The PDF is still being prepared…',\n documentFailed: 'The document could not be opened.',\n reviewTitle: 'Review',\n reviewDescription: 'Each document against each review column.',\n document: 'Document',\n empty: '—',\n showMore: 'Show more',\n showLess: 'Show less',\n wordTitle: 'Tracked changes',\n}\n\n/** How often, and how long apart, the PDF is fetched again while it is still being rendered. */\nconst SIGN_PDF_RETRIES = 4\nexport const SIGN_PDF_RETRY_DELAY_MS = 1500\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\n/**\n * The sign flow on one document version: its PDF is fetched, then the blocks sign dialog.\n *\n * What is signed is the PDF `GET /view?version=` serves (a Word or Markdown document's rendition),\n * never the original's download, so the hash the server checks is of the bytes shown here. A\n * rendition still being written is fetched again a few times; a version superseded since the step\n * was set offers the current one instead.\n */\nexport function WorkflowSignDialog({\n docRef,\n onClose,\n labels,\n}: {\n /** `doc-…` or `doc-…@v3`. */\n docRef: string\n onClose: () => void\n labels: WorkflowRunnerDialogLabels\n}) {\n const arbi = useArbi()\n const { user, ensureWorkspaceOpen } = useConnectedWorkspace()\n const tools = useOptionalDocumentTools()\n const { id, version: stepVersion } = splitDocRef(docRef)\n // The version the step names, until the signer opens the current one instead.\n const [version, setVersion] = useState(stepVersion)\n const [pdf, setPdf] = useState<Blob | null>(null)\n const [preparing, setPreparing] = useState(false)\n const [failed, setFailed] = useState(false)\n useEffect(() => {\n let live = true\n setPdf(null)\n setFailed(false)\n setPreparing(false)\n void (async () => {\n try {\n await ensureWorkspaceOpen()\n const client = arbi.getClient().fetch\n const ref = version ? `${id}@v${version}` : id\n for (let attempt = 0; ; attempt++) {\n try {\n const blob = await fetchDocumentPdf(client, ref)\n if (live) setPdf(blob)\n return\n } catch (err) {\n if (!live || attempt >= SIGN_PDF_RETRIES) throw err\n setPreparing(true)\n await wait(SIGN_PDF_RETRY_DELAY_MS)\n if (!live) return\n }\n }\n } catch {\n if (live) setFailed(true)\n }\n })()\n return () => {\n live = false\n }\n }, [arbi, id, version, ensureWorkspaceOpen])\n\n if (!pdf)\n return (\n <ModalScaffold\n open\n onOpenChange={(o) => !o && onClose()}\n title={labels.loadingDocument}\n size=\"sm\"\n testId=\"workflow-sign-loading\"\n >\n <ModalScaffold.Body>\n <p className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n {failed ? (\n labels.documentFailed\n ) : (\n <>\n <Loader2 className=\"size-4 animate-spin\" />{' '}\n {preparing ? labels.preparingDocument : labels.loadingDocument}\n </>\n )}\n </p>\n </ModalScaffold.Body>\n </ModalScaffold>\n )\n const dialog = (\n <SignDocumentDialog\n // A new PDF is a new signing: the form starts again on it.\n key={version ?? 'current'}\n open\n onOpenChange={(o) => !o && onClose()}\n documentId={id}\n pdfBlob={pdf}\n version={version}\n // Superseded since the step was set: sign the current version, after seeing it.\n onOpenCurrent={() => setVersion(undefined)}\n />\n )\n // A host with its own document tools keeps them (its notices, its document opening).\n return tools ? (\n dialog\n ) : (\n <DocumentToolsProvider\n client={arbi.getClient().fetch}\n user={user ? { name: user.name, email: user.email } : null}\n >\n {dialog}\n </DocumentToolsProvider>\n )\n}\n\n/** A tracked-changes version in the native Word editor. */\nexport function WorkflowWordDialog({\n docRef,\n title,\n onClose,\n labels,\n}: {\n docRef: string\n title?: string\n onClose: () => void\n labels: WorkflowRunnerDialogLabels\n}) {\n const { id } = splitDocRef(docRef)\n return (\n <ModalScaffold\n open\n onOpenChange={(o) => !o && onClose()}\n title={title ?? labels.wordTitle}\n size=\"xl\"\n testId=\"workflow-word-dialog\"\n >\n <ModalScaffold.Body className=\"h-[70dvh] p-0\">\n <ConnectedNativeDocxEditor documentId={id} title={title ?? labels.wordTitle} />\n </ModalScaffold.Body>\n </ModalScaffold>\n )\n}\n\n/** A tabular review's grid: each document (row) against each column (label), with its value. */\nexport function WorkflowReviewGridDialog({\n tags,\n documents,\n onClose,\n onOpenDocument,\n labels,\n}: {\n tags: string[]\n documents: string[]\n onClose: () => void\n onOpenDocument?: (docId: string) => void\n labels: WorkflowRunnerDialogLabels\n}) {\n const { workspaceId } = useConnectedWorkspace()\n const allTags = useTags(workspaceId ?? undefined)\n // The workspace's documents carry their review values (doctags); the review's rows are its own.\n const all = useDocuments(workspaceId ?? undefined)\n // The grid waits for its column names and for documents fetched since it opened: before, its\n // headers would be the raw tag ids and its cells the values cached before the review ran.\n const isLoading =\n allTags.isLoading || all.isLoading || (all.isFetching && !all.isFetchedAfterMount)\n const docs = (all.data ?? []).filter((d) => documents.includes(d.external_id))\n const columns = useMemo(\n () =>\n tags.map((id) => ({\n id,\n name: allTags.data?.find((t) => t.external_id === id)?.name ?? id,\n })),\n [tags, allTags.data]\n )\n return (\n <ModalScaffold\n open\n onOpenChange={(o) => !o && onClose()}\n title={labels.reviewTitle}\n description={labels.reviewDescription}\n showDescription\n size=\"xl\"\n testId=\"workflow-review-grid\"\n >\n <ModalScaffold.Body className=\"overflow-auto\">\n {isLoading ? (\n <p className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Loader2 className=\"size-4 animate-spin\" /> {labels.loadingDocument}\n </p>\n ) : (\n <table className=\"w-full border-collapse text-sm\">\n <thead>\n <tr>\n <th className=\"sticky left-0 z-10 border-b border-border bg-background p-2 text-left align-bottom font-medium\">\n {labels.document}\n </th>\n {columns.map((c) => (\n <th\n key={c.id}\n className=\"border-b border-border p-2 text-left align-bottom font-medium\"\n >\n <div className={`${VALUE_WIDTH} line-clamp-2 break-words`} title={c.name}>\n {c.name}\n </div>\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {docs.map((d) => (\n <tr key={d.external_id} data-testid={`workflow-review-grid-row-${d.external_id}`}>\n <td className=\"sticky left-0 z-10 border-b border-border bg-background p-2 align-top\">\n <DocumentName onClick={onOpenDocument && (() => onOpenDocument(d.external_id))}>\n {d.file_name ?? d.external_id}\n </DocumentName>\n </td>\n {columns.map((c) => {\n const note = d.doctags?.find((t) => t.tag_ext_id === c.id)?.note\n return (\n <td\n key={c.id}\n className=\"border-b border-border p-2 align-top text-muted-foreground\"\n >\n <ReviewValue value={note || labels.empty} labels={labels} />\n </td>\n )\n })}\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </ModalScaffold.Body>\n </ModalScaffold>\n )\n}\n\n/*\n * Widths sit on a block inside each cell: an auto-layout table ignores `max-width` on a cell, so a\n * long file name or answer would otherwise widen its column, or (without wrapping) spill into the\n * next one. The grid scrolls sideways when the columns do not fit.\n */\nconst DOCUMENT_WIDTH = 'w-40 sm:w-56'\nconst VALUE_WIDTH = 'min-w-48 max-w-80'\n\n/** The row's document: its name wraps over two lines at most, the full name on hover. */\nfunction DocumentName({ onClick, children }: { onClick?: () => void; children: string }) {\n const className = `${DOCUMENT_WIDTH} line-clamp-2 break-words text-left font-medium`\n return onClick ? (\n <button\n type=\"button\"\n onClick={onClick}\n title={children}\n className={`${className} text-primary hover:underline`}\n >\n {children}\n </button>\n ) : (\n <div title={children} className={className}>\n {children}\n </div>\n )\n}\n\n/** A review value: four lines, then a toggle to read the rest in place. */\nfunction ReviewValue({ value, labels }: { value: string; labels: WorkflowRunnerDialogLabels }) {\n const ref = useRef<HTMLDivElement>(null)\n const [expanded, setExpanded] = useState(false)\n const [clamped, setClamped] = useState(false)\n useLayoutEffect(() => {\n const el = ref.current\n if (el && !expanded) setClamped(el.scrollHeight > el.clientHeight + 1)\n }, [value, expanded])\n return (\n <div className={VALUE_WIDTH}>\n <div\n ref={ref}\n title={clamped && !expanded ? value : undefined}\n className={`whitespace-pre-line break-words ${expanded ? '' : 'line-clamp-4'}`}\n >\n {value}\n </div>\n {(clamped || expanded) && (\n <button\n type=\"button\"\n onClick={() => setExpanded((e) => !e)}\n className=\"mt-1 text-xs font-medium text-primary hover:underline\"\n >\n {expanded ? labels.showLess : labels.showMore}\n </button>\n )}\n </div>\n )\n}\n","/**\n * A stepped workflow run in its work thread, end to end: `useWorkflowThread` keeps the run on the\n * server (the thread's plan, its activity, its turns) and `WorkflowRunner` shows it. Agent answers\n * are the thread's messages; uploads go into the open workspace; a review can notify the people\n * who should approve it, in the run's thread. The host keeps its wording, its commits\n * (`options.commit`) and its finish screen.\n *\n * The labels a workflow needs (`requiredLabels`, a tabular review's columns) are found or created\n * in the run's workspace before its thread is created, named on every request.\n *\n * `layout=\"page\"` is the run as a page of its own: the workflow's header, where it runs (a\n * project, chosen with `ProjectPicker variant=\"run\"` or made by one of its steps, else the open\n * workspace), that workspace opened and its labels set up, then the run: the thread with the\n * steps' chevron bar on top (`ConnectedThreadTaskBar variant=\"steps\"`) and the current step beside\n * it. Opening another workspace meanwhile never moves the run: the page says so and offers the\n * run's workspace back.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n AiAnswer,\n useArbi,\n useArbiSessionStore,\n useDocuments,\n useWorkspaceUsers,\n} from '@arbidocs/react'\nimport { Button, cn } from '@arbidocs/react/ui'\nimport { ExternalLink, Loader2, MessageSquare } from 'lucide-react'\nimport {\n WorkflowRunner,\n type WorkflowRunnerFile,\n type WorkflowRunnerProps,\n} from '../agents/workflows/WorkflowRunner'\nimport type { WorkflowRunnerActions } from '../agents/workflows/StepParts'\nimport { WorkflowStepBar } from '../agents/workflows/WorkflowStepBar'\nimport { splitDocRef, stepLevels } from '../agents/workflows/run'\nimport { stepKindOf } from '../agents/workflows/stepKinds'\nimport { stepDocuments } from '../agents/workflows/StepDocuments'\nimport type {\n WorkflowAgentStep,\n WorkflowDefinition,\n WorkflowInputs,\n WorkflowStepState,\n WorkflowUploadStep,\n} from '../agents/workflows/types'\nimport { requiredLabelsOf, withLabelIds } from '../agents/workflows/requiredLabels'\nimport { PageHeader, type PageHeaderProps } from '../components/PageHeader'\nimport { ConnectedThreadTaskBar } from './tasks/ConnectedThreadTaskBar'\nimport type { ProjectSummary } from './projects/useProjectSummaries'\nimport { useEnsureRequiredLabels, useRequiredLabels } from './workflows/useRequiredLabels'\nimport {\n DEFAULT_WORKFLOW_RUN_PAGE_LABELS,\n WorkflowRunPreparing,\n WorkflowRunProjectChooser,\n WorkflowRunTargetLine,\n WorkflowRunWorkspaceChangedError,\n WorkflowRunWorkspaceNotice,\n useWorkflowRunTarget,\n type WorkflowRunPageLabels,\n type WorkflowRunTarget,\n type WorkflowRunTargetOptions,\n} from './workflows/WorkflowRunPage'\nimport { useConnectedWorkspace } from './ConnectionProvider'\nimport { useDocumentFilter } from './workspaceData'\nimport { useWorkflowThread, type UseWorkflowThreadOptions } from './useWorkflowThread'\nimport { WorkflowRunThread } from './WorkflowRunThread'\nimport type { ChatCitationTarget } from '../chat/chat-page-types'\nimport { useBlocksEnvironment } from '../provider/environment'\nimport { useOpenCitation } from '../chat/useOpenCitation'\nimport {\n DEFAULT_WORKFLOW_RUNNER_DIALOG_LABELS,\n WorkflowReviewGridDialog,\n WorkflowSignDialog,\n WorkflowWordDialog,\n type WorkflowRunnerDialogLabels,\n} from './WorkflowRunnerDialogs'\n\nexport interface ConnectedWorkflowRunnerLabels {\n notify: string\n /** An agent step's answer, in the thread layout: a link to it in the thread. */\n showInThread: string\n /** The thread layout's panel toggle, when the panel folds (a narrow container). */\n currentStep: string\n /** A finished step whose answer is still being fetched. */\n loadingAnswer: string\n notified: string\n openThread: string\n}\n\nexport const DEFAULT_CONNECTED_WORKFLOW_RUNNER_LABELS: ConnectedWorkflowRunnerLabels = {\n notify: 'Ask to approve',\n showInThread: 'Show in the thread',\n currentStep: 'Current step',\n notified: 'Notified.',\n openThread: 'Open the thread',\n loadingAnswer: 'Fetching the answer…',\n}\n\nexport interface ConnectedWorkflowRunnerProps extends Omit<\n WorkflowRunnerProps,\n | 'run'\n | 'renderAgentOutput'\n | 'onUpload'\n | 'uploading'\n | 'files'\n | 'onRetryUpload'\n | 'onRemoveUpload'\n | 'renderReview'\n | 'actions'\n | 'nameOfDoc'\n | 'compact'\n | 'hideStepBar'\n> {\n workflow: WorkflowDefinition\n /** The run's bindings: an existing thread, commits, prompt wording, workflow lookup. */\n options?: UseWorkflowThreadOptions\n /** Open a conversation (the run's thread): the host navigates. */\n onOpenConversation?: (conversationId: string) => void\n /** The muted line an agent step shows before its answer. */\n emptyHint?: (step: WorkflowAgentStep) => string | undefined\n connectedLabels?: Partial<ConnectedWorkflowRunnerLabels>\n /**\n * Open a document (a version: `version`; at a page: `page`, from a citation). Default: the\n * environment's `openDocument`. In the thread layout a citation opens its document with it too,\n * unless `onOpenCitation` is given.\n */\n onOpenDocument?: (documentId: string, version?: number, page?: number) => void\n /**\n * The thread layout's citation open action, as `ChatPage`'s `onOpenCitation` (the cited\n * document, page and passage). Absent: `onOpenDocument`, else the environment's `openDocument`\n * at the cited passage.\n */\n onOpenCitation?: (target: ChatCitationTarget) => void\n /** Open an email step's draft in native mail. Default: the environment's `openMail`; a host\n * without mail: no button. */\n onOpenDraft?: (draftId: string) => void\n /** Show an answer in the run's thread. Absent: no link. */\n onOpenMessage?: (messageId: string) => void\n /**\n * Take over what the runner otherwise opens itself: the sign flow, the Word editor for a\n * tracked-changes version, a tabular review's grid.\n */\n actions?: Pick<WorkflowRunnerActions, 'sign' | 'openRedline' | 'openReview'>\n dialogLabels?: Partial<WorkflowRunnerDialogLabels>\n /**\n * `thread` (default): once the run has its thread, the page is that thread, live (follow-ups,\n * answers with their sources, documents), with the step bar on top and the current step in a\n * compact panel beside it; steps' answers link to their message instead of being repeated.\n * Before the thread exists (the first form), it is the stepper: one step at a time.\n * `page`: the run as a page of its own (its header, where it runs, its set-up, then `thread`'s\n * arrangement with the thread's step bar), with the page and project options below.\n */\n layout?: 'thread' | 'page'\n /**\n * `page`: where the run's project comes from (`pick`: chosen on the page; `{ step, project }`:\n * made by that form step from its inputs). Absent: no project, the run works in `workspaceId`,\n * else the open workspace.\n */\n projectFrom?: WorkflowRunTargetOptions['projectFrom']\n /** `page`: the project, when the host keeps it (e.g. in its address). Absent: kept here. */\n projectId?: string | null\n /** `page`: a project was chosen or made. */\n onProjectChange?: (projectId: string) => void\n /** `page`: a new run's prefills from its project (a client's name, a reference…). */\n inputsFromProject?: (project: ProjectSummary) => WorkflowInputs\n /** `page`: a project made on the page or by the run's step; may return inputs for the run. */\n onProjectCreated?: WorkflowRunTargetOptions['onProjectCreated']\n /** `page`, without a project: the workspace the run works in. Absent: the open one. */\n workspaceId?: string\n /** `page`: the header's eyebrow, leading (a back button), description and extra actions. */\n pageHeader?: Partial<Omit<PageHeaderProps, 'tabs' | 'testId'>>\n pageLabels?: Partial<WorkflowRunPageLabels>\n}\n\n/** What the page layout hands the run once it can start. */\ninterface RunnerPageContext {\n target: WorkflowRunTarget\n labelIds: Record<string, string>\n /** The page's label set-up: the run's start reuses what it already did. */\n ensureLabels: ReturnType<typeof useEnsureRequiredLabels>\n labels: WorkflowRunPageLabels\n}\n\n/** A workspace document, as an upload step lists it. */\nexport type WorkflowRunnerDocument = NonNullable<ReturnType<typeof useDocuments>['data']>[number]\n\n/** What the runner has open itself. */\ntype OpenDialog =\n | { kind: 'sign'; docRef: string }\n | { kind: 'word'; docRef: string; title: string }\n | { kind: 'review'; tags: string[]; documents: string[] }\n\nexport function ConnectedWorkflowRunner(props: ConnectedWorkflowRunnerProps) {\n return props.layout === 'page' ? <RunnerPage {...props} /> : <RunnerBody {...props} />\n}\n\nfunction RunnerBody({\n workflow: given,\n options,\n onOpenConversation,\n emptyHint,\n connectedLabels,\n onOpenDocument: hostOpenDocument,\n onOpenCitation,\n onOpenDraft: hostOpenDraft,\n onOpenMessage,\n actions: hostActions,\n dialogLabels,\n testIdPrefix = 'workflow-run',\n page,\n // The page's options the run itself uses (the page layout takes the rest; `WorkflowRunner`\n // ignores them).\n projectFrom,\n inputsFromProject,\n ...runnerProps\n}: ConnectedWorkflowRunnerProps & { page?: RunnerPageContext }) {\n const l = { ...DEFAULT_CONNECTED_WORKFLOW_RUNNER_LABELS, ...connectedLabels }\n const environment = useBlocksEnvironment()\n const openInEnvironment = useCallback(\n (id: string, version?: number, page?: number) =>\n environment.openDocument(id, { ...(version && { version }), ...(page && { page }) }),\n [environment]\n )\n const onOpenDocument = hostOpenDocument ?? openInEnvironment\n const { openMail } = environment\n const draftInMail = useMemo(\n () => openMail && ((draftId: string) => openMail({ draftId })),\n [openMail]\n )\n const onOpenDraft = hostOpenDraft ?? draftInMail\n const citationInEnvironment = useOpenCitation()\n const dl = { ...DEFAULT_WORKFLOW_RUNNER_DIALOG_LABELS, ...dialogLabels }\n const arbi = useArbi()\n const { ensureWorkspaceOpen, userId, workspaceId } = useConnectedWorkspace()\n const wsId = workspaceId ?? undefined\n const session = useArbiSessionStore()\n const openRef = useRef(workspaceId)\n openRef.current = workspaceId\n\n // The labels the workflow needs, by key: set up by the page before the run, else as it starts.\n const required = requiredLabelsOf(given)\n const ownEnsureLabels = useEnsureRequiredLabels()\n const ensureLabels = page?.ensureLabels ?? ownEnsureLabels\n const [startedLabelIds, setStartedLabelIds] = useState<Record<string, string>>({})\n const pageLabelIds = page?.labelIds\n const labelIds = useMemo(\n () => ({ ...pageLabelIds, ...startedLabelIds }),\n [pageLabelIds, startedLabelIds]\n )\n // A project step (`projectFrom: { step }`) is one the page commits: it makes the project.\n const pageTarget = page?.target\n const projectStep = pageTarget && typeof projectFrom === 'object' ? projectFrom.step : undefined\n const workflow = useMemo(\n () => withCommitStep(withLabelIds(given, labelIds), projectStep),\n [given, labelIds, projectStep]\n )\n // As the run's thread is about to be created: its workspace (the page's, else the one open as it\n // starts) has its labels, and is still the one open, or the run does not start.\n const hostBeforeStart = options?.beforeStart\n const noWorkspace = page?.labels.noWorkspace\n const beforeStart = useMemo(() => {\n if (!pageTarget && !required.length) return hostBeforeStart\n return async () => {\n const openNow = () => session.getState().workspaceId ?? openRef.current ?? undefined\n // The run's workspace as of the moment it starts, before anything is awaited.\n const ws = pageTarget ? pageTarget.targetRef.current : openNow()\n if (!ws) throw new Error(noWorkspace ?? DEFAULT_WORKFLOW_RUN_PAGE_LABELS.noWorkspace)\n const fromHost = await hostBeforeStart?.()\n const ids = { ...(await ensureLabels(required, ws)), ...fromHost?.labelIds }\n if (openNow() !== ws) throw new WorkflowRunWorkspaceChangedError(ws)\n pageTarget?.pin(ws)\n setStartedLabelIds(ids)\n return { labelIds: ids }\n }\n }, [hostBeforeStart, pageTarget, noWorkspace, required, ensureLabels, session])\n // The page's project step makes the project, then the host's own commit for it runs.\n const hostCommit = options?.commit\n const commit = useMemo(() => {\n if (!pageTarget || typeof projectFrom !== 'object') return hostCommit\n const step = projectFrom.step\n return {\n ...hostCommit,\n [step]: async (inputs: WorkflowInputs) => {\n const made = await pageTarget.makeProject(projectFrom.project(inputs), inputs)\n const merged = { ...inputs, ...made.inputs }\n const fromHost = await hostCommit?.[step]?.(merged)\n return { ...made.inputs, ...(fromHost ?? {}) }\n },\n }\n }, [hostCommit, pageTarget, projectFrom])\n // A new run on a project starts from what the project says.\n const project = pageTarget?.project\n const hostInitial = options?.initialInputs\n const initialInputs = useMemo(\n () =>\n project && inputsFromProject\n ? { ...inputsFromProject(project), ...hostInitial }\n : hostInitial,\n [project, inputsFromProject, hostInitial]\n )\n const { data: docs = [], refetch } = useDocuments(wsId)\n // An upload step lists the documents a person browses (the host's `documentFilter`).\n const documentFilter = useDocumentFilter()\n // The files being sent on the run's upload steps, and those that did not upload (until retried\n // or removed): the step waits for them.\n const [sending, setSending] = useState<PendingUpload[]>([])\n // The files added on each upload step in this run (doc id -> step id), and their names (listed\n // under them before the workspace's documents catch up).\n const [added, setAdded] = useState<Record<string, string>>({})\n const [addedNames, setAddedNames] = useState<Record<string, string>>({})\n const addedRef = useRef(added)\n addedRef.current = added\n const { view, conversationId, people } = useWorkflowThread(workflow, {\n ...options,\n commit,\n initialInputs,\n beforeStart,\n // An upload step records exactly the files added on it (else the server's guess).\n documentsFor:\n options?.documentsFor ??\n ((stepId) =>\n Object.entries(addedRef.current).flatMap(([doc, step]) => (step === stepId ? [doc] : []))),\n })\n const [dialog, setDialog] = useState<OpenDialog | null>(null)\n const inThread = !!conversationId\n // A run already under way stays in the workspace it is in.\n useEffect(() => {\n const ws = pageTarget?.targetRef.current\n if (conversationId && ws) pageTarget?.pin(ws)\n }, [conversationId, pageTarget])\n // The message the thread scrolls to (a step's answer, picked from the panel).\n const [target, setTarget] = useState<string | undefined>(undefined)\n const nameOfDoc = useCallback(\n (id: string) => docs.find((d) => d.external_id === id)?.file_name ?? undefined,\n [docs]\n )\n const actions = useMemo<WorkflowRunnerActions>(\n () => ({\n me: userId,\n openDocument:\n onOpenDocument &&\n ((ref) => {\n const { id, version } = splitDocRef(ref)\n onOpenDocument(id, version)\n }),\n openDraft: onOpenDraft && ((draftId) => onOpenDraft(draftId)),\n // In the thread layout an answer is right there: scroll to it.\n openMessage: inThread ? setTarget : onOpenMessage,\n sign:\n hostActions?.sign ??\n ((_step, state) => {\n const w = state.waiting\n if (w?.doc_ext_id) setDialog({ kind: 'sign', docRef: w.doc_ext_id })\n }),\n openRedline:\n hostActions?.openRedline ??\n ((ref) =>\n setDialog({ kind: 'word', docRef: ref, title: nameOfDoc(splitDocRef(ref).id) ?? '' })),\n openReview:\n hostActions?.openReview ??\n ((tags, documents) => setDialog({ kind: 'review', tags, documents })),\n }),\n [userId, onOpenDocument, onOpenDraft, onOpenMessage, hostActions, nameOfDoc, inThread]\n )\n\n // A citation in the thread opens its document as the regular chat does (the host's handler).\n const openCitation = useMemo<((target: ChatCitationTarget) => void) | undefined>(\n () =>\n onOpenCitation ??\n (hostOpenDocument\n ? (t) => {\n const docId = t.documentId ?? t.passage?.documentId\n if (docId) hostOpenDocument(docId, undefined, t.page ?? t.passage?.page ?? undefined)\n }\n : citationInEnvironment),\n [onOpenCitation, hostOpenDocument, citationInEnvironment]\n )\n\n const uploadSeq = useRef(0)\n const sendingRef = useRef(sending)\n sendingRef.current = sending\n // Send these files for a step, one after another; one that fails stays listed with its error.\n const send = useCallback(\n async (batch: PendingUpload[]) => {\n if (!batch.length) return\n const keys = new Set(batch.map((p) => p.key))\n const mark = (key: string, patch: Partial<PendingUpload> | null) =>\n setSending((all) =>\n patch === null\n ? all.filter((p) => p.key !== key)\n : all.map((p) => (p.key === key ? { ...p, ...patch } : p))\n )\n setSending((all) => [\n ...all.filter((p) => !keys.has(p.key)),\n ...batch.map((p) => ({ ...p, status: 'uploading' as const, error: undefined })),\n ])\n try {\n // The server resolves the target workspace from the session: make sure it is open.\n await ensureWorkspaceOpen()\n } catch (e) {\n for (const p of batch) mark(p.key, { status: 'failed', error: uploadError(e) })\n return\n }\n for (const p of batch) {\n try {\n const { doc_ext_ids = [] } = (await arbi.documents.uploadFile(p.file, p.file.name)) ?? {}\n if (!doc_ext_ids.length) throw new Error('No document came back')\n setAdded((a) => ({\n ...a,\n ...Object.fromEntries(doc_ext_ids.map((id) => [id, p.stepId])),\n }))\n setAddedNames((n) => ({\n ...n,\n ...Object.fromEntries(doc_ext_ids.map((id) => [id, p.file.name])),\n }))\n mark(p.key, null)\n } catch (e) {\n mark(p.key, { status: 'failed', error: uploadError(e) })\n }\n }\n await refetch()\n },\n [arbi, ensureWorkspaceOpen, refetch]\n )\n const onUpload = useCallback(\n (files: File[], step: WorkflowUploadStep) =>\n send(\n files.map((file) => ({\n key: `upload-${++uploadSeq.current}`,\n file,\n stepId: step.id,\n status: 'uploading' as const,\n }))\n ),\n [send]\n )\n const onRetryUpload = useCallback(\n (file: WorkflowRunnerFile) => {\n const p = sendingRef.current.find((x) => x.key === file.id)\n if (p) void send([p])\n },\n [send]\n )\n const onRemoveUpload = useCallback(\n (file: WorkflowRunnerFile) => setSending((all) => all.filter((p) => p.key !== file.id)),\n []\n )\n\n const files = [\n ...sending.map<WorkflowRunnerFile>((p) => ({\n id: p.key,\n name: p.file.name,\n status: p.status === 'failed' ? 'upload-failed' : 'uploading',\n error: p.error,\n addedFor: p.stepId,\n })),\n ...runnerFiles(docs, added, documentFilter, addedNames),\n ]\n // Watch the files just added until they are read (the step waits for them).\n const reading = files.some((f) => f.addedFor && f.status === 'processing')\n useEffect(() => {\n if (!reading) return\n const t = setInterval(() => void refetch(), READ_POLL_MS)\n return () => clearInterval(t)\n }, [reading, refetch])\n\n const renderAgentOutput = (step: WorkflowAgentStep, state: WorkflowStepState | undefined) => {\n const status = state?.status\n // Beside the thread an answer is not repeated: it links to its message.\n if (inThread) {\n const id = state?.responseId\n return id && status === 'done' ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setTarget(id)}\n data-testid={`${testIdPrefix}-${step.id}-show-in-thread`}\n >\n <MessageSquare className=\"size-4\" /> {l.showInThread}\n </Button>\n ) : null\n }\n if (!state?.text && status !== 'done') return null\n // Finished, its answer not read yet (the thread is fetched again until it is).\n if (!state?.text && state?.responseId) {\n return (\n <p\n className=\"flex items-center gap-2 text-sm text-muted-foreground\"\n data-testid={`${testIdPrefix}-${step.id}-answer-loading`}\n >\n <Loader2 className=\"size-4 animate-spin\" /> {l.loadingAnswer}\n </p>\n )\n }\n return (\n <AiAnswer\n status={status === 'running' ? 'running' : 'done'}\n text={state?.text ?? ''}\n emptyHint={emptyHint?.(step)}\n testId={`${testIdPrefix}-${step.id}-answer`}\n />\n )\n }\n\n const runner = (compact: boolean) => (\n <WorkflowRunner\n people={people}\n {...runnerProps}\n workflow={workflow}\n run={view}\n renderAgentOutput={renderAgentOutput}\n renderReview={(step) =>\n conversationId ? (\n <ReviewNotify\n conversationId={conversationId}\n workspaceId={wsId}\n labels={l}\n testId={`${testIdPrefix}-${step.id}`}\n />\n ) : null\n }\n onUpload={onUpload}\n uploading={sending.some((p) => p.status === 'uploading')}\n files={files}\n onRetryUpload={onRetryUpload}\n onRemoveUpload={onRemoveUpload}\n actions={actions}\n nameOfDoc={nameOfDoc}\n testIdPrefix={testIdPrefix}\n hideStepBar={compact}\n compact={compact}\n className={compact ? undefined : runnerProps.className}\n />\n )\n\n const openThread = conversationId && onOpenConversation && (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => onOpenConversation(conversationId)}\n data-testid={`${testIdPrefix}-open-thread`}\n >\n <ExternalLink className=\"size-4\" /> {l.openThread}\n </Button>\n )\n // The page: the thread's own step bar (what happened in each step, from the server), held to\n // the step the panel shows, with the way to the thread beside it.\n const pageBar = page && inThread && conversationId && (\n <div className=\"flex min-w-0 items-center gap-2\">\n <div className=\"min-w-0 flex-1\">\n <ConnectedThreadTaskBar\n variant=\"steps\"\n conversationId={conversationId}\n currentStepId={view.current}\n onSelectStep={view.goTo}\n renderIcon={runnerProps.renderIcon}\n />\n </div>\n {openThread}\n </div>\n )\n\n return (\n <div className={page ? 'flex min-h-0 flex-1 flex-col gap-3' : 'space-y-3'}>\n {openThread && !pageBar && <div className=\"flex justify-end\">{openThread}</div>}\n {pageBar}\n {inThread && conversationId ? (\n <>\n {!page && (\n <WorkflowStepBar\n run={view}\n levels={stepLevels(view.steps)}\n doneTitle={\n (workflow.run.kind === 'steps' ? workflow.run.completion?.title : undefined) ??\n runnerProps.labels?.complete ??\n 'Done'\n }\n icon={(key) =>\n key && runnerProps.renderIcon ? runnerProps.renderIcon(key) : undefined\n }\n tid={(suffix) => `${testIdPrefix}-${suffix}`}\n />\n )}\n <WorkflowRunThread\n className={page ? 'min-h-[480px] flex-1 rounded-xl border border-border' : undefined}\n conversationId={conversationId}\n workspaceId={wsId}\n stepOf={(id) => {\n const step = view.steps.find((s) => s.id === id)\n if (!step) return undefined\n // Its document, one click from its chip: the latest version, in the host's viewer\n // (else the Word dialog).\n const states = Object.fromEntries(\n view.steps.flatMap((s) => {\n const state = view.stateOf(s.id)\n return state ? [[s.id, state]] : []\n })\n )\n const ref = stepDocuments(view.steps, states, id).at(-1)\n const open = actions.openDocument ?? actions.openRedline\n return {\n title: step.title,\n kind: stepKindOf(step),\n phase: view.phaseOf(id),\n document:\n ref && open\n ? { name: nameOfDoc(splitDocRef(ref).id) ?? ref, onOpen: () => open(ref) }\n : undefined,\n }\n }}\n targetMessageId={target}\n onOpenCitation={openCitation}\n labels={{ workflows: l.currentStep }}\n aside={runner(true)}\n />\n </>\n ) : (\n runner(false)\n )}\n {dialog?.kind === 'sign' && (\n <WorkflowSignDialog docRef={dialog.docRef} onClose={() => setDialog(null)} labels={dl} />\n )}\n {dialog?.kind === 'word' && (\n <WorkflowWordDialog\n docRef={dialog.docRef}\n title={dialog.title || undefined}\n onClose={() => setDialog(null)}\n labels={dl}\n />\n )}\n {dialog?.kind === 'review' && (\n <WorkflowReviewGridDialog\n tags={dialog.tags}\n documents={dialog.documents}\n onClose={() => setDialog(null)}\n onOpenDocument={onOpenDocument && ((id) => onOpenDocument(id))}\n labels={dl}\n />\n )}\n </div>\n )\n}\n\n/**\n * The run as a page: the workflow's header and where it runs, then what has to happen before the\n * run can start (a project chosen, its workspace opened, the labels set up), then the run. Once\n * the run is on screen it stays mounted (what was typed is kept) and only greys out while another\n * workspace is open.\n */\nfunction RunnerPage(props: ConnectedWorkflowRunnerProps) {\n const {\n workflow,\n projectFrom,\n projectId,\n onProjectChange,\n onProjectCreated,\n workspaceId,\n pageHeader,\n pageLabels,\n testIdPrefix = 'workflow-run',\n } = props\n const l = { ...DEFAULT_WORKFLOW_RUN_PAGE_LABELS, ...pageLabels }\n const { openProject } = useBlocksEnvironment()\n const target = useWorkflowRunTarget({\n projectFrom,\n projectId,\n onProjectChange,\n workspaceId,\n onProjectCreated,\n })\n const required = requiredLabelsOf(workflow)\n const ensure = useEnsureRequiredLabels()\n const labels = useRequiredLabels(required, target.target, ensure, target.stage === 'ready')\n const fromStep = typeof projectFrom === 'object'\n // A project step runs before there is a workspace: its labels are set up as the run starts.\n const labelsReady = !required.length || labels.status === 'ready' || (fromStep && !target.target)\n const [shown, setShown] = useState(false)\n if (!shown && target.stage === 'ready' && labelsReady) setShown(true)\n const workspaceName = target.targetName ?? l.thisWorkspace\n const tid = (suffix: string) => `${testIdPrefix}-${suffix}`\n const blocked = target.stage === 'switch' || target.stage === 'opening'\n\n return (\n <div\n className=\"flex h-full min-h-0 w-full flex-col gap-4 overflow-auto p-4 sm:p-6\"\n data-testid={tid('page')}\n >\n <PageHeader\n {...pageHeader}\n title={pageHeader?.title ?? workflow.title}\n description={pageHeader?.description ?? (workflow.details || workflow.description)}\n testId={tid('page-header')}\n />\n <WorkflowRunTargetLine\n project={target.project}\n workspaceName={target.targetName}\n fromStep={fromStep && !target.projectId}\n onOpenProject={projectFrom ? openProject : undefined}\n labels={l}\n testId={testIdPrefix}\n />\n {target.stage === 'pick' && (\n <WorkflowRunProjectChooser\n projects={target.projects}\n loading={target.projectsLoading}\n onPick={target.pick}\n onCreate={(name) => target.makeProject({ name })}\n creating={target.creating}\n labels={l}\n testId={testIdPrefix}\n />\n )}\n {target.stage === 'switch' && (\n <WorkflowRunWorkspaceNotice\n workspaceName={workspaceName}\n onOpen={target.openTarget}\n labels={l}\n testId={testIdPrefix}\n />\n )}\n {!shown && (target.stage === 'loading' || target.stage === 'opening') && (\n <WorkflowRunPreparing\n stage={target.stage}\n workspaceName={workspaceName}\n labels={required}\n l={l}\n testId={testIdPrefix}\n />\n )}\n {!shown && target.stage === 'ready' && !labelsReady && (\n <WorkflowRunPreparing\n stage=\"labels\"\n workspaceName={workspaceName}\n labels={required}\n failed={labels.status === 'failed'}\n error={labels.error}\n onRetry={labels.retry}\n l={l}\n testId={testIdPrefix}\n />\n )}\n {shown && (\n <div\n className={cn(\n 'flex min-h-0 flex-1 flex-col',\n blocked && 'pointer-events-none select-none opacity-50'\n )}\n aria-disabled={blocked || undefined}\n data-testid={tid('page-run')}\n >\n <RunnerBody\n {...props}\n // A run on another project is another run.\n key={target.projectId ?? 'run'}\n page={{ target, labelIds: labels.ids, ensureLabels: ensure, labels: l }}\n />\n </div>\n )}\n </div>\n )\n}\n\n/** The workflow with step `stepId` committed by the host (it makes the run's project). */\nfunction withCommitStep(\n workflow: WorkflowDefinition,\n stepId: string | undefined\n): WorkflowDefinition {\n if (!stepId || workflow.run.kind !== 'steps') return workflow\n return {\n ...workflow,\n run: {\n ...workflow.run,\n steps: workflow.run.steps.map((s) => (s.id === stepId ? { ...s, commit: true } : s)),\n },\n }\n}\n\nconst READ_POLL_MS = 3000\n\n/** A file being sent on an upload step, or one that did not upload (`error`). */\ninterface PendingUpload {\n key: string\n file: File\n stepId: string\n status: 'uploading' | 'failed'\n error?: string\n}\n\nfunction uploadError(e: unknown): string {\n return e instanceof Error && e.message ? e.message : String(e || 'Upload failed')\n}\n\n/**\n * The upload step's files: the workspace's documents the host's `documentFilter` keeps, plus every\n * file added on one of the run's upload steps (`added`: doc id -> step id), which the step waits on.\n * A file added that the workspace does not list yet is shown as being read (`names` gives its name).\n */\nexport function runnerFiles(\n docs: WorkflowRunnerDocument[],\n added: Record<string, string>,\n fileFilter?: (doc: WorkflowRunnerDocument) => boolean,\n names: Record<string, string> = {}\n): WorkflowRunnerFile[] {\n const listed = new Set(docs.map((d) => d.external_id))\n return [\n ...docs\n .filter((d) => !fileFilter || added[d.external_id] || fileFilter(d))\n .map((d) => ({\n id: d.external_id,\n name: d.file_name ?? d.external_id,\n status: fileStatus(d.status),\n addedFor: added[d.external_id],\n })),\n ...Object.entries(added)\n .filter(([id]) => !listed.has(id))\n .map(([id, stepId]) => ({\n id,\n name: names[id] ?? id,\n status: 'processing' as const,\n addedFor: stepId,\n })),\n ]\n}\n\n/** A document's processing status as the upload step shows it; unknown stays unknown. */\nexport function fileStatus(status: string | null | undefined): WorkflowRunnerFile['status'] {\n const s = status?.toLowerCase()\n if (!s) return undefined\n if (s === 'failed') return 'failed'\n if (s === 'completed' || s === 'empty' || s === 'low-content') return 'ready'\n return 'processing'\n}\n\n/** Who should approve: the workspace's people (not agents), notified about the run's thread. */\nfunction ReviewNotify({\n conversationId,\n workspaceId,\n labels,\n testId,\n}: {\n conversationId: string\n workspaceId: string | undefined\n labels: ConnectedWorkflowRunnerLabels\n testId: string\n}) {\n const arbi = useArbi()\n const { live, userId, ensureWorkspaceOpen } = useConnectedWorkspace()\n const { data: members = [] } = useWorkspaceUsers(workspaceId, {\n enabled: live && !!workspaceId,\n beforeFetch: ensureWorkspaceOpen,\n })\n const people = members.filter(\n (m) =>\n !m.agent_ext_id && !m.user.external_id.startsWith('agt-') && m.user.external_id !== userId\n )\n const [picked, setPicked] = useState<string[]>([])\n const [sent, setSent] = useState(false)\n const [busy, setBusy] = useState(false)\n if (people.length === 0) return null\n const toggle = (id: string) =>\n setPicked((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]))\n\n return (\n <div className=\"space-y-3\" data-testid={`${testId}-notify`}>\n <div className=\"flex flex-wrap gap-1.5\">\n {people.map((m) => {\n const name =\n [m.user.given_name, m.user.family_name].filter(Boolean).join(' ') || m.user.email\n const on = picked.includes(m.user.external_id)\n return (\n <button\n key={m.user.external_id}\n type=\"button\"\n onClick={() => toggle(m.user.external_id)}\n aria-pressed={on}\n className={cn(\n 'rounded-full border px-2.5 py-1 text-xs',\n on\n ? 'border-primary bg-primary/10 text-primary'\n : 'border-border text-muted-foreground'\n )}\n data-testid={`${testId}-person-${m.user.external_id}`}\n >\n {name}\n </button>\n )\n })}\n </div>\n <div className=\"flex items-center gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!picked.length || busy}\n onClick={async () => {\n setBusy(true)\n try {\n await arbi.conversations.notify(conversationId, picked)\n setSent(true)\n } finally {\n setBusy(false)\n }\n }}\n data-testid={`${testId}-notify-send`}\n >\n {labels.notify}\n </Button>\n {sent && <span className=\"text-xs text-muted-foreground\">{labels.notified}</span>}\n </div>\n </div>\n )\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport { useWorkflows, type WorkflowResponse } from '@arbidocs/react'\n\n/** A saved workflow, a new one, or a host catalogue entry opened as a template. */\nexport type WorkflowBuilderSelection =\n { kind: 'saved'; id: string } | { kind: 'new' } | { kind: 'template'; id: string }\n\nexport interface WorkflowsPageStateOptions {\n initialBuilder?: WorkflowBuilderSelection\n /** A host deep link to consume once the saved workflow has loaded. */\n historyWorkflowId?: string | null\n onHistoryWorkflowConsumed?: () => void\n}\n\n/** Shared selection lifecycle for workflow tables, builders and history views. No routing or layout. */\nexport function useWorkflowsPageState({\n initialBuilder,\n historyWorkflowId,\n onHistoryWorkflowConsumed,\n}: WorkflowsPageStateOptions = {}) {\n const { data: workflows = [] } = useWorkflows({ live: true })\n const [builder, setBuilder] = useState<WorkflowBuilderSelection | null>(initialBuilder ?? null)\n const [builderKey, setBuilderKey] = useState(0)\n const [historyIds, setHistoryIds] = useState<string[]>([])\n const [activeHistoryId, setActiveHistoryId] = useState<string | null>(null)\n // Resolve against current query data: renaming/deleting a workflow cannot leave a stale dialog.\n const historyFor = workflows.find((workflow) => workflow.external_id === activeHistoryId) ?? null\n const historyTabs = historyIds.flatMap((id) => {\n const workflow = workflows.find((item) => item.external_id === id)\n return workflow ? [workflow] : []\n })\n\n const openHistory = useCallback((workflow: WorkflowResponse | null) => {\n const id = workflow?.external_id ?? null\n if (id) setHistoryIds((ids) => (ids.includes(id) ? ids : [...ids, id]))\n setActiveHistoryId(id)\n }, [])\n const closeHistoryTab = useCallback((id: string) => {\n setHistoryIds((ids) => ids.filter((item) => item !== id))\n setActiveHistoryId((active) => (active === id ? null : active))\n }, [])\n const builderKeyRef = useRef(builderKey)\n builderKeyRef.current = builderKey\n const openBuilder = useCallback((selection: WorkflowBuilderSelection) => {\n setBuilder(selection)\n // Reopening a template/new/saved selection resets its unsaved canvas; saving does not.\n setBuilderKey((key) => key + 1)\n }, [])\n /**\n * A save finished (it lands once the workflows are re-read): the builder it came from (its\n * `builderKey`, default the current one) now edits the saved workflow. A save the person left\n * meanwhile (Back, or another workflow opened) changes nothing: it never reopens the builder.\n */\n const builderSaved = useCallback((id: string, fromKey?: number) => {\n if (fromKey !== undefined && fromKey !== builderKeyRef.current) return\n setBuilder((open) => (open ? { kind: 'saved', id } : null))\n }, [])\n\n useEffect(() => {\n const workflow = workflows.find((item) => item.external_id === historyWorkflowId)\n if (!workflow) return\n openHistory(workflow)\n onHistoryWorkflowConsumed?.()\n }, [historyWorkflowId, onHistoryWorkflowConsumed, openHistory, workflows])\n\n return {\n workflows,\n builder,\n builderKey,\n openBuilder,\n closeBuilder: () => setBuilder(null),\n builderSaved,\n historyFor,\n historyTabs,\n activeHistoryId,\n openHistory,\n closeHistoryTab,\n selectHistoryTab: setActiveHistoryId,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/connection/workflows/useSkillsEnabled.ts","../src/connection/workflows/useWorkflowDefinitions.ts","../src/connection/workflows/useWorkflowTasks.ts","../src/connection/tasks/ConnectedTaskComposer.tsx","../src/connection/ConnectedWorkflowHistory.tsx","../src/connection/tasks/useTaskPeople.tsx","../src/connection/tasks/ConnectedThreadTaskBar.tsx","../src/connection/workflows/useRequiredLabels.ts","../src/connection/projects/useProjectSummaries.ts","../src/connection/workflows/WorkflowRunPage.tsx","../src/connection/WorkflowRunThread.tsx","../src/connection/useWorkflowThread.ts","../src/connection/WorkflowRunnerDialogs.tsx","../src/connection/ConnectedWorkflowRunner.tsx","../src/connection/workflows/useWorkflowsPageState.ts"],"names":["useMemo","useDocuments","useArbiSessionState","jsx","useAgents","useCallback","useUpdateConversation","useState","useWorkspaceUsers","useArbiSession","getUserDisplayName","getDocumentTitle","jsxs","Button","useEffect","useWorkspaces","useRef","useArbi","useCreateWork","useActOnStep","useConversationActivity","Fragment","Loader2","useTags","page","useArbiSessionStore","files","useWorkflows"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,MAAM,EAAE,IAAA,EAAM,YAAA,EAAa,GAAI,eAAA,EAAgB;AAC/C,EAAA,OAAO,cAAc,WAAA,IAAe,KAAA;AACtC;ACwBO,SAAS,sBAAA,GAAuD;AACrE,EAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAS,GAAI,SAAA,EAAU;AACrC,EAAA,MAAM,QAAQ,gBAAA,EAAiB;AAC/B,EAAA,MAAM,gBAAgB,gBAAA,EAAiB;AACvC,EAAA,OAAO,QAAQ,MAAM;AAEnB,IAAA,MAAM,EAAE,IAAA,EAAM,QAAA,EAAU,MAAA,EAAQ,YAAW,GAAI,mBAAA;AAAA,MAC7C,aAAA;AAAA,MACA,YAAY;AAAC,KACf;AACA,IAAA,MAAM,GAAA,GAAM,CAAC,GAAG,QAAA,EAAU,GAAG,UAAU,CAAA;AACvC,IAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,GAAA,CAAI,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,EAAA,EAAI,CAAC,CAAC,CAAC,CAAA;AAC9C,IAAA,MAAM,MAAA,GAAS,gBAAA,CAAiB,OAAA,CAAQ,CAAC,EAAA,KAAO;AAC9C,MA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,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,gBAAA,EAAkB;AAAA,GACpB;AACF","file":"chunk-AWFEB4YJ.js","sourcesContent":["/**\n * The one gate for everything skill-shaped in the app: the empty chat's Start list, the skill\n * entries of the slash menu, the sidebar's Skills item, the Skills browser's entry points and the\n * typed `/skill` interception. It is the personal `show_skills` user setting, default off; the\n * switch lives in Settings, Experimental (developers only), so today only developers have it.\n */\n\nimport { useUserSettings } from '@arbidocs/react'\n\nexport function useSkillsEnabled(): boolean {\n const { data: userSettings } = useUserSettings()\n return userSettings?.show_skills ?? false\n}\n","/**\n * The one list of workflows: the seeded ones plus every skill the user can invoke (each degraded\n * to a single-field form from its `arg_hint`). The dashboard tiles, the slash menu, tasks and\n * agents all read this.\n */\n\nimport { useMemo } from 'react'\nimport { useSkills } from '@arbidocs/react'\nimport { mergeSkillWorkflows } from '../../agents/workflows/workflow'\nimport { type WorkflowDefinition } from '../../agents/workflows/types'\nimport {\n CUSTOM_TASK,\n DASHBOARD_OPERATIONS,\n DASHBOARD_PINNED,\n REMIND_TASK,\n} from '../../agents/workflows/catalogue/seed'\nimport { useSkillsEnabled } from './useSkillsEnabled'\nimport { sortByRecentUse, useWorkflowUsage } from '../../agents/workflows/catalogue/workflow-usage'\nimport { WEB_WORKFLOWS } from '../../agents/workflows/catalogue/registry'\n\nexport interface UseWorkflowDefinitionsResult {\n /** Every skill workflow of this host: built-ins plus the user's and the marketplace's (one list). */\n skills: WorkflowDefinition[]\n /** The user has skills switched on (`show_skills`): the gate of every skill-shaped surface. */\n skillsEnabled: boolean\n /**\n * The empty chat's Start section: built-ins first (their own order), then the user's own and\n * marketplace skills by recent use, then name. EMPTY for users without skills enabled.\n */\n start: WorkflowDefinition[]\n /** The dashboard Start band: pinned skills in order, then the operation launchers. */\n dashboard: WorkflowDefinition[]\n /** What a task can run: schedulable skills plus a free instruction and a reminder. */\n forTasks: WorkflowDefinition[]\n}\n\nexport function useWorkflowDefinitions(): UseWorkflowDefinitionsResult {\n const { data: listings } = useSkills()\n const usage = useWorkflowUsage()\n const skillsEnabled = useSkillsEnabled()\n return useMemo(() => {\n // An uploaded skill of a built-in's slug is used instead of it.\n const { host: builtins, skills: fromServer } = mergeSkillWorkflows(\n WEB_WORKFLOWS,\n listings ?? []\n )\n const all = [...builtins, ...fromServer]\n const byId = new Map(all.map((w) => [w.id, w]))\n const pinned = DASHBOARD_PINNED.flatMap((id) => {\n const w = byId.get(id)\n return w ? [w] : []\n })\n return {\n skills: all,\n skillsEnabled,\n start: skillsEnabled ? [...builtins, ...sortByRecentUse(fromServer, usage)] : [],\n dashboard: [...pinned, ...DASHBOARD_OPERATIONS],\n forTasks: [CUSTOM_TASK, ...all.filter((w) => w.schedulable), REMIND_TASK],\n }\n }, [listings, usage, skillsEnabled])\n}\n","/**\n * Creating and updating work and workflows from the composer, in one place.\n *\n * \"Now\" is an assistant query with task options (the person's own run: the thread becomes a task); a plain\n * to-do creates work with no run. Any other start (a date, a repeat, an event, after another task) saves a workflow\n * that creates the work when it fires. The request mapping is shared with every host (and tested in\n * blocks): `taskComposerToCreateRequest` decides which.\n *\n * Workspace authorization is a per-run, least-privilege choice (`auth_mode`) composed over the shipped\n * workspace-access-request + grant machinery:\n * - Now -> no tier: the query runs as the person asking, with their own access.\n * - Workflow -> `scheduled_require_auth` by default (asks at run time), or `scheduled_permanent`\n * (\"keep access\"): standing membership so unattended runs can decrypt while the owner\n * is away. Only this tier grants membership.\n */\n\nimport {\n useCreateWorkflow,\n useGrantAgentAccess,\n useRunWorkflow,\n useUpdateWorkflow,\n useDocuments,\n useArbiSessionState,\n useCreateWork,\n useStartTaskQuery,\n useUpdateConversation,\n} from '@arbidocs/react'\nimport { getDocumentTitle } from '@arbidocs/react/ui'\nimport type { components } from '@arbidocs/client'\nimport { useCallback, useMemo } from 'react'\nimport {\n composerToWorkflowUpdate,\n taskComposerToCreateRequest,\n taskComposerToUpdateRequest,\n} from '../../agents/tasks/taskRequest'\nimport { type TaskComposerValues } from '../../agents/tasks/taskComposerTypes'\nimport { type WorkflowDefinition } from '../../agents/workflows/types'\nimport type { TaskPlan } from '../../agents/workflows/planSteps'\nimport { useBlocksEnvironment } from '../../provider/environment'\n\ntype Task = components['schemas']['ConversationResponse']\ntype Workflow = components['schemas']['WorkflowResponse']\n\nexport interface TaskSubmitContext {\n workflow: WorkflowDefinition\n values: TaskComposerValues\n /** Goal checklist for agent work, if one was drafted. */\n plan?: TaskPlan | null\n}\n\n/** What a composer submission created. `ran` is null for work no agent runs. */\nexport type CreateOutcome =\n | { kind: 'work'; task: Pick<Task, 'title'> & { external_id?: string }; ran: boolean | null }\n | { kind: 'workflow'; workflow: Workflow }\n\nexport function useWorkflowTasks() {\n const createWork = useCreateWork()\n const runWorkflow = useRunWorkflow()\n const startQuery = useStartTaskQuery()\n const createWorkflow = useCreateWorkflow()\n const updateConversation = useUpdateConversation()\n const updateWorkflowMutation = useUpdateWorkflow()\n const activeWorkspaceId = useArbiSessionState((s) => s.workspaceId)\n const { openFiles } = useBlocksEnvironment()\n\n // Standing access for a workflow's agent, so its unattended runs can read the workspace. An agent\n // that is already a member makes the server refuse the re-grant: that is no failure here.\n const { mutateAsync: grant } = useGrantAgentAccess()\n const grantAgentAccess = useCallback(\n (agentExtId: string, workspaceId: string) =>\n grant({ agentExtId, workspaceId }).then(\n () => undefined,\n () => undefined\n ),\n [grant]\n )\n // File names for the prompt's wording (\"the document <name>\"): the server is told the ids as well.\n const { data: documents = [] } = useDocuments()\n const documentTitles = useMemo(\n () =>\n Object.fromEntries(documents.map((d) => [d.external_id, getDocumentTitle(d, d.external_id)])),\n [documents]\n )\n\n /**\n * Create work or a workflow. `forceWorkflow` is for the workflow dialog, where even a reminder is\n * saved as a workflow.\n */\n const create = useCallback(\n async (ctx: TaskSubmitContext, forceWorkflow = false): Promise<CreateOutcome> => {\n const request = taskComposerToCreateRequest(\n { ...ctx, documentTitles, plan: ctx.plan ?? null },\n activeWorkspaceId ?? undefined,\n forceWorkflow\n )\n if (request.kind === 'workflow') {\n const workflow = await createWorkflow.mutateAsync(request.body)\n // Keep access: deposit the key for the agent the server assigned (the Assistant when none was\n // picked), while the owner is here, so unattended runs start on their own.\n const workspaceId = workflow.workspace_ext_id ?? request.body.workspace_ext_id\n if (\n workflow.auth_mode === 'scheduled_permanent' &&\n !workflow.on_demand &&\n workflow.agent_ext_id &&\n workspaceId\n ) {\n await grantAgentAccess(workflow.agent_ext_id, workspaceId)\n }\n if (ctx.workflow.documentAction && ctx.values.when === 'now' && !forceWorkflow) {\n const result = await runWorkflow.mutateAsync(workflow.external_id)\n if (result.error) throw new Error(result.error)\n openFiles()\n }\n return { kind: 'workflow', workflow }\n }\n if (request.kind === 'query') {\n // Run now is the person's own assistant query: it makes the thread a task and runs it.\n const { conversationId } = await startQuery.start(request.query)\n return {\n kind: 'work',\n task: { external_id: conversationId, title: request.query.task.title ?? null },\n ran: true,\n }\n }\n // A plain to-do (or reminder): a task with no run.\n const task = await createWork.mutateAsync(request.body)\n return { kind: 'work', task, ran: null }\n },\n [\n activeWorkspaceId,\n createWork,\n createWorkflow,\n documentTitles,\n grantAgentAccess,\n startQuery,\n runWorkflow,\n openFiles,\n ]\n )\n\n /** PATCH the editable fields of a task (the instruction, workspace and agent stay as created). */\n const update = useCallback(\n async (task: Pick<Task, 'external_id'> & { is_owner?: boolean }, ctx: TaskSubmitContext) => {\n const patch = taskComposerToUpdateRequest({ ...ctx, plan: ctx.plan ?? null })\n // Who can see a task is its owner's to change: an editor's save leaves it out.\n if (task.is_owner === false) delete patch.shared\n await updateConversation.mutateAsync({ conversationId: task.external_id, patch })\n },\n [updateConversation]\n )\n\n /** PATCH a workflow: its name, trigger and action. */\n const updateWorkflow = useCallback(\n async (\n workflow: Pick<Workflow, 'external_id' | 'agent_ext_id' | 'workspace_ext_id'> & {\n is_owner?: boolean\n },\n ctx: TaskSubmitContext\n ) => {\n const patch = composerToWorkflowUpdate({ ...ctx, documentTitles, plan: ctx.plan ?? null })\n // Sharing a workflow is its owner's: an editor's save leaves it out.\n if (workflow.is_owner === false) delete patch.shared\n const workspaceId = workflow.workspace_ext_id ?? activeWorkspaceId\n const updated = await updateWorkflowMutation.mutateAsync({\n workflowId: workflow.external_id,\n patch,\n })\n // The agent the server keeps (the Assistant when none was picked) gets the key for unattended runs.\n const agentId = updated.agent_ext_id ?? patch.agent_ext_id ?? workflow.agent_ext_id\n if (\n updated.auth_mode === 'scheduled_permanent' &&\n !updated.on_demand &&\n agentId &&\n workspaceId\n ) {\n await grantAgentAccess(agentId, workspaceId)\n }\n },\n [activeWorkspaceId, documentTitles, grantAgentAccess, updateWorkflowMutation]\n )\n\n return {\n create,\n update,\n updateWorkflow,\n isPending:\n createWork.isPending ||\n startQuery.isPending ||\n createWorkflow.isPending ||\n updateConversation.isPending ||\n updateWorkflowMutation.isPending,\n }\n}\n","/**\n * Create / edit a task, or create / edit a workflow: the `TaskComposer` block, connected.\n *\n * A task is a conversation with a status. \"Now\" (or a plain to-do) creates it; any other start (at a\n * time, on an event, after another task) saves a workflow that creates it when it fires. Pick the\n * workflow definition (or write your own instruction), fill its form, choose when, and who does it.\n * Everything the backend needs beyond that (authorization tier, name, notification, goal checklist)\n * is derived or folded under \"More options\". The API mapping lives in `useWorkflowTasks`, shared with\n * \"launch as another agent\". With `kind=\"workflow\"` it is the workflow dialog the Workflows page uses.\n */\n\nimport {\n useAgents,\n useAgentWorkspaces,\n useArbiSessionState,\n useDocuments,\n usePlanWork,\n useTags,\n useWorkflows,\n useWorkItems,\n useWorkspaces,\n} from '@arbidocs/react'\nimport type { components } from '@arbidocs/client'\nimport { useEffect, useMemo, useState } from 'react'\nimport { Button } from '@arbidocs/react/ui'\nimport { TaskComposer } from '../../agents/tasks/TaskComposer'\nimport { TaskPlan as TaskPlanForm } from '../../agents/tasks/TaskPlan'\nimport type { TaskPlan } from '../../agents/workflows/planSteps'\nimport { moveTargets, type TaskListRow } from '../../agents/tasks/taskRows'\nimport { taskToComposerValues, workflowToComposerValues } from '../../agents/tasks/taskRequest'\nimport { type AgentOption } from '../../agents/workflows/AgentSelect'\nimport { type TaskComposerValues } from '../../agents/tasks/taskComposerTypes'\nimport { ArbiApiError } from '@arbidocs/sdk/browser'\nimport { detectTimeZone, listTimeZones } from '../../calendar/zone'\nimport { useBlocksEnvironment } from '../../provider/environment'\nimport { useOpenWorkflow } from '../workflows/useOpenWorkflow'\n\ntype Task = components['schemas']['ConversationResponse']\ntype Workflow = components['schemas']['WorkflowResponse']\nimport {\n CUSTOM_TASK_ID,\n REMIND_TASK_ID,\n renderWorkflowIcon,\n} from '../../agents/workflows/catalogue/seed'\nimport { useWorkflowDefinitions } from '../workflows/useWorkflowDefinitions'\nimport { useWorkflowTasks } from '../workflows/useWorkflowTasks'\nimport { AUTOMATION_EVENTS } from '../../agents/tasks/taskHelpers'\nimport {\n ConnectedWorkflowDocumentsField,\n useConnectedWorkflowScopeSource,\n} from '../ConnectedWorkflowLauncher'\n\nexport interface ConnectedTaskComposerProps {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** `workflow` is the workflow dialog (new, or `workflow` to edit); the default adds a task. */\n kind?: 'work' | 'workflow'\n /** Save an on-demand recipe instead of running immediately. */\n saveOnly?: boolean\n /** Present -> edit this task; absent -> create. */\n task?: Task | null\n /** `kind=\"workflow\"` only: present -> edit this workflow. */\n workflow?: Workflow | null\n /** Create-mode default assignee (the Agents page's \"Assign task\"). */\n initialAgentExtId?: string\n /** `kind=\"workflow\"` create-mode template: opens with this workflow definition (a skill's) selected. */\n initialWorkflowId?: string\n /** `kind=\"workflow\"` create-mode: open on the Run later view (when, which agent, access). */\n startLater?: boolean\n /** A prompt carried from the quick task launcher into scheduling. */\n initialShared?: boolean\n initialPrompt?: string\n /** A saved recipe copied into a new schedule; the original is not edited. */\n launchWorkflow?: Workflow\n /** Create-mode parent: opens as \"Add sub-task\" under this task. */\n initialParentTaskExtId?: string\n}\n\n/** What \"always allowed\" means: the workspaces the agent will hold standing access to. */\nfunction StandingAccessNote({\n agentId,\n activeWorkspaceName,\n}: {\n agentId: string\n activeWorkspaceName: string | null\n}) {\n const { data: held = [] } = useAgentWorkspaces(agentId, { enabled: agentId !== '' })\n const names = new Set(held.map((w) => w.name))\n if (activeWorkspaceName) names.add(activeWorkspaceName)\n return (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"task-standing-access\">\n {agentId === '' ? 'Your own assistant needs no grant.' : 'It will hold standing access to: '}\n {agentId !== '' && (\n <span className=\"font-medium text-foreground\">\n {[...names].join(', ') || 'no workspace yet'}\n </span>\n )}\n </p>\n )\n}\n\nexport function ConnectedTaskComposer({\n open,\n onOpenChange,\n kind = 'work',\n saveOnly = false,\n task,\n workflow: editingWorkflow,\n initialWorkflowId,\n startLater: startLaterProp,\n initialPrompt,\n initialShared,\n launchWorkflow,\n initialAgentExtId,\n initialParentTaskExtId,\n}: ConnectedTaskComposerProps) {\n const { notify, openConversation, openUpload } = useBlocksEnvironment()\n // Scheduling (\"Run later\") belongs to Workflows: offered while the host has its page.\n const openWorkflow = useOpenWorkflow()\n const automationsEnabled = openWorkflow !== undefined\n const startLater = startLaterProp && automationsEnabled\n const isWorkflow = kind === 'workflow'\n const isEdit = isWorkflow ? !!editingWorkflow : !!task\n const { forTasks: baseSkills, skills } = useWorkflowDefinitions()\n const { data: reviewFields = [] } = useTags()\n const scheduledSkills = useMemo(\n () => [\n ...baseSkills,\n {\n id: '__document_review__',\n title: 'AI Review',\n description: 'Write answers and citations into document fields.',\n documentAction: 'annotate_documents' as const,\n run: { kind: 'operation' as const },\n landing: 'files' as const,\n inputs: [\n { name: 'scope', type: 'scope' as const, label: 'Documents', by: ['labels' as const] },\n {\n name: 'output',\n type: 'select' as const,\n label: 'Review field',\n required: true,\n description:\n 'Choose a field with saved AI instructions. Create one using AI Review in Files.',\n options: reviewFields\n .filter((field) => field.instruction)\n .map((field) => ({ value: field.external_id, label: field.name })),\n },\n {\n name: 'overwrite',\n type: 'boolean' as const,\n label: 'Regenerate existing answers',\n default: false,\n },\n ],\n },\n {\n id: '__document_email__',\n title: 'Email latest documents',\n description: 'Email me links to documents added since the previous successful digest.',\n documentAction: 'email_documents' as const,\n run: { kind: 'operation' as const },\n landing: 'files' as const,\n inputs: [\n { name: 'scope', type: 'scope' as const, label: 'Documents', by: ['labels' as const] },\n {\n name: 'latest',\n type: 'boolean' as const,\n label: 'Only documents added since the last digest',\n default: true,\n },\n ],\n },\n ],\n [baseSkills, reviewFields]\n )\n // A skill opened from the library runs now even if it cannot be scheduled: offer it as a template too.\n const forTasks = useMemo(() => {\n const picked = initialWorkflowId ? skills.find((w) => w.id === initialWorkflowId) : undefined\n return picked &&\n !scheduledSkills.some((w) => w.id === picked.id) &&\n picked.run.kind === 'prompt'\n ? [...scheduledSkills, picked]\n : scheduledSkills\n }, [scheduledSkills, skills, initialWorkflowId])\n const { data: workspaceAutomations = [] } = useWorkflows()\n const { data: agents = [] } = useAgents()\n const { data: workspaces = [] } = useWorkspaces()\n const planWork = usePlanWork()\n const { tasks: allTasks } = useWorkItems()\n const { data: documents = [] } = useDocuments()\n const { create, update, updateWorkflow, isPending } = useWorkflowTasks()\n // The files behind a template's file fields: the same pieces the skill launcher wires.\n const scopeSource = useConnectedWorkflowScopeSource()\n const activeWorkspaceId = useArbiSessionState((s) => s.workspaceId)\n const activeWorkspace = useMemo(\n () => workspaces.find((w) => w.external_id === activeWorkspaceId) ?? null,\n [workspaces, activeWorkspaceId]\n )\n const timezones = useMemo(() => listTimeZones(), [])\n // The plan lists documents by id; show their names.\n const documentNames = useMemo(\n () =>\n Object.fromEntries(\n documents.flatMap((d) => (d.file_name ? [[d.external_id, d.file_name]] : []))\n ),\n [documents]\n )\n // Tasks a new task can be part of: any other task that keeps the sub-task tree within its maximum\n // depth and (when editing) is not the task itself or one of its descendants. A workflow can wait on\n // any task, finished ones included (they re-open and finish again).\n const taskOptions = useMemo(() => {\n const label = (t: TaskListRow) => t.title?.trim() || 'Untitled task'\n if (isWorkflow) return allTasks.map((t) => ({ id: t.external_id, name: label(t) }))\n const subject: TaskListRow = task ?? { external_id: '__new__' }\n return moveTargets<TaskListRow>(\n [...allTasks.filter((t) => t.external_id !== subject.external_id), subject],\n subject\n ).map((t) => ({ id: t.external_id, name: label(t) }))\n }, [allTasks, task, isWorkflow])\n // The owner's main agent: what a scheduled workflow runs as unless another is picked.\n const defaultAgentId = useMemo(\n () => (agents.find((a) => a.given_name === 'Assistant') ?? agents[0])?.external_id,\n [agents]\n )\n const agentOptions = useMemo<AgentOption[]>(\n () => agents.map((a) => ({ id: a.external_id, label: a.given_name || a.email })),\n [agents]\n )\n\n // What the composer opens with: the edit target, or (create) the preset assignee.\n const initialValues = useMemo(() => {\n const ids = {\n customWorkflowId: CUSTOM_TASK_ID,\n reminderWorkflowId: REMIND_TASK_ID,\n definitions: forTasks,\n }\n const base = launchWorkflow\n ? {\n ...workflowToComposerValues(launchWorkflow, ids),\n when: 'once' as const,\n runAt: '',\n rrule: '',\n eventKind: '',\n afterTaskId: '',\n name: '',\n }\n : editingWorkflow\n ? workflowToComposerValues(editingWorkflow, ids)\n : task\n ? taskToComposerValues(task, ids)\n : isWorkflow\n ? {\n // Run now is the default start; scheduling is the fallback in the same field.\n assignee: 'agent' as const,\n workflowId: initialWorkflowId ?? CUSTOM_TASK_ID,\n when: startLater ? ('once' as const) : ('now' as const),\n ...(initialPrompt\n ? {\n inputs: {\n [initialWorkflowId === REMIND_TASK_ID ? 'message' : 'instruction']:\n initialPrompt,\n },\n }\n : {}),\n // A scheduled run needs an agent: the owner's Assistant unless another is picked.\n ...(startLater && defaultAgentId ? { agentId: defaultAgentId } : {}),\n }\n : initialAgentExtId\n ? // Assigning an agent means agentic work: the free instruction, and tell me when done.\n { agentId: initialAgentExtId, workflowId: CUSTOM_TASK_ID, notifyOnComplete: true }\n : {}\n return {\n timezone: detectTimeZone(),\n ...base,\n ...(initialShared !== undefined && !task && !editingWorkflow\n ? { shared: initialShared }\n : {}),\n ...(!task && !isWorkflow && initialParentTaskExtId\n ? { parentTaskId: initialParentTaskExtId }\n : {}),\n }\n }, [\n forTasks,\n task,\n editingWorkflow,\n isWorkflow,\n initialWorkflowId,\n startLater,\n initialPrompt,\n initialShared,\n launchWorkflow,\n defaultAgentId,\n initialAgentExtId,\n initialParentTaskExtId,\n ])\n\n const [plan, setPlan] = useState<TaskPlan | null>(null)\n useEffect(() => {\n if (open) setPlan(task?.plan ?? editingWorkflow?.plan ?? launchWorkflow?.plan ?? null) // the stored plan when editing agent work\n }, [open, task, editingWorkflow, launchWorkflow])\n\n const handleGeneratePlan = async (values: TaskComposerValues) => {\n if (!activeWorkspace) {\n notify('Open a workspace first — the plan is scoped to it', 'warning')\n return\n }\n const objective = String(values.inputs.instruction ?? '').trim()\n if (!objective) {\n notify('Write the instruction first — it’s the planner’s objective', 'warning')\n return\n }\n try {\n const drafted = await planWork.mutateAsync({\n objective,\n max_passes: plan?.max_passes ?? 3,\n })\n setPlan(drafted)\n notify('Drafted a plan — review the checklist', 'success')\n } catch {\n notify('Could not draft a plan', 'error')\n }\n }\n\n const submit = async (submitted: TaskComposerValues, options?: { runOnce?: boolean }) => {\n // A task for me is a plain to-do and runs no workflow.\n const chosen =\n forTasks.find((w) => w.id === submitted.workflowId) ??\n (submitted.assignee === 'me' ? forTasks[0] : undefined)\n if (!chosen) return\n if (plan && !plan.goal.trim()) {\n notify('The plan needs a goal', 'warning')\n return\n }\n if (plan && plan.criteria.some((c) => !c.text.trim())) {\n notify('Every checklist criterion needs text (or remove it)', 'warning')\n return\n }\n const ctx = {\n workflow: chosen,\n values: submitted,\n plan: chosen.id === CUSTOM_TASK_ID ? plan : null,\n }\n try {\n if (isWorkflow && editingWorkflow && !options?.runOnce) {\n await updateWorkflow(editingWorkflow, ctx)\n notify(`Updated “${editingWorkflow.name}”`, 'success')\n } else if (isEdit && task) {\n await update(task, ctx)\n notify(`Updated “${task.title ?? 'task'}”`, 'success')\n } else {\n const created = await create(ctx, saveOnly && !options?.runOnce)\n if (created.kind === 'workflow') {\n notify(`Saved “${created.workflow.name}”.`, 'success')\n // The saved workflow, on the Workflows page.\n openWorkflow?.()\n } else {\n const name = created.task.title ?? 'task'\n if ((created.ran || options?.runOnce) && created.task.external_id) {\n // The run is a thread: go and watch it, rather than leave a toast to say it started.\n openConversation(created.task.external_id)\n } else {\n notify(\n created.ran === null\n ? `Added “${name}”`\n : 'Task created, but the run could not start',\n created.ran === false ? 'warning' : 'success'\n )\n }\n }\n }\n onOpenChange(false)\n } catch (error) {\n const what = `Failed to ${isEdit ? 'update' : 'create'} the ${isWorkflow ? 'workflow' : 'task'}`\n notify(\n error instanceof Error && error.message.startsWith('Open a workspace')\n ? error.message\n : error instanceof ArbiApiError && error.detail\n ? `${what}: ${error.detail}`\n : what,\n 'error'\n )\n }\n }\n\n return (\n <TaskComposer\n key={editingWorkflow?.external_id ?? task?.external_id ?? 'new'}\n open={open}\n onOpenChange={onOpenChange}\n kind={kind}\n saveOnly={saveOnly}\n hideRunLater={!automationsEnabled}\n defaultAgentId={defaultAgentId}\n isEdit={isEdit}\n workflows={forTasks}\n agents={agentOptions}\n tasks={taskOptions}\n initialValues={initialValues}\n timezones={timezones}\n eventOptions={AUTOMATION_EVENTS}\n eventWorkflowOptions={workspaceAutomations\n .filter((item) => item.external_id !== editingWorkflow?.external_id)\n .map((item) => ({ id: item.external_id, label: item.name }))}\n isPending={isPending}\n planDrafting={planWork.isPending}\n hasPlan={plan !== null}\n renderIcon={renderWorkflowIcon}\n scopeSource={scopeSource}\n renderDocuments={(field, value, onChange) => (\n <ConnectedWorkflowDocumentsField\n field={field}\n value={value}\n onChange={onChange}\n onAddFiles={openUpload}\n />\n )}\n addFilesAction={\n openUpload && (\n <Button size=\"sm\" onClick={() => openUpload()} data-testid=\"workflow-add-files-first\">\n Add files\n </Button>\n )\n }\n onDropFiles={openUpload && ((files) => openUpload(files))}\n standingAccess={(values) => (\n <StandingAccessNote\n agentId={values.agentId}\n activeWorkspaceName={activeWorkspace?.name ?? null}\n />\n )}\n labels={{\n ...(isWorkflow\n ? {\n titleNewWorkflow: 'New workflow',\n titleEditWorkflow: 'Edit workflow',\n workflowNamePlaceholder: 'Name this workflow',\n createWorkflow: 'Create workflow',\n saveWorkflow: 'Save workflow',\n descriptionWorkflow: 'Choose what happens and when this workflow starts.',\n eventHint: 'Choose the workspace event that starts this workflow.',\n runAsAgentHint: 'Scheduled AI work runs as your chosen assistant when you are away.',\n }\n : {}),\n ...(plan\n ? { addAndStart: 'Approve plan and start', addAndSchedule: 'Approve plan and schedule' }\n : {}),\n }}\n onSubmit={submit}\n goal={(values) =>\n values.workflowId === CUSTOM_TASK_ID ? (\n <TaskPlanForm\n plan={plan}\n onChange={setPlan}\n onGenerate={() => handleGeneratePlan(values)}\n isGenerating={planWork.isPending}\n workspaceName={activeWorkspace?.name ?? null}\n documentNames={documentNames}\n objective={String(values.inputs.instruction ?? '')}\n />\n ) : null\n }\n />\n )\n}\n","/**\n * A saved workflow's history and a task's activity, bound to the connection.\n *\n * - `ConnectedWorkflowHistory`: every run of a workflow (re-read while shown), each with when, what\n * it was (a thread, an email, an AI review, a reminder) and how it went; a run's thread opens\n * through the environment's `openConversation`, a document action's result through the host.\n * - `ConnectedTaskActivityDialog`: a task's timeline (re-read while it runs), with who did what.\n */\n\nimport { useCallback, type ReactNode } from 'react'\nimport { useAgents, useConversationActivity, useWorkflowRuns } from '@arbidocs/react'\nimport { formatRelativeTime } from '@arbidocs/react/ui'\nimport {\n TaskRunsDialog,\n type TaskRunView,\n type TaskRunsDialogLabels,\n} from '../agents/tasks/TaskRunsDialog'\nimport { TaskActivityDialog } from '../agents/tasks/TaskActivityDialog'\nimport type { TaskActivityEvent } from '../agents/tasks/TaskActivityTimeline'\nimport { PersonPill } from '../agents/tasks/PersonPill'\nimport { fmtDate } from '../lib/format'\nimport { useBlocksEnvironment } from '../provider/environment'\nimport { useConnectedWorkspace } from './ConnectionProvider'\nimport { useConnectedWorkspaceRole } from './ConnectedWorkflowsTable'\n\ntype WorkflowRun = NonNullable<ReturnType<typeof useWorkflowRuns>['data']>[number]\n\n/** What a run was, in a word. */\nconst RUN_KIND: Record<string, string> = {\n email_documents: 'Email',\n annotate_documents: 'AI Review',\n reminder: 'Reminder',\n}\nconst DOCUMENT_ACTIONS = new Set(['email_documents', 'annotate_documents'])\n\n/** A run as the history lists it: when, what, on how many documents. */\nexport function workflowRunView(\n run: WorkflowRun,\n formatDate: (iso: string) => string\n): TaskRunView {\n const documents = DOCUMENT_ACTIONS.has(run.action_type)\n ? ` · ${run.document_ext_ids.length} documents`\n : ''\n return {\n id: `execution-${run.id}`,\n // An AI review that finished has a result to open (its fields over its documents).\n resultId:\n run.action_type === 'annotate_documents' && run.status === 'completed'\n ? String(run.id)\n : undefined,\n status: run.status,\n when: `${formatDate(run.created_at)} · ${RUN_KIND[run.action_type] ?? 'Thread'}${documents}`,\n error: run.error,\n conversationId: run.conversation_ext_id ?? undefined,\n }\n}\n\nexport interface ConnectedWorkflowHistoryProps {\n /** The workflow (`null`: closed). */\n workflow: { external_id: string; name: string } | null\n onOpenChange: (open: boolean) => void\n /** In the page rather than a dialog. */\n inline?: boolean\n hideHeader?: boolean\n formatDate?: (iso: string) => string\n /** Open a document action's result (an AI review's fields): the host's. Absent: no Open. */\n onOpenResult?: (run: WorkflowRun) => void\n /** Under a failed run: e.g. a way to report it. */\n renderErrorReport?: (run: TaskRunView) => ReactNode\n labels?: Partial<TaskRunsDialogLabels>\n}\n\nexport function ConnectedWorkflowHistory({\n workflow,\n onOpenChange,\n inline,\n hideHeader,\n formatDate = fmtDate,\n onOpenResult,\n renderErrorReport,\n labels,\n}: ConnectedWorkflowHistoryProps) {\n const { openConversation } = useBlocksEnvironment()\n const { data: runs = [], isLoading } = useWorkflowRuns(workflow?.external_id)\n return (\n <TaskRunsDialog\n inline={inline}\n hideHeader={hideHeader}\n open={!!workflow}\n onOpenChange={onOpenChange}\n taskName={workflow?.name}\n renderErrorReport={renderErrorReport}\n isLoading={isLoading}\n labels={{\n title: (name) => `History — ${name}`,\n description: 'Executions and results of this workflow.',\n empty: 'This workflow hasn’t run yet.',\n ...labels,\n }}\n runs={runs.map((run) => workflowRunView(run, formatDate))}\n onOpenResult={\n onOpenResult &&\n ((id) => {\n const run = runs.find((r) => String(r.id) === id)\n if (run) onOpenResult(run)\n })\n }\n onOpenRun={(conversationId) => openConversation(conversationId)}\n />\n )\n}\n\n/** Relative time, compact for list rows. */\nconst relativeTime = (iso: string) => formatRelativeTime(iso, { style: 'short' })\n\nexport interface ConnectedTaskActivityDialogProps {\n conversationId: string\n taskName: string\n /** The run is generating right now: the timeline then re-reads itself every few seconds. */\n live?: boolean\n onClose: () => void\n formatExact?: (iso: string) => string\n}\n\nexport function ConnectedTaskActivityDialog({\n conversationId,\n taskName,\n live,\n onClose,\n formatExact = fmtDate,\n}: ConnectedTaskActivityDialogProps) {\n const activity = useConversationActivity(conversationId, { live })\n const { data: agents = [] } = useAgents()\n const { userId } = useConnectedWorkspace()\n const { members } = useConnectedWorkspaceRole()\n const renderPerson = useCallback(\n (id: string | null | undefined) => {\n const isMe = !!id && id === userId\n const member = members.find((m) => m.user.external_id === id)?.user\n const name =\n (member && [member.given_name, member.family_name].filter(Boolean).join(' ')) ||\n member?.email\n const person = { id, label: isMe ? 'You' : name || 'Someone', isMe }\n return <PersonPill person={person} />\n },\n [userId, members]\n )\n const agentName = useCallback(\n (agentId: string) => agents.find((a) => a.external_id === agentId)?.given_name ?? undefined,\n [agents]\n )\n return (\n <TaskActivityDialog\n open\n onOpenChange={(open) => !open && onClose()}\n taskName={taskName}\n events={activity.data as TaskActivityEvent[] | undefined}\n isLoading={activity.isLoading}\n isError={activity.isError}\n renderPerson={renderPerson}\n agentName={agentName}\n formatRelative={relativeTime}\n formatExact={formatExact}\n />\n )\n}\n","import { useCallback, useMemo, type ReactNode } from 'react'\nimport { useAgents, useArbiSession, useWorkspaceUsers } from '@arbidocs/react'\nimport { getUserDisplayName, isAgent } from '@arbidocs/react/ui'\nimport { PersonPill, type TaskPerson } from '../../agents/tasks/PersonPill'\nimport { DocumentUser } from '../files/fields/DocumentUser'\n\n/** The workspace roles that can edit it. */\nconst EDITOR_ROLES: readonly string[] = ['owner', 'collaborator']\n\n/**\n * People who can own tasks here: humans (never agents) who can edit the workspace, other than me\n * (the task list shows me as \"Me\"). They name each task's owner.\n */\nexport function useTaskPeople(): { id: string; label: string }[] {\n const { data: members = [] } = useWorkspaceUsers()\n const currentUserExtId = useArbiSession().user?.external_id\n return useMemo(\n () =>\n members\n .filter(\n (m) =>\n !isAgent(m.user) &&\n m.user.external_id !== currentUserExtId &&\n EDITOR_ROLES.includes(m.role)\n )\n .map((m) => ({ id: m.user.external_id, label: getUserDisplayName(m.user) })),\n [members, currentUserExtId]\n )\n}\n\n/**\n * How the Tasks table draws a person: the host's own user pill (presence, a click to message, the\n * rich tooltip) when the person is a member or agent we know, else the plain shared pill.\n */\nexport function useRenderTaskPerson(): (person: TaskPerson) => ReactNode {\n const { data: members = [] } = useWorkspaceUsers()\n const { data: agents = [] } = useAgents()\n const byId = useMemo(() => {\n const map = new Map(members.map((m) => [m.user.external_id, m.user]))\n for (const agent of agents) if (!map.has(agent.external_id)) map.set(agent.external_id, agent)\n return map\n }, [members, agents])\n return useCallback(\n (person: TaskPerson) => {\n const user = person.id ? byId.get(person.id) : undefined\n return user ? <DocumentUser user={user} variant=\"pill\" /> : <PersonPill person={person} />\n },\n [byId]\n )\n}\n","import { useState, type ReactNode } from 'react'\nimport type { components } from '@arbidocs/client'\nimport { useConnectedThreadActivity } from './useConnectedThreadActivity'\nimport { MoreHorizontal } from 'lucide-react'\nimport {\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from '@arbidocs/react/ui'\nimport { TaskFlow } from '../../agents/tasks/TaskFlow'\nimport {\n WorkflowThreadStartedBy,\n WorkflowThreadStrip,\n} from '../../agents/tasks/WorkflowThreadStrip'\nimport { ThreadFollowMenuItem } from '../../activity/NotificationRelevanceControls'\nimport {\n assigneeName,\n canAssign,\n runFieldsOf,\n splitDocRef,\n stepStatesFromActivity,\n type WorkflowActivityEvent,\n} from '../../agents/workflows/run'\nimport { fromPlanSteps, type TaskPlanStep } from '../../agents/workflows/planSteps'\nimport { type WorkflowInputs } from '../../agents/workflows/types'\nimport { RenameDialog } from '../../settings/Projects'\nimport { getEntityLabel, getDocumentTitle, getUserDisplayName } from '@arbidocs/react/ui'\nimport {\n useActOnStep,\n useArbiSession,\n useCanEditShared,\n useConversationItems,\n useDocuments,\n useFollowThread,\n useUpdateConversation,\n useWorkspaceUsers,\n} from '@arbidocs/react'\nimport { WorkflowStepAction } from '../../agents/workflows/WorkflowStepAction'\nimport { useBlocksEnvironment } from '../../provider/environment'\n\nexport interface ConnectedThreadTaskBarProps {\n conversationId: string | null | undefined\n /**\n * `bar` (default): the thread's whole top bar — a run's steps (as many as fit) or what happened,\n * linked threads and the thread's options. `steps`: only a run's steps on the chevron bar,\n * previous, current and next, the rest behind \"…N\" (a run page's step bar, under its own header).\n */\n variant?: 'bar' | 'steps'\n /** `steps`: the step in view, when the host keeps it (its runner's current step). */\n currentStepId?: string | null\n /** `steps`: a step was gone to on the bar. */\n onSelectStep?: (stepId: string) => void\n /** Draws a step's icon name. Absent: its kind's icon. */\n renderIcon?: (icon: string) => ReactNode\n}\n\n/**\n * A thread's top bar: a workflow run's steps (each person's step done from here), or what\n * happened in the thread, the threads linked to it, and its options (follow, mark done, rename).\n * One shared, persisted history for tasks and ordinary conversations.\n */\nexport function ConnectedThreadTaskBar({\n conversationId,\n variant = 'bar',\n currentStepId,\n onSelectStep,\n renderIcon,\n}: ConnectedThreadTaskBarProps) {\n const { conversations } = useConversationItems()\n const { activity, items, related, signals, startedBy } =\n useConnectedThreadActivity(conversationId)\n const canEditShared = useCanEditShared()\n const update = useUpdateConversation()\n const actOnStep = useActOnStep()\n const [error, setError] = useState<string | null>(null)\n const [busy, setBusy] = useState(false)\n const [renameOpen, setRenameOpen] = useState(false)\n const follow = useFollowThread(conversationId)\n const [newTitle, setNewTitle] = useState('')\n const { data: members = [] } = useWorkspaceUsers()\n const { data: documents = [] } = useDocuments()\n const me = useArbiSession().user?.external_id\n const { notify, openDocument, openFiles, openMail } = useBlocksEnvironment()\n const task = conversations.find((c) => c.external_id === conversationId)\n if (!conversationId) return null\n const nameOf = (id: string) => {\n const person = members.find((m) => m.user.external_id === id)?.user\n return person ? getUserDisplayName(person) : undefined\n }\n const steps = fromPlanSteps((task?.plan?.steps ?? []) as TaskPlanStep[])\n const states = stepStatesFromActivity((activity.data ?? []) as WorkflowActivityEvent[])\n const runInputs = (task?.skill_inputs ?? {}) as WorkflowInputs\n const stepCall = (body: components['schemas']['StepActionRequest']) =>\n actOnStep.mutateAsync({ conversationId, body })\n const canEdit = Boolean(task?.is_owner || (task?.is_shared && canEditShared))\n const renameThread = () => {\n const title = newTitle.trim()\n if (!title) return\n setBusy(true)\n setError(null)\n update\n .mutateAsync({ conversationId, patch: { title } })\n .then(() => {\n setRenameOpen(false)\n notify(`${getEntityLabel('CONVERSATION')} renamed successfully`, 'success')\n })\n .catch((e: unknown) =>\n setError(e instanceof Error ? e.message : 'Could not rename the thread')\n )\n .finally(() => setBusy(false))\n }\n const strip = (\n <WorkflowThreadStrip\n renderIcon={renderIcon}\n {...(variant === 'steps' ? { maxSpan: 3, current: currentStepId, onSelectStep } : {})}\n steps={steps}\n states={states}\n items={items}\n assigneeOf={(step) =>\n canAssign(step)\n ? assigneeName(step.assignee, {\n // A step that is the viewer's own reads \"Waiting for you\".\n nameOf: (id) => (id === me ? 'you' : nameOf(id)),\n inputs: runInputs,\n fields: runFieldsOf(steps),\n announcedTo: states[step.id]?.announcedTo,\n })\n : undefined\n }\n signals={signals}\n startedBy={startedBy}\n // The documents first: what a step drafted, what an approval approves.\n nameOfDoc={(id) => {\n const doc = documents.find((d) => d.external_id === id)\n return doc ? getDocumentTitle(doc) : undefined\n }}\n onOpenDocument={(ref) => openDocument(splitDocRef(ref).id)}\n inputs={runInputs}\n nameOf={(id) => (id === me ? 'you' : nameOf(id))}\n onSkip={\n canEdit\n ? (step) =>\n void actOnStep\n .mutateAsync({ conversationId, body: { step, action: 'skip' } })\n .catch((e: unknown) =>\n notify(e instanceof Error ? e.message : 'Could not skip the step', 'error')\n )\n : undefined\n }\n renderStepAction={(step, phase) =>\n // A signer or a draft's person acts on their step even on a thread they cannot edit.\n canEdit || phase === 'waiting' || phase === 'done' ? (\n <WorkflowStepAction\n step={step}\n phase={phase}\n steps={steps}\n states={states}\n inputs={runInputs}\n me={me}\n nameOf={nameOf}\n onComplete={(inputs) => stepCall({ step: step.id, action: 'complete', inputs })}\n onSendBack={(to, note) =>\n stepCall({ step: step.id, action: 'send_back', to, ...(note ? { note } : {}) })\n }\n onDecline={(note) =>\n stepCall({ step: step.id, action: 'decline', ...(note ? { note } : {}) })\n }\n onOpenDocument={(id) => openDocument(id)}\n onOpenDraft={openMail && ((draftId) => openMail({ draftId }))}\n onOpenReview={() => openFiles()}\n />\n ) : null\n }\n />\n )\n if (variant === 'steps')\n return task?.plan?.steps?.length ? (\n <div className=\"flex min-w-0 items-center\" data-testid=\"thread-task-bar-steps\">\n {strip}\n </div>\n ) : null\n return (\n <div\n className=\"flex min-w-0 items-center gap-2 border-b border-border px-2 py-1\"\n data-testid=\"thread-task-bar\"\n >\n {task?.plan?.steps?.length ? (\n // A workflow run: its named steps, with what happened in the thread under each.\n strip\n ) : items.length || startedBy ? (\n <>\n {/* A linked run without steps of its own still says what started it. */}\n {startedBy && <WorkflowThreadStartedBy origin={startedBy} />}\n <TaskFlow items={items.filter((item) => !item.step)} />\n </>\n ) : (\n // Ordinary chats record no activity events, so an empty ribbon says nothing rather than\n // \"No recorded activity yet\" while the answer and its steps are right there in the thread.\n <span className=\"min-w-0 flex-1 px-2 text-xs text-muted-foreground\">\n {activity.isLoading\n ? 'Loading activity…'\n : activity.isError\n ? 'Could not load activity'\n : null}\n </span>\n )}\n {related.map((link) => (\n <button\n key={link.id}\n onClick={link.onSelect}\n title={link.title}\n className=\"max-w-36 truncate text-[10px] text-muted-foreground hover:text-primary hover:underline\"\n data-testid={`thread-related-${link.id}`}\n >\n ↗ {link.label}\n </button>\n ))}\n {activity.isError && (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => void activity.refetch()}>\n Retry\n </Button>\n )}\n {/* Completion is a human decision: any editor can mark it done. */}\n {/* Rename is offered on every editable thread, tasks and ordinary chats alike. */}\n {/* Following is anyone's own choice: it is on every thread they can see. */}\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n size=\"icon\"\n variant=\"ghost\"\n className=\"size-8 shrink-0\"\n aria-label=\"Thread options\"\n >\n <MoreHorizontal className=\"size-4\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <ThreadFollowMenuItem\n following={follow.following}\n onFollowingChange={(on) =>\n // Following changes nothing on screen: say what it does.\n follow.setFollowing(on, {\n onSuccess: () =>\n notify(\n on\n ? 'Following this thread: you’ll be notified of everything in it'\n : 'Unfollowed this thread',\n 'success'\n ),\n onError: () =>\n notify(\n on ? 'Could not follow this thread' : 'Could not unfollow this thread',\n 'error'\n ),\n })\n }\n disabled={follow.isLoading || follow.isSaving}\n />\n {canEdit && task?.status && (\n <DropdownMenuItem\n disabled={busy}\n onSelect={() => {\n setBusy(true)\n void update\n .mutateAsync({\n conversationId,\n patch: { status: task.status === 'done' ? 'todo' : 'done' },\n })\n .catch((e: unknown) =>\n setError(e instanceof Error ? e.message : 'Could not update the thread')\n )\n .finally(() => setBusy(false))\n }}\n >\n {task.status === 'done' ? 'Reopen thread' : 'Mark done'}\n </DropdownMenuItem>\n )}\n {canEdit && (\n <DropdownMenuItem\n disabled={busy}\n onSelect={() => {\n setNewTitle(task?.title ?? '')\n setRenameOpen(true)\n }}\n data-testid=\"rename-thread-item\"\n >\n Rename\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n {error && (\n <span role=\"alert\" className=\"text-xs text-destructive\">\n {error}\n </span>\n )}\n <RenameDialog\n open={renameOpen}\n onClose={() => setRenameOpen(false)}\n title={`Rename ${getEntityLabel('CONVERSATION')}`}\n labels={{ description: 'Rename the conversation title' }}\n fieldLabel={`${getEntityLabel('CONVERSATION')} Title`}\n placeholder=\"Enter title\"\n value={newTitle}\n onChange={setNewTitle}\n onSave={renameThread}\n isSaving={busy}\n canSave={!!newTitle.trim()}\n dialogTestId=\"rename-thread-modal\"\n />\n </div>\n )\n}\n","/**\n * A workflow's required labels (`requiredLabels`), made to exist in the workspace a run works in.\n * The workspace is always named on the requests (`tags.list({ workspaceId })`,\n * `useCreateTag` with `workspaceId`), never taken from whichever workspace is open when they are\n * sent: a switch while the labels are being set up cannot put them in the wrong workspace.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useArbi, useCreateTag } from '@arbidocs/react'\nimport { matchRequiredLabels } from '../../agents/workflows/requiredLabels'\nimport type { WorkflowRequiredLabel } from '../../agents/workflows/types'\n\n/** Label ids by key. */\nexport type RequiredLabelIds = Record<string, string>\n\n/**\n * `ensure(labels, workspaceId)`: the labels' ids in that workspace, by key, creating the ones it\n * does not have (an existing label of the same name, in any case, is used). One set-up per\n * workspace at a time: a second call while one is under way waits for it; a finished one is kept.\n */\nexport function useEnsureRequiredLabels(): (\n labels: readonly WorkflowRequiredLabel[],\n workspaceId: string\n) => Promise<RequiredLabelIds> {\n const arbi = useArbi()\n const { mutateAsync: createTag } = useCreateTag()\n const done = useRef(new Map<string, Promise<RequiredLabelIds>>())\n return useCallback(\n (labels, workspaceId) => {\n if (!labels.length) return Promise.resolve({})\n const key = `${workspaceId}\\n${labels.map((l) => `${l.key}=${l.name}`).join('\\n')}`\n const known = done.current.get(key)\n if (known) return known\n const setUp = (async () => {\n const existing = await arbi.tags.list({ workspaceId })\n const { ids, missing } = matchRequiredLabels(labels, existing)\n for (const label of missing) {\n const tag = await createTag({\n name: label.name,\n instruction: label.instruction ?? null,\n shared: label.shared ?? true,\n tagType: {\n type: label.format?.type ?? 'checkbox',\n options: label.format?.options ?? [],\n },\n workspaceId,\n })\n ids[label.key] = tag.external_id\n }\n return ids\n })()\n done.current.set(key, setUp)\n // A failed set-up is tried again next time.\n setUp.catch(() => done.current.delete(key))\n return setUp\n },\n [arbi, createTag]\n )\n}\n\nexport interface RequiredLabelsState {\n /** `idle`: nothing to set up (no labels, or no workspace yet). */\n status: 'idle' | 'preparing' | 'ready' | 'failed'\n /** The labels' ids in the workspace, by key, once ready. */\n ids: RequiredLabelIds\n error: string | null\n retry: () => void\n}\n\n/**\n * Set the labels up in `workspaceId` as soon as it is known (`enabled`), for a page that shows the\n * set-up before the run. A new workspace starts over; what an earlier workspace's set-up returns\n * late is dropped.\n */\nexport function useRequiredLabels(\n labels: readonly WorkflowRequiredLabel[],\n workspaceId: string | undefined,\n ensure: ReturnType<typeof useEnsureRequiredLabels>,\n enabled = true\n): RequiredLabelsState {\n const [state, setState] = useState<Omit<RequiredLabelsState, 'retry'> & { for?: string }>({\n status: 'idle',\n ids: {},\n error: null,\n })\n const [attempt, setAttempt] = useState(0)\n const active = enabled && !!workspaceId && labels.length > 0\n const signature = labels.map((l) => `${l.key}=${l.name}`).join('\\n')\n const latest = useRef({ labels, ensure })\n latest.current = { labels, ensure }\n useEffect(() => {\n if (!active || !workspaceId) return\n let live = true\n setState({ status: 'preparing', ids: {}, error: null, for: workspaceId })\n latest.current.ensure(latest.current.labels, workspaceId).then(\n (ids) => live && setState({ status: 'ready', ids, error: null, for: workspaceId }),\n (e: unknown) =>\n live &&\n setState({\n status: 'failed',\n ids: {},\n error: e instanceof Error && e.message ? e.message : String(e),\n for: workspaceId,\n })\n )\n return () => {\n live = false\n }\n }, [active, workspaceId, signature, attempt])\n const retry = useCallback(() => setAttempt((a) => a + 1), [])\n if (!active) return { status: 'idle', ids: {}, error: null, retry }\n // Until the effect has started for this workspace, it is being prepared.\n if (state.for !== workspaceId) return { status: 'preparing', ids: {}, error: null, retry }\n return { status: state.status, ids: state.ids, error: state.error, retry }\n}\n","/**\n * Projects joined with their workspaces: what a project list or a project page shows of each\n * project (its details, workspaces, documents, threads, people, storage and AI quota), from the\n * shared `useProjects` and `useWorkspaces` lists (no request of its own). A project is created with\n * `useCreateProject` (`@arbidocs/react`).\n *\n * Generic: a site's words for a project (\"matter\", \"engagement\"…) and for its fields live in its\n * own config; these are the backend's project and its `client`, `client_ref`, `stage`,\n * `lead_user`, `budget` and host `fields`.\n */\n\nimport { useMemo } from 'react'\nimport type { components } from '@arbidocs/client'\nimport { useProjects, useProjectUsage, useWorkspaces } from '@arbidocs/react'\nimport {\n isAgentAccount,\n workspaceConversationCount,\n workspaceDocumentCount,\n workspaceGroupStats,\n type GroupedWorkspace,\n} from '../../workspaces/workspace-groups'\n\ntype ProjectResponse = components['schemas']['ProjectResponse']\ntype ProjectBudget = components['schemas']['ProjectBudget']\n\n/** A workspace of a project, with its counts. */\nexport interface ProjectWorkspaceSummary {\n id: string\n name: string\n description?: string\n isPublic: boolean\n documentCount: number\n conversationCount: number\n memberCount: number\n filesMb: number\n updatedAt: string\n}\n\n/** A member of any of the project's workspaces; possibly an agent (`agt-…`). */\nexport interface ProjectMemberSummary {\n id: string\n name: string\n email: string\n role: string\n isAgent: boolean\n}\n\n/** A project and the work it groups. */\nexport interface ProjectSummary {\n id: string\n name: string\n createdAt: string\n subscription: string\n workspaces: ProjectWorkspaceSummary[]\n workspaceCount: number\n documentCount: number\n conversationCount: number\n /** Everyone in the project's workspaces, agents included (`isAgent`). */\n members: ProjectMemberSummary[]\n /** The people (no agents). */\n memberCount: number\n filesMb: number\n storageUsedGb: number\n storageLimitGb: number\n /** AI usage this period against the project's limit (the quota's units). */\n aiUsageUsed: number\n aiUsageLimit: number\n client: string | null\n clientRef: string | null\n stage: string | null\n /** The project's lead (`usr-…`). */\n leadUser: string | null\n budget: ProjectBudget | null\n /** The host's own fields on the project. */\n fields: Record<string, unknown>\n}\n\nfunction workspaceSummary(w: GroupedWorkspace): ProjectWorkspaceSummary {\n return {\n id: w.external_id,\n name: w.name,\n description: w.description ?? undefined,\n isPublic: !!w.is_public,\n documentCount: workspaceDocumentCount(w),\n conversationCount: workspaceConversationCount(w),\n memberCount: w.users?.length ?? 0,\n filesMb: w.user_files_mb ?? 0,\n updatedAt: w.updated_at,\n }\n}\n\nfunction distinctMembers(workspaces: readonly GroupedWorkspace[]): ProjectMemberSummary[] {\n const byId = new Map<string, ProjectMemberSummary>()\n for (const w of workspaces) {\n for (const member of w.users ?? []) {\n const user = member.user\n const id = user?.external_id\n if (!id || byId.has(id)) continue\n const name = [user.given_name, user.family_name].filter(Boolean).join(' ').trim()\n byId.set(id, {\n id,\n name: name || user.email || 'Unknown',\n email: user.email ?? '',\n role: member.role ?? 'member',\n isAgent:\n Boolean((member as { agent_ext_id?: string | null }).agent_ext_id) ||\n isAgentAccount(user),\n })\n }\n }\n return [...byId.values()]\n}\n\n/** Join projects with their workspaces; the projects with the most work first. */\nexport function buildProjectSummaries(\n projects: readonly ProjectResponse[] | undefined,\n workspaces: readonly GroupedWorkspace[] | undefined\n): ProjectSummary[] {\n const byProject = new Map<string, GroupedWorkspace[]>()\n for (const w of workspaces ?? []) {\n const id = w.project_ext_id\n if (!id) continue\n byProject.set(id, [...(byProject.get(id) ?? []), w])\n }\n const summaries = (projects ?? []).map((p): ProjectSummary => {\n const own = byProject.get(p.external_id) ?? []\n const storage = p.quotas?.storage_gb\n const aiUsage = p.quotas?.ai_usage\n const stats = workspaceGroupStats(own)\n return {\n id: p.external_id,\n name: p.name,\n createdAt: p.created_at,\n subscription: p.subscription ?? 'none',\n workspaces: own.map(workspaceSummary),\n workspaceCount: own.length,\n documentCount: stats.documents,\n conversationCount: stats.conversations,\n members: distinctMembers(own),\n memberCount: stats.members,\n filesMb: own.reduce((sum, w) => sum + (w.user_files_mb ?? 0), 0),\n storageUsedGb: storage?.used ?? 0,\n storageLimitGb: storage?.limit ?? 0,\n aiUsageUsed: aiUsage?.used ?? 0,\n aiUsageLimit: aiUsage?.limit ?? 0,\n client: p.client ?? null,\n clientRef: p.client_ref ?? null,\n stage: p.stage ?? null,\n leadUser: p.lead_user ?? null,\n budget: p.budget ?? null,\n fields: p.fields ?? {},\n }\n })\n const work = (s: ProjectSummary) => s.documentCount + s.conversationCount\n return summaries.sort((a, b) => work(b) - work(a))\n}\n\n/** Every project the caller has, joined with its workspaces. */\nexport function useProjectSummaries() {\n const projects = useProjects()\n const workspaces = useWorkspaces()\n const summaries = useMemo(\n () =>\n buildProjectSummaries(\n projects.data as ProjectResponse[] | undefined,\n workspaces.data as GroupedWorkspace[] | undefined\n ),\n [projects.data, workspaces.data]\n )\n return {\n projects: summaries,\n isLoading: projects.isLoading || workspaces.isLoading,\n isError: projects.isError || workspaces.isError,\n error: projects.error ?? workspaces.error,\n }\n}\n\n/** One project's summary, with its AI usage this period. */\nexport function useProjectSummary(projectId: string | undefined) {\n const { projects, isLoading, isError } = useProjectSummaries()\n const project = useMemo(() => projects.find((p) => p.id === projectId), [projects, projectId])\n const usage = useProjectUsage(projectId, 0, { enabled: !!projectId })\n return { project, usage: usage.data, usageLoading: usage.isLoading, isLoading, isError }\n}\n\n/** The workspace a project's work runs in: the one with the most work. */\nexport function primaryProjectWorkspace(\n project: Pick<ProjectSummary, 'workspaces'>\n): ProjectWorkspaceSummary | undefined {\n const work = (w: ProjectWorkspaceSummary) => w.documentCount + w.conversationCount\n return [...project.workspaces].sort((a, b) => work(b) - work(a))[0]\n}\n","/**\n * The parts of a workflow run as a page (`ConnectedWorkflowRunner layout=\"page\"`): where the run\n * works (a project, chosen on the page with `ProjectPicker variant=\"run\"` or created by one of the\n * run's own steps, else the open workspace), opening that workspace, setting up the labels the\n * workflow needs there (`requiredLabels`), and saying so when another workspace has been opened\n * meanwhile. The runner composes them around its usual parts.\n *\n * The run's workspace is decided here and named on every request that sets it up, so nothing the\n * person does in another tab or panel (opening another workspace) moves the run.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react'\nimport {\n useArbiSessionStore,\n useCreateProject,\n useWorkspaces,\n type CreatedProject,\n type CreateProjectVars,\n} from '@arbidocs/react'\nimport { Button, Card, Input, Label, entityNoun } from '@arbidocs/react/ui'\nimport { AlertTriangle, Check, FolderKanban, Loader2, Plus } from 'lucide-react'\nimport type { WorkflowInputs, WorkflowRequiredLabel } from '../../agents/workflows/types'\nimport { ProjectOptionRow, ProjectPicker } from '../../workspaces/WorkspaceFormParts'\nimport { useConnectedWorkspace } from '../ConnectionProvider'\nimport {\n primaryProjectWorkspace,\n useProjectSummaries,\n type ProjectSummary,\n} from '../projects/useProjectSummaries'\nimport { useSelectWorkspace } from '../useSelectWorkspace'\n\n/**\n * Where a run's project comes from:\n * - `pick`: the person chooses one on the page (or makes a new one) before the run;\n * - `{ step, project }`: the run's own form step `step` makes it from what was filled in\n * (`project(inputs)`), and the rest of the run works in its new workspace.\n */\nexport type WorkflowRunProjectFrom =\n | 'pick'\n | {\n step: string\n project: (inputs: WorkflowInputs) => Omit<CreateProjectVars, 'workspace'>\n }\n\nexport interface WorkflowRunPageLabels {\n /** The target line's lead-in (\"Runs in\"). */\n runsIn: string\n /** The project chooser's heading. */\n chooseProject: string\n chooseProjectHint: string\n pickPlaceholder: string\n newProject: string\n newProjectName: string\n createProject: string\n /** Before a project step has made the project. */\n projectFromStep: string\n /** `{name}` is replaced. */\n opening: string\n /** `{name}` is replaced. */\n wrongWorkspace: string\n /** `{name}` is replaced. */\n openWorkspace: string\n preparingLabels: string\n labelsFailed: string\n retry: string\n openProject: string\n /** The run's workspace, before its name has loaded. */\n thisWorkspace: string\n /** The run would start before it has a workspace (a project step not done yet). */\n noWorkspace: string\n noProjects: string\n}\n\nexport const DEFAULT_WORKFLOW_RUN_PAGE_LABELS: WorkflowRunPageLabels = {\n runsIn: 'Runs in',\n chooseProject: `Choose the ${entityNoun('PROJECT')} to run it on`,\n chooseProjectHint: `The run, its documents and its results stay in the ${entityNoun('PROJECT')}.`,\n pickPlaceholder: `Select ${entityNoun('PROJECT')}`,\n newProject: `New ${entityNoun('PROJECT')}`,\n newProjectName: 'Name',\n createProject: 'Create and continue',\n projectFromStep: `A new ${entityNoun('PROJECT')}, from the first step`,\n opening: 'Opening {name}…',\n wrongWorkspace: 'This run works in {name}, which is not the workspace open now.',\n openWorkspace: 'Open {name}',\n preparingLabels: 'Setting up the review columns',\n labelsFailed: 'The review columns could not be set up.',\n retry: 'Try again',\n openProject: `Open the ${entityNoun('PROJECT')}`,\n thisWorkspace: 'this workspace',\n noWorkspace: 'There is no workspace for this run yet.',\n noProjects: `No ${entityNoun('PROJECT', 'PLURAL')} yet.`,\n}\n\n/** The run's workspace has been left while its run was being started. */\nexport class WorkflowRunWorkspaceChangedError extends Error {\n constructor(readonly workspaceId: string) {\n super('The workspace this run works in is no longer open.')\n this.name = 'WorkflowRunWorkspaceChangedError'\n }\n}\n\nexport interface WorkflowRunTargetOptions {\n projectFrom?: WorkflowRunProjectFrom\n /** The project, kept by the host (e.g. in its address). Absent: kept here. */\n projectId?: string | null\n onProjectChange?: (projectId: string) => void\n /** Without a project: the workspace the run works in. Absent: the open one. */\n workspaceId?: string\n /** A new project, made on the page or by the run's step (the host's own follow-up). */\n onProjectCreated?: (\n project: CreatedProject,\n inputs: WorkflowInputs\n ) => Promise<WorkflowInputs | void> | WorkflowInputs | void\n}\n\nexport type WorkflowRunStage = 'pick' | 'loading' | 'opening' | 'switch' | 'ready'\n\n/**\n * Where a page's run works and how far it is from ready: `pick` (no project yet), `loading` (the\n * project is being read), `opening` (its workspace is being opened), `switch` (another workspace\n * is open), `ready`.\n */\nexport function useWorkflowRunTarget({\n projectFrom,\n projectId: controlled,\n onProjectChange,\n workspaceId: fixedWorkspace,\n onProjectCreated,\n}: WorkflowRunTargetOptions) {\n const { workspaceId: open } = useConnectedWorkspace()\n const session = useArbiSessionStore()\n const selectWorkspace = useSelectWorkspace()\n const createProject = useCreateProject()\n const { projects, isLoading: projectsLoading } = useProjectSummaries()\n const { data: workspaces } = useWorkspaces()\n const [own, setOwn] = useState<string | null>(null)\n const projectId = controlled !== undefined ? controlled : own\n // A project the run made (its workspace before the lists have it).\n const [created, setCreated] = useState<{ projectId: string; workspaceId: string } | null>(null)\n // The workspace the run started in: from then on it is the run's, whatever is opened later.\n const [startedIn, setStartedIn] = useState<string | null>(null)\n const project = projectId ? projects.find((p) => p.id === projectId) : undefined\n const projectWorkspace =\n created && created.projectId === projectId\n ? created.workspaceId\n : project\n ? primaryProjectWorkspace(project)?.id\n : undefined\n\n // A run on a project works in the project's workspace (none until there is one); otherwise in\n // the host's workspace, else the open one.\n const target: string | undefined =\n startedIn ?? (projectFrom ? projectWorkspace : (fixedWorkspace ?? open ?? undefined))\n const targetRef = useRef(target)\n targetRef.current = target\n\n // The workspace open now, as of this moment (not of the last render).\n const openNow = useCallback(() => session.getState().workspaceId ?? open ?? null, [session, open])\n\n // A chosen project's workspace is opened once; leaving it later is the person's choice, and the\n // page says so instead of pulling them back.\n const [opening, setOpening] = useState<string | null>(null)\n const tried = useRef(new Set<string>())\n useEffect(() => {\n if (!target || target === open || startedIn || tried.current.has(target)) return\n tried.current.add(target)\n setOpening(target)\n selectWorkspace(target)\n .catch(() => {})\n .finally(() => setOpening((o) => (o === target ? null : o)))\n }, [target, open, startedIn, selectWorkspace])\n\n const pick = useCallback(\n (id: string) => {\n setOwn(id)\n onProjectChange?.(id)\n },\n [onProjectChange]\n )\n\n /** Make a project with its first workspace, open that, and run there. */\n const makeProject = useCallback(\n async (vars: Omit<CreateProjectVars, 'workspace'>, inputs: WorkflowInputs = {}) => {\n const made = await createProject.mutateAsync({ plan: 'free', ...vars, workspace: {} })\n const ws = made.workspace?.external_id\n if (!ws) throw new Error(`The ${entityNoun('PROJECT')} has no workspace`)\n setCreated({ projectId: made.external_id, workspaceId: ws })\n targetRef.current = ws\n setOwn(made.external_id)\n onProjectChange?.(made.external_id)\n tried.current.add(ws)\n await selectWorkspace(ws)\n const extra = await onProjectCreated?.(made, inputs)\n return { project: made, workspaceId: ws, inputs: extra ?? undefined }\n },\n [createProject, onProjectChange, selectWorkspace, onProjectCreated]\n )\n\n const nameOf = (id: string | undefined) =>\n id\n ? (project?.workspaces.find((w) => w.id === id)?.name ??\n (workspaces as Array<{ external_id: string; name: string }> | undefined)?.find(\n (w) => w.external_id === id\n )?.name)\n : undefined\n\n const stage: WorkflowRunStage =\n projectFrom === 'pick' && !projectId && !startedIn\n ? 'pick'\n : projectFrom && projectId && !target\n ? 'loading'\n : target && target !== open\n ? opening === target\n ? 'opening'\n : 'switch'\n : 'ready'\n\n return {\n stage,\n target,\n targetRef,\n targetName: nameOf(target),\n openNow,\n project,\n projectId,\n projects,\n projectsLoading,\n pick,\n makeProject,\n creating: createProject.isPending,\n /** The run started in `workspaceId`: it stays the run's. */\n pin: setStartedIn,\n openTarget: () => (target ? selectWorkspace(target) : Promise.resolve()),\n }\n}\n\nexport type WorkflowRunTarget = ReturnType<typeof useWorkflowRunTarget>\n\n/** Choose a project for the run, or make a new one. */\nexport function WorkflowRunProjectChooser({\n projects,\n loading,\n onPick,\n onCreate,\n creating,\n labels,\n testId,\n}: {\n projects: ProjectSummary[]\n loading?: boolean\n onPick: (projectId: string) => void\n onCreate: (name: string) => Promise<unknown>\n creating?: boolean\n labels: WorkflowRunPageLabels\n testId: string\n}) {\n const [adding, setAdding] = useState(false)\n const [name, setName] = useState('')\n const [error, setError] = useState<string | null>(null)\n const options = useMemo(\n () =>\n projects.map((p) => ({\n id: p.id,\n content: (\n <ProjectOptionRow\n identity={<span className=\"truncate\">{p.name}</span>}\n meta={p.client ?? undefined}\n />\n ),\n })),\n [projects]\n )\n const submit = (e: FormEvent) => {\n e.preventDefault()\n const n = name.trim()\n if (!n) return\n setError(null)\n onCreate(n).catch((err: unknown) =>\n setError(err instanceof Error && err.message ? err.message : String(err))\n )\n }\n return (\n <Card className=\"max-w-2xl space-y-4 p-5 sm:p-6\" data-testid={`${testId}-choose-project`}>\n <div className=\"space-y-1\">\n <h2 className=\"text-base font-semibold\">{labels.chooseProject}</h2>\n <p className=\"text-sm text-muted-foreground\">{labels.chooseProjectHint}</p>\n </div>\n {loading ? (\n <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n ) : projects.length ? (\n <ProjectPicker\n variant=\"run\"\n options={options}\n onChange={onPick}\n onCreate={() => setAdding(true)}\n labels={{ placeholder: labels.pickPlaceholder, create: labels.newProject }}\n testId={`${testId}-project-select`}\n />\n ) : (\n <p className=\"text-sm text-muted-foreground\">{labels.noProjects}</p>\n )}\n {adding || (!loading && !projects.length) ? (\n <form\n onSubmit={submit}\n className=\"space-y-2 border-t border-border pt-4\"\n data-testid={`${testId}-new-project`}\n >\n <Label htmlFor={`${testId}-new-project-name`}>{labels.newProjectName}</Label>\n <div className=\"flex flex-col gap-2 sm:flex-row\">\n <Input\n id={`${testId}-new-project-name`}\n value={name}\n onChange={(e) => setName(e.target.value)}\n autoFocus={adding}\n className=\"sm:max-w-md\"\n data-testid={`${testId}-new-project-name`}\n />\n <Button\n type=\"submit\"\n disabled={!name.trim() || creating}\n data-testid={`${testId}-new-project-create`}\n >\n {creating ? <Loader2 className=\"size-4 animate-spin\" /> : <Plus className=\"size-4\" />}\n {labels.createProject}\n </Button>\n </div>\n {error && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {error}\n </p>\n )}\n </form>\n ) : null}\n </Card>\n )\n}\n\n/** \"Runs in <project> · <workspace>\": where the run works, and a way to the project. */\nexport function WorkflowRunTargetLine({\n project,\n workspaceName,\n fromStep,\n onOpenProject,\n labels,\n testId,\n}: {\n project?: Pick<ProjectSummary, 'id' | 'name'>\n workspaceName?: string\n fromStep?: boolean\n onOpenProject?: (projectId: string) => void\n labels: WorkflowRunPageLabels\n testId: string\n}) {\n const where = project?.name ?? (fromStep ? labels.projectFromStep : undefined)\n if (!where && !workspaceName) return null\n return (\n <div\n className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-sm\"\n data-testid={`${testId}-target`}\n >\n <span className=\"text-muted-foreground\">{labels.runsIn}</span>\n <span className=\"flex min-w-0 items-center gap-1.5 font-medium\">\n <FolderKanban className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden />\n <span className=\"truncate\">{where ?? workspaceName}</span>\n {where && workspaceName && project?.name !== workspaceName && (\n <span className=\"truncate font-normal text-muted-foreground\">· {workspaceName}</span>\n )}\n </span>\n {project && onOpenProject && (\n <Button\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0\"\n onClick={() => onOpenProject(project.id)}\n data-testid={`${testId}-open-project`}\n >\n {labels.openProject}\n </Button>\n )}\n </div>\n )\n}\n\n/** Opening the run's workspace, or setting up its labels: what is being done, and a retry. */\nexport function WorkflowRunPreparing({\n stage,\n workspaceName,\n labels: required,\n failed,\n error,\n onRetry,\n l,\n testId,\n}: {\n stage: 'loading' | 'opening' | 'labels'\n workspaceName: string\n labels: readonly WorkflowRequiredLabel[]\n failed?: boolean\n error?: string | null\n onRetry?: () => void\n l: WorkflowRunPageLabels\n testId: string\n}) {\n if (stage !== 'labels')\n return (\n <p\n className=\"flex items-center gap-2 text-sm text-muted-foreground\"\n data-testid={`${testId}-preparing`}\n >\n <Loader2 className=\"size-4 animate-spin\" />\n {l.opening.replace('{name}', workspaceName)}\n </p>\n )\n return (\n <Card className=\"max-w-2xl space-y-3 p-5\" data-testid={`${testId}-preparing`}>\n <h2 className=\"flex items-center gap-2 text-sm font-semibold\">\n {failed ? (\n <AlertTriangle className=\"size-4 text-destructive\" />\n ) : (\n <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n )}\n {failed ? l.labelsFailed : l.preparingLabels}\n </h2>\n <ul className=\"flex flex-wrap gap-1.5\">\n {required.map((label) => (\n <li\n key={label.key}\n className=\"rounded-full border border-border px-2.5 py-0.5 text-xs text-muted-foreground\"\n >\n {label.name}\n </li>\n ))}\n </ul>\n {failed && (\n <div className=\"flex flex-wrap items-center gap-3\">\n {error && <p className=\"text-sm text-muted-foreground\">{error}</p>}\n <Button size=\"sm\" variant=\"outline\" onClick={onRetry} data-testid={`${testId}-retry`}>\n {l.retry}\n </Button>\n </div>\n )}\n </Card>\n )\n}\n\n/** Another workspace is open than the run's: open the run's to go on. */\nexport function WorkflowRunWorkspaceNotice({\n workspaceName,\n onOpen,\n labels,\n testId,\n}: {\n workspaceName: string\n onOpen: () => Promise<unknown>\n labels: WorkflowRunPageLabels\n testId: string\n}) {\n const [busy, setBusy] = useState(false)\n return (\n <div\n role=\"status\"\n className=\"flex flex-col gap-3 rounded-lg border border-warning/40 bg-warning/10 p-4 sm:flex-row sm:items-center\"\n data-testid={`${testId}-switch`}\n >\n <AlertTriangle className=\"size-5 shrink-0 text-warning\" aria-hidden />\n <p className=\"min-w-0 flex-1 text-sm\">\n {labels.wrongWorkspace.replace('{name}', workspaceName)}\n </p>\n <Button\n size=\"sm\"\n disabled={busy}\n onClick={() => {\n setBusy(true)\n void onOpen().finally(() => setBusy(false))\n }}\n data-testid={`${testId}-open-workspace`}\n >\n {busy ? <Loader2 className=\"size-4 animate-spin\" /> : <Check className=\"size-4\" />}\n {labels.openWorkspace.replace('{name}', workspaceName)}\n </Button>\n </div>\n )\n}\n","/**\n * A workflow run's thread, live and interactive: the blocks `ChatPage` held to the run's one\n * conversation (people ask follow-ups, see the answers and their sources, open documents), with\n * the current step's panel beside it (`aside`). Step messages show as their step's chip.\n */\n\nimport type { ReactNode } from 'react'\nimport { ConversationScope, useConversation } from '@arbidocs/react'\nimport { ChatPage } from '../chat/ChatPage'\nimport type { ChatCitationTarget, ChatPageLabels, WorkflowStepView } from '../chat/chat-page-types'\n\nexport interface WorkflowRunThreadProps {\n conversationId: string\n workspaceId: string | undefined\n /** The current step's panel. */\n aside?: ReactNode\n /** A step by id: its title, kind and phase (step messages show as its chip). */\n stepOf?: (stepId: string) => WorkflowStepView | undefined\n /** Scroll to and mark this message (a step's answer). */\n targetMessageId?: string\n onOpenCitation?: (target: ChatCitationTarget) => void\n labels?: Partial<ChatPageLabels>\n className?: string\n}\n\nexport function WorkflowRunThread(props: WorkflowRunThreadProps) {\n // The run's conversation, in a scope of its own: the page's chat stays where it is.\n return (\n <ConversationScope workspaceId={props.workspaceId} conversationId={props.conversationId}>\n <RunThread {...props} />\n </ConversationScope>\n )\n}\n\nfunction RunThread({\n conversationId,\n workspaceId,\n aside,\n stepOf,\n targetMessageId,\n onOpenCitation,\n labels,\n className,\n}: WorkflowRunThreadProps) {\n const chat = useConversation({ workspaceId })\n return (\n <ChatPage\n chat={{ ...chat, threads: chat.threads.filter((t) => t.id === conversationId) }}\n singleThread\n documentsRequired={false}\n aside={aside}\n asideBreakpoint={52}\n workflowStepOf={stepOf}\n targetMessageId={targetMessageId}\n onOpenCitation={onOpenCitation}\n labels={labels}\n className={className ?? 'h-[min(78dvh,860px)] min-h-[480px] rounded-xl border border-border'}\n />\n )\n}\n","/**\n * A stepped workflow run that lives in a work thread on the server. The thread's plan carries the\n * steps; its activity log says where each step is; the work runner starts each agent step as a\n * turn in the thread. This hook reads all of that and does the person's part: it starts the thread\n * (with the run's inputs and the steps' prompts composed from them), completes forms, uploads and\n * reviews, skips, and retries a failed step. A run whose first open step is an agent or action\n * step starts when the person presses Start: the thread is created and the server starts that\n * step. `WorkflowRunner` shows the result.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n useActOnStep,\n useArbi,\n useConversationActivity,\n useConversationThreads,\n useConversations,\n useCreateWork,\n useWorkspaceUsers,\n type ConversationResponse,\n} from '@arbidocs/react'\nimport { fromPlanSteps, toPlanSteps, type TaskPlanStep } from '../agents/workflows/planSteps'\nimport {\n initialRunInputs,\n runThreadTitle,\n stepFields,\n stepStatesFromActivity,\n workflowSteps,\n type StepComposeOptions,\n type WorkflowActivityEvent,\n} from '../agents/workflows/run'\nimport { useWorkflowView, type WorkflowRunView } from '../agents/workflows/useWorkflowView'\nimport { withLabelIds } from '../agents/workflows/requiredLabels'\nimport type {\n WorkflowDefinition,\n WorkflowInputs,\n WorkflowStep,\n WorkflowStepState,\n} from '../agents/workflows/types'\nimport { useConnectedWorkspace } from './ConnectionProvider'\n\nexport interface UseWorkflowThreadOptions extends StepComposeOptions {\n /**\n * An existing run to show (its thread). Absent: a new run starts when its first step is done,\n * or, when that is an agent or action step, when the person starts it.\n */\n conversationId?: string\n /** The thread was created (store its id to come back to the run). */\n onStarted?: (conversationId: string) => void\n /**\n * The host's commits, by step id (`commit: true` steps): done before the step is recorded, e.g.\n * create and open the matter the run belongs in (the thread is created in the open workspace).\n * May return inputs to merge into the run.\n */\n commit?: Record<string, (inputs: WorkflowInputs) => Promise<WorkflowInputs | void>>\n /** Prefills for a new run. */\n initialInputs?: WorkflowInputs\n /** The agent that runs the agent steps (`agt-…`); absent = the person's own assistant. */\n agentId?: string\n /**\n * The files added on an upload step in this run (doc ids): sent when it is completed, so the\n * step records exactly them.\n */\n documentsFor?: (stepId: string) => string[]\n /**\n * Called as the run's thread is about to be created, after any commit: the host makes the run's\n * workspace ready (its required labels, `requiredLabels`) and may refuse (throw), e.g. when the\n * open workspace is no longer the run's. The label ids it returns go into the steps\n * (`withLabelIds`).\n */\n beforeStart?: () => Promise<{ labelIds?: Record<string, string> } | void>\n}\n\nexport interface WorkflowThread {\n view: WorkflowRunView\n /** The run's thread, once it exists. */\n conversationId: string | undefined\n conversation: ConversationResponse | undefined\n /** A workspace member's name by id. */\n nameOf: (id: string) => string | undefined\n /** The workspace's people (not agents): what a person field offers. */\n people: Array<{ value: string; label: string }>\n}\n\nconst STARTING = new Set(['pending', 'running'])\n\n/**\n * The values a form or a fielded review collected (what is recorded with it on the thread). A\n * review's blank optional fields are left out: the server checks each one given.\n */\nfunction formValues(step: WorkflowStep, inputs: WorkflowInputs): WorkflowInputs | undefined {\n const fields = stepFields(step)\n if (!fields.length) return undefined\n if (step.kind === 'form')\n return Object.fromEntries(fields.map((f) => [f.name, inputs[f.name] ?? '']))\n const given = fields.flatMap((f) => {\n const v = inputs[f.name]\n return v === undefined || v === '' ? [] : [[f.name, v] as const]\n })\n return given.length ? Object.fromEntries(given) : undefined\n}\n\n/** How many times missing answers are fetched again before giving up (about three minutes). */\nexport const ANSWER_RETRY_CAP = 16\n\n/** The wait before the `attempt`th fetch of missing answers: at once, then 1s doubling to 15s. */\nexport function answerRetryDelay(attempt: number): number {\n return attempt === 0 ? 0 : Math.min(1000 * 2 ** (attempt - 1), 15_000)\n}\n\n/**\n * Fetch again, with backoff and a cap, while `missing` (the ids of finished steps' answers not\n * read yet) is not empty. A change in what is missing starts the count again.\n */\nfunction useAnswerRetry(missing: string, refetch: () => Promise<unknown>) {\n const [attempt, setAttempt] = useState(0)\n const [prev, setPrev] = useState(missing)\n if (prev !== missing) {\n setPrev(missing)\n setAttempt(0)\n }\n const refetchRef = useRef(refetch)\n refetchRef.current = refetch\n useEffect(() => {\n if (!missing || attempt >= ANSWER_RETRY_CAP) return\n const t = setTimeout(() => {\n void refetchRef.current()\n setAttempt((a) => a + 1)\n }, answerRetryDelay(attempt))\n return () => clearTimeout(t)\n }, [missing, attempt])\n}\n\nexport function useWorkflowThread(\n workflow: WorkflowDefinition,\n options: UseWorkflowThreadOptions = {}\n): WorkflowThread {\n const arbi = useArbi()\n const { ensureWorkspaceOpen, live, workspaceId } = useConnectedWorkspace()\n const wsId = workspaceId ?? undefined\n const [threadId, setThreadId] = useState(options.conversationId)\n const [localInputs, setLocalInputs] = useState<WorkflowInputs>(() =>\n initialRunInputs(workflow, options.initialInputs)\n )\n // What the person typed: it wins over the thread's copy, which only learns a form's values when\n // that step is completed (until then it holds them blank).\n const [edits, setEdits] = useState<WorkflowInputs>({})\n const [localStates, setLocalStates] = useState<Record<string, WorkflowStepState>>({})\n const createWork = useCreateWork()\n const actOnStep = useActOnStep()\n\n const conversations = useConversations(wsId, { enabled: !!threadId, live: true })\n const members = useWorkspaceUsers(wsId, {\n enabled: live && !!wsId,\n beforeFetch: ensureWorkspaceOpen,\n })\n const nameOf = useCallback(\n (id: string) => {\n const u = members.data?.find((m) => m.user.external_id === id)?.user\n return u ? [u.given_name, u.family_name].filter(Boolean).join(' ') || u.email : undefined\n },\n [members.data]\n )\n const conversation = conversations.data?.find((c) => c.external_id === threadId)\n const steps = useMemo(\n () =>\n workflowSteps(workflow).length > 0\n ? workflowSteps(workflow)\n : fromPlanSteps((conversation?.plan?.steps ?? []) as TaskPlanStep[]),\n [workflow, conversation?.plan?.steps]\n )\n\n // Poll while an agent step is on its way (the server starts it, then runs it).\n const activity = useConversationActivity(threadId, { live: !!threadId })\n const serverStates = useMemo(\n () => stepStatesFromActivity((activity.data ?? []) as WorkflowActivityEvent[]),\n [activity.data]\n )\n const working = steps.some(\n (s) =>\n (s.kind === 'agent' || s.kind === 'action') &&\n STARTING.has(serverStates[s.id]?.status ?? 'pending')\n )\n const threads = useConversationThreads(threadId, { enabled: !!threadId, live: working })\n // Only answers with text: the assistant's message exists (empty) from the moment its turn\n // starts and is filled when the turn ends, which can be after the step is recorded done.\n const answers = useMemo(() => {\n const byId = new Map<string, string>()\n for (const t of threads.data?.threads ?? [])\n for (const m of t.history)\n if (m.role === 'assistant' && m.content?.trim()) byId.set(m.external_id, m.content)\n return byId\n }, [threads.data])\n\n // A step can finish as the run stops (the last one always does): nothing is polled then, and\n // the activity log no longer changes. Fetch the messages again, backing off, until every\n // finished step's answer is in (or the cap is reached; a new missing answer starts again).\n const missing = Object.values(serverStates)\n .flatMap((st) =>\n st.status === 'done' && st.responseId && !answers.has(st.responseId) ? [st.responseId] : []\n )\n .sort()\n .join(' ')\n useAnswerRetry(missing, threads.refetch)\n\n const states = useMemo(() => {\n if (!threadId) return localStates\n const out: Record<string, WorkflowStepState> = {}\n for (const [id, s] of Object.entries(serverStates))\n out[id] = { ...s, text: s.responseId ? answers.get(s.responseId) : undefined }\n return out\n }, [threadId, localStates, serverStates, answers])\n\n const inputs = useMemo(\n () =>\n threadId\n ? { ...localInputs, ...(conversation?.skill_inputs ?? {}), ...edits }\n : { ...localInputs, ...edits },\n [threadId, localInputs, conversation?.skill_inputs, edits]\n ) as WorkflowInputs\n\n const refresh = useCallback(async () => {\n await Promise.all([activity.refetch(), conversations.refetch()])\n }, [activity, conversations])\n\n const act = useCallback(\n async (\n id: string,\n body: {\n step: string\n action: 'complete' | 'skip' | 'send_back' | 'decline'\n inputs?: WorkflowInputs\n documents?: string[]\n to?: string\n note?: string\n }\n ) => {\n await actOnStep.mutateAsync({ conversationId: id, body })\n await refresh()\n },\n [actOnStep, refresh]\n )\n\n // The run starts: its thread, in the workspace now open, with the steps and the inputs so far.\n // Creating it starts the first ready agent step on the server; the steps skipped before it existed\n // are then recorded (which starts what they made ready).\n const createThread = useCallback(\n async (values: WorkflowInputs, done?: string): Promise<string> => {\n const prepared = await options.beforeStart?.()\n const planned = prepared?.labelIds ? withLabelIds(workflow, prepared.labelIds) : workflow\n await ensureWorkspaceOpen()\n const created = await createWork.mutateAsync({\n title: runThreadTitle(workflow, values).slice(0, 60),\n description: workflow.description || null,\n prompt: null,\n skill_ref: null,\n skill_inputs: values as Record<string, unknown>,\n agent_ext_id: options.agentId ?? null,\n auth_mode: 'run_now_temp',\n plan: {\n goal: '',\n criteria: [],\n max_passes: 3,\n documents: [],\n steps: toPlanSteps(planned, {\n inputs: values,\n resolveWorkflow: options.resolveWorkflow,\n compose: options.compose,\n }),\n },\n })\n const id = created.external_id\n setThreadId(id)\n if (done) setLocalStates((s) => ({ ...s, [done]: { status: 'done' } }))\n options.onStarted?.(id)\n for (const [stepId, st] of Object.entries(localStates))\n if (st.status === 'skipped')\n await actOnStep.mutateAsync({\n conversationId: id,\n body: { step: stepId, action: 'skip' },\n })\n return id\n },\n [ensureWorkspaceOpen, createWork, workflow, options, localStates, actOnStep]\n )\n\n const complete = useCallback(\n async (step: WorkflowStep) => {\n let values = inputs\n const commit = step.commit ? options.commit?.[step.id] : undefined\n if (commit && localStates[step.id]?.status !== 'done') {\n values = { ...values, ...((await commit(values)) ?? {}) }\n setLocalInputs(values)\n setEdits({})\n }\n const id = threadId ?? (await createThread(values, step.id))\n const documents = step.kind === 'upload' ? options.documentsFor?.(step.id) : undefined\n await act(id, {\n step: step.id,\n action: 'complete',\n inputs: formValues(step, values),\n ...(documents?.length ? { documents } : {}),\n })\n },\n [inputs, options, localStates, threadId, createThread, act]\n )\n\n // Start the ready agent or action step nothing else will start: create the run's thread (the\n // server starts the step), or run the thread again (the server could not start it before).\n const start = useCallback(async () => {\n if (!threadId) {\n await createThread(inputs)\n await refresh()\n return\n }\n await arbi.conversations.runWithAuth(threadId)\n await refresh()\n }, [threadId, createThread, inputs, arbi, refresh])\n\n const skip = useCallback(\n async (stepId: string) => {\n if (!threadId) {\n setLocalStates((s) => ({ ...s, [stepId]: { status: 'skipped' } }))\n return\n }\n await act(threadId, { step: stepId, action: 'skip' })\n },\n [threadId, act]\n )\n\n const retry = useCallback(\n async (_stepId: string) => {\n if (!threadId) return\n // Running the thread again retries its failed step.\n await arbi.conversations.runWithAuth(threadId)\n await refresh()\n },\n [arbi, threadId, refresh]\n )\n\n const sendBack = useCallback(\n async (stepId: string, to: string, note?: string) => {\n if (!threadId) return\n await act(threadId, { step: stepId, action: 'send_back', to, ...(note ? { note } : {}) })\n },\n [threadId, act]\n )\n\n const decline = useCallback(\n async (stepId: string, note?: string) => {\n if (!threadId) return\n await act(threadId, { step: stepId, action: 'decline', ...(note ? { note } : {}) })\n },\n [threadId, act]\n )\n\n // A run opened later opens where it is once its log has arrived (not at its first step).\n const loaded = !options.conversationId || activity.isSuccess || activity.isError\n\n // Nothing will start a ready agent or action step unless the person does: there is no thread\n // yet, or the thread's run is not under way (it could not start: `last_error` says why).\n const idle = !!conversation && !conversation.in_progress\n const anyRunning = Object.values(states).some((s) => s.status === 'running')\n const needsStart = !threadId || (idle && !anyRunning)\n const runError = idle ? (conversation?.last_error ?? null) : null\n\n const view = useWorkflowView({\n steps,\n states,\n inputs,\n setInput: (name, value) => setEdits((i) => ({ ...i, [name]: value })),\n complete,\n skip,\n retry,\n start,\n needsStart,\n runError,\n sendBack,\n decline,\n nameOf,\n loaded,\n isLocked: (id) => states[id]?.status === 'done',\n })\n\n const people = useMemo(\n () =>\n (members.data ?? [])\n .filter((m) => !m.user.external_id.startsWith('agt-'))\n .map((m) => ({\n value: m.user.external_id,\n label: nameOf(m.user.external_id) ?? m.user.external_id,\n })),\n [members.data, nameOf]\n )\n\n return { view, conversationId: threadId, conversation, nameOf, people }\n}\n","/**\n * What the connected runner opens itself when the host does not take over: the sign flow for a\n * signature step (the blocks `SignDocumentDialog` on the document's PDF), the native Word editor\n * for a tracked-changes version, and a tabular review's grid (its documents by its columns).\n */\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport { useArbi, useDocuments, useTags } from '@arbidocs/react'\nimport {\n DocumentToolsProvider,\n fetchDocumentPdf,\n useOptionalDocumentTools,\n} from '@arbidocs/react/document-tools'\nimport { Loader2 } from 'lucide-react'\nimport { SignDocumentDialog } from '../document-tools/SignDocumentDialog'\nimport { ModalScaffold } from '../settings/ModalScaffold'\nimport { splitDocRef } from '../agents/workflows/run'\nimport { ConnectedNativeDocxEditor } from './docx/ConnectedNativeDocxEditor'\nimport { useConnectedWorkspace } from './ConnectionProvider'\n\nexport interface WorkflowRunnerDialogLabels {\n loadingDocument: string\n preparingDocument: string\n documentFailed: string\n reviewTitle: string\n reviewDescription: string\n document: string\n empty: string\n showMore: string\n showLess: string\n wordTitle: string\n}\n\nexport const DEFAULT_WORKFLOW_RUNNER_DIALOG_LABELS: WorkflowRunnerDialogLabels = {\n loadingDocument: 'Opening the document…',\n preparingDocument: 'The PDF is still being prepared…',\n documentFailed: 'The document could not be opened.',\n reviewTitle: 'Review',\n reviewDescription: 'Each document against each review column.',\n document: 'Document',\n empty: '—',\n showMore: 'Show more',\n showLess: 'Show less',\n wordTitle: 'Tracked changes',\n}\n\n/** How often, and how long apart, the PDF is fetched again while it is still being rendered. */\nconst SIGN_PDF_RETRIES = 4\nexport const SIGN_PDF_RETRY_DELAY_MS = 1500\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\n/**\n * The sign flow on one document version: its PDF is fetched, then the blocks sign dialog.\n *\n * What is signed is the PDF `GET /view?version=` serves (a Word or Markdown document's rendition),\n * never the original's download, so the hash the server checks is of the bytes shown here. A\n * rendition still being written is fetched again a few times; a version superseded since the step\n * was set offers the current one instead.\n */\nexport function WorkflowSignDialog({\n docRef,\n onClose,\n labels,\n}: {\n /** `doc-…` or `doc-…@v3`. */\n docRef: string\n onClose: () => void\n labels: WorkflowRunnerDialogLabels\n}) {\n const arbi = useArbi()\n const { user, ensureWorkspaceOpen } = useConnectedWorkspace()\n const tools = useOptionalDocumentTools()\n const { id, version: stepVersion } = splitDocRef(docRef)\n // The version the step names, until the signer opens the current one instead.\n const [version, setVersion] = useState(stepVersion)\n const [pdf, setPdf] = useState<Blob | null>(null)\n const [preparing, setPreparing] = useState(false)\n const [failed, setFailed] = useState(false)\n useEffect(() => {\n let live = true\n setPdf(null)\n setFailed(false)\n setPreparing(false)\n void (async () => {\n try {\n await ensureWorkspaceOpen()\n const client = arbi.getClient().fetch\n const ref = version ? `${id}@v${version}` : id\n for (let attempt = 0; ; attempt++) {\n try {\n const blob = await fetchDocumentPdf(client, ref)\n if (live) setPdf(blob)\n return\n } catch (err) {\n if (!live || attempt >= SIGN_PDF_RETRIES) throw err\n setPreparing(true)\n await wait(SIGN_PDF_RETRY_DELAY_MS)\n if (!live) return\n }\n }\n } catch {\n if (live) setFailed(true)\n }\n })()\n return () => {\n live = false\n }\n }, [arbi, id, version, ensureWorkspaceOpen])\n\n if (!pdf)\n return (\n <ModalScaffold\n open\n onOpenChange={(o) => !o && onClose()}\n title={labels.loadingDocument}\n size=\"sm\"\n testId=\"workflow-sign-loading\"\n >\n <ModalScaffold.Body>\n <p className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n {failed ? (\n labels.documentFailed\n ) : (\n <>\n <Loader2 className=\"size-4 animate-spin\" />{' '}\n {preparing ? labels.preparingDocument : labels.loadingDocument}\n </>\n )}\n </p>\n </ModalScaffold.Body>\n </ModalScaffold>\n )\n const dialog = (\n <SignDocumentDialog\n // A new PDF is a new signing: the form starts again on it.\n key={version ?? 'current'}\n open\n onOpenChange={(o) => !o && onClose()}\n documentId={id}\n pdfBlob={pdf}\n version={version}\n // Superseded since the step was set: sign the current version, after seeing it.\n onOpenCurrent={() => setVersion(undefined)}\n />\n )\n // A host with its own document tools keeps them (its notices, its document opening).\n return tools ? (\n dialog\n ) : (\n <DocumentToolsProvider\n client={arbi.getClient().fetch}\n user={user ? { name: user.name, email: user.email } : null}\n >\n {dialog}\n </DocumentToolsProvider>\n )\n}\n\n/** A tracked-changes version in the native Word editor. */\nexport function WorkflowWordDialog({\n docRef,\n title,\n onClose,\n labels,\n}: {\n docRef: string\n title?: string\n onClose: () => void\n labels: WorkflowRunnerDialogLabels\n}) {\n const { id } = splitDocRef(docRef)\n return (\n <ModalScaffold\n open\n onOpenChange={(o) => !o && onClose()}\n title={title ?? labels.wordTitle}\n size=\"xl\"\n testId=\"workflow-word-dialog\"\n >\n <ModalScaffold.Body className=\"h-[70dvh] p-0\">\n <ConnectedNativeDocxEditor documentId={id} title={title ?? labels.wordTitle} />\n </ModalScaffold.Body>\n </ModalScaffold>\n )\n}\n\n/** A tabular review's grid: each document (row) against each column (label), with its value. */\nexport function WorkflowReviewGridDialog({\n tags,\n documents,\n onClose,\n onOpenDocument,\n labels,\n}: {\n tags: string[]\n documents: string[]\n onClose: () => void\n onOpenDocument?: (docId: string) => void\n labels: WorkflowRunnerDialogLabels\n}) {\n const { workspaceId } = useConnectedWorkspace()\n const allTags = useTags(workspaceId ?? undefined)\n // The workspace's documents carry their review values (doctags); the review's rows are its own.\n const all = useDocuments(workspaceId ?? undefined)\n // The grid waits for its column names and for documents fetched since it opened: before, its\n // headers would be the raw tag ids and its cells the values cached before the review ran.\n const isLoading =\n allTags.isLoading || all.isLoading || (all.isFetching && !all.isFetchedAfterMount)\n const docs = (all.data ?? []).filter((d) => documents.includes(d.external_id))\n const columns = useMemo(\n () =>\n tags.map((id) => ({\n id,\n name: allTags.data?.find((t) => t.external_id === id)?.name ?? id,\n })),\n [tags, allTags.data]\n )\n return (\n <ModalScaffold\n open\n onOpenChange={(o) => !o && onClose()}\n title={labels.reviewTitle}\n description={labels.reviewDescription}\n showDescription\n size=\"xl\"\n testId=\"workflow-review-grid\"\n >\n <ModalScaffold.Body className=\"overflow-auto\">\n {isLoading ? (\n <p className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Loader2 className=\"size-4 animate-spin\" /> {labels.loadingDocument}\n </p>\n ) : (\n <table className=\"w-full border-collapse text-sm\">\n <thead>\n <tr>\n <th className=\"sticky left-0 z-10 border-b border-border bg-background p-2 text-left align-bottom font-medium\">\n {labels.document}\n </th>\n {columns.map((c) => (\n <th\n key={c.id}\n className=\"border-b border-border p-2 text-left align-bottom font-medium\"\n >\n <div className={`${VALUE_WIDTH} line-clamp-2 break-words`} title={c.name}>\n {c.name}\n </div>\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {docs.map((d) => (\n <tr key={d.external_id} data-testid={`workflow-review-grid-row-${d.external_id}`}>\n <td className=\"sticky left-0 z-10 border-b border-border bg-background p-2 align-top\">\n <DocumentName onClick={onOpenDocument && (() => onOpenDocument(d.external_id))}>\n {d.file_name ?? d.external_id}\n </DocumentName>\n </td>\n {columns.map((c) => {\n const note = d.doctags?.find((t) => t.tag_ext_id === c.id)?.note\n return (\n <td\n key={c.id}\n className=\"border-b border-border p-2 align-top text-muted-foreground\"\n >\n <ReviewValue value={note || labels.empty} labels={labels} />\n </td>\n )\n })}\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </ModalScaffold.Body>\n </ModalScaffold>\n )\n}\n\n/*\n * Widths sit on a block inside each cell: an auto-layout table ignores `max-width` on a cell, so a\n * long file name or answer would otherwise widen its column, or (without wrapping) spill into the\n * next one. The grid scrolls sideways when the columns do not fit.\n */\nconst DOCUMENT_WIDTH = 'w-40 sm:w-56'\nconst VALUE_WIDTH = 'min-w-48 max-w-80'\n\n/** The row's document: its name wraps over two lines at most, the full name on hover. */\nfunction DocumentName({ onClick, children }: { onClick?: () => void; children: string }) {\n const className = `${DOCUMENT_WIDTH} line-clamp-2 break-words text-left font-medium`\n return onClick ? (\n <button\n type=\"button\"\n onClick={onClick}\n title={children}\n className={`${className} text-primary hover:underline`}\n >\n {children}\n </button>\n ) : (\n <div title={children} className={className}>\n {children}\n </div>\n )\n}\n\n/** A review value: four lines, then a toggle to read the rest in place. */\nfunction ReviewValue({ value, labels }: { value: string; labels: WorkflowRunnerDialogLabels }) {\n const ref = useRef<HTMLDivElement>(null)\n const [expanded, setExpanded] = useState(false)\n const [clamped, setClamped] = useState(false)\n useLayoutEffect(() => {\n const el = ref.current\n if (el && !expanded) setClamped(el.scrollHeight > el.clientHeight + 1)\n }, [value, expanded])\n return (\n <div className={VALUE_WIDTH}>\n <div\n ref={ref}\n title={clamped && !expanded ? value : undefined}\n className={`whitespace-pre-line break-words ${expanded ? '' : 'line-clamp-4'}`}\n >\n {value}\n </div>\n {(clamped || expanded) && (\n <button\n type=\"button\"\n onClick={() => setExpanded((e) => !e)}\n className=\"mt-1 text-xs font-medium text-primary hover:underline\"\n >\n {expanded ? labels.showLess : labels.showMore}\n </button>\n )}\n </div>\n )\n}\n","/**\n * A stepped workflow run in its work thread, end to end: `useWorkflowThread` keeps the run on the\n * server (the thread's plan, its activity, its turns) and `WorkflowRunner` shows it. Agent answers\n * are the thread's messages; uploads go into the open workspace; a review can notify the people\n * who should approve it, in the run's thread. The host keeps its wording, its commits\n * (`options.commit`) and its finish screen.\n *\n * The labels a workflow needs (`requiredLabels`, a tabular review's columns) are found or created\n * in the run's workspace before its thread is created, named on every request.\n *\n * `layout=\"page\"` is the run as a page of its own: the workflow's header, where it runs (a\n * project, chosen with `ProjectPicker variant=\"run\"` or made by one of its steps, else the open\n * workspace), that workspace opened and its labels set up, then the run: the thread with the\n * steps' chevron bar on top (`ConnectedThreadTaskBar variant=\"steps\"`) and the current step beside\n * it. Opening another workspace meanwhile never moves the run: the page says so and offers the\n * run's workspace back.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n AiAnswer,\n useArbi,\n useArbiSessionStore,\n useDocuments,\n useWorkspaceUsers,\n} from '@arbidocs/react'\nimport { Button, cn } from '@arbidocs/react/ui'\nimport { ExternalLink, Loader2, MessageSquare } from 'lucide-react'\nimport {\n WorkflowRunner,\n type WorkflowRunnerFile,\n type WorkflowRunnerProps,\n} from '../agents/workflows/WorkflowRunner'\nimport type { WorkflowRunnerActions } from '../agents/workflows/StepParts'\nimport { WorkflowStepBar } from '../agents/workflows/WorkflowStepBar'\nimport { splitDocRef, stepLevels } from '../agents/workflows/run'\nimport { stepKindOf } from '../agents/workflows/stepKinds'\nimport { stepDocuments } from '../agents/workflows/StepDocuments'\nimport type {\n WorkflowAgentStep,\n WorkflowDefinition,\n WorkflowInputs,\n WorkflowStepState,\n WorkflowUploadStep,\n} from '../agents/workflows/types'\nimport { requiredLabelsOf, withLabelIds } from '../agents/workflows/requiredLabels'\nimport { PageHeader, type PageHeaderProps } from '../components/PageHeader'\nimport { ConnectedThreadTaskBar } from './tasks/ConnectedThreadTaskBar'\nimport type { ProjectSummary } from './projects/useProjectSummaries'\nimport { useEnsureRequiredLabels, useRequiredLabels } from './workflows/useRequiredLabels'\nimport {\n DEFAULT_WORKFLOW_RUN_PAGE_LABELS,\n WorkflowRunPreparing,\n WorkflowRunProjectChooser,\n WorkflowRunTargetLine,\n WorkflowRunWorkspaceChangedError,\n WorkflowRunWorkspaceNotice,\n useWorkflowRunTarget,\n type WorkflowRunPageLabels,\n type WorkflowRunTarget,\n type WorkflowRunTargetOptions,\n} from './workflows/WorkflowRunPage'\nimport { useConnectedWorkspace } from './ConnectionProvider'\nimport { useDocumentFilter } from './workspaceData'\nimport { useWorkflowThread, type UseWorkflowThreadOptions } from './useWorkflowThread'\nimport { WorkflowRunThread } from './WorkflowRunThread'\nimport type { ChatCitationTarget } from '../chat/chat-page-types'\nimport { useBlocksEnvironment } from '../provider/environment'\nimport { useOpenCitation } from '../chat/useOpenCitation'\nimport {\n DEFAULT_WORKFLOW_RUNNER_DIALOG_LABELS,\n WorkflowReviewGridDialog,\n WorkflowSignDialog,\n WorkflowWordDialog,\n type WorkflowRunnerDialogLabels,\n} from './WorkflowRunnerDialogs'\n\nexport interface ConnectedWorkflowRunnerLabels {\n notify: string\n /** An agent step's answer, in the thread layout: a link to it in the thread. */\n showInThread: string\n /** The thread layout's panel toggle, when the panel folds (a narrow container). */\n currentStep: string\n /** A finished step whose answer is still being fetched. */\n loadingAnswer: string\n notified: string\n openThread: string\n}\n\nexport const DEFAULT_CONNECTED_WORKFLOW_RUNNER_LABELS: ConnectedWorkflowRunnerLabels = {\n notify: 'Ask to approve',\n showInThread: 'Show in the thread',\n currentStep: 'Current step',\n notified: 'Notified.',\n openThread: 'Open the thread',\n loadingAnswer: 'Fetching the answer…',\n}\n\nexport interface ConnectedWorkflowRunnerProps extends Omit<\n WorkflowRunnerProps,\n | 'run'\n | 'renderAgentOutput'\n | 'onUpload'\n | 'uploading'\n | 'files'\n | 'onRetryUpload'\n | 'onRemoveUpload'\n | 'renderReview'\n | 'actions'\n | 'nameOfDoc'\n | 'compact'\n | 'hideStepBar'\n> {\n workflow: WorkflowDefinition\n /** The run's bindings: an existing thread, commits, prompt wording, workflow lookup. */\n options?: UseWorkflowThreadOptions\n /** Open a conversation (the run's thread): the host navigates. */\n onOpenConversation?: (conversationId: string) => void\n /** The muted line an agent step shows before its answer. */\n emptyHint?: (step: WorkflowAgentStep) => string | undefined\n connectedLabels?: Partial<ConnectedWorkflowRunnerLabels>\n /**\n * Open a document (a version: `version`; at a page: `page`, from a citation). Default: the\n * environment's `openDocument`. In the thread layout a citation opens its document with it too,\n * unless `onOpenCitation` is given.\n */\n onOpenDocument?: (documentId: string, version?: number, page?: number) => void\n /**\n * The thread layout's citation open action, as `ChatPage`'s `onOpenCitation` (the cited\n * document, page and passage). Absent: `onOpenDocument`, else the environment's `openDocument`\n * at the cited passage.\n */\n onOpenCitation?: (target: ChatCitationTarget) => void\n /** Open an email step's draft in native mail. Default: the environment's `openMail`; a host\n * without mail: no button. */\n onOpenDraft?: (draftId: string) => void\n /** Show an answer in the run's thread. Absent: no link. */\n onOpenMessage?: (messageId: string) => void\n /**\n * Take over what the runner otherwise opens itself: the sign flow, the Word editor for a\n * tracked-changes version, a tabular review's grid.\n */\n actions?: Pick<WorkflowRunnerActions, 'sign' | 'openRedline' | 'openReview'>\n dialogLabels?: Partial<WorkflowRunnerDialogLabels>\n /**\n * `thread` (default): once the run has its thread, the page is that thread, live (follow-ups,\n * answers with their sources, documents), with the step bar on top and the current step in a\n * compact panel beside it; steps' answers link to their message instead of being repeated.\n * Before the thread exists (the first form), it is the stepper: one step at a time.\n * `page`: the run as a page of its own (its header, where it runs, its set-up, then `thread`'s\n * arrangement with the thread's step bar), with the page and project options below.\n */\n layout?: 'thread' | 'page'\n /**\n * `page`: where the run's project comes from (`pick`: chosen on the page; `{ step, project }`:\n * made by that form step from its inputs). Absent: no project, the run works in `workspaceId`,\n * else the open workspace.\n */\n projectFrom?: WorkflowRunTargetOptions['projectFrom']\n /** `page`: the project, when the host keeps it (e.g. in its address). Absent: kept here. */\n projectId?: string | null\n /** `page`: a project was chosen or made. */\n onProjectChange?: (projectId: string) => void\n /** `page`: a new run's prefills from its project (a client's name, a reference…). */\n inputsFromProject?: (project: ProjectSummary) => WorkflowInputs\n /** `page`: a project made on the page or by the run's step; may return inputs for the run. */\n onProjectCreated?: WorkflowRunTargetOptions['onProjectCreated']\n /** `page`, without a project: the workspace the run works in. Absent: the open one. */\n workspaceId?: string\n /** `page`: the header's eyebrow, leading (a back button), description and extra actions. */\n pageHeader?: Partial<Omit<PageHeaderProps, 'tabs' | 'testId'>>\n pageLabels?: Partial<WorkflowRunPageLabels>\n}\n\n/** What the page layout hands the run once it can start. */\ninterface RunnerPageContext {\n target: WorkflowRunTarget\n labelIds: Record<string, string>\n /** The page's label set-up: the run's start reuses what it already did. */\n ensureLabels: ReturnType<typeof useEnsureRequiredLabels>\n labels: WorkflowRunPageLabels\n}\n\n/** A workspace document, as an upload step lists it. */\nexport type WorkflowRunnerDocument = NonNullable<ReturnType<typeof useDocuments>['data']>[number]\n\n/** What the runner has open itself. */\ntype OpenDialog =\n | { kind: 'sign'; docRef: string }\n | { kind: 'word'; docRef: string; title: string }\n | { kind: 'review'; tags: string[]; documents: string[] }\n\nexport function ConnectedWorkflowRunner(props: ConnectedWorkflowRunnerProps) {\n return props.layout === 'page' ? <RunnerPage {...props} /> : <RunnerBody {...props} />\n}\n\nfunction RunnerBody({\n workflow: given,\n options,\n onOpenConversation,\n emptyHint,\n connectedLabels,\n onOpenDocument: hostOpenDocument,\n onOpenCitation,\n onOpenDraft: hostOpenDraft,\n onOpenMessage,\n actions: hostActions,\n dialogLabels,\n testIdPrefix = 'workflow-run',\n page,\n // The page's options the run itself uses (the page layout takes the rest; `WorkflowRunner`\n // ignores them).\n projectFrom,\n inputsFromProject,\n ...runnerProps\n}: ConnectedWorkflowRunnerProps & { page?: RunnerPageContext }) {\n const l = { ...DEFAULT_CONNECTED_WORKFLOW_RUNNER_LABELS, ...connectedLabels }\n const environment = useBlocksEnvironment()\n const openInEnvironment = useCallback(\n (id: string, version?: number, page?: number) =>\n environment.openDocument(id, { ...(version && { version }), ...(page && { page }) }),\n [environment]\n )\n const onOpenDocument = hostOpenDocument ?? openInEnvironment\n const { openMail } = environment\n const draftInMail = useMemo(\n () => openMail && ((draftId: string) => openMail({ draftId })),\n [openMail]\n )\n const onOpenDraft = hostOpenDraft ?? draftInMail\n const citationInEnvironment = useOpenCitation()\n const dl = { ...DEFAULT_WORKFLOW_RUNNER_DIALOG_LABELS, ...dialogLabels }\n const arbi = useArbi()\n const { ensureWorkspaceOpen, userId, workspaceId } = useConnectedWorkspace()\n const wsId = workspaceId ?? undefined\n const session = useArbiSessionStore()\n const openRef = useRef(workspaceId)\n openRef.current = workspaceId\n\n // The labels the workflow needs, by key: set up by the page before the run, else as it starts.\n const required = requiredLabelsOf(given)\n const ownEnsureLabels = useEnsureRequiredLabels()\n const ensureLabels = page?.ensureLabels ?? ownEnsureLabels\n const [startedLabelIds, setStartedLabelIds] = useState<Record<string, string>>({})\n const pageLabelIds = page?.labelIds\n const labelIds = useMemo(\n () => ({ ...pageLabelIds, ...startedLabelIds }),\n [pageLabelIds, startedLabelIds]\n )\n // A project step (`projectFrom: { step }`) is one the page commits: it makes the project.\n const pageTarget = page?.target\n const projectStep = pageTarget && typeof projectFrom === 'object' ? projectFrom.step : undefined\n const workflow = useMemo(\n () => withCommitStep(withLabelIds(given, labelIds), projectStep),\n [given, labelIds, projectStep]\n )\n // As the run's thread is about to be created: its workspace (the page's, else the one open as it\n // starts) has its labels, and is still the one open, or the run does not start.\n const hostBeforeStart = options?.beforeStart\n const noWorkspace = page?.labels.noWorkspace\n const beforeStart = useMemo(() => {\n if (!pageTarget && !required.length) return hostBeforeStart\n return async () => {\n const openNow = () => session.getState().workspaceId ?? openRef.current ?? undefined\n // The run's workspace as of the moment it starts, before anything is awaited.\n const ws = pageTarget ? pageTarget.targetRef.current : openNow()\n if (!ws) throw new Error(noWorkspace ?? DEFAULT_WORKFLOW_RUN_PAGE_LABELS.noWorkspace)\n const fromHost = await hostBeforeStart?.()\n const ids = { ...(await ensureLabels(required, ws)), ...fromHost?.labelIds }\n if (openNow() !== ws) throw new WorkflowRunWorkspaceChangedError(ws)\n pageTarget?.pin(ws)\n setStartedLabelIds(ids)\n return { labelIds: ids }\n }\n }, [hostBeforeStart, pageTarget, noWorkspace, required, ensureLabels, session])\n // The page's project step makes the project, then the host's own commit for it runs.\n const hostCommit = options?.commit\n const commit = useMemo(() => {\n if (!pageTarget || typeof projectFrom !== 'object') return hostCommit\n const step = projectFrom.step\n return {\n ...hostCommit,\n [step]: async (inputs: WorkflowInputs) => {\n const made = await pageTarget.makeProject(projectFrom.project(inputs), inputs)\n const merged = { ...inputs, ...made.inputs }\n const fromHost = await hostCommit?.[step]?.(merged)\n return { ...made.inputs, ...(fromHost ?? {}) }\n },\n }\n }, [hostCommit, pageTarget, projectFrom])\n // A new run on a project starts from what the project says.\n const project = pageTarget?.project\n const hostInitial = options?.initialInputs\n const initialInputs = useMemo(\n () =>\n project && inputsFromProject\n ? { ...inputsFromProject(project), ...hostInitial }\n : hostInitial,\n [project, inputsFromProject, hostInitial]\n )\n const { data: docs = [], refetch } = useDocuments(wsId)\n // An upload step lists the documents a person browses (the host's `documentFilter`).\n const documentFilter = useDocumentFilter()\n // The files being sent on the run's upload steps, and those that did not upload (until retried\n // or removed): the step waits for them.\n const [sending, setSending] = useState<PendingUpload[]>([])\n // The files added on each upload step in this run (doc id -> step id), and their names (listed\n // under them before the workspace's documents catch up).\n const [added, setAdded] = useState<Record<string, string>>({})\n const [addedNames, setAddedNames] = useState<Record<string, string>>({})\n const addedRef = useRef(added)\n addedRef.current = added\n const { view, conversationId, people } = useWorkflowThread(workflow, {\n ...options,\n commit,\n initialInputs,\n beforeStart,\n // An upload step records exactly the files added on it (else the server's guess).\n documentsFor:\n options?.documentsFor ??\n ((stepId) =>\n Object.entries(addedRef.current).flatMap(([doc, step]) => (step === stepId ? [doc] : []))),\n })\n const [dialog, setDialog] = useState<OpenDialog | null>(null)\n const inThread = !!conversationId\n // A run already under way stays in the workspace it is in.\n useEffect(() => {\n const ws = pageTarget?.targetRef.current\n if (conversationId && ws) pageTarget?.pin(ws)\n }, [conversationId, pageTarget])\n // The message the thread scrolls to (a step's answer, picked from the panel).\n const [target, setTarget] = useState<string | undefined>(undefined)\n const nameOfDoc = useCallback(\n (id: string) => docs.find((d) => d.external_id === id)?.file_name ?? undefined,\n [docs]\n )\n const actions = useMemo<WorkflowRunnerActions>(\n () => ({\n me: userId,\n openDocument:\n onOpenDocument &&\n ((ref) => {\n const { id, version } = splitDocRef(ref)\n onOpenDocument(id, version)\n }),\n openDraft: onOpenDraft && ((draftId) => onOpenDraft(draftId)),\n // In the thread layout an answer is right there: scroll to it.\n openMessage: inThread ? setTarget : onOpenMessage,\n sign:\n hostActions?.sign ??\n ((_step, state) => {\n const w = state.waiting\n if (w?.doc_ext_id) setDialog({ kind: 'sign', docRef: w.doc_ext_id })\n }),\n openRedline:\n hostActions?.openRedline ??\n ((ref) =>\n setDialog({ kind: 'word', docRef: ref, title: nameOfDoc(splitDocRef(ref).id) ?? '' })),\n openReview:\n hostActions?.openReview ??\n ((tags, documents) => setDialog({ kind: 'review', tags, documents })),\n }),\n [userId, onOpenDocument, onOpenDraft, onOpenMessage, hostActions, nameOfDoc, inThread]\n )\n\n // A citation in the thread opens its document as the regular chat does (the host's handler).\n const openCitation = useMemo<((target: ChatCitationTarget) => void) | undefined>(\n () =>\n onOpenCitation ??\n (hostOpenDocument\n ? (t) => {\n const docId = t.documentId ?? t.passage?.documentId\n if (docId) hostOpenDocument(docId, undefined, t.page ?? t.passage?.page ?? undefined)\n }\n : citationInEnvironment),\n [onOpenCitation, hostOpenDocument, citationInEnvironment]\n )\n\n const uploadSeq = useRef(0)\n const sendingRef = useRef(sending)\n sendingRef.current = sending\n // Send these files for a step, one after another; one that fails stays listed with its error.\n const send = useCallback(\n async (batch: PendingUpload[]) => {\n if (!batch.length) return\n const keys = new Set(batch.map((p) => p.key))\n const mark = (key: string, patch: Partial<PendingUpload> | null) =>\n setSending((all) =>\n patch === null\n ? all.filter((p) => p.key !== key)\n : all.map((p) => (p.key === key ? { ...p, ...patch } : p))\n )\n setSending((all) => [\n ...all.filter((p) => !keys.has(p.key)),\n ...batch.map((p) => ({ ...p, status: 'uploading' as const, error: undefined })),\n ])\n try {\n // The server resolves the target workspace from the session: make sure it is open.\n await ensureWorkspaceOpen()\n } catch (e) {\n for (const p of batch) mark(p.key, { status: 'failed', error: uploadError(e) })\n return\n }\n for (const p of batch) {\n try {\n const { doc_ext_ids = [] } = (await arbi.documents.uploadFile(p.file, p.file.name)) ?? {}\n if (!doc_ext_ids.length) throw new Error('No document came back')\n setAdded((a) => ({\n ...a,\n ...Object.fromEntries(doc_ext_ids.map((id) => [id, p.stepId])),\n }))\n setAddedNames((n) => ({\n ...n,\n ...Object.fromEntries(doc_ext_ids.map((id) => [id, p.file.name])),\n }))\n mark(p.key, null)\n } catch (e) {\n mark(p.key, { status: 'failed', error: uploadError(e) })\n }\n }\n await refetch()\n },\n [arbi, ensureWorkspaceOpen, refetch]\n )\n const onUpload = useCallback(\n (files: File[], step: WorkflowUploadStep) =>\n send(\n files.map((file) => ({\n key: `upload-${++uploadSeq.current}`,\n file,\n stepId: step.id,\n status: 'uploading' as const,\n }))\n ),\n [send]\n )\n const onRetryUpload = useCallback(\n (file: WorkflowRunnerFile) => {\n const p = sendingRef.current.find((x) => x.key === file.id)\n if (p) void send([p])\n },\n [send]\n )\n const onRemoveUpload = useCallback(\n (file: WorkflowRunnerFile) => setSending((all) => all.filter((p) => p.key !== file.id)),\n []\n )\n\n const files = [\n ...sending.map<WorkflowRunnerFile>((p) => ({\n id: p.key,\n name: p.file.name,\n status: p.status === 'failed' ? 'upload-failed' : 'uploading',\n error: p.error,\n addedFor: p.stepId,\n })),\n ...runnerFiles(docs, added, documentFilter, addedNames),\n ]\n // Watch the files just added until they are read (the step waits for them).\n const reading = files.some((f) => f.addedFor && f.status === 'processing')\n useEffect(() => {\n if (!reading) return\n const t = setInterval(() => void refetch(), READ_POLL_MS)\n return () => clearInterval(t)\n }, [reading, refetch])\n\n const renderAgentOutput = (step: WorkflowAgentStep, state: WorkflowStepState | undefined) => {\n const status = state?.status\n // Beside the thread an answer is not repeated: it links to its message.\n if (inThread) {\n const id = state?.responseId\n return id && status === 'done' ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setTarget(id)}\n data-testid={`${testIdPrefix}-${step.id}-show-in-thread`}\n >\n <MessageSquare className=\"size-4\" /> {l.showInThread}\n </Button>\n ) : null\n }\n if (!state?.text && status !== 'done') return null\n // Finished, its answer not read yet (the thread is fetched again until it is).\n if (!state?.text && state?.responseId) {\n return (\n <p\n className=\"flex items-center gap-2 text-sm text-muted-foreground\"\n data-testid={`${testIdPrefix}-${step.id}-answer-loading`}\n >\n <Loader2 className=\"size-4 animate-spin\" /> {l.loadingAnswer}\n </p>\n )\n }\n return (\n <AiAnswer\n status={status === 'running' ? 'running' : 'done'}\n text={state?.text ?? ''}\n emptyHint={emptyHint?.(step)}\n testId={`${testIdPrefix}-${step.id}-answer`}\n />\n )\n }\n\n const runner = (compact: boolean) => (\n <WorkflowRunner\n people={people}\n {...runnerProps}\n workflow={workflow}\n run={view}\n renderAgentOutput={renderAgentOutput}\n renderReview={(step) =>\n conversationId ? (\n <ReviewNotify\n conversationId={conversationId}\n workspaceId={wsId}\n labels={l}\n testId={`${testIdPrefix}-${step.id}`}\n />\n ) : null\n }\n onUpload={onUpload}\n uploading={sending.some((p) => p.status === 'uploading')}\n files={files}\n onRetryUpload={onRetryUpload}\n onRemoveUpload={onRemoveUpload}\n actions={actions}\n nameOfDoc={nameOfDoc}\n testIdPrefix={testIdPrefix}\n hideStepBar={compact}\n compact={compact}\n className={compact ? undefined : runnerProps.className}\n />\n )\n\n const openThread = conversationId && onOpenConversation && (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => onOpenConversation(conversationId)}\n data-testid={`${testIdPrefix}-open-thread`}\n >\n <ExternalLink className=\"size-4\" /> {l.openThread}\n </Button>\n )\n // The page: the thread's own step bar (what happened in each step, from the server), held to\n // the step the panel shows, with the way to the thread beside it.\n const pageBar = page && inThread && conversationId && (\n <div className=\"flex min-w-0 items-center gap-2\">\n <div className=\"min-w-0 flex-1\">\n <ConnectedThreadTaskBar\n variant=\"steps\"\n conversationId={conversationId}\n currentStepId={view.current}\n onSelectStep={view.goTo}\n renderIcon={runnerProps.renderIcon}\n />\n </div>\n {openThread}\n </div>\n )\n\n return (\n <div className={page ? 'flex min-h-0 flex-1 flex-col gap-3' : 'space-y-3'}>\n {openThread && !pageBar && <div className=\"flex justify-end\">{openThread}</div>}\n {pageBar}\n {inThread && conversationId ? (\n <>\n {!page && (\n <WorkflowStepBar\n run={view}\n levels={stepLevels(view.steps)}\n doneTitle={\n (workflow.run.kind === 'steps' ? workflow.run.completion?.title : undefined) ??\n runnerProps.labels?.complete ??\n 'Done'\n }\n icon={(key) =>\n key && runnerProps.renderIcon ? runnerProps.renderIcon(key) : undefined\n }\n tid={(suffix) => `${testIdPrefix}-${suffix}`}\n />\n )}\n <WorkflowRunThread\n className={page ? 'min-h-[480px] flex-1 rounded-xl border border-border' : undefined}\n conversationId={conversationId}\n workspaceId={wsId}\n stepOf={(id) => {\n const step = view.steps.find((s) => s.id === id)\n if (!step) return undefined\n // Its document, one click from its chip: the latest version, in the host's viewer\n // (else the Word dialog).\n const states = Object.fromEntries(\n view.steps.flatMap((s) => {\n const state = view.stateOf(s.id)\n return state ? [[s.id, state]] : []\n })\n )\n const ref = stepDocuments(view.steps, states, id).at(-1)\n const open = actions.openDocument ?? actions.openRedline\n return {\n title: step.title,\n kind: stepKindOf(step),\n phase: view.phaseOf(id),\n document:\n ref && open\n ? { name: nameOfDoc(splitDocRef(ref).id) ?? ref, onOpen: () => open(ref) }\n : undefined,\n }\n }}\n targetMessageId={target}\n onOpenCitation={openCitation}\n labels={{ workflows: l.currentStep }}\n aside={runner(true)}\n />\n </>\n ) : (\n runner(false)\n )}\n {dialog?.kind === 'sign' && (\n <WorkflowSignDialog docRef={dialog.docRef} onClose={() => setDialog(null)} labels={dl} />\n )}\n {dialog?.kind === 'word' && (\n <WorkflowWordDialog\n docRef={dialog.docRef}\n title={dialog.title || undefined}\n onClose={() => setDialog(null)}\n labels={dl}\n />\n )}\n {dialog?.kind === 'review' && (\n <WorkflowReviewGridDialog\n tags={dialog.tags}\n documents={dialog.documents}\n onClose={() => setDialog(null)}\n onOpenDocument={onOpenDocument && ((id) => onOpenDocument(id))}\n labels={dl}\n />\n )}\n </div>\n )\n}\n\n/**\n * The run as a page: the workflow's header and where it runs, then what has to happen before the\n * run can start (a project chosen, its workspace opened, the labels set up), then the run. Once\n * the run is on screen it stays mounted (what was typed is kept) and only greys out while another\n * workspace is open.\n */\nfunction RunnerPage(props: ConnectedWorkflowRunnerProps) {\n const {\n workflow,\n projectFrom,\n projectId,\n onProjectChange,\n onProjectCreated,\n workspaceId,\n pageHeader,\n pageLabels,\n testIdPrefix = 'workflow-run',\n } = props\n const l = { ...DEFAULT_WORKFLOW_RUN_PAGE_LABELS, ...pageLabels }\n const { openProject } = useBlocksEnvironment()\n const target = useWorkflowRunTarget({\n projectFrom,\n projectId,\n onProjectChange,\n workspaceId,\n onProjectCreated,\n })\n const required = requiredLabelsOf(workflow)\n const ensure = useEnsureRequiredLabels()\n const labels = useRequiredLabels(required, target.target, ensure, target.stage === 'ready')\n const fromStep = typeof projectFrom === 'object'\n // A project step runs before there is a workspace: its labels are set up as the run starts.\n const labelsReady = !required.length || labels.status === 'ready' || (fromStep && !target.target)\n const [shown, setShown] = useState(false)\n if (!shown && target.stage === 'ready' && labelsReady) setShown(true)\n const workspaceName = target.targetName ?? l.thisWorkspace\n const tid = (suffix: string) => `${testIdPrefix}-${suffix}`\n const blocked = target.stage === 'switch' || target.stage === 'opening'\n\n return (\n <div\n className=\"flex h-full min-h-0 w-full flex-col gap-4 overflow-auto p-4 sm:p-6\"\n data-testid={tid('page')}\n >\n <PageHeader\n {...pageHeader}\n title={pageHeader?.title ?? workflow.title}\n description={pageHeader?.description ?? (workflow.details || workflow.description)}\n testId={tid('page-header')}\n />\n <WorkflowRunTargetLine\n project={target.project}\n workspaceName={target.targetName}\n fromStep={fromStep && !target.projectId}\n onOpenProject={projectFrom ? openProject : undefined}\n labels={l}\n testId={testIdPrefix}\n />\n {target.stage === 'pick' && (\n <WorkflowRunProjectChooser\n projects={target.projects}\n loading={target.projectsLoading}\n onPick={target.pick}\n onCreate={(name) => target.makeProject({ name })}\n creating={target.creating}\n labels={l}\n testId={testIdPrefix}\n />\n )}\n {target.stage === 'switch' && (\n <WorkflowRunWorkspaceNotice\n workspaceName={workspaceName}\n onOpen={target.openTarget}\n labels={l}\n testId={testIdPrefix}\n />\n )}\n {!shown && (target.stage === 'loading' || target.stage === 'opening') && (\n <WorkflowRunPreparing\n stage={target.stage}\n workspaceName={workspaceName}\n labels={required}\n l={l}\n testId={testIdPrefix}\n />\n )}\n {!shown && target.stage === 'ready' && !labelsReady && (\n <WorkflowRunPreparing\n stage=\"labels\"\n workspaceName={workspaceName}\n labels={required}\n failed={labels.status === 'failed'}\n error={labels.error}\n onRetry={labels.retry}\n l={l}\n testId={testIdPrefix}\n />\n )}\n {shown && (\n <div\n className={cn(\n 'flex min-h-0 flex-1 flex-col',\n blocked && 'pointer-events-none select-none opacity-50'\n )}\n aria-disabled={blocked || undefined}\n data-testid={tid('page-run')}\n >\n <RunnerBody\n {...props}\n // A run on another project is another run.\n key={target.projectId ?? 'run'}\n page={{ target, labelIds: labels.ids, ensureLabels: ensure, labels: l }}\n />\n </div>\n )}\n </div>\n )\n}\n\n/** The workflow with step `stepId` committed by the host (it makes the run's project). */\nfunction withCommitStep(\n workflow: WorkflowDefinition,\n stepId: string | undefined\n): WorkflowDefinition {\n if (!stepId || workflow.run.kind !== 'steps') return workflow\n return {\n ...workflow,\n run: {\n ...workflow.run,\n steps: workflow.run.steps.map((s) => (s.id === stepId ? { ...s, commit: true } : s)),\n },\n }\n}\n\nconst READ_POLL_MS = 3000\n\n/** A file being sent on an upload step, or one that did not upload (`error`). */\ninterface PendingUpload {\n key: string\n file: File\n stepId: string\n status: 'uploading' | 'failed'\n error?: string\n}\n\nfunction uploadError(e: unknown): string {\n return e instanceof Error && e.message ? e.message : String(e || 'Upload failed')\n}\n\n/**\n * The upload step's files: the workspace's documents the host's `documentFilter` keeps, plus every\n * file added on one of the run's upload steps (`added`: doc id -> step id), which the step waits on.\n * A file added that the workspace does not list yet is shown as being read (`names` gives its name).\n */\nexport function runnerFiles(\n docs: WorkflowRunnerDocument[],\n added: Record<string, string>,\n fileFilter?: (doc: WorkflowRunnerDocument) => boolean,\n names: Record<string, string> = {}\n): WorkflowRunnerFile[] {\n const listed = new Set(docs.map((d) => d.external_id))\n return [\n ...docs\n .filter((d) => !fileFilter || added[d.external_id] || fileFilter(d))\n .map((d) => ({\n id: d.external_id,\n name: d.file_name ?? d.external_id,\n status: fileStatus(d.status),\n addedFor: added[d.external_id],\n })),\n ...Object.entries(added)\n .filter(([id]) => !listed.has(id))\n .map(([id, stepId]) => ({\n id,\n name: names[id] ?? id,\n status: 'processing' as const,\n addedFor: stepId,\n })),\n ]\n}\n\n/** A document's processing status as the upload step shows it; unknown stays unknown. */\nexport function fileStatus(status: string | null | undefined): WorkflowRunnerFile['status'] {\n const s = status?.toLowerCase()\n if (!s) return undefined\n if (s === 'failed') return 'failed'\n if (s === 'completed' || s === 'empty' || s === 'low-content') return 'ready'\n return 'processing'\n}\n\n/** Who should approve: the workspace's people (not agents), notified about the run's thread. */\nfunction ReviewNotify({\n conversationId,\n workspaceId,\n labels,\n testId,\n}: {\n conversationId: string\n workspaceId: string | undefined\n labels: ConnectedWorkflowRunnerLabels\n testId: string\n}) {\n const arbi = useArbi()\n const { live, userId, ensureWorkspaceOpen } = useConnectedWorkspace()\n const { data: members = [] } = useWorkspaceUsers(workspaceId, {\n enabled: live && !!workspaceId,\n beforeFetch: ensureWorkspaceOpen,\n })\n const people = members.filter(\n (m) =>\n !m.agent_ext_id && !m.user.external_id.startsWith('agt-') && m.user.external_id !== userId\n )\n const [picked, setPicked] = useState<string[]>([])\n const [sent, setSent] = useState(false)\n const [busy, setBusy] = useState(false)\n if (people.length === 0) return null\n const toggle = (id: string) =>\n setPicked((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]))\n\n return (\n <div className=\"space-y-3\" data-testid={`${testId}-notify`}>\n <div className=\"flex flex-wrap gap-1.5\">\n {people.map((m) => {\n const name =\n [m.user.given_name, m.user.family_name].filter(Boolean).join(' ') || m.user.email\n const on = picked.includes(m.user.external_id)\n return (\n <button\n key={m.user.external_id}\n type=\"button\"\n onClick={() => toggle(m.user.external_id)}\n aria-pressed={on}\n className={cn(\n 'rounded-full border px-2.5 py-1 text-xs',\n on\n ? 'border-primary bg-primary/10 text-primary'\n : 'border-border text-muted-foreground'\n )}\n data-testid={`${testId}-person-${m.user.external_id}`}\n >\n {name}\n </button>\n )\n })}\n </div>\n <div className=\"flex items-center gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!picked.length || busy}\n onClick={async () => {\n setBusy(true)\n try {\n await arbi.conversations.notify(conversationId, picked)\n setSent(true)\n } finally {\n setBusy(false)\n }\n }}\n data-testid={`${testId}-notify-send`}\n >\n {labels.notify}\n </Button>\n {sent && <span className=\"text-xs text-muted-foreground\">{labels.notified}</span>}\n </div>\n </div>\n )\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport { useWorkflows, type WorkflowResponse } from '@arbidocs/react'\n\n/** A saved workflow, a new one, or a host catalogue entry opened as a template. */\nexport type WorkflowBuilderSelection =\n { kind: 'saved'; id: string } | { kind: 'new' } | { kind: 'template'; id: string }\n\nexport interface WorkflowsPageStateOptions {\n initialBuilder?: WorkflowBuilderSelection\n /** A host deep link to consume once the saved workflow has loaded. */\n historyWorkflowId?: string | null\n onHistoryWorkflowConsumed?: () => void\n}\n\n/** Shared selection lifecycle for workflow tables, builders and history views. No routing or layout. */\nexport function useWorkflowsPageState({\n initialBuilder,\n historyWorkflowId,\n onHistoryWorkflowConsumed,\n}: WorkflowsPageStateOptions = {}) {\n const { data: workflows = [] } = useWorkflows({ live: true })\n const [builder, setBuilder] = useState<WorkflowBuilderSelection | null>(initialBuilder ?? null)\n const [builderKey, setBuilderKey] = useState(0)\n const [historyIds, setHistoryIds] = useState<string[]>([])\n const [activeHistoryId, setActiveHistoryId] = useState<string | null>(null)\n // Resolve against current query data: renaming/deleting a workflow cannot leave a stale dialog.\n const historyFor = workflows.find((workflow) => workflow.external_id === activeHistoryId) ?? null\n const historyTabs = historyIds.flatMap((id) => {\n const workflow = workflows.find((item) => item.external_id === id)\n return workflow ? [workflow] : []\n })\n\n const openHistory = useCallback((workflow: WorkflowResponse | null) => {\n const id = workflow?.external_id ?? null\n if (id) setHistoryIds((ids) => (ids.includes(id) ? ids : [...ids, id]))\n setActiveHistoryId(id)\n }, [])\n const closeHistoryTab = useCallback((id: string) => {\n setHistoryIds((ids) => ids.filter((item) => item !== id))\n setActiveHistoryId((active) => (active === id ? null : active))\n }, [])\n const builderKeyRef = useRef(builderKey)\n builderKeyRef.current = builderKey\n const openBuilder = useCallback((selection: WorkflowBuilderSelection) => {\n setBuilder(selection)\n // Reopening a template/new/saved selection resets its unsaved canvas; saving does not.\n setBuilderKey((key) => key + 1)\n }, [])\n /**\n * A save finished (it lands once the workflows are re-read): the builder it came from (its\n * `builderKey`, default the current one) now edits the saved workflow. A save the person left\n * meanwhile (Back, or another workflow opened) changes nothing: it never reopens the builder.\n */\n const builderSaved = useCallback((id: string, fromKey?: number) => {\n if (fromKey !== undefined && fromKey !== builderKeyRef.current) return\n setBuilder((open) => (open ? { kind: 'saved', id } : null))\n }, [])\n\n useEffect(() => {\n const workflow = workflows.find((item) => item.external_id === historyWorkflowId)\n if (!workflow) return\n openHistory(workflow)\n onHistoryWorkflowConsumed?.()\n }, [historyWorkflowId, onHistoryWorkflowConsumed, openHistory, workflows])\n\n return {\n workflows,\n builder,\n builderKey,\n openBuilder,\n closeBuilder: () => setBuilder(null),\n builderSaved,\n historyFor,\n historyTabs,\n activeHistoryId,\n openHistory,\n closeHistoryTab,\n selectHistoryTab: setActiveHistoryId,\n }\n}\n"]}
|