@runfusion/fusion 0.77.0-beta.0 → 0.77.0-beta.2
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/dist/bin.js +387 -72
- package/dist/child-process-worker.js +2479 -2196
- package/dist/client/.vite/manifest.json +262 -262
- package/dist/client/assets/{AgentDetailView-0G9qFd4j.js → AgentDetailView-Dew3af1O.js} +1 -1
- package/dist/client/assets/{AgentPermissionPolicyEditor-BM68g7wo.js → AgentPermissionPolicyEditor-CxPQffiY.js} +1 -1
- package/dist/client/assets/{AgentsView-DkOUZWw4.js → AgentsView-Cr4LDGdt.js} +3 -3
- package/dist/client/assets/ChatView-cNYtYx05.js +13 -0
- package/dist/client/assets/{CommandCenter-DxRSFWNc.js → CommandCenter-DCC90LOP.js} +1 -1
- package/dist/client/assets/{DevServerView-DO-bqJFE.js → DevServerView-B5b520w6.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-Cp2gddTE.js → DirectoryPicker-1JvRd5mC.js} +1 -1
- package/dist/client/assets/{DocumentsView-D0E-3G96.js → DocumentsView-ksK9f7xt.js} +1 -1
- package/dist/client/assets/{EvalsView-BoFVq5hw.js → EvalsView-a3LhgRSo.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-CS1Sdogm.js → ExperimentalAgentOnboardingModal-vdVa8h7F.js} +1 -1
- package/dist/client/assets/{GoalsView-sybf7JY4.js → GoalsView-Dz2o91fd.js} +1 -1
- package/dist/client/assets/{InsightsView-nHa7aShn.js → InsightsView-De3R_46d.js} +1 -1
- package/dist/client/assets/{MemoryView-D0IG44za.js → MemoryView-Cagk2wZG.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-CU76weJe.js → PiExtensionsManager-C9JABO_4.js} +1 -1
- package/dist/client/assets/{PluginManager-DyT8XbcG.js → PluginManager-D2csmdQa.js} +1 -1
- package/dist/client/assets/{PullRequestView-CnxWUSen.js → PullRequestView-DT8vTeVi.js} +1 -1
- package/dist/client/assets/{ReportModal-CMrmMQjD.js → ReportModal-YMP6V4vu.js} +1 -1
- package/dist/client/assets/{ResearchView-BTytQSgy.js → ResearchView-cNsjYu8F.js} +1 -1
- package/dist/client/assets/{SecretsView-BuSH5J87.js → SecretsView-BAmf7KyS.js} +1 -1
- package/dist/client/assets/{SessionTerminal-D04kYRrT.js → SessionTerminal-BjGcxq22.js} +1 -1
- package/dist/client/assets/{SettingsModal-Dm-ngbRr.js → SettingsModal-C_9RiEI7.js} +1 -1
- package/dist/client/assets/{SettingsModal-xSLhH7Tr.js → SettingsModal-DLfy2e_5.js} +4 -4
- package/dist/client/assets/{SettingsTextareaRow-CHPgocEp.js → SettingsTextareaRow-D8RHSj8b.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-y88aXNIQ.js → SetupWizardModal-DRJ96pHQ.js} +2 -2
- package/dist/client/assets/{SkillsView-CYyQW1Hv.js → SkillsView-DyeCwYit.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-hYeoz1X8.js → WorkflowNodeEditor-C5Jc9w_A.js} +3 -3
- package/dist/client/assets/{agent-import-generation-CjiYXzCr.js → agent-import-generation-SCPNeF25.js} +1 -1
- package/dist/client/assets/{agentsOrgChartLayout-C0UP_X3z.js → agentsOrgChartLayout-CqKtNCjy.js} +1 -1
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-Dd6GPcqM.js → architectureDiagram-3BPJPVTR-Cz2HYn0b.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-CC6pLxlz.js → blockDiagram-GPEHLZMM-IimJVscG.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-DxMP_l6y.js → c4Diagram-AAUBKEIU-C-xii7zn.js} +1 -1
- package/dist/client/assets/channel-D-UHgx8G.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-BKYToL43.js → chunk-2J33WTMH-DQ-9Xccu.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-Bg6rjQb3.js → chunk-4BX2VUAB-DmdAX9Bx.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-CPUwbbGa.js → chunk-55IACEB6-IF2bk5IL.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-DScQBCvv.js → chunk-727SXJPM-AeYpIzVu.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-DbX7uaXK.js → chunk-AQP2D5EJ-DV942DD9.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-DvYKea1c.js → chunk-FMBD7UC4-Bt_riVlZ.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-CH-Tvw7w.js → chunk-ND2GUHAM-CbyjNbXR.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-CbyEvOoM.js → chunk-QZHKN3VN-DqiRniYQ.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-Do-8MdAc.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Do-8MdAc.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-BPB5fV3A.js → cose-bilkent-S5V4N54A-UCvthviL.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-CilYJ3rR.js → dagre-BM42HDAG-DnMlT1Oi.js} +1 -1
- package/dist/client/assets/{dashboard-view-dChSM_So.js → dashboard-view-C9D0aoRW.js} +1 -1
- package/dist/client/assets/dashboard-view-Cz0sp2Wl.js +1 -0
- package/dist/client/assets/{dashboard-view-DoLU6FxZ.js → dashboard-view-JysoyDRX.js} +1 -1
- package/dist/client/assets/{dashboard-view-DnVf3tmI.js → dashboard-view-myjM9tr8.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-m9u1Qhyx.js → diagram-2AECGRRQ-BYFiqXGw.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-DVr7Kf0N.js → diagram-5GNKFQAL-DZU3pSYq.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-D7sgJDFx.js → diagram-KO2AKTUF-0ybdKuMm.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-DNKNDS6r.js → diagram-LMA3HP47-Rxbgnbsp.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-1Bff4FWn.js → diagram-OG6HWLK6-BAU_hTeV.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-DGua1UHN.js → erDiagram-TEJ5UH35-zr8HrwTt.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-UDfDtwsE.js → flowDiagram-I6XJVG4X-CrTw0iFw.js} +1 -1
- package/dist/client/assets/{folder-open-CteOypVk.js → folder-open-DnAlsXXn.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-COdmD328.js → ganttDiagram-6RSMTGT7-CCORsxxz.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-SUSls7Kw.js → gitGraphDiagram-PVQCEYII-C07wWSjj.js} +1 -1
- package/dist/client/assets/index-B_z7OKl4.js +2818 -0
- package/dist/client/assets/index-DPo-IAb2.css +1 -0
- package/dist/client/assets/{infoDiagram-5YYISTIA-e_DloXj7.js → infoDiagram-5YYISTIA-hAeccD_4.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-DVWqihXg.js → ishikawaDiagram-YF4QCWOH-WLCzv-NH.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-BcPY-XP0.js → journeyDiagram-JHISSGLW-ClnasNhy.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-BCFG2Jle.js → kanban-definition-UN3LZRKU-CAuARhUz.js} +1 -1
- package/dist/client/assets/{mermaid.core-5yPje9Bi.js → mermaid.core-Bh02RvfX.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-DDApeT3K.js → mindmap-definition-RKZ34NQL-KNTlbW4V.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-N61_jyeP.js → pieDiagram-4H26LBE5-BouAfBEw.js} +1 -1
- package/dist/client/assets/{puzzle-BkaCP30D.js → puzzle-CC8Ur3Cy.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-C5qHiApF.js → quadrantDiagram-W4KKPZXB-wTdkCUJU.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-C71okgzt.js → requirementDiagram-4Y6WPE33-BnjY4Tc_.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-B2iKyLjB.js → sankeyDiagram-5OEKKPKP-C-QsS08u.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-DfdoYKKk.js → sequenceDiagram-3UESZ5HK-DD36MILE.js} +1 -1
- package/dist/client/assets/{shield-alert-BNSeDB8l.js → shield-alert-DcXc56Fy.js} +1 -1
- package/dist/client/assets/{standing-instructions-template-pZtzo1lK.js → standing-instructions-template-BF5y1BLz.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-lS-sUi12.js → stateDiagram-AJRCARHV-WTq1wQr1.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-DXJNDrV9.js → stateDiagram-v2-BHNVJYJU-eILJdjII.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-CCwvX81K.js → timeline-definition-PNZ67QCA-PRNwI0NR.js} +1 -1
- package/dist/client/assets/{upload-CDovVbu2.js → upload-qH_64O-B.js} +1 -1
- package/dist/client/assets/{useDiscoveredSkillsCache-BYqP-afh.js → useDiscoveredSkillsCache-C-GPCNaO.js} +1 -1
- package/dist/client/assets/{users-CTqECGLo.js → users-D2UesRE4.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-DaiR5nv9.js → vennDiagram-CIIHVFJN-CG2Z4T4O.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-hA5IHyPW.js → wardley-L42UT6IY-gO_fGvF9.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-CILUNESc.js → wardleyDiagram-YWT4CUSO-BkyNpjUb.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-72eNMmjz.js → xychartDiagram-2RQKCTM6-CMlZsiPq.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +345 -61
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugin-sdk/index.js +29 -2
- package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +269 -16
- package/dist/plugins/fusion-plugin-acp-runtime/mcp-schema-server.cjs +171 -0
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-linear-import/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
- package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-quality/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-quality/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-todos/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-todos/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +29 -2
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/dist/client/assets/ChatView-BPSm2JIH.js +0 -13
- package/dist/client/assets/channel-DlCEMoEf.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-Bc92O8Ks.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Bc92O8Ks.js +0 -1
- package/dist/client/assets/dashboard-view-BnGe8cWo.js +0 -1
- package/dist/client/assets/index-0ovTXt3t.css +0 -1
- package/dist/client/assets/index-DpCHwyiD.js +0 -2818
|
@@ -16225,6 +16225,7 @@ function applyPromptOverridesToIr(ir, overrides) {
|
|
|
16225
16225
|
function defaultCodingWorkflowIr() {
|
|
16226
16226
|
return resolveDefaultWorkflowIr();
|
|
16227
16227
|
}
|
|
16228
|
+
var inflightSelectionReads = /* @__PURE__ */ new WeakMap();
|
|
16228
16229
|
async function resolveWorkflowIrById(store, workflowId, irCache) {
|
|
16229
16230
|
let projectId;
|
|
16230
16231
|
try {
|
|
@@ -16268,8 +16269,34 @@ function didFallBackToDefault(ir) {
|
|
|
16268
16269
|
async function resolveWorkflowIrForTaskWithProvenance(store, taskId, irCache, selectionCache) {
|
|
16269
16270
|
let workflowId;
|
|
16270
16271
|
try {
|
|
16271
|
-
const
|
|
16272
|
-
|
|
16272
|
+
const isSelectionCached = selectionCache?.has(taskId) ?? false;
|
|
16273
|
+
let selection = isSelectionCached && selectionCache ? selectionCache.get(taskId) : void 0;
|
|
16274
|
+
if (!isSelectionCached) {
|
|
16275
|
+
let inflight;
|
|
16276
|
+
let coalesced = false;
|
|
16277
|
+
if (selectionCache) {
|
|
16278
|
+
inflight = inflightSelectionReads.get(selectionCache);
|
|
16279
|
+
if (!inflight) {
|
|
16280
|
+
inflight = /* @__PURE__ */ new Map();
|
|
16281
|
+
inflightSelectionReads.set(selectionCache, inflight);
|
|
16282
|
+
}
|
|
16283
|
+
const pending = inflight.get(taskId);
|
|
16284
|
+
if (pending) {
|
|
16285
|
+
selection = await pending;
|
|
16286
|
+
coalesced = true;
|
|
16287
|
+
}
|
|
16288
|
+
}
|
|
16289
|
+
if (!coalesced) {
|
|
16290
|
+
const readPromise = store.getTaskWorkflowSelectionAsync ? store.getTaskWorkflowSelectionAsync(taskId) : Promise.resolve(store.getTaskWorkflowSelection(taskId));
|
|
16291
|
+
if (inflight) inflight.set(taskId, readPromise);
|
|
16292
|
+
try {
|
|
16293
|
+
selection = await readPromise;
|
|
16294
|
+
} finally {
|
|
16295
|
+
inflight?.delete(taskId);
|
|
16296
|
+
}
|
|
16297
|
+
}
|
|
16298
|
+
selectionCache?.set(taskId, selection);
|
|
16299
|
+
}
|
|
16273
16300
|
workflowId = selection?.workflowId;
|
|
16274
16301
|
} catch {
|
|
16275
16302
|
return { ir: defaultCodingWorkflowIr(), source: "default" };
|
|
@@ -16105,6 +16105,7 @@ function applyPromptOverridesToIr(ir, overrides) {
|
|
|
16105
16105
|
function defaultCodingWorkflowIr() {
|
|
16106
16106
|
return resolveDefaultWorkflowIr();
|
|
16107
16107
|
}
|
|
16108
|
+
var inflightSelectionReads = /* @__PURE__ */ new WeakMap();
|
|
16108
16109
|
async function resolveWorkflowIrById(store, workflowId, irCache) {
|
|
16109
16110
|
let projectId;
|
|
16110
16111
|
try {
|
|
@@ -16148,8 +16149,34 @@ function didFallBackToDefault(ir) {
|
|
|
16148
16149
|
async function resolveWorkflowIrForTaskWithProvenance(store, taskId, irCache, selectionCache) {
|
|
16149
16150
|
let workflowId;
|
|
16150
16151
|
try {
|
|
16151
|
-
const
|
|
16152
|
-
|
|
16152
|
+
const isSelectionCached = selectionCache?.has(taskId) ?? false;
|
|
16153
|
+
let selection = isSelectionCached && selectionCache ? selectionCache.get(taskId) : void 0;
|
|
16154
|
+
if (!isSelectionCached) {
|
|
16155
|
+
let inflight;
|
|
16156
|
+
let coalesced = false;
|
|
16157
|
+
if (selectionCache) {
|
|
16158
|
+
inflight = inflightSelectionReads.get(selectionCache);
|
|
16159
|
+
if (!inflight) {
|
|
16160
|
+
inflight = /* @__PURE__ */ new Map();
|
|
16161
|
+
inflightSelectionReads.set(selectionCache, inflight);
|
|
16162
|
+
}
|
|
16163
|
+
const pending = inflight.get(taskId);
|
|
16164
|
+
if (pending) {
|
|
16165
|
+
selection = await pending;
|
|
16166
|
+
coalesced = true;
|
|
16167
|
+
}
|
|
16168
|
+
}
|
|
16169
|
+
if (!coalesced) {
|
|
16170
|
+
const readPromise = store.getTaskWorkflowSelectionAsync ? store.getTaskWorkflowSelectionAsync(taskId) : Promise.resolve(store.getTaskWorkflowSelection(taskId));
|
|
16171
|
+
if (inflight) inflight.set(taskId, readPromise);
|
|
16172
|
+
try {
|
|
16173
|
+
selection = await readPromise;
|
|
16174
|
+
} finally {
|
|
16175
|
+
inflight?.delete(taskId);
|
|
16176
|
+
}
|
|
16177
|
+
}
|
|
16178
|
+
selectionCache?.set(taskId, selection);
|
|
16179
|
+
}
|
|
16153
16180
|
workflowId = selection?.workflowId;
|
|
16154
16181
|
} catch {
|
|
16155
16182
|
return { ir: defaultCodingWorkflowIr(), source: "default" };
|
|
@@ -16105,6 +16105,7 @@ function applyPromptOverridesToIr(ir, overrides) {
|
|
|
16105
16105
|
function defaultCodingWorkflowIr() {
|
|
16106
16106
|
return resolveDefaultWorkflowIr();
|
|
16107
16107
|
}
|
|
16108
|
+
var inflightSelectionReads = /* @__PURE__ */ new WeakMap();
|
|
16108
16109
|
async function resolveWorkflowIrById(store2, workflowId, irCache) {
|
|
16109
16110
|
let projectId2;
|
|
16110
16111
|
try {
|
|
@@ -16148,8 +16149,34 @@ function didFallBackToDefault(ir) {
|
|
|
16148
16149
|
async function resolveWorkflowIrForTaskWithProvenance(store2, taskId, irCache, selectionCache) {
|
|
16149
16150
|
let workflowId;
|
|
16150
16151
|
try {
|
|
16151
|
-
const
|
|
16152
|
-
|
|
16152
|
+
const isSelectionCached = selectionCache?.has(taskId) ?? false;
|
|
16153
|
+
let selection = isSelectionCached && selectionCache ? selectionCache.get(taskId) : void 0;
|
|
16154
|
+
if (!isSelectionCached) {
|
|
16155
|
+
let inflight;
|
|
16156
|
+
let coalesced = false;
|
|
16157
|
+
if (selectionCache) {
|
|
16158
|
+
inflight = inflightSelectionReads.get(selectionCache);
|
|
16159
|
+
if (!inflight) {
|
|
16160
|
+
inflight = /* @__PURE__ */ new Map();
|
|
16161
|
+
inflightSelectionReads.set(selectionCache, inflight);
|
|
16162
|
+
}
|
|
16163
|
+
const pending = inflight.get(taskId);
|
|
16164
|
+
if (pending) {
|
|
16165
|
+
selection = await pending;
|
|
16166
|
+
coalesced = true;
|
|
16167
|
+
}
|
|
16168
|
+
}
|
|
16169
|
+
if (!coalesced) {
|
|
16170
|
+
const readPromise = store2.getTaskWorkflowSelectionAsync ? store2.getTaskWorkflowSelectionAsync(taskId) : Promise.resolve(store2.getTaskWorkflowSelection(taskId));
|
|
16171
|
+
if (inflight) inflight.set(taskId, readPromise);
|
|
16172
|
+
try {
|
|
16173
|
+
selection = await readPromise;
|
|
16174
|
+
} finally {
|
|
16175
|
+
inflight?.delete(taskId);
|
|
16176
|
+
}
|
|
16177
|
+
}
|
|
16178
|
+
selectionCache?.set(taskId, selection);
|
|
16179
|
+
}
|
|
16153
16180
|
workflowId = selection?.workflowId;
|
|
16154
16181
|
} catch {
|
|
16155
16182
|
return { ir: defaultCodingWorkflowIr(), source: "default" };
|
|
@@ -173406,6 +173406,7 @@ function applyPromptOverridesToIr(ir, overrides) {
|
|
|
173406
173406
|
function defaultCodingWorkflowIr() {
|
|
173407
173407
|
return resolveDefaultWorkflowIr();
|
|
173408
173408
|
}
|
|
173409
|
+
var inflightSelectionReads = /* @__PURE__ */ new WeakMap();
|
|
173409
173410
|
async function resolveWorkflowIrById(store, workflowId, irCache) {
|
|
173410
173411
|
let projectId;
|
|
173411
173412
|
try {
|
|
@@ -173449,8 +173450,34 @@ function didFallBackToDefault(ir) {
|
|
|
173449
173450
|
async function resolveWorkflowIrForTaskWithProvenance(store, taskId, irCache, selectionCache) {
|
|
173450
173451
|
let workflowId;
|
|
173451
173452
|
try {
|
|
173452
|
-
const
|
|
173453
|
-
|
|
173453
|
+
const isSelectionCached = selectionCache?.has(taskId) ?? false;
|
|
173454
|
+
let selection = isSelectionCached && selectionCache ? selectionCache.get(taskId) : void 0;
|
|
173455
|
+
if (!isSelectionCached) {
|
|
173456
|
+
let inflight;
|
|
173457
|
+
let coalesced = false;
|
|
173458
|
+
if (selectionCache) {
|
|
173459
|
+
inflight = inflightSelectionReads.get(selectionCache);
|
|
173460
|
+
if (!inflight) {
|
|
173461
|
+
inflight = /* @__PURE__ */ new Map();
|
|
173462
|
+
inflightSelectionReads.set(selectionCache, inflight);
|
|
173463
|
+
}
|
|
173464
|
+
const pending = inflight.get(taskId);
|
|
173465
|
+
if (pending) {
|
|
173466
|
+
selection = await pending;
|
|
173467
|
+
coalesced = true;
|
|
173468
|
+
}
|
|
173469
|
+
}
|
|
173470
|
+
if (!coalesced) {
|
|
173471
|
+
const readPromise = store.getTaskWorkflowSelectionAsync ? store.getTaskWorkflowSelectionAsync(taskId) : Promise.resolve(store.getTaskWorkflowSelection(taskId));
|
|
173472
|
+
if (inflight) inflight.set(taskId, readPromise);
|
|
173473
|
+
try {
|
|
173474
|
+
selection = await readPromise;
|
|
173475
|
+
} finally {
|
|
173476
|
+
inflight?.delete(taskId);
|
|
173477
|
+
}
|
|
173478
|
+
}
|
|
173479
|
+
selectionCache?.set(taskId, selection);
|
|
173480
|
+
}
|
|
173454
173481
|
workflowId = selection?.workflowId;
|
|
173455
173482
|
} catch {
|
|
173456
173483
|
return { ir: defaultCodingWorkflowIr(), source: "default" };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runfusion/fusion",
|
|
3
|
-
"version": "0.77.0-beta.
|
|
3
|
+
"version": "0.77.0-beta.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Fusion CLI: HTTP API server, daemon, dashboard launcher, and task tooling for the Fusion AI coding agent.",
|
|
6
6
|
"homepage": "https://github.com/Runfusion/Fusion#readme",
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{r as a,j as t}from"./vendor-react-SZ_qB27O.js";import{c as si,S as mn,r as jt,e as Rs,cJ as js,du as Xi,dv as qi,dw as da,b as Q,dx as Gi,dy as Dt,dz as At,dA as ya,dB as Qi,dC as Yi,dD as Ji,dE as Zi,dF as eo,dG as to,bh as no,c_ as Ca,dH as Ce,db as ao,cv as ii,c3 as wn,dI as so,dJ as io,ar as yn,dK as oo,dL as ro,bS as co,K as lo,aK as uo,b3 as xn,a2 as mo,d9 as ho,dM as fo,aY as go,dN as po,dO as oi,dP as ri,dQ as vo,dR as bo,W as xo,dS as wo,dT as yo,dU as As,dV as Co,dW as ko,dX as Ts,G as So,dY as Mo,z as No,B as Ro,aI as jo,dZ as ua,C as hn,d_ as fn,d$ as Es,cW as Ds,D as ma,P as pt,V as Ao,bU as Is,de as Ls,dd as To,X as Ps,aJ as Eo,e0 as Do,F as ha,e1 as fa,e2 as Fs,e3 as ga,e4 as $s,e5 as _s,e6 as zs,e7 as Io,dj as ci,e8 as Lo,cV as Bs}from"./index-DpCHwyiD.js";import{u as _e}from"./vendor-i18n-Duky4gdQ.js";import{SessionTerminal as Os}from"./SessionTerminal-D04kYRrT.js";import{u as Po}from"./useDiscoveredSkillsCache-BYqP-afh.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./shield-alert-BNSeDB8l.js";/**
|
|
2
|
-
* @license lucide-react v1.7.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const Fo=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],li=si("hash",Fo);/**
|
|
7
|
-
* @license lucide-react v1.7.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const $o=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],_o=si("tag",$o);function gn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function zo(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function pa(i,r){const h=zo(),p=r?.warm===!0,m=gn(),f=new Map;let M=!1,C=!1;return{mark(I){M||C||!h||f.has(I)||f.set(I,gn())},complete:I=>{if(!h||M||C){M=!0;return}M=!0,f.set("complete",gn());const D=Array.from(f.entries()).sort((A,N)=>A[1]-N[1]);let k=m;const s={};for(const[A,N]of D)s[A]=Math.max(0,N-k),k=N;const v=Math.max(0,gn()-m);try{console.debug("[room-open]",{roomId:i,warm:p,totalMs:v,phases:s,...I??{}})}catch{}},cancel(){C=!0,M=!0}}}const $e="fusion:chat-active-room";class di extends Error{roomId;constructor(r,h){super(r),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=h}}function ka(i){return[...i].sort((r,h)=>new Date(h.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function Ge(i,r){const h=i.findIndex(m=>m.id===r.id);if(h===-1)return ka([r,...i]);const p=[...i];return p[h]=r,ka(p)}function Ie(i){try{return JSON.parse(i.data)}catch{return null}}function va(i){return i.slice().reverse()}function Bo(i,r,h){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:i,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...h?.length?{attachments:h}:{},createdAt:new Date().toISOString()}}function Hs(i,r,h){if(i.some(m=>m.id===r.id))return i;const p=h?i.findIndex(m=>m.id===h):-1;if(p>=0){const m=[...i];return m[p]=r,m}if(r.role==="user"){const m=i.findIndex(f=>f.role==="user"&&f.id.startsWith("temp-")&&f.content.trim()===r.content.trim());if(m>=0){const f=[...i];return f[m]=r,f}}return[...i,r]}function Oo(i,r){const{t:h}=_e("app"),p=`${mn.CHAT_ROOMS}:${i??"global"}`,m=`${mn.ACTIVE_CHAT_ROOM_ID}:${i??"global"}`,f=a.useCallback(c=>`${mn.CHAT_ROOM_MESSAGES_PREFIX}${i??"global"}:${c}`,[i]),M=a.useCallback(c=>`${mn.CHAT_ROOM_MEMBERS_PREFIX}${i??"global"}:${c}`,[i]),[C,b]=a.useState(()=>{const c=jt(p,{maxAgeMs:Rs});return Array.isArray(c)?c:[]}),[I,D]=a.useState(()=>C.length===0),[k,s]=a.useState(null),[v,A]=a.useState(()=>{const c=jt(m,{maxAgeMs:js});return c?C.find(S=>S.id===c)??null:null}),[N,y]=a.useState([]),[l,P]=a.useState([]),[$,U]=a.useState(!1),B=a.useRef(C),j=a.useRef(v),Y=a.useRef(0),se=a.useRef(i);B.current=C,j.current=v,se.current!==i&&(se.current=i,Y.current+=1);const J=a.useCallback(async c=>{if(!c){y([]),P([]),U(!1);return}const S=pa(c.id,{warm:!1});S.mark("select");const g=jt(f(c.id),{maxAgeMs:Xi}),u=jt(M(c.id),{maxAgeMs:Rs}),T=Array.isArray(g)&&g.length>0,L=Array.isArray(u)&&u.length>0;T||L?(S.mark("cache-hit"),T&&(P(g),S.mark("hydrate")),L&&y(u),U(!1)):(P([]),U(!0));try{const[W,ve]=await Promise.all([qi(c.id,i),da(c.id,{limit:100,order:"desc"},i)]);S.mark("members-fetch"),S.mark("messages-fetch"),Q(M(c.id),W.members,{maxBytes:5e5});const ee=va(ve.messages);Q(f(c.id),ee,{maxBytes:5e5}),j.current?.id===c.id&&(y(W.members),P(ee),S.mark("hydrate"))}catch{!T&&!L&&(y([]),P([]))}finally{U(!1),S.complete({warm:T,membersCached:L})}},[M,f,i]),E=a.useCallback(async()=>{B.current.length===0&&D(!0);try{const c=await Gi({},i),S=ka(c.rooms);b(S),Q(p,S,{maxBytes:5e5}),s(null);const g=jt(m,{maxAgeMs:js})??Dt($e,i);if(g){const u=S.find(T=>T.id===g)??null;u?(A(u),J(u)):(At($e,i),Q(m,"",{maxBytes:5e5}))}}catch(c){const S=c instanceof Error?c.message:h("chatRooms.error.failedToLoad","Failed to load chat rooms");s(S),r?.(S,"error")}finally{D(!1)}},[m,r,J,i,p]),O=a.useCallback(c=>{if(!c){j.current=null,A(null),At($e,i),Q(m,"",{maxBytes:5e5}),J(null);return}const S=B.current.find(g=>g.id===c)??null;j.current=S,A(S),S&&(ya($e,S.id,i),Q(m,S.id,{maxBytes:5e5}),J(S))},[m,J,i]),R=a.useCallback(async c=>{const g=(await Qi({name:c.name,memberAgentIds:c.memberAgentIds},i)).room;return b(u=>Ge(u,g)),j.current=g,A(g),ya($e,g.id,i),Q(m,g.id,{maxBytes:5e5}),await J(g),g},[m,J,i]),_=a.useCallback(async(c,S)=>{const u=(await Yi(c,S,i)).room;return b(T=>Ge(T,u)),j.current?.id===u.id&&(j.current=u,A(u)),u},[i]),ce=a.useCallback(async c=>{await Ji(c,i),b(S=>S.filter(g=>g.id!==c)),Q(f(c),[],{maxBytes:5e5}),Q(M(c),[],{maxBytes:5e5}),j.current?.id===c&&(j.current=null,A(null),y([]),P([]),At($e,i),Q(m,"",{maxBytes:5e5}))},[m,M,f,i]),ae=a.useCallback(async(c,S)=>{const g=j.current,u=g?.id;if(!u)throw new Error(h("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const T=pa(u,{warm:!1}),L=S?.files?.map(ee=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:ee.name,originalName:ee.name,mimeType:ee.type||"application/octet-stream",size:ee.size,createdAt:new Date().toISOString()})),W=Bo(u,c,L?.length?L:S?.attachments);j.current?.id===u&&P(ee=>{const he=[...ee,W];return Q(f(u),he,{maxBytes:5e5}),he});let ve=!1;try{const ee=[];if(S?.files?.length)for(const fe of S.files)try{const ze=await Zi(u,fe,i);ee.push(ze.attachment)}catch{throw new Error(h("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:fe.name}))}const he=[...S?.attachments??[],...ee],ke=await eo(u,{content:c,...he.length?{attachments:he}:{}},i);ve=!0;try{S?.onDelivered?.()}catch{}ke.message?.createdAt&&g&&b(fe=>Ge(fe,{...g,updatedAt:ke.message.createdAt})),j.current?.id===u&&P(fe=>{const ze=Hs(fe,ke.message,W.id);return Q(f(u),ze,{maxBytes:5e5}),ze});const ie=await da(u,{limit:100,order:"desc"},i),Le=va(ie.messages);if(Q(f(u),Le,{maxBytes:5e5}),j.current?.id!==u)return;P(Le),T.mark("hydrate")}catch(ee){let he=null;try{const ie=await da(u,{limit:100,order:"desc"},i);he=va(ie.messages),Q(f(u),he,{maxBytes:5e5}),j.current?.id===u&&(P(he),T.mark("hydrate"))}catch{!ve&&j.current?.id===u&&P(ie=>{const Le=ie.filter(fe=>fe.id!==W.id);return Q(f(u),Le,{maxBytes:5e5}),Le})}const ke=he?.some(ie=>ie.role==="user"&&ie.content.trim()===W.content.trim());if(ve||ke){const ie=ee instanceof Error&&ee.message.trim()?ee.message:h("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new di(ie,u)}throw ee}finally{T.complete({source:"send-room-message"})}},[f,i]),me=a.useCallback(async c=>{!c||!B.current.some(S=>S.id===c)||(await to(c,i),Q(f(c),[],{maxBytes:5e5}),j.current?.id===c&&P([]))},[f,i]);return a.useEffect(()=>{E()},[E]),a.useEffect(()=>{const c=Y.current,S=i?`/api/events?projectId=${encodeURIComponent(i)}`:"/api/events";return no(S,{onReconnect:()=>{Ca({view:"useChatRooms",trigger:"sse-reconnect",projectId:i,replayAttempted:!1});const g=j.current?.id;if(g){const u=pa(g,{warm:!0});u.mark("sse-reconnect-refresh"),E().finally(()=>u.complete({source:"sse-reconnect"}));return}E()},events:{"chat:room:created":g=>{if(Y.current!==c)return;const u=Ie(g);u&&b(T=>Ge(T,u))},"chat:room:updated":g=>{if(Y.current!==c)return;const u=Ie(g);u&&(b(T=>Ge(T,u)),j.current?.id===u.id&&(j.current=u,A(u)))},"chat:room:deleted":g=>{if(Y.current!==c)return;const u=Ie(g);u?.id&&(b(T=>T.filter(L=>L.id!==u.id)),Q(f(u.id),[],{maxBytes:5e5}),Q(M(u.id),[],{maxBytes:5e5}),j.current?.id===u.id&&(j.current=null,A(null),y([]),P([]),At($e,i),Q(m,"",{maxBytes:5e5})))},"chat:room:member:added":g=>{if(Y.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||y(T=>{if(T.some(W=>W.agentId===u.agentId))return T;const L=[...T,u];return Q(M(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:member:removed":g=>{if(Y.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||y(T=>{const L=T.filter(W=>W.agentId!==u.agentId);return Q(M(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:message:added":g=>{if(Y.current!==c)return;const u=Ie(g);u&&(b(T=>{const L=T.find(W=>W.id===u.roomId);return L?Ge(T,{...L,updatedAt:u.createdAt}):T}),j.current?.id===u.roomId&&P(T=>{const L=Hs(T,u);return L===T?T:(Q(f(u.roomId),L,{maxBytes:5e5}),L)}))},"chat:room:message:updated":g=>{if(Y.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||P(T=>{const L=T.map(W=>W.id===u.id?u:W);return Q(f(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:message:deleted":g=>{if(Y.current!==c)return;const u=Ie(g);u?.id&&P(T=>{const L=T.filter(ve=>ve.id!==u.id),W=j.current?.id;return W&&Q(f(W),L,{maxBytes:5e5}),L})},"chat:room:messages:cleared":g=>{if(Y.current!==c)return;const u=Ie(g);u?.roomId&&(Q(f(u.roomId),[],{maxBytes:5e5}),j.current?.id===u.roomId&&P([]),b(T=>{const L=T.find(W=>W.id===u.roomId);return L?Ge(T,{...L,updatedAt:new Date().toISOString()}):T}))}}})},[m,M,f,i,E]),a.useEffect(()=>{v&&(C.some(c=>c.id===v.id)||(j.current=null,A(null),y([]),P([]),At($e,i),Q(m,"",{maxBytes:5e5})))},[v,m,i,C]),{rooms:C,roomsLoading:I,roomsError:k,activeRoom:v,activeRoomMembers:N,messages:l,messagesLoading:$,selectRoom:O,createRoom:R,updateRoomSettings:_,deleteRoom:ce,sendRoomMessage:ae,clearRoom:me,refreshRooms:E}}const Tt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},Us=200;function Sa(i){if(!i)return null;const r=new Date(i).getTime();return Number.isFinite(r)?r:null}function ui(i){const r=Object.entries(i);if(r.length<=Us)return i;const h=r.map(([p,m])=>({id:p,timestamp:m,value:Sa(m)??0})).sort((p,m)=>m.value-p.value).slice(0,Us);return Object.fromEntries(h.map(({id:p,timestamp:m})=>[p,m]))}function pn(i){if(!i)return{};try{const r=JSON.parse(i);if(!r||typeof r!="object")return{};const h={};for(const[p,m]of Object.entries(r))typeof p=="string"&&typeof m=="string"&&(h[p]=m);return ui(h)}catch{return{}}}function Ho(i){const[r,h]=a.useState(()=>{try{return pn(Dt(Tt.direct,i))}catch{return{}}}),[p,m]=a.useState(()=>{try{return pn(Dt(Tt.room,i))}catch{return{}}});a.useEffect(()=>{try{h(pn(Dt(Tt.direct,i)))}catch{h({})}try{m(pn(Dt(Tt.room,i)))}catch{m({})}},[i]);const f=a.useMemo(()=>({direct:r,room:p}),[r,p]),M=a.useCallback((k,s)=>{const v=ui(s);try{ya(Tt[k],JSON.stringify(v),i)}catch{}return v},[i]),C=a.useCallback((k,s)=>{if(k==="direct"){h(v=>M(k,s(v)));return}m(v=>M(k,s(v)))},[M]),b=a.useCallback((k,s,v)=>{const A=Sa(v);if(A===null)return!1;const N=f[k][s],y=Sa(N);return y===null?!0:A>y},[f]),I=a.useCallback((k,s,v)=>{if(!s)return;const A=v??new Date().toISOString();C(k,N=>({...N,[s]:A}))},[C]),D=a.useCallback((k,s)=>{s.length!==0&&C(k,v=>{const A={...v};for(const N of s)N.id&&(A[N.id]=N.lastActivityAt??new Date().toISOString());return A})},[C]);return{isUnread:b,markRead:I,markAllRead:D}}const Uo=["",...so];function Ks({level:i,onChange:r,defaultThinkingLevel:h="off",showTargetSection:p=!0,models:m=[],favoriteProviders:f=[],favoriteModels:M=[],agents:C=[],agentId:b,modelProvider:I,modelId:D,onChangeModel:k,disabled:s=!1}){const{t:v}=_e("app"),[A,N]=a.useState(!1),[y,l]=a.useState(()=>b&&b!==Ce?"agent":"model"),P=a.useRef(null),$=i??"",U=I&&D?`${I}/${D}`:"",B=b&&b!==Ce?b:"",j=$!==""||p&&(!!U||!!B),Y="chat-thinking-level-listbox";a.useEffect(()=>{if(!A)return;const c=S=>{const g=S.target;if(!(g instanceof Node))return;!P.current?.contains(g)&&!io(g)&&N(!1)};return document.addEventListener("pointerdown",c),document.addEventListener("touchstart",c),()=>{document.removeEventListener("pointerdown",c),document.removeEventListener("touchstart",c)}},[A]),a.useEffect(()=>{N(!1),l(B?"agent":"model")},[$,B,U]);const se=a.useMemo(()=>C.find(c=>c.id===B),[C,B]),J=c=>c===""?v("modelSelection.thinkingDefault","Default ({{level}})",{level:h??"off"}):v(`models.options.${c}`,c==="xhigh"?"Very High":c.charAt(0).toUpperCase()+c.slice(1)),E=c=>{N(!1),r(c)},O=c=>{const S=c.indexOf("/");S<=0||(N(!1),k?.({modelProvider:c.slice(0,S),modelId:c.slice(S+1)}))},R=c=>{c&&(N(!1),k?.({agentId:c}))},_=c=>{l(c)},ce=c=>{c.key==="Escape"&&N(!1)},ae=(c,S)=>{if(c.key==="Escape"){c.preventDefault(),N(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),E(S))},me=(c,S)=>{if(c.key==="Escape"){c.preventDefault(),N(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),R(S))};return t.jsxs("div",{className:"chat-thinking-level-root",ref:P,children:[t.jsx("button",{type:"button",className:`btn-icon chat-thinking-btn${j?" chat-thinking-btn--active":""}`,"data-testid":"chat-thinking-btn","aria-haspopup":"dialog","aria-expanded":A,"aria-controls":Y,"aria-label":v("chat.thinkingLevelButton","Thinking level"),title:v("chat.thinkingLevelButton","Thinking level"),disabled:s,onClick:()=>N(c=>!c),onKeyDown:ce,children:t.jsx(ao,{size:16})}),A?t.jsxs("div",{className:"chat-thinking-popover",role:"presentation","data-testid":"chat-thinking-popover",children:[p?t.jsxs("section",{className:"chat-thinking-target-section","aria-label":v("chat.modelAgentSection","Model / Agent"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:v("chat.modelAgentSection","Model / Agent")}),t.jsxs("div",{className:"chat-thinking-mode-toggle","data-testid":"chat-thinking-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${y==="model"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-model","aria-pressed":y==="model",onPointerDown:c=>{c.button===0&&_("model")},onClick:c=>{c.detail===0&&_("model")},children:v("chat.newChatModeModel","Model")}),t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${y==="agent"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-agent","aria-pressed":y==="agent",onPointerDown:c=>{c.button===0&&_("agent")},onClick:c=>{c.detail===0&&_("agent")},children:v("chat.newChatModeAgent","Agent")})]}),y==="model"?t.jsxs("div",{className:"chat-thinking-model-picker","data-testid":"chat-thinking-model-picker",children:[t.jsx(ii,{models:m,value:U,onChange:O,label:v("chat.newChatModeModel","Model"),placeholder:v("chat.selectModel","Select a model"),disabled:!k||m.length===0,favoriteProviders:f,favoriteModels:M,menuWidth:"readable"}),m.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-model-empty",children:v("chat.noModelsAvailable","No models available")}):null]}):t.jsx("div",{className:"chat-thinking-agent-list","data-testid":"chat-thinking-agent-list",children:C.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-agent-empty",children:v("chat.noAgentsAvailable","No agents available")}):C.map(c=>{const S=B===c.id;return t.jsxs("button",{type:"button",className:`chat-thinking-agent-item${S?" chat-thinking-agent-item--selected":""}`,"data-testid":`chat-thinking-agent-${c.id}`,"aria-pressed":S,disabled:!k,onClick:()=>R(c.id),onKeyDown:g=>me(g,c.id),children:[t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thinking-agent-name",children:c.name||c.id}),c.role?t.jsx("span",{className:"chat-thinking-agent-role",children:c.role}):null]},c.id)})}),se?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-agent",children:v("chat.currentAgentTarget","Current agent: {{name}}",{name:se.name||se.id})}):U?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-model",children:v("chat.currentModelTarget","Current model: {{model}}",{model:U})}):t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-default",children:v("chat.currentDefaultTarget","Using the default chat target")})]}):null,t.jsxs("section",{className:"chat-thinking-level-section","aria-label":v("chat.thinkingLevelButton","Thinking level"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:v("chat.thinkingLevelSection","Thinking level")}),t.jsx("div",{id:Y,className:"chat-thinking-popover-list",role:"listbox","aria-label":v("chat.thinkingLevelButton","Thinking level"),children:Uo.map(c=>{const S=$===c;return t.jsx("button",{type:"button",role:"option","aria-selected":S,className:`chat-thinking-popover-option${S?" active":""}`,"data-testid":`chat-thinking-option-${c||"default"}`,onClick:()=>E(c),onKeyDown:g=>ae(g,c),children:J(c)},c||"default")})})]})]}):null]})}function Ws(i){return i.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function mi(i,r){const h=r.trim();if(!h)return!0;const p=Ws(h);return Ws(i).includes(p)||i.toLowerCase().includes(h.toLowerCase())}function Vs({agents:i,filter:r,highlightedIndex:h,visible:p,onSelect:m,position:f="below",roomMemberIds:M,roomName:C}){const{t:b}=_e("app"),I=a.useMemo(()=>i.filter(N=>mi(N.name,r)),[i,r]),D=!!M,k=D&&r.trim().length>0,s=a.useMemo(()=>D?I.filter(N=>M?.has(N.id)):I,[I,M,D]),v=a.useMemo(()=>D?I.filter(N=>!M?.has(N.id)):[],[I,M,D]),A=k?[...s,...v]:s;return p?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${f}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":b("agentMention.suggestionsLabel","Agent mention suggestions"),children:A.length===0?t.jsx("div",{className:"agent-mention-empty",children:b("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[D&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:C?b("agentMention.membersOf","Members of #{{roomName}}",{roomName:C}):b("agentMention.roomMembers","Room members")}),s.map((N,y)=>t.jsxs("button",{type:"button",className:`agent-mention-item${y===h?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${N.id}`,onMouseDown:l=>l.preventDefault(),onClick:()=>m(N),role:"option","aria-selected":y===h,children:[t.jsx(yn,{agent:N,size:20}),D&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":b("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:N.name}),t.jsx("span",{className:"agent-mention-role",children:N.role})]},N.id)),D&&!k&&v.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:b("agentMention.typeToSearch","Type to search other agents")}),D&&k&&v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:b("agentMention.otherAgents","Other agents")}),v.map((N,y)=>{const l=s.length+y;return t.jsxs("button",{type:"button",className:`agent-mention-item${l===h?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${N.id}`,onMouseDown:P=>P.preventDefault(),onClick:()=>m(N),role:"option","aria-selected":l===h,children:[t.jsx(yn,{agent:N,size:20}),t.jsx("span",{className:"agent-mention-name",children:N.name}),t.jsx("span",{className:"agent-mention-role",children:N.role})]},N.id)})]})]})}):null}function Ko(i,r){return i+r}function Wo({visible:i,position:r,tasks:h,files:p,selectedIndex:m,onSelectTask:f,onSelectFile:M,loading:C}){const{t:b}=_e("app");if(!i)return null;const I=h.length>0,D=p.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:r.top,left:r.left},"data-testid":"file-mention-popup",onMouseDown:k=>{k.preventDefault()},children:[C&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!C&&!I&&!D&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:b("fileMention.empty","No tasks or files found")}),!C&&(I||D)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[I&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:b("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":b("fileMention.taskMatches","Task matches"),children:h.map((k,s)=>{const v=s;return t.jsxs("li",{className:`file-mention-popup-item${v===m?" file-mention-popup-item--selected":""}`,onClick:()=>f(k),role:"option","aria-selected":v===m,"data-testid":`task-mention-item-${v}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(li,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:k.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${k.column}`,children:k.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:k.title})]})]},k.id)})})]}),D&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:b("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":b("fileMention.fileMatches","File matches"),children:p.map((k,s)=>{const v=Ko(h.length,s),A=oo(k.path);return t.jsxs("li",{className:`file-mention-popup-item${v===m?" file-mention-popup-item--selected":""}`,onClick:()=>M(k),role:"option","aria-selected":v===m,"data-testid":`file-mention-item-${v}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(ro,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:k.name}),A&&t.jsx("span",{className:"file-mention-popup-item-path",children:A})]})]},k.path)})})]})]})]})}function Vo(i,r=[],h){const p=i.trim().replace(/^#/,""),m=(M,C)=>h?h(M,C):C;if(!p)return{ok:!1,error:m("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(p))return{ok:!1,error:m("createRoom.lowercase","Use lowercase letters only.")};const f=p.toLowerCase();return f.length>80?{ok:!1,error:m("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(f)?/^[-_]|[-_]$/.test(f)?{ok:!1,error:m("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:r.some(M=>M.toLowerCase()===f)?{ok:!1,error:m("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:f}:{ok:!1,error:m("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Xo({isOpen:i,onClose:r,onCreate:h,projectId:p,existingRoomNames:m=[]}){const{t:f}=_e("app"),[M,C]=a.useState(""),[b,I]=a.useState([]),[D,k]=a.useState(""),[s,v]=a.useState([]),[A,N]=a.useState(!1),[y,l]=a.useState(null),[P,$]=a.useState(!1),U=a.useRef(null),B=a.useRef(null);a.useEffect(()=>{i&&(B.current=document.activeElement instanceof HTMLElement?document.activeElement:null,N(!0),l(null),co(void 0,p).then(R=>I(R)).catch(()=>{I([]),l(f("createRoom.failedLoadAgents","Failed to load agents."))}).finally(()=>N(!1)))},[i,p]),a.useEffect(()=>{if(!i){C(""),k(""),v([]),l(null),$(!1);return}const R=window.requestAnimationFrame(()=>U.current?.focus());return()=>window.cancelAnimationFrame(R)},[i]),a.useEffect(()=>{if(!i)return;const R=_=>{_.key==="Escape"&&r()};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[i,r]),a.useEffect(()=>{i||B.current?.focus()},[i]);const j=a.useMemo(()=>Vo(M,m,f),[M,m,f]),Y=a.useMemo(()=>{const R=D.trim().toLowerCase();return R?b.filter(_=>_.name.toLowerCase().includes(R)):b},[b,D]),se=a.useMemo(()=>b.filter(R=>s.includes(R.id)),[b,s]),J=j.ok&&s.length>0&&!P&&!A;if(!i)return null;const E=R=>{P||v(_=>_.includes(R)?_.filter(ce=>ce!==R):[..._,R])},O=async()=>{if(!j.ok){l(j.error);return}if(s.length===0){l(f("createRoom.selectMember","Select at least one member."));return}l(null),$(!0);try{await h({name:j.name,displayName:`#${j.name}`,memberAgentIds:s}),r()}catch(R){l(R instanceof Error?R.message:f("createRoom.failedCreate","Failed to create room."))}finally{$(!1)}};return t.jsx(lo,{windowKey:"create-room",title:f("createRoom.title","Create room"),ariaLabel:f("createRoom.title","Create room"),onClose:r,modal:!0,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--create-room",defaultSize:{width:640,height:640},minSize:{width:360,height:400},persistGeometryKey:"floating-window:create-room",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,layer:"utility",children:t.jsxs("div",{className:"modal create-room-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:f("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":f("actions.close","Close"),onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:f("createRoom.nameLabel","Room name")}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:U,id:"create-room-name",className:"input",value:M,disabled:P,onChange:R=>{const _=R.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();C(_)}})]}),!j.ok&&t.jsx("div",{className:"form-error",children:j.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:f("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:f("createRoom.searchAgents","Search agents"),value:D,disabled:P,onChange:R=>k(R.target.value)})]}),se.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:se.map(R=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>E(R.id),disabled:P,children:[R.name," ×"]},R.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:A?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(uo,{label:f("createRoom.loadingAgents","Loading agents...")})}):Y.length===0?t.jsx("div",{className:"create-room-modal-empty",children:b.length===0?f("createRoom.noAgents","No agents in this project yet."):f("createRoom.noMatch","No agents match your search.")}):Y.map(R=>{const _=s.includes(R.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${_?" create-room-modal-member-row--selected":""}`,onClick:()=>E(R.id),disabled:P,children:[t.jsx(yn,{agent:R,size:20}),t.jsx("span",{children:R.name}),t.jsx("span",{className:"create-room-modal-member-role",children:R.role})]},R.id)})}),y&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:y})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:P,children:f("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void O(),disabled:!J,children:P?f("createRoom.creating","Creating..."):f("createRoom.create","Create room")})]})]})})}function qo({cliSessionId:i,tier:r,projectId:h,renderTranscript:p,renderComposer:m,queuedCount:f=0,terminalProps:M}){const{t:C}=_e("app"),b=r==="generic",[I,D]=a.useState(b?"terminal":"transcript");if(b)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx(Os,{sessionId:i,projectId:h,...M})});const k=I==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":r,"data-view":I,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":C("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!k,className:`cli-chat-surface__tab${k?"":" is-active"}`,onClick:()=>D("transcript"),children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:C("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":k,className:`cli-chat-surface__tab${k?" is-active":""}`,onClick:()=>D("terminal"),children:[t.jsx(mo,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:C("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:k?t.jsx(Os,{sessionId:i,projectId:h,...M}):p()}),!k&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[f>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:C("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:f})}),m()]})]})}const Go=200,Qo=8,Yo=8;function Xs(){return new DOMException("The operation was aborted.","AbortError")}function qs(i,r){return r.aborted?Promise.reject(Xs()):new Promise((h,p)=>{const m=()=>p(Xs());r.addEventListener("abort",m,{once:!0}),i.then(f=>{r.removeEventListener("abort",m),h(f)},f=>{r.removeEventListener("abort",m),p(f)})})}function Gs(i,r,h){const p=i.slice(0,r),m=i.slice(r+1),f=m.match(/[\s]|$/),M=f?f.index??m.length:m.length,C=m.slice(M);return`${p}${h}${C}`}function Jo(i={}){const{projectId:r,workspace:h="project"}=i,[p,m]=a.useState(!1),[f,M]=a.useState(""),[C,b]=a.useState(-1),[I,D]=a.useState([]),[k,s]=a.useState([]),[v,A]=a.useState(!1),[N,y]=a.useState(0),l=a.useRef(null),P=a.useRef(null),$=[...I.map(E=>({kind:"task",task:E})),...k.map(E=>({kind:"file",file:E}))];a.useEffect(()=>()=>{l.current&&clearTimeout(l.current),P.current?.abort()},[]);const U=a.useCallback((E,O)=>{if(O<0||O>E.length){m(!1);return}const R=_=>/[a-zA-Z0-9/_.-]/.test(_);for(let _=O-1;_>=0;_--){if(E[_]==="#"){if(_===0){const ae=E.slice(_+1,O);b(_),M(ae),y(0),m(!0);return}const ce=E[_-1];if(/[\s,.;:!?'"()[\]{}]/.test(ce)){const ae=E.slice(_+1,O);b(_),M(ae),y(0),m(!0);return}m(!1);return}if(!R(E[_])){m(!1);return}}m(!1)},[]),B=a.useCallback(()=>{P.current?.abort(),m(!1),M(""),b(-1),D([]),s([]),y(0),A(!1)},[]),j=a.useCallback(async E=>{if(!E.trim()){D([]),s([]),A(!1);return}P.current?.abort();const O=new AbortController;P.current=O;try{A(!0);const[R,_]=await Promise.allSettled([qs(ho(20,0,r,E),O.signal),qs(fo(E,h,r),O.signal)]);if(O.signal.aborted)return;const ce=R.status==="fulfilled"?R.value.slice(0,Qo).map(me=>({id:me.id,title:me.title??"",column:me.column})):[],ae=_.status==="fulfilled"?_.value.files.slice(0,Yo):[];D(ce),s(ae),y(0)}catch(R){R.name!=="AbortError"&&(D([]),s([]))}finally{O.signal.aborted||A(!1)}},[h,r]);a.useEffect(()=>{if(p)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{j(f)},Go),()=>{l.current&&clearTimeout(l.current)}},[f,p,j]);const Y=a.useCallback((E,O)=>!p||C<0?O:Gs(O,C,`#${E.id}`),[p,C]),se=a.useCallback((E,O)=>!p||C<0?O:Gs(O,C,`#${E.path}`),[p,C]),J=a.useCallback((E,O)=>{if(!p||$.length===0)return!1;switch(E.key){case"ArrowDown":return E.preventDefault(),y(R=>Math.min(R+1,$.length-1)),!0;case"ArrowUp":return E.preventDefault(),y(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return $[N]?(E.preventDefault(),!0):!1;case"Escape":return E.preventDefault(),B(),!0;default:return!1}},[p,$,N,B]);return{mentionActive:p,tasks:I,files:k,combinedItems:$,loading:v,mentionQuery:f,selectedIndex:N,setSelectedIndex:y,detectMention:U,selectTask:Y,selectFile:se,dismissMention:B,handleKeyDown:J}}function Zo(i,r){const h=i.reduce((p,m)=>p+(m.content?.length??0),0)+(r?.length??0);return Math.ceil(h/4)}function Qs(i){if(!Number.isFinite(i)||i<=0)return"0";if(i<1e3)return String(Math.round(i));const r=i/1e3;return r<10?`~${Number(r.toFixed(1))}k`:`${Math.round(r)}k`}const Ma=640,er=200,tr=200,vt=8;function yr(i){const r=i.trim();return r?`${r}
|
|
12
|
-
|
|
13
|
-
`:""}function nr(i,r,h,p,m,f,M){const C=Math.max(vt,f-p-vt),b=Math.max(vt,M-m-vt),I=h?i-p:i;return{x:Math.min(Math.max(vt,I),C),y:Math.min(Math.max(vt,r),b)}}const Ys="__SKIP__";let ba=!1;function ar(i,r=Ma){return i>r?"auto":"hidden"}function sr(i,r=Ma){return Math.max(40,Math.min(i,r))}function ir(i,r){const h=new Date(i),m=new Date().getTime()-h.getTime(),f=Math.floor(m/1e3),M=Math.floor(f/60),C=Math.floor(M/60),b=Math.floor(C/24);return f<60?r("chat.relativeTimeJustNow","just now"):M<60?r("chat.relativeTimeMinutes","{{count}}m ago",{count:M}):C<24?r("chat.relativeTimeHours","{{count}}h ago",{count:C}):b<7?r("chat.relativeTimeDays","{{count}}d ago",{count:b}):h.toLocaleDateString()}const or=280,vn=180,bn=500,Js="fusion:chat-sidebar-width",xa="fusion:chat-scope",rr="fusion:chat-draft:";function Zs(i,r){return i.slice(r+1).find(h=>h.role==="user")?.content}function ei(i,r){return r?`${rr}${i}:${r}`:null}function ti(i){if(!i)return"";try{return localStorage.getItem(i)??""}catch{return""}}const cr=["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm","video/quicktime","text/plain","text/markdown","application/json","text/yaml","text/x-toml","text/csv","application/xml"],ni="image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm,video/quicktime,.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml",wa=Io;function lr(i,r){const h=i.slice(0,r),p=/(^|[\s\n])@([\w-]*)$/.exec(h);if(!p)return null;const m=p[2]??"",f=h.length-m.length-1;return{filter:m,start:f,end:r}}function dr(i){const r=i?.runtimeConfig;if(!r||typeof r!="object")return null;const h=Reflect.get(r,"modelProvider"),p=Reflect.get(r,"modelId");return typeof h!="string"||h.trim().length===0||typeof p!="string"||p.trim().length===0?null:{provider:h,modelId:p}}function ai(i,r,h){if(i?.modelProvider&&i?.modelId)return{provider:i.modelProvider,modelId:i.modelId};const p=dr(r??void 0);return p||(h.provider&&h.modelId?{provider:h.provider,modelId:h.modelId}:null)}function ur({projectId:i,defaultModel:r,defaultKind:h,defaultAgentId:p,defaultThinkingLevel:m,defaultSelectedThinkingLevel:f,onClose:M,onCreate:C}){const{t:b}=_e("app"),[I,D]=a.useState(h??"agent"),{agents:k,loading:s}=oi(i),[v,A]=a.useState(p??""),{models:N,favoriteProviders:y,favoriteModels:l,loading:P,refresh:$}=ri(),U=r.provider&&r.modelId?`${r.provider}/${r.modelId}`:"",[B,j]=a.useState(U),[Y,se]=a.useState(f??""),[J,E]=a.useState(y),[O,R]=a.useState(l);a.useEffect(()=>{E(y)},[y]),a.useEffect(()=>{R(l)},[l]),a.useEffect(()=>{h&&D(h)},[h]),a.useEffect(()=>{p&&A(g=>g||p)},[p]),a.useEffect(()=>{U&&j(g=>g||U)},[U]),a.useEffect(()=>{f&&se(g=>g||f)},[f]);const _=a.useCallback(async g=>{const u=J,L=u.includes(g)?u.filter(W=>W!==g):[g,...u];E(L);try{await Bs({favoriteProviders:L,favoriteModels:O}),await $()}catch{E(u)}},[J,O,$]),ce=a.useCallback(async g=>{const u=O,L=u.includes(g)?u.filter(W=>W!==g):[g,...u];R(L);try{await Bs({favoriteProviders:J,favoriteModels:L}),await $()}catch{R(u)}},[O,J,$]),ae=B||U,me=g=>{if(g.preventDefault(),I==="agent"){if(!v)return;C({agentId:v});return}if(!ae)return;const u=ae.indexOf("/");if(u<=0)return;const T=ae.slice(0,u),L=ae.slice(u+1);C({agentId:Ce,modelProvider:T,modelId:L,thinkingLevel:Y||void 0})},c=I==="agent"?!v:!ae,S=ci(M,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...S,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("h3",{children:b("chat.newChatTitle","New Chat")}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${I==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{D("agent")},children:b("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${I==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{D("model"),A(""),j(g=>g||U)},children:b("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:me,children:[I==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[b("chat.newChatModeAgent","Agent"),s?t.jsx("div",{className:"chat-new-dialog-loading",children:b("chat.loadingAgents","Loading agents...")}):k.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:b("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:k.map(g=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${v===g.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>A(g.id),"data-testid":`agent-option-${g.id}`,children:[t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:g.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:g.role})]},g.id))})]}),I==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:P?t.jsx("div",{className:"chat-new-dialog-loading",children:b("chat.loadingModels","Loading models...")}):t.jsx(ii,{models:N,value:B,onChange:j,label:b("chat.newChatModeModel","Model"),placeholder:b("chat.selectModel","Select a model"),favoriteProviders:J,onToggleFavorite:_,favoriteModels:O,onToggleModelFavorite:ce,showThinkingLevel:!0,thinkingLevel:Y,onThinkingLevelChange:se,defaultThinkingLevel:m??"off"})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:M,children:b("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:c,children:b("chat.create","Create")})]})]})]})})}function Et({children:i,onClose:r}){const h=ci(r,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...h,children:i})}function Cr({projectId:i,addToast:r,floating:h=!1,compactLayout:p=!1,onPopOut:m,onMaximize:f,onMinimize:M,onClose:C,chatCommandContext:b,initialComposerDraft:I,initialComposerDraftNonce:D,onSendAsReport:k}){const{t:s}=_e("app");a.useEffect(()=>(Ca({view:"ChatView",trigger:ba?"route-active":"remount",projectId:i,replayAttempted:!1}),ba=!1,()=>{ba=!0,Ca({view:"ChatView",trigger:"route-inactive",projectId:i,replayAttempted:!1})}),[i]);const[v,A]=a.useState(null);a.useEffect(()=>{let e=!1;return A(null),go(i).then(n=>{e||A(n)}).catch(()=>{e||A(null)}),()=>{e=!0}},[i]);const N=v?.defaultThinkingLevel??"off",y=a.useMemo(()=>v?.chatDefaultKind==="agent"&&v.chatDefaultAgentId?{kind:"agent",agentId:v.chatDefaultAgentId}:v?.chatDefaultKind==="model"&&v.chatDefaultModelProvider&&v.chatDefaultModelId?{kind:"model",modelProvider:v.chatDefaultModelProvider,modelId:v.chatDefaultModelId,thinkingLevel:v.chatDefaultThinkingLevel}:null,[v]),{activeSession:l,sessionsLoading:P,messages:$,messagesLoading:U,isStreaming:B,streamingText:j,streamingThinking:Y,streamingToolCalls:se,selectSession:J,createSession:E,archiveSession:O,archivedSessions:R,refreshArchivedSessions:_,unarchiveSession:ce,renameSession:ae,pinSession:me,pinnedCount:c,setSessionModel:S,setSessionThinkingLevel:g,deleteSession:u,tags:T=[],selectedTagId:L,setSelectedTagId:W,createTag:ve,renameTag:ee,deleteTag:he,setSessionTags:ke,sendMessage:ie,editMessageAndResend:Le,stopStreaming:fe,pendingMessages:ze,clearPendingMessage:Cn,loadMoreMessages:Na,hasMoreMessages:kn,searchQuery:hi,setSearchQuery:fi,filteredSessions:Be,agentsMap:Sn}=po(i,r),[gi,Mn]=a.useState(!1),Oe=!0,[F,Qe]=a.useState(()=>{try{if(localStorage.getItem(xa)==="rooms"&&Oe)return"rooms"}catch{}return"direct"}),w=Oo(i,r),{isUnread:Ra,markRead:de}=Ho(i),[q,oe]=a.useState(()=>{const e=ei(F,F==="rooms"?w.activeRoom?.id:l?.id);return ti(e)}),[G,Se]=a.useState(null),[Ye,pi]=a.useState(!1),Nn=a.useRef(null),ja=(e,n,o,d)=>{typeof window>"u"||Se({sessionId:e,anchorX:n,anchorY:o,anchorRight:d?.anchorRight??!1,x:n,y:o})};a.useLayoutEffect(()=>{if(!G||!Nn.current||typeof window>"u")return;const e=Nn.current,n=e.getBoundingClientRect(),o=n.width||e.offsetWidth||tr,d=n.height||e.offsetHeight,x=nr(G.anchorX,G.anchorY,G.anchorRight,o,d,window.innerWidth,window.innerHeight);(x.x!==G.x||x.y!==G.y)&&Se({...G,...x})},[G]);const[It,Lt]=a.useState(null),[Rn,jn]=a.useState(""),[Aa,Pt]=a.useState(null),[Ta,Ft]=a.useState(null),[An,Ea]=a.useState(""),[Tn,bt]=a.useState(null),[En,Da]=a.useState(""),[Ia,$t]=a.useState(null),[xt,He]=a.useState(!0),[Je,Dn]=a.useState(or),[vi,_t]=a.useState(!1),{agentsMap:La}=oi(i),be=a.useMemo(()=>Sn.size>0?Sn:La,[La,Sn]),{models:In,favoriteProviders:bi,favoriteModels:xi,defaultProvider:Pa,defaultModelId:Fa}=ri(),zt=a.useMemo(()=>({provider:Pa,modelId:Fa}),[Fa,Pa]),wi=a.useMemo(()=>y?.kind==="model"?{provider:y.modelProvider,modelId:y.modelId}:zt,[y,zt]),{skills:Ln,loading:yi}=Po(i),[Ze,Ue]=a.useState(!1),[wt,yt]=a.useState(""),[et,Ke]=a.useState(0),[tt,nt]=a.useState(""),[Me,at]=a.useState(!1),[Bt,Ot]=a.useState(0),[Pn,st]=a.useState(-1),[ge,Ht]=a.useState([]),[$a,it]=a.useState(!1),[_a,Ut]=a.useState(!1),[ot,za]=a.useState({}),[Kt,Ne]=a.useState(!1),[Wt,Ct]=a.useState(!1),{pushNav:Ba}=vo(),[,Vt]=a.useState(!1),[Ci,ki]=a.useState({top:0,left:0}),V=Jo({projectId:i}),Fn=a.useCallback(e=>{if(!e||!V.mentionActive)return;const n=e.getBoundingClientRect();ki({top:n.top-260,left:n.left+8})},[V.mentionActive]),Oa=a.useRef(null),Ha=a.useRef(null),Ua=a.useRef(null),Ka=a.useRef(null),le=a.useRef(!1),Xt=a.useRef(null),Wa=a.useRef(null),Pe=a.useRef(null),qt=a.useRef(0),$n=a.useRef(null),kt=a.useRef(null),Re=a.useRef(null),re=a.useRef(null),_n=a.useRef(null),rt=a.useRef(null),[zn,Si]=a.useState(()=>new Set),Gt=a.useRef(!1),je=a.useRef(null),Ae=a.useRef(null),Z=a.useRef(null),Qt=a.useRef(null),Va=a.useRef(void 0),Bn=a.useRef(!1),Yt=a.useRef(null),Xa=a.useRef([]),ct=a.useRef(0),St=a.useRef(new Map),On=a.useRef(!1),Jt=bo(),We=Jt==="mobile",Hn=Jt==="tablet",qa=a.useRef(null),[Mi,Ga]=a.useState(!1);a.useLayoutEffect(()=>{if(!h){Ga(!1);return}const e=qa.current;if(!e||typeof ResizeObserver>"u")return;const n=()=>{Ga(e.getBoundingClientRect().width<=768)};n();const o=new ResizeObserver(n);return o.observe(e),()=>o.disconnect()},[h]);const H=We||Mi||p;a.useEffect(()=>{l?.id&&de("direct",l.id,l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,de]),a.useEffect(()=>{w.activeRoom?.id&&de("room",w.activeRoom.id,w.activeRoom.updatedAt)},[w.activeRoom?.id,w.activeRoom?.updatedAt,de]),a.useEffect(()=>{if(!l?.id||$.length===0)return;const e=$[$.length-1];de("direct",l.id,e?.createdAt??l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,de,$]),a.useEffect(()=>{if(!w.activeRoom?.id||w.messages.length===0)return;const e=w.messages[w.messages.length-1];de("room",w.activeRoom.id,e?.createdAt??w.activeRoom.updatedAt)},[de,w.activeRoom?.id,w.activeRoom?.updatedAt,w.messages]),a.useEffect(()=>{try{const e=localStorage.getItem(Js);if(!e)return;const n=Number.parseInt(e,10);if(Number.isNaN(n))return;const o=Math.max(vn,Math.min(bn,n));Dn(o)}catch{}},[]),a.useEffect(()=>{try{const e=localStorage.getItem(xa);if(e==="direct"){Qe("direct");return}e==="rooms"&&Oe&&Qe("rooms")}catch{}},[Oe]),a.useEffect(()=>{try{localStorage.setItem(xa,F)}catch{}},[Oe,F]);const ue=ei(F,F==="rooms"?w.activeRoom?.id:l?.id),Un=a.useRef(ue),Kn=a.useRef(!1);a.useEffect(()=>{if(ue!==Un.current){if(Un.current=ue,Kn.current){Kn.current=!1;return}oe(ti(ue))}},[ue]),a.useEffect(()=>{if(!(!ue||Un.current!==ue))try{if(q){localStorage.setItem(ue,q);return}localStorage.removeItem(ue)}catch{}},[ue,q]);const te=F==="rooms"&&!!w.activeRoom,{keyboardOverlap:Qa,keyboardOpen:Zt}=xo({enabled:(H||Hn)&&(!!l||te),allowNonMobileViewport:Hn}),Mt=Hn&&Zt,en=a.useMemo(()=>{const e=wt.trim().toLowerCase();return(e?Ln.filter(o=>o.name.toLowerCase().includes(e)):Ln).slice(0,10)},[Ln,wt]),Wn=a.useMemo(()=>b?wo(wt,zs):[],[b,wt]),xe=a.useMemo(()=>{const e=Wn.map(o=>({kind:"command",command:o,disabled:!b?.agentRunning})),n=en.map(o=>({kind:"skill",skill:o}));return[...e,...n]},[Wn,en,b]),lt=a.useMemo(()=>Array.from(be.values()),[be]),Te=a.useMemo(()=>F!=="rooms"||!w.activeRoom?null:{roomId:w.activeRoom.id,roomName:w.activeRoom.name,memberIds:new Set(w.activeRoomMembers.map(e=>e.agentId))},[Oe,F,w.activeRoom,w.activeRoomMembers]),Ve=a.useMemo(()=>{const e=lt.filter(d=>mi(d.name,tt));if(!Te)return e;const n=e.filter(d=>Te.memberIds.has(d.id));if(tt.trim().length===0)return n;const o=e.filter(d=>!Te.memberIds.has(d.id));return[...n,...o]},[lt,tt,Te]),Vn=a.useMemo(()=>{const e=new Map;for(const n of lt)e.set(n.name.toLowerCase(),n);return e},[lt]),Ni=a.useMemo(()=>en.map(e=>e.id).join("\0"),[en]);a.useEffect(()=>{Ke(0)},[Ni]),a.useEffect(()=>{Ot(0)},[tt,Me]),a.useEffect(()=>()=>{Re.current!==null&&window.clearTimeout(Re.current)},[]),a.useEffect(()=>{const e=Ha.current;if(!e||!kn||U)return;const n=new IntersectionObserver(o=>{o[0].isIntersecting&&Na()},{threshold:.1});return n.observe(e),()=>n.disconnect()},[kn,U,Na]);const dt=a.useCallback(()=>te?w.activeRoom?.id??null:l?.id??null,[te,w.activeRoom?.id,l?.id]),Ya=a.useCallback((e,n)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(n)}"]`):e.querySelector(`.chat-message[data-message-id="${n.replace(/"/g,'\\"')}"]`),[]),Ja=a.useCallback(()=>{const e=re.current;if(!e)return;const n=e.getBoundingClientRect().top,o=new Set;e.querySelectorAll(".chat-message--assistant:not(.chat-message--failure)[data-message-id]").forEach(d=>{const x=d.getAttribute("data-message-id");x&&d.getBoundingClientRect().top<n&&o.add(x)}),Si(d=>d.size===o.size&&Array.from(d).every(x=>o.has(x))?d:o)},[]),tn=a.useCallback(()=>{!re.current||rt.current!==null||(rt.current=window.requestAnimationFrame(()=>{rt.current=null,Ja()}))},[Ja]),nn=a.useCallback(()=>{const e=re.current,n=dt();if(!e||!n)return;const o=e.scrollTop,d=e.querySelectorAll(".chat-message[data-message-id]"),x=Array.from(d).find(K=>K.offsetTop+K.offsetHeight>=o)??d[0]??null,z=x?.getAttribute("data-message-id")??null,X=x?x.offsetTop-o:0;kt.current={threadId:n,scrollTop:o,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:z,anchorOffset:X,wasPinnedBefore:!le.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[dt]),Za=a.useCallback(()=>{const e=re.current;if(!e)return;const o=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Ut(!o),le.current=!o,nn(),tn()},[nn,tn]),Ee=a.useCallback((e,n)=>{if(!e.isConnected||!n?.force&&le.current)return;let o=0,d=0,x=-1;const z=6,X=()=>{if(e.isConnected&&!(!n?.force&&le.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===x?d+=1:(d=0,x=e.scrollHeight),o+=1,o>=z||d>=2){Ut(!1),le.current=!1;return}window.requestAnimationFrame(X)}};X()},[]),ut=te?w.messages:$;a.useLayoutEffect(()=>(tn(),()=>{rt.current!==null&&(window.cancelAnimationFrame(rt.current),rt.current=null)}),[ut,tn]),a.useLayoutEffect(()=>{const e=re.current,n=dt(),o=kt.current;if(!e||!n||!o||o.threadId!==n||o.wasPinnedBefore)return;const d=(typeof performance<"u"?performance.now():Date.now())-o.capturedAtMs,x=e.scrollHeight>e.clientHeight,z=d>3e3,X=o.scrollTop<=0&&o.anchorOffset<=0&&x;if(!le.current||z||X){kt.current=null;return}let K=o.scrollTop;if(o.anchorMessageId){const pe=Ya(e,o.anchorMessageId);pe?K=pe.offsetTop-o.anchorOffset:K=o.scrollTop+(e.scrollHeight-o.scrollHeight)}else K=o.scrollTop+(e.scrollHeight-o.scrollHeight);e.scrollTop=Math.max(0,K),le.current=!0,Ut(!0),kt.current=null},[ut,dt,Ya]);const Xn=a.useCallback(e=>{},[ut.length,te]),we=a.useCallback(e=>{Xn(e);const n=re.current;n&&(kt.current=null,le.current=!1,Ee(n))},[Ee,Xn]);a.useLayoutEffect(()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null);const e=te?w.activeRoom?.id??null:l?.id??null;if(!e){Xt.current=null;return}const n={threadId:e,loaded:te?!w.messagesLoading:!U,hasMessages:te?w.messages.length>0:$.length>0},o=Xt.current,d=o?.threadId!==e,x=o?.threadId===e&&!o.loaded&&n.loaded,z=o?.threadId===e&&!o.hasMessages&&n.hasMessages;if(!(o===null||d||x||z))return;const K=re.current;if(K)return Xn(d?"thread-change":x?"finished-loading":z?"first-messages":"mount"),Ee(K,{force:!0}),te||(Pe.current=window.setTimeout(()=>{if(Pe.current=null,le.current)return;const pe=re.current;pe&&Ee(pe)},250)),Xt.current=n,()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null)}},[te,w.activeRoom?.id,w.messages.length,w.messagesLoading,l?.id,$.length,U,Ee]),a.useEffect(()=>{!B||le.current||we("streaming")},[B,j,Y,we]),a.useEffect(()=>{const e=dt();if(!e){qt.current=0,$n.current=null;return}if($n.current!==e){$n.current=e,qt.current=ut.length;return}const n=qt.current,o=ut.length,d=o>n,x=!le.current;qt.current=o,d&&x&&we("new-message")},[ut,dt,we]),a.useEffect(()=>{Qa<=0||!re.current||we("keyboard")},[Qa,we]),yo(We&&Zt),a.useLayoutEffect(()=>{if(!We||!l&&!te||typeof window>"u")return;const e=_n.current,n=window.visualViewport;if(!e||!n)return;const o=x=>{if(!(x instanceof HTMLElement))return!1;if(x.tagName==="TEXTAREA")return!0;if(x.tagName!=="INPUT")return!1;const z=x.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(z)},d=()=>{if(Gt.current){e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange="";return}const x=Math.max(0,window.innerHeight-n.offsetTop-n.height),z=n.offsetTop||0;e.style.setProperty("--vv-height",`${n.height}px`),e.style.setProperty("--vv-offset-top",`${z}px`),e.style.setProperty("--keyboard-overlap",`${x}px`);const X=(x>0||z>0)&&o(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",X),e.style.setProperty("--chat-keyboard-accessory-clearance",X&&ga()?"calc(var(--space-2xl) + var(--space-md))":"0px"),X&&z>0?(e.style.transform=`translateY(${z}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return d(),n.addEventListener("resize",d),n.addEventListener("scroll",d),document.addEventListener("focusin",d),document.addEventListener("focusout",d),window.addEventListener("pageshow",d),document.addEventListener("visibilitychange",d),()=>{n.removeEventListener("resize",d),n.removeEventListener("scroll",d),document.removeEventListener("focusin",d),document.removeEventListener("focusout",d),window.removeEventListener("pageshow",d),document.removeEventListener("visibilitychange",d),e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange=""}},[l,We,te]),a.useEffect(()=>{const e=()=>Se(null);if(G)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[G]),a.useEffect(()=>{if(!We||!Zt)return;const e=n=>{n.target?.closest(".chat-messages")||n.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[We,Zt]),a.useEffect(()=>{const e=Wa.current;if(Wa.current=F,F==="rooms"&&!w.activeRoom){Xt.current=null;return}if(!(F==="direct"&&(e===null||e==="rooms"))&&!(F==="rooms"&&(e===null||e==="direct")))return;const d=re.current;d&&(Ee(d,{force:!0}),le.current=!1,Ut(!1))},[F,w.activeRoom,Ee]),a.useEffect(()=>{if(!l&&!te||te&&!H)return;const e=()=>{const o=!le.current;nn(),o&&H&&re.current&&we("visibility-restore")},n=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pageshow",e)}},[H,We,l,te,nn,we]),a.useEffect(()=>{if(te||typeof ResizeObserver>"u")return;const e=re.current;if(!e)return;const n=new ResizeObserver(()=>{le.current||Ee(e)});return n.observe(e),()=>{n.disconnect()}},[te,Ee,l?.id,F]),a.useEffect(()=>{Xa.current=ge},[ge]),a.useEffect(()=>()=>{for(const e of Xa.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of St.current.values())window.clearTimeout(e);St.current.clear()},[]);const mt=a.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const o of Array.from(e)){if(!cr.includes(o.type))continue;const d=o.type.startsWith("image/");n.push({file:o,previewUrl:d?URL.createObjectURL(o):""})}n.length>0&&Ht(o=>[...o,...n])},[]),es=a.useCallback(e=>{Ht(n=>{const o=n[e];return o?.previewUrl&&URL.revokeObjectURL(o.previewUrl),n.filter((d,x)=>x!==e)})},[]),ts=a.useCallback(e=>{mt(e.clipboardData?.files)},[mt]),ht=a.useCallback(async e=>{try{return await E(e),Mn(!1),H&&He(!1),!0}catch{return r(s("chat.failedToCreateSession","Failed to create chat session"),"error"),!1}},[E,r,H,s]),an=a.useCallback(()=>{if(v?.chatNewSessionMode==="always-default"&&y){if(y.kind==="agent"){ht({agentId:y.agentId});return}ht({agentId:Ce,modelProvider:y.modelProvider,modelId:y.modelId,thinkingLevel:y.thinkingLevel});return}Mn(!0)},[y,v?.chatNewSessionMode,ht]),ne=a.useCallback(e=>{const n=e??Z.current;if(!n)return;const o=Jt==="tablet"?er:Ma;n.style.height="auto",n.style.height=`${sr(n.scrollHeight,o)}px`,n.style.overflowY=ar(n.scrollHeight,o)},[Jt]),Ri=As({textareaRef:Z,value:q,onChange:oe,onResize:()=>ne(Z.current),projectId:i}),ji=As({textareaRef:Qt,value:q,onChange:oe,onResize:()=>ne(Qt.current),projectId:i}),Ai=a.useCallback(e=>{Z.current=e,e&&ne(e)},[ne]),Ti=a.useCallback(e=>{Qt.current=e,e&&ne(e)},[ne]);a.useLayoutEffect(()=>{ne(F==="rooms"?Qt.current:Z.current),Bn.current&&(Bn.current=!1,Z.current?.focus())},[F,q,l?.id,w.activeRoom?.id,ne]),a.useEffect(()=>{if(D===void 0||D===Va.current||!I?.trim())return;Va.current=D;const e=n=>{n&&(Kn.current=!0),Qe("direct"),Bn.current=!0,oe(I)};if(!B&&v?.chatNewSessionMode==="always-default"&&y){const n=y.kind==="agent"?{agentId:y.agentId}:{agentId:Ce,modelProvider:y.modelProvider,modelId:y.modelId,thinkingLevel:y.thinkingLevel};ht(n).then(o=>e(o||F!=="direct"));return}e(F!=="direct")},[y,F,v?.chatNewSessionMode,ht,I,D,B,ne]);const ft=a.useCallback(()=>{if(oe(""),ue)try{localStorage.removeItem(ue)}catch{}Ue(!1),yt(""),at(!1),nt(""),st(-1),Ht(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[ue]),Xe=a.useCallback(e=>{Ht(n=>{const o=n.filter(d=>e.has(d.file));for(const d of o)d.previewUrl&&URL.revokeObjectURL(d.previewUrl);return n.filter(d=>!e.has(d.file))})},[]),qn=a.useCallback(()=>{const e=q.trim(),n=ge.map(d=>d.file);if(!e&&n.length===0||!l)return;if(b){const d=Co(e,zs);if(d){if(!b.agentRunning){r(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}if(n.length>0){r(s("chat.commandNoAttachments","Attachments aren't supported with commands — remove them before sending"),"warning");return}ft(),d.command.run({taskId:b.taskId,projectId:b.projectId,remainder:d.remainder}).then(()=>{r(s("chat.commandSteerSuccess","Sent to the running agent"),"success")}).catch(x=>{const z=x instanceof Error&&x.message.trim()?x.message:s("chat.commandSteerFailed","Failed to send to the running agent");r(z,"error")});return}}if(e==="/clear"||e==="/new"){if(n.length>0){r(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}if(l.agentId.startsWith(ko)){ft(),r(s("chat.newNotAllowedForTaskChat","This chat is tied to a task — /new and /clear can't clear it"),"warning");return}ft(),Cn(),fe(),E({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0,thinkingLevel:l.thinkingLevel??void 0}).catch(()=>{r(s("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}if(B&&n.length>0){r(s("chat.attachmentsNotQueued","Attachments can't be queued while a reply is streaming — wait for it to finish"),"warning");return}const o=new Set(n);oe("");try{ie(e,n,{onAccepted:()=>Xe(o),onDelivered:()=>Xe(o),onFailed:()=>{oe(d=>d||e)}})}catch{oe(e)}},[q,ge,l,ft,fe,Cn,E,r,ie,b,B,Xe,s]),Gn=a.useCallback(async()=>{const e=q.trim(),n=ge.map(o=>o.file);if(!(!e&&n.length===0)){if(F==="rooms"){if(!w.activeRoom)return;if(e==="/clear"||e==="/new"){if(n.length>0){r(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}ft();try{await w.clearRoom(w.activeRoom.id)}catch{r(s("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(On.current)return;On.current=!0;const o=q,d=new Set(n);oe("");try{await w.sendRoomMessage(e,{files:n,onDelivered:()=>Xe(d)}),Xe(d)}catch(x){if(x instanceof di){Xe(d);const X=x.message.trim()?x.message:s("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");r(s("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:X}),"error");return}oe(o);const z=x instanceof Error&&x.message.trim()?x.message:s("chat.failedToSendRoomMessage","Failed to send room message");r(z,"error")}finally{On.current=!1}return}qn()}},[q,ge,Oe,F,w,w.clearRoom,ft,r,qn,Xe]),sn=a.useCallback(async e=>{if(F==="rooms"){if(!w.activeRoom)return;try{await w.sendRoomMessage(e)}catch(n){const o=n instanceof Error&&n.message.trim()?n.message:s("chat.failedToSendRoomMessage","Failed to send room message");r(o,"error")}return}l&&ie(e)},[l,r,Oe,F,w,ie,s]),Qn=a.useCallback(e=>{oe(n=>{const o=wa(n);if(!o)return n;const d=`/skill:${e.name} `,x=n.slice(0,o.start)+d+n.slice(o.end);return window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus())}),x}),Ue(!1),yt(""),Ke(0)},[ne]),Yn=a.useCallback((e,n)=>{if(n){r(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}oe(o=>{const d=wa(o);if(!d)return o;const x=`${e.trigger} `,z=o.slice(0,d.start)+x+o.slice(d.end);return window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus())}),z}),Ue(!1),yt(""),Ke(0)},[ne,r,s]),on=a.useCallback(e=>{const n=Z.current;if(!n||Pn<0)return;const o=n.selectionStart??ct.current,d=n.selectionEnd??o,x=Math.max(o,d),z=Math.min(Pn,x),K=`${`@${e.name.replace(/\s+/g,"_")}`} `,pe=q.slice(0,z)+K+q.slice(x),gt=z+K.length;oe(pe),at(!1),nt(""),Ot(0),st(-1),window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus(),Z.current.setSelectionRange(gt,gt))})},[Pn,q,ne]),Nt=a.useCallback((e,n)=>{const d=Z.current?.selectionStart??ct.current,x=q.lastIndexOf("#",d),z=x>=0?x+n.length:e.length;oe(e),V.dismissMention(),Vt(!1),window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus(),Z.current.setSelectionRange(z,z))})},[V,q,ne]),ns=a.useCallback(e=>{if(ct.current=e.currentTarget.selectionStart??ct.current,V.mentionActive&&V.combinedItems.length>0){if(V.handleKeyDown(e,q),e.key==="Enter"||e.key==="Tab"){const n=V.combinedItems[V.selectedIndex];n?.kind==="task"?Nt(V.selectTask(n.task,q),`#${n.task.id}`):n?.kind==="file"&&Nt(V.selectFile(n.file,q),`#${n.file.path}`)}return}if(Me&&e.key==="ArrowDown"){e.preventDefault(),Ve.length>0&&Ot(n=>(n+1)%Ve.length);return}if(Me&&e.key==="ArrowUp"){e.preventDefault(),Ve.length>0&&Ot(n=>n===0?Ve.length-1:n-1);return}if(Me&&e.key==="Enter"){e.preventDefault();const n=Ve[Bt]??Ve[0];n&&on(n);return}if(Me&&e.key==="Escape"){e.preventDefault(),at(!1),nt(""),st(-1);return}if(Ze&&e.key==="ArrowDown"){e.preventDefault(),xe.length>0&&Ke(n=>(n+1)%xe.length);return}if(Ze&&e.key==="ArrowUp"){e.preventDefault(),xe.length>0&&Ke(n=>n===0?xe.length-1:n-1);return}if(Ze&&(e.key==="Enter"||e.key==="Tab")&&xe.length>0){e.preventDefault();const n=xe[et]??xe[0];n?.kind==="skill"?Qn(n.skill):n?.kind==="command"&&Yn(n.command,n.disabled);return}if(Ze&&e.key==="Escape"){e.preventDefault(),Ue(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Gn())},[Me,Ve,Bt,on,Ze,xe,et,Qn,Yn,Gn,V,Nt,q]),rn=a.useCallback((e,n)=>{const o=lr(e,n);if(o){at(!0),nt(o.filter),st(o.start);return}at(!1),nt(""),st(-1)},[]),as=a.useCallback(e=>{const n=e.target,o=n.value,d=n.selectionStart??o.length;ne(n),ct.current=d,oe(o);const x=wa(o);x?(Ue(!0),yt(x.filter)):(Ue(!1),yt("")),rn(o,d),V.detectMention(o,d),Vt(V.mentionActive),V.mentionActive&&Fn(n)},[rn,ne]),cn=a.useCallback(e=>{const n=e.currentTarget,o=n.selectionStart??n.value.length;ct.current=o,rn(n.value,o),V.detectMention(n.value,o),Vt(V.mentionActive),V.mentionActive&&Fn(n)},[rn,V,Fn]),ss=a.useCallback(e=>{e.key!=="Escape"&&cn(e)},[cn]),is=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(Gt.current=!0,je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{Gt.current=!1,je.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),Ae.current!==null&&window.clearTimeout(Ae.current),Ae.current=window.setTimeout(()=>{Ae.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Re.current!==null&&window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{Ue(!1),at(!1),nt(""),st(-1),Vt(!1),V.dismissMention(),Re.current=null},120)},[V]),os=a.useCallback(()=>{Gt.current=!1,je.current!==null&&(window.clearTimeout(je.current),je.current=null),Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},[]);a.useEffect(()=>()=>{je.current!==null&&window.clearTimeout(je.current),Ae.current!==null&&window.clearTimeout(Ae.current)},[]);const rs=a.useCallback(async e=>{Se(null);try{await O(e),r(s("chat.conversationArchived","Conversation archived"),"success")}catch{r(s("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[O,r]),Ei=a.useCallback(async e=>{try{await ce(e),r(s("chat.conversationRestored","Conversation restored"),"success")}catch{r(s("chat.failedToRestoreConversation","Failed to restore conversation"),"error")}},[ce,r,s]),cs=a.useCallback(e=>{const n=Be.find(o=>o.id===e)??(l?.id===e?l:null);Se(null),Ne(!1),jn(n?.title??""),Lt({sessionId:e,title:n?.title??""})},[l,Be]),ls=a.useCallback(async()=>{if(It)try{await ae(It.sessionId,Rn),Lt(null),jn(""),r(s("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[r,It,ae,Rn,s]),ds=a.useCallback(async(e,n)=>{Se(null),Ne(!1);try{await me(e,n),r(n?s("chat.conversationPinned","Conversation pinned"):s("chat.conversationUnpinned","Conversation unpinned"),"success")}catch{}},[r,me,s]),Di=a.useCallback(async e=>{Pt(null),Se(null);try{await u(e),r(s("chat.conversationDeleted","Conversation deleted"),"success")}catch{r(s("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[u,r]),Rt=a.useCallback(e=>{try{localStorage.setItem(Js,String(e))}catch{}},[]),Ii=a.useCallback(e=>{if(H||Mt)return;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;typeof n.setPointerCapture=="function"&&n.setPointerCapture(e.pointerId);const o=e.clientX,d=Je;let x=d;document.body.style.userSelect="none";const z=K=>{const pe=K.clientX-o,gt=Math.max(vn,Math.min(bn,d+pe));x=gt,Dn(gt),Rt(gt)},X=K=>{typeof n.releasePointerCapture=="function"&&n.releasePointerCapture(K.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",X),Rt(x)};document.addEventListener("pointermove",z),document.addEventListener("pointerup",X)},[H,Rt,Je,Mt]),Li=a.useCallback(e=>{if(H||Mt||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const n=e.shiftKey?50:10,o=e.key==="ArrowLeft"?-n:n,d=Math.max(vn,Math.min(bn,Je+o));Dn(d),Rt(d)},[H,Rt,Je,Mt]),us=a.useCallback(e=>{const n=Be.find(o=>o.id===e);de("direct",e,n?.lastMessageAt??n?.updatedAt),J(e),Ne(!1),H&&He(!1)},[Be,H,de,J]),Jn=a.useCallback(()=>{J(""),He(!0),Ne(!1)},[J]),Zn=a.useCallback(()=>{w.selectRoom(null),He(!0),Ne(!1)},[w]),Pi=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(xn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:s("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:an,children:[t.jsx(pt,{size:16}),s("chat.newChat","New Chat")]})]}),De=ai(l,l?.agentId?be.get(l.agentId)??null:null,zt),ea=a.useMemo(()=>{if(!De?.provider||!De.modelId)return null;const e=In.find(n=>n.provider===De.provider&&n.id===De.modelId);return e?.contextWindow?e.contextWindow:null},[De?.modelId,De?.provider,In]),Fi=a.useMemo(()=>Zo($,B?j:void 0),[B,$,j]),Fe=Ts(De?.provider,De?.modelId),qe=De?.provider??null,ta=!!(l||B||$.length>0),ln=H&&!xt&&(F==="rooms"?te:ta),dn=H?ln:F==="rooms"?te:!!l,ms=a.useRef(dn);a.useEffect(()=>{const e=ms.current;ms.current=dn,H&&(e||!dn||Ba({type:"view",revert:F==="rooms"?Zn:Jn}))},[F,Jn,Zn,dn,H,Ba]);const hs=l?.agentId===Ce?Fe??"Fusion":l?.title||be.get(l?.agentId??"")?.name||l?.agentId||"Chat",$i=l?.title||s("chat.untitledSession","Untitled"),_i=!!(Fe&&Fe!==hs),zi=!H&&ta&&ea!==null,fs=Qs(Fi),un=ea!==null?Qs(ea):null,na=un?s("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:fs,total:un}):null,Bi=ln&&F==="direct"&&!!l,gs=ln&&F==="direct",ps=ln&&F==="rooms",aa=be.get(l?.agentId??"")?.name||(l?.agentId===Ce?Fe??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),sa=!1,ia=l?.agentId===Ce,Oi=e=>e.length>50?`${e.slice(0,50)}…`:e;a.useEffect(()=>{if(!Kt)return;const e=n=>{Ua.current?.contains(n.target)||Ne(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Kt]),a.useEffect(()=>{if(!Wt)return;const e=o=>{Ka.current?.contains(o.target)||Ct(!1)},n=o=>{o.key==="Escape"&&Ct(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",n)}},[Wt]),a.useEffect(()=>{(!H||F!=="direct"||xt)&&Ne(!1)},[H,F,xt]),a.useEffect(()=>{Ct(!1)},[w.activeRoom?.id]);const vs=a.useCallback((e,n)=>{const o=St.current.get(e);o&&window.clearTimeout(o),za(x=>({...x,[e]:n}));const d=window.setTimeout(()=>{za(x=>{const{[e]:z,...X}=x;return X}),St.current.delete(e)},2e3);St.current.set(e,d)},[]),bs=a.useCallback(async(e,n)=>{const o=await So(n);vs(e,o?"success":"error")},[vs]),oa=l?.agentId===Ce,ra=a.useCallback((e,n,o,d,x=!0)=>{const z=oa&&o==="assistant",X=x&&o==="assistant"&&k?Mo(n,s("chat.reportFallbackTitle","Chat report")):null;if(!(!z&&!X?.handoff))return t.jsxs(t.Fragment,{children:[z&&t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${ot[e]==="success"?" chat-message-copy-action--success":""}${ot[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":d??`chat-copy-response-${e}`,"aria-label":ot[e]==="success"?s("chat.responseCopied","Response copied"):ot[e]==="error"?s("chat.copyFailed","Copy failed"):s("chat.copyResponse","Copy response"),onClick:()=>{bs(e,n)},children:ot[e]==="success"?t.jsx(No,{size:14}):t.jsx(Ro,{size:14})}),X?.handoff&&t.jsx("button",{type:"button",className:"btn-icon","data-testid":`chat-send-as-report-${e}`,"aria-label":s("chat.sendAsReport","Send as report"),onClick:()=>{X.truncated&&r(s("chat.reportTrimmed","Message trimmed to 2000 characters for mail"),"warning"),k?.(X.handoff)},children:t.jsx(jo,{size:14})})]})},[r,ot,bs,k,oa,s]),ca=a.useCallback(e=>{const n=re.current;if(!n)return;const o=`[data-testid="chat-message-${e}"]`,d=n.querySelector(o);if(!d)return;const x=d.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,z=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:x,behavior:z?"auto":"smooth"})},[]),xs=l?.cliExecutorAdapterId??null,la=!!xs,Hi=xs==="generic"?"generic":"hybrid",Ui=l?.cliSessionFile||l?.id||"",ws=!la&&!B,ys=()=>t.jsxs("div",{className:"chat-messages",ref:re,onScroll:Za,children:[t.jsx("div",{ref:Ha,className:"chat-load-more-sentinel",children:kn&&U&&t.jsx("div",{className:"chat-loading-older",children:s("chat.loadingOlderMessages","Loading older messages…")})}),B?t.jsxs(t.Fragment,{children:[$.map((e,n)=>t.jsx(fa,{message:e,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,activeSessionId:l?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:null,copyAction:ra(e.id,e.content,e.role),onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===$.length-1&&!B,submittedQuestionAnswer:Zs($,n),onQuestionSubmit:sn,canEdit:ws,onEditMessage:Le},e.id)),t.jsx(Lo,{streamingText:j,streamingThinking:Y,streamingToolCalls:se,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,copyAction:oa&&j?ra("__streaming__",j,"assistant","chat-copy-response-streaming",!1):void 0,onQuestionSubmit:sn})]}):U?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):$.length===0&&!l?Pi():$.length===0&&l?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsx(t.Fragment,{children:$.map((e,n)=>t.jsx(fa,{message:e,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,activeSessionId:l?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:null,copyAction:ra(e.id,e.content,e.role),onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===$.length-1&&!B,submittedQuestionAnswer:Zs($,n),onQuestionSubmit:sn,canEdit:ws,onEditMessage:Le},e.id))}),t.jsx("div",{ref:Oa})]}),Cs=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file","data-testid":"chat-file-input",accept:ni,multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),Ze&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":s("chat.skillSuggestions","Skill suggestions"),children:yi&&Wn.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:s("chat.loadingSkills","Loading skills…")}):xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:wt?s("chat.noSkillsFound","No skills found"):s("chat.noSkillsAvailable","No skills available")}):xe.map((e,n)=>e.kind==="command"?t.jsxs("button",{type:"button",role:"option","aria-selected":n===et,"aria-disabled":e.disabled,className:`chat-skill-menu-item chat-command-menu-item${n===et?" chat-skill-menu-item--highlighted":""}${e.disabled?" chat-command-menu-item--disabled":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Ke(n),onClick:()=>Yn(e.command,e.disabled),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.command.trigger}),t.jsx("span",{className:"chat-skill-menu-item-description",children:e.disabled?s("chat.commandNoRunningAgentHint","No running agent to steer"):e.command.description})]},`command-${e.command.trigger}`):t.jsxs("button",{type:"button",role:"option","aria-selected":n===et,className:`chat-skill-menu-item${n===et?" chat-skill-menu-item--highlighted":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Ke(n),onClick:()=>Qn(e.skill),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.skill.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.skill.relativePath,children:e.skill.relativePath})]},e.skill.id))}),ge.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ge.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),ze.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:ze.map((e,n)=>t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:s("chat.queuedMessage","Queued: {{preview}}",{preview:Oi(e)})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":s("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${n}`,onClick:()=>Cn(n),children:"×"})]},`${n}-${e}`))}),t.jsx("div",{className:"chat-pending-divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":s("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Fs,{size:16})}),!la&&t.jsx(Ks,{level:l?.thinkingLevel,defaultThinkingLevel:N,models:In,favoriteProviders:bi,favoriteModels:xi,agents:Array.from(be.values()),agentId:l?.agentId,modelProvider:l?.modelProvider,modelId:l?.modelId,onChange:e=>{l&&g(l.id,e)},onChangeModel:e=>{l&&S(l.id,e)},disabled:!l}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),it(!0)},onDragLeave:()=>it(!1),onDrop:e=>{e.preventDefault(),it(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ai,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:cn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ga()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Vs,{agents:lt,filter:tt,highlightedIndex:Bt,visible:Me,onSelect:on,position:"below",roomMemberIds:Te?.memberIds,roomName:Te?.roomName}),t.jsx(Wo,{visible:V.mentionActive&&!Me,position:Ci,tasks:V.tasks,files:V.files,selectedIndex:V.selectedIndex,onSelectTask:e=>{Nt(V.selectTask(e,q),`#${e.id}`)},onSelectFile:e=>{Nt(V.selectFile(e,q),`#${e.path}`)},loading:V.loading})]}),t.jsx($s,{...Ri.micProps}),t.jsx(_s,{isStreaming:B,canSend:!!(q.trim()||ge.length>0),onSend:qn,onStop:fe})]})]}),Ki=H?void 0:{width:`${Je}px`},ks=Ye?R:Be,Ss=ks.filter(e=>e.pinnedAt!=null),Ms=ks.filter(e=>e.pinnedAt==null),ye=G?Be.find(e=>e.id===G.sessionId)??(l?.id===G.sessionId?l:void 0):void 0,Ns=a.useCallback(async()=>{const e=An.trim();if(!e)return;let n;try{n=await ve(e)}catch{r(s("chat.failedToCreateTag","Failed to create tag"),"error");return}if(G?.sessionId){const o=(ye?.tags??[]).map(d=>d.id);if(!o.includes(n.id))try{await ke(G.sessionId,[...o,n.id])}catch{r(s("chat.failedToUpdateTags","Failed to update tags"),"error");return}}Ea("")},[r,G,ye,ve,An,ke,s]),Wi=Bi?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Ua,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":Kt,onClick:()=>Ne(e=>!e),children:[qe?t.jsx(ua,{provider:qe,size:"md"}):t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:$i}),t.jsx(hn,{size:16,"aria-hidden":"true"})]}),Kt&&t.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[[{id:"pinned",label:s("chat.pinned","Pinned"),testId:"chat-mobile-pinned-divider",sessions:Ss},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-mobile-recent-divider",sessions:Ms}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-mobile-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>t.jsxs("div",{className:`chat-mobile-session-option-row${l?.id===n.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${l?.id===n.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${n.id}`,onClick:()=>us(n.id),children:t.jsxs("span",{className:"chat-mobile-session-option-title",children:[n.title||s("chat.untitledSession","Untitled"),n.pinnedAt?t.jsx(fn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null]})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-pin","data-testid":`chat-mobile-session-pin-${n.id}`,"aria-label":n.pinnedAt?s("chat.unpinConversationAria","Unpin conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}):s("chat.pinConversationAria","Pin conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}),title:!n.pinnedAt&&c>=3?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:!n.pinnedAt&&c>=3,onClick:()=>ds(n.id,!n.pinnedAt),children:n.pinnedAt?t.jsx(Es,{size:14}):t.jsx(fn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-archive","data-testid":`chat-mobile-session-archive-${n.id}`,"aria-label":s("chat.archive","Archive"),onClick:()=>void rs(n.id),children:t.jsx(Ds,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${n.id}`,"aria-label":s("chat.renameConversationAria","Rename conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}),onClick:()=>cs(n.id),children:t.jsx(ma,{size:14})})]},n.id))]},e.id)),t.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Ne(!1),an()},children:[t.jsx(pt,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.newChat","New Chat")})]})]})]}):null,Vi=t.jsxs("div",{className:"chat-sidebar-scope-toggle chat-view-header-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${F==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":F==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>Qe("direct"),children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeDirect","Direct")})]}),t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${F==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":F==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>Qe("rooms"),children:[t.jsx(li,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:qa,className:`chat-view${h?" chat-view--floating":""}${H?" chat-view--narrow":""}${gs?" chat-view--mobile-direct-thread":""}`,children:[t.jsx(Ao,{icon:xn,title:s("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[gs?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn-icon chat-back-btn",onClick:Jn,"data-testid":"chat-back-btn","aria-label":s("chat.backToConversations","Back to conversations"),children:t.jsx(Is,{size:16})}),Wi]}):Vi,H?null:t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:an,"data-testid":"chat-new-btn",children:[t.jsx(pt,{size:14}),s("chat.newChat","New Chat")]}),!h&&m?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:m,"aria-label":s("chat.popOut","Pop out chat"),title:s("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:t.jsx(Ls,{size:16})}):null,h&&f?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:f,"aria-label":s("chat.maximizeToChatView","Open in Chat view"),title:s("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:t.jsx(Ls,{size:16})}):null,h&&M?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:M,"aria-label":s("chat.minimizeToQuickChat","Minimize to quick chat"),title:s("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:t.jsx(To,{size:16})}):null,h&&C?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:C,"aria-label":s("chat.closeChat","Close chat"),title:s("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(Ps,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${xt?"":" chat-sidebar--hidden"}`,style:Ki,children:[F==="direct"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-sidebar-search-container",children:[t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(Eo,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:s("chat.searchConversations","Search conversations..."),value:hi,onChange:e=>fi(e.target.value),"data-testid":"chat-search-input"})]}),t.jsxs("label",{className:"chat-tag-filter",htmlFor:"chat-tag-filter",children:[t.jsx(_o,{size:14,"aria-hidden":"true"}),t.jsxs("select",{id:"chat-tag-filter",value:L??"",onChange:e=>W(e.target.value||null),"data-testid":"chat-tag-filter","aria-label":s("chat.filterByTag","Filter conversations by tag"),children:[t.jsx("option",{value:"",children:s("chat.allTags","All tags")}),T.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),L?t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.clearTagFilter","Clear tag filter"),onClick:()=>W(null),children:t.jsx(Ps,{size:14})}):null]})]}),t.jsx("div",{className:"chat-archived-toggle",children:t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":"chat-archived-toggle",onClick:()=>{const e=!Ye;pi(e),e&&_()},children:Ye?"Active conversations":"Archived conversations"})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:P?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.loadingConversations","Loading...")}):(Ye?R:Be).length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.noConversationsYet","No conversations yet")}):t.jsx(t.Fragment,{children:[{id:"pinned",label:s("chat.pinned","Pinned"),testId:"chat-pinned-divider",sessions:Ss},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-recent-divider",sessions:Ms}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>{const o=l?.id===n.id,d=!o&&Ra("direct",n.id,n.lastMessageAt??n.updatedAt),x=ai(n,be.get(n.agentId)??null,zt),z=Ts(x?.provider,x?.modelId)??"Fusion",X=n.title||s("chat.untitledSession","Untitled");return t.jsxs("div",{className:`chat-session-item${o?" chat-session-item--active":""}`,onClick:()=>us(n.id),onContextMenu:K=>{K.preventDefault(),ja(n.id,K.clientX,K.clientY)},"data-testid":Ye?`chat-archived-session-${n.id}`:`chat-session-${n.id}`,children:[t.jsx("button",{type:"button",className:"btn-icon chat-session-menu-btn","data-testid":"chat-session-menu-btn","aria-label":s("chat.conversationActionsAria","Conversation actions for {{title}}",{title:X}),"aria-haspopup":"menu","aria-expanded":G?.sessionId===n.id,onClick:K=>{if(K.stopPropagation(),G?.sessionId===n.id){Se(null);return}const pe=K.currentTarget.getBoundingClientRect();ja(n.id,pe.right,pe.bottom,{anchorRight:!0})},children:t.jsx(Do,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[X,n.pinnedAt?t.jsx(fn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null,d?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${n.id}`,"aria-label":s("chat.unreadMessages","Unread messages")}):null]}),t.jsx("div",{className:"chat-session-preview",children:n.lastMessagePreview||s("chat.noMessages","No messages")}),(n.tags??[]).length>0?t.jsx("div",{className:"chat-session-tags","data-testid":`chat-session-tags-${n.id}`,children:(n.tags??[]).map(K=>t.jsx("span",{className:"chat-session-tag",children:K.name},K.id))}):null,n.matchedMessagePreview?t.jsx("div",{className:"chat-session-preview chat-session-preview--matched","data-testid":`chat-session-matched-preview-${n.id}`,children:s("chat.matchedInMessage",'Matched: "{{preview}}"',{preview:n.matchedMessagePreview})}):null,Ye?t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":`chat-archived-restore-${n.id}`,onClick:K=>{K.stopPropagation(),Ei(n.id)},children:"Restore"}):null,t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[x?.provider?t.jsx(ua,{provider:x.provider,size:"sm"}):null,t.jsx("span",{children:be.get(n.agentId)?.name||(n.agentId===Ce?z:n.agentId.slice(0,30))})]}),t.jsx("span",{children:n.updatedAt?ir(n.updatedAt,s):""})]})]},n.id)})]},e.id))})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!H&&t.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>_t(!0),children:[t.jsx(pt,{size:14}),s("chat.createRoom","Create room")]})}),w.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:s("chat.noRoomsYet","No rooms yet.")}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:w.rooms.map(e=>{const n=w.activeRoom?.id===e.id,o=!n&&Ra("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${n?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{de("room",e.id,e.updatedAt),w.selectRoom(e.id),H&&He(!1)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),de("room",e.id,e.updatedAt),w.selectRoom(e.id),H&&He(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name-row",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":s("chat.unreadMessages","Unread messages")}):null]}),n?t.jsx("span",{className:"chat-room-item-meta",children:s("chat.roomMemberCount","{{count}} member",{count:w.activeRoomMembers.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":s("chat.deleteRoom","Delete room {{name}}",{name:e.name}),onClick:d=>{d.stopPropagation(),Ft(e.id)},children:t.jsx(ha,{size:14})})]},e.id)})})]}),F==="rooms"?H?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>_t(!0),children:[t.jsx(pt,{size:14}),s("chat.createRoom","Create room")]})}):null:H?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:an,"data-testid":"chat-new-btn",children:[t.jsx(pt,{size:14}),s("chat.newChat","New Chat")]})}):null]}),!H&&xt&&!Mt&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":vn,"aria-valuemax":bn,"aria-valuenow":Je,"aria-label":s("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Ii,onKeyDown:Li}),G&&t.jsxs("div",{className:"chat-session-context-menu",ref:Nn,role:"menu",style:{top:G.y,left:G.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>ds(G.sessionId,!ye?.pinnedAt),"data-testid":"chat-context-pin",title:c>=3&&!ye?.pinnedAt?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:c>=3&&!ye?.pinnedAt,children:[ye?.pinnedAt?t.jsx(Es,{size:14}):t.jsx(fn,{size:14}),ye?.pinnedAt?s("chat.unpin","Unpin"):s("chat.pin","Pin")]}),t.jsxs("button",{onClick:()=>cs(G.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(ma,{size:14}),s("chat.rename","Rename")]}),t.jsxs("div",{className:"chat-session-tag-menu",role:"group","aria-label":s("chat.conversationTags","Conversation tags"),children:[T.map(e=>{const n=(ye?.tags??[]).some(o=>o.id===e.id);return t.jsxs("div",{className:"chat-tag-menu-item",children:[t.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,"data-testid":`chat-context-tag-${e.id}`,onClick:()=>void ke(G.sessionId,n?(ye?.tags??[]).filter(o=>o.id!==e.id).map(o=>o.id):[...(ye?.tags??[]).map(o=>o.id),e.id]).catch(()=>r(s("chat.failedToUpdateTags","Failed to update tags"),"error")),children:[n?"✓ ":"",e.name]}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.renameTag","Rename tag {{name}}",{name:e.name}),"data-testid":`chat-context-rename-tag-${e.id}`,onClick:o=>{o.stopPropagation(),Da(e.name),bt(e)},children:t.jsx(ma,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.deleteTag","Delete tag {{name}}",{name:e.name}),"data-testid":`chat-context-delete-tag-${e.id}`,onClick:o=>{o.stopPropagation(),$t(e)},children:t.jsx(ha,{size:14})})]},e.id)}),t.jsxs("div",{className:"chat-tag-create-row",children:[t.jsx("input",{className:"input",value:An,placeholder:s("chat.newTag","New tag"),"aria-label":s("chat.newTag","New tag"),onChange:e=>Ea(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ns())}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Ns(),children:s("chat.addTag","Add")})]})]}),t.jsxs("button",{onClick:()=>rs(G.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Ds,{size:14}),s("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{Se(null),Pt(G.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(ha,{size:14}),s("chat.delete","Delete")]})]}),It&&t.jsx(Et,{onClose:()=>Lt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-dialog-title",children:s("chat.renameConversationTitle","Rename Conversation")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.renameConversationBody","Choose a new name for this conversation. Leave it blank to show Untitled.")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-input",children:s("chat.conversationName","Conversation name")}),t.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Rn,placeholder:s("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>jn(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),ls())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Lt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void ls(),"data-testid":"chat-rename-save",children:s("chat.save","Save")})]})]})}),Tn&&t.jsx(Et,{onClose:()=>bt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-tag-dialog-title",children:s("chat.renameTagTitle","Rename tag")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-tag-input",children:s("chat.tagName","Tag name")}),t.jsx("input",{id:"chat-rename-tag-input",className:"input chat-rename-input",value:En,"data-testid":"chat-rename-tag-input",onChange:e=>Da(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),ee(Tn.id,En).then(()=>bt(null)).catch(()=>r(s("chat.failedToRenameTag","Failed to rename tag"),"error")))},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>bt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary","data-testid":"chat-rename-tag-save",onClick:()=>void ee(Tn.id,En).then(()=>bt(null)).catch(()=>r(s("chat.failedToRenameTag","Failed to rename tag"),"error")),children:s("chat.save","Save")})]})]})}),Ia&&t.jsx(Et,{onClose:()=>$t(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-delete-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-delete-tag-dialog-title",children:s("chat.deleteTagTitle","Delete tag?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteTagBody","This removes the tag from all conversations, but does not delete conversations.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>$t(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger","data-testid":"chat-delete-tag-confirm",onClick:()=>void he(Ia.id).then(()=>$t(null)).catch(()=>r(s("chat.failedToDeleteTag","Failed to delete tag"),"error")),children:s("chat.delete","Delete")})]})]})}),Aa&&t.jsx(Et,{onClose:()=>Pt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:s("chat.deleteConversationTitle","Delete Conversation?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteConversationBody","This action cannot be undone. All messages in this conversation will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Di(Aa),children:s("chat.delete","Delete")})]})]})}),Ta&&t.jsx(Et,{onClose:()=>Ft(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:s("chat.deleteRoomTitle","Delete Room?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteRoomBody","This action cannot be undone. This room and all its messages will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Ft(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await w.deleteRoom(Ta),Ft(null)}catch{r(s("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:s("chat.delete","Delete")})]})]})}),F==="rooms"?t.jsxs("div",{ref:_n,className:"chat-thread",children:[w.activeRoom?t.jsxs(t.Fragment,{children:[(!H||ps)&&t.jsxs("div",{className:"chat-room-thread-header",children:[ps&&t.jsx("button",{className:"btn-icon",onClick:Zn,"data-testid":"chat-back-btn",children:t.jsx(Is,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:Ka,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":Wt,onClick:()=>Ct(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",w.activeRoom.name]}),t.jsx(hn,{size:16,"aria-hidden":"true"})]}),Wt&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:w.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===w.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{de("room",e.id,e.updatedAt),w.selectRoom(e.id),Ct(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:w.activeRoomMembers.map(e=>t.jsx(yn,{agent:be.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:re,onScroll:Za,children:[w.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):w.messages.filter(e=>e.content.trim()!==Ys).length===0?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):w.messages.filter(e=>e.content.trim()!==Ys).map(e=>{const n=e.senderAgentId?be.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):s("chat.you","You"),o={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(fa,{message:o,forcePlain:!1,agentName:n,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:w.activeRoom?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:Te,onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:!1,onQuestionSubmit:sn},e.id)}),t.jsx("div",{ref:Oa})]}),w.activeRoom&&_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(hn,{size:14}),s("chat.latest","Latest")]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:s("chat.selectRoomOrCreate","Select a room or create one")}),w.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file",accept:ni,multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),ge.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ge.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":s("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Fs,{size:16})}),t.jsx(Ks,{level:w.activeRoom.thinkingLevel,defaultThinkingLevel:N,showTargetSection:!1,onChange:e=>{w.updateRoomSettings(w.activeRoom.id,{thinkingLevel:e||null}).catch(()=>{r(s("chat.failedToUpdateRoomThinkingLevel","Failed to update room thinking effort"),"error")})}}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),it(!0)},onDragLeave:()=>it(!1),onDrop:e=>{e.preventDefault(),it(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ti,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:cn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ga()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Vs,{agents:lt,filter:tt,highlightedIndex:Bt,visible:Me,onSelect:on,position:"below",roomMemberIds:Te?.memberIds,roomName:Te?.roomName})]}),t.jsx($s,{...ji.micProps}),t.jsx(_s,{isStreaming:!1,canSend:!!(q.trim()||ge.length>0),onSend:Gn})]})]})]}):t.jsxs("div",{ref:_n,className:"chat-thread",children:[!H&&(ta||!H)&&t.jsx("div",{className:"chat-thread-header",children:t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[qe?t.jsx(ua,{provider:qe,size:"md"}):t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:hs}),_i&&t.jsx("span",{className:"chat-model-tag",children:Fe}),zi&&un&&na?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:na,"aria-label":na,children:[fs," / ",un]}):null]})}),la?t.jsx(qo,{cliSessionId:Ui,tier:Hi,projectId:i,renderTranscript:ys,renderComposer:()=>l?Cs():null}):t.jsxs(t.Fragment,{children:[ys(),_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(hn,{size:14}),s("chat.latest","Latest")]}),l&&Cs()]})]}),t.jsx(Xo,{isOpen:vi,onClose:()=>_t(!1),projectId:i,existingRoomNames:w.rooms.map(e=>e.name),onCreate:async e=>{await w.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),F!=="rooms"&&Qe("rooms"),_t(!1),H&&He(!1)}})]}),gi&&t.jsx(ur,{projectId:i,defaultModel:wi,defaultKind:y?.kind,defaultAgentId:y?.kind==="agent"?y.agentId:void 0,defaultThinkingLevel:N,defaultSelectedThinkingLevel:y?.kind==="model"?y.thinkingLevel:void 0,onClose:()=>Mn(!1),onCreate:ht})]})}export{Cr as ChatView,yr as buildIssueChatPrefill,sr as clampChatInputHeight,nr as resolveChatContextMenuPosition,ar as resolveChatInputOverflowY,ai as resolveSessionProvider};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{U as a,C as n}from"./mermaid.core-5yPje9Bi.js";const t=(r,o)=>a.lang.round(n.parse(r)[o]);export{t as c};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as a,c as s,a as t,C as e}from"./chunk-727SXJPM-DScQBCvv.js";import{_ as i}from"./mermaid.core-5yPje9Bi.js";import"./vendor-reactflow-BlIeoTu4.js";import"./chunk-FMBD7UC4-DvYKea1c.js";import"./chunk-ND2GUHAM-CH-Tvw7w.js";import"./chunk-55IACEB6-CPUwbbGa.js";import"./chunk-2J33WTMH-BKYToL43.js";import"./index-DpCHwyiD.js";import"./vendor-react-SZ_qB27O.js";import"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-xterm-BNq00GSj.js";import"./step-yuy0qJer.js";var k={parser:t,get db(){return new e},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{k as diagram};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as a,c as s,a as t,C as e}from"./chunk-727SXJPM-DScQBCvv.js";import{_ as i}from"./mermaid.core-5yPje9Bi.js";import"./vendor-reactflow-BlIeoTu4.js";import"./chunk-FMBD7UC4-DvYKea1c.js";import"./chunk-ND2GUHAM-CH-Tvw7w.js";import"./chunk-55IACEB6-CPUwbbGa.js";import"./chunk-2J33WTMH-BKYToL43.js";import"./index-DpCHwyiD.js";import"./vendor-react-SZ_qB27O.js";import"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-xterm-BNq00GSj.js";import"./step-yuy0qJer.js";var k={parser:t,get db(){return new e},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{k as diagram};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e,j as H}from"./vendor-react-SZ_qB27O.js";import{e9 as vt,ea as Xt,dy as Yt,dA as _t,dz as jt}from"./index-DpCHwyiD.js";import{Z as $t,a as Gt,M as Wt,R as Ft}from"./zoom-out-DzDzWQt1.js";import"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./createLucideIcon-CshVyKO4.js";const xt=4,wt=300,Lt=24;function Ut({taskId:n,position:i,scale:r,canDrag:a,onPositionChange:f,onDragStateChange:u,onDragEnd:y,onDoubleTap:b}){const[I,z]=e.useState(!1),M=e.useRef(null),C=e.useRef(i),X=e.useRef(!1),o=e.useRef(null),c=e.useRef(!1);C.current=i,c.current=I;const d=e.useCallback(()=>{o.current=null},[]),T=e.useCallback(l=>{M.current=null,z(!1),c.current=!1,l&&(u?.(!1),y?.(),X.current=!0,d())},[y,u,d]),E=e.useCallback(l=>{if(!l.isPrimary)return;if(l.defaultPrevented){d();return}const P=Date.now();o.current&&P-o.current.timeStamp>wt&&d(),a&&l.stopPropagation();const x=l.currentTarget;a&&typeof x.setPointerCapture=="function"&&x.setPointerCapture(l.pointerId),M.current={pointerId:l.pointerId,pointerType:l.pointerType,startPointer:{x:l.clientX,y:l.clientY},startPosition:C.current,defaultPrevented:l.defaultPrevented,movedBeyondThreshold:!1}},[a,d]),A=e.useCallback(l=>{const P=M.current;if(!P||P.pointerId!==l.pointerId)return;a&&l.stopPropagation();const x=l.clientX-P.startPointer.x,U=l.clientY-P.startPointer.y,O=Math.hypot(x,U);if(O>=xt&&(P.movedBeyondThreshold=!0),!a){P.movedBeyondThreshold&&d();return}if(!c.current&&O>=xt&&(z(!0),c.current=!0,u?.(!0),d()),O<xt)return;const V=r>0?r:1;f(n,{x:P.startPosition.x+x/V,y:P.startPosition.y+U/V})},[a,u,f,d,r,n]),G=e.useCallback((l,P)=>{if(!b||P.defaultPrevented||P.movedBeyondThreshold)return Date.now()-(o.current?.timeStamp??0)>wt&&d(),!1;if(P.pointerType==="mouse")return d(),!1;const x={timeStamp:Date.now(),point:{x:P.startPointer.x,y:P.startPointer.y}},U=o.current;return!U||x.timeStamp-U.timeStamp>wt||Math.hypot(x.point.x-U.point.x,x.point.y-U.point.y)>Lt?(o.current=x,!1):(X.current=!0,d(),b(),!0)},[b,d]),Z=e.useCallback(l=>{const P=M.current;if(!P||P.pointerId!==l.pointerId)return;a&&l.stopPropagation(),a&&typeof l.currentTarget.hasPointerCapture=="function"&&l.currentTarget.hasPointerCapture(l.pointerId)&&typeof l.currentTarget.releasePointerCapture=="function"&&l.currentTarget.releasePointerCapture(l.pointerId);const x=c.current;!x&&G(l,P)&&l.preventDefault(),T(x)},[a,T,G]),W=e.useCallback(l=>{const P=M.current;!P||P.pointerId!==l.pointerId||(a&&l.stopPropagation(),a&&typeof l.currentTarget.hasPointerCapture=="function"&&l.currentTarget.hasPointerCapture(l.pointerId)&&typeof l.currentTarget.releasePointerCapture=="function"&&l.currentTarget.releasePointerCapture(l.pointerId),d(),T(c.current))},[a,T,d]),$=e.useCallback(l=>{X.current&&(X.current=!1,l.preventDefault(),l.stopPropagation())},[]);return e.useMemo(()=>({isDragging:I,onPointerDown:E,onPointerMove:A,onPointerUp:Z,onPointerCancel:W,onClickCapture:$}),[I,$,W,E,A,Z])}const Bt=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function Zt(n){return n?n.charAt(0).toUpperCase()+n.slice(1):"Executing"}function Kt({taskColumnFlags:n,style:i,position:r,scale:a,isSelected:f=!1,isHighlighted:u=!1,isDimmed:y=!1,onMouseEnter:b,onMouseLeave:I,onClick:z,onNodePositionChange:M,onNodeDragStateChange:C,onNodeDragEnd:X,...o}){const{task:c,globalPaused:d,taskStuckTimeoutMs:T,lastFetchTimeMs:E,onOpenDetail:A}=o,G=c.status==="failed",Z=c.paused===!0,W=vt(c,T,E,n),$=c.column==="in-progress"||Bt.has(c.status),l=c.status==="awaiting-approval"&&!$,P=!d&&!G&&!Z&&!W&&!l&&$,x=typeof c.currentStep=="number"&&c.currentStep>=0&&Array.isArray(c.steps)&&c.currentStep<c.steps.length,U=c.column==="in-review",O=Ut({taskId:c.id,position:r,scale:a,canDrag:f,onPositionChange:M,onDragStateChange:C,onDragEnd:X,onDoubleTap:()=>A(c)});return H.jsxs("div",{className:`graph-task-node${f?" graph-node--draggable graph-task-node--selected":""}${O.isDragging?" graph-node--dragging":""}${u?" graph-task-node--highlighted graph-node--highlighted":""}${y?" graph-task-node--dimmed graph-node--dimmed":""}${P?" graph-task-node--active":""}${U?" graph-task-node--in-review":""}`,style:i,draggable:!1,"data-testid":`graph-task-node-${c.id}`,"data-current-step":P&&x?String(c.currentStep):void 0,onMouseEnter:b,onMouseLeave:I,onClick:z,onDoubleClick:V=>{V.defaultPrevented||A(c)},onClickCapture:O.onClickCapture,onPointerDown:O.onPointerDown,onPointerMove:O.onPointerMove,onPointerUp:O.onPointerUp,onPointerCancel:O.onPointerCancel,children:[P?H.jsx("div",{className:"graph-task-active-indicator",children:H.jsx("span",{className:"graph-task-active-indicator-text",children:Zt(c.status)})}):null,H.jsx(Xt,{...o,taskColumnFlags:n,onOpenDetail:()=>{},disableDrag:!0})]})}function Vt({zoom:n,onZoomIn:i,onZoomOut:r,onFitToGraph:a,onResetView:f}){return H.jsxs("div",{className:"graph-toolbar","data-testid":"graph-toolbar",children:[H.jsx("button",{className:"btn btn-icon",title:"Zoom in (Ctrl+=)","aria-label":"Zoom in",onClick:i,children:H.jsx($t,{size:16})}),H.jsx("button",{className:"btn btn-icon",title:"Zoom out (Ctrl+-)","aria-label":"Zoom out",onClick:r,children:H.jsx(Gt,{size:16})}),H.jsxs("div",{className:"graph-toolbar__zoom-label","aria-live":"polite",children:[Math.round(n*100),"%"]}),H.jsx("button",{className:"btn btn-icon",title:"Fit to graph (Ctrl+Shift+F)","aria-label":"Fit to graph",onClick:a,children:H.jsx(Wt,{size:16})}),H.jsx("button",{className:"btn btn-icon",title:"Reset view (Ctrl+0)","aria-label":"Reset view",onClick:f,children:H.jsx(Ft,{size:16})})]})}const qt=280,Jt=100;function Qt({edges:n,positions:i,nodeWidth:r=qt,nodeHeight:a=Jt,nodeHeights:f,highlightedEdgeIds:u}){const y=!!(u&&u.size>0);return H.jsxs("svg",{className:"dependency-graph-edges","aria-hidden":"true",children:[H.jsx("defs",{children:H.jsx("marker",{id:"dependency-graph-arrowhead",markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",markerUnits:"strokeWidth",children:H.jsx("path",{d:"M 0 0 L 10 3.5 L 0 7 z",style:{fill:"var(--border)"}})})}),n.map(b=>{const I=i.get(b.source),z=i.get(b.target);if(!I||!z)return null;const M=`${b.source}->${b.target}`,C=y&&(u?.has(M)??!1),X=I.x+r/2,o=I.y+(f?.get(b.source)??a),c=z.x+r/2,d=z.y,T=o+(d-o)/2;return H.jsx("path",{"data-testid":"dependency-edge","data-edge-id":M,className:`dependency-graph-edge${C?" graph-edge--highlighted":""}${y&&!C?" graph-edge--dimmed":""}`,d:`M ${X} ${o} C ${X} ${T}, ${c} ${T}, ${c} ${d}`,fill:"none",markerEnd:"url(#dependency-graph-arrowhead)",style:{opacity:y&&!C?.15:1,stroke:C?"var(--todo)":"var(--border)",strokeWidth:C?"var(--space-xs)":"var(--btn-border-width)",transition:"opacity var(--transition-fast), stroke var(--transition-fast), stroke-width var(--transition-fast)"}},M)})]})}const te=new Set(["done","archived"]);function ee(n){return n.filter(i=>typeof i.column=="string"&&i.column.length>0&&!te.has(i.column))}const ne={nodeWidth:280,nodeHeight:100,horizontalGap:40,verticalGap:80,orientation:"vertical"};function kt(n,i){const r={...ne,...i},a=n.nodes.map(o=>o.task.id);if(a.length===0)return new Map;const f=new Map,u=new Map;for(const o of a)u.set(o,0),f.set(o,[]);for(const o of n.edges)!u.has(o.source)||!u.has(o.target)||(f.get(o.target)?.push(o.source),u.set(o.source,(u.get(o.source)??0)+1));const y=a.filter(o=>(u.get(o)??0)===0),b=[];for(;y.length>0;){const o=y.shift();b.push(o);for(const c of f.get(o)??[]){const d=(u.get(c)??0)-1;u.set(c,d),d===0&&y.push(c)}}for(const o of a)b.includes(o)||b.push(o);const I=new Map;for(const o of b){const c=n.edges.filter(T=>T.source===o).map(T=>T.target);let d=0;for(const T of c)d=Math.max(d,(I.get(T)??0)+1);I.set(o,d)}const z=new Map;for(const o of a){const c=I.get(o)??0,d=z.get(c)??[];d.push(o),z.set(c,d)}const M=new Map,C=Array.from(z.keys()).sort((o,c)=>o-c),X=new Map;if(r.orientation==="vertical"){let o=0;for(const c of C){X.set(c,o);const d=z.get(c)??[],T=Math.max(r.nodeHeight,...d.map(E=>r.measuredHeights?.get(E)??r.nodeHeight));o+=T+r.verticalGap}}for(const o of C){const c=z.get(o)??[];if(c.sort(),r.orientation==="horizontal"){const G=-(c.reduce(($,l)=>$+(r.measuredHeights?.get(l)??r.nodeHeight),0)+Math.max(0,c.length-1)*r.verticalGap)/2,Z=o*(r.nodeWidth+r.horizontalGap);let W=G;for(const $ of c)M.set($,{x:Z,y:W}),W+=(r.measuredHeights?.get($)??r.nodeHeight)+r.verticalGap;continue}const E=-(c.length*r.nodeWidth+Math.max(0,c.length-1)*r.horizontalGap)/2;c.forEach((A,G)=>{const Z=E+G*(r.nodeWidth+r.horizontalGap),W=X.get(o)??o*(r.nodeHeight+r.verticalGap);M.set(A,{x:Z,y:W})})}return M}function re(n){return e.useMemo(()=>{const i=n.map(f=>({task:f})),r=new Set(n.map(f=>f.id)),a=n.flatMap(f=>(f.dependencies??[]).filter(u=>r.has(u)).map(u=>({source:f.id,target:u})));return{nodes:i,edges:a}},[n])}const ut=.1,lt=3,Dt=40,oe=200;function nt(n,i,r){return Math.min(r,Math.max(i,n))}function se(n){if(!(n instanceof HTMLElement))return!1;const i=n.tagName.toLowerCase();return n.isContentEditable||i==="input"||i==="textarea"||i==="select"}function ie(){const[n,i]=e.useState({x:0,y:0}),[r,a]=e.useState(1),[f,u]=e.useState(!1),y=e.useRef(n),b=e.useRef(r),I=e.useRef(null),z=e.useRef(null),M=e.useRef(new Map),C=e.useRef(null),X=e.useRef({minX:0,minY:0,maxX:0,maxY:0});e.useEffect(()=>{y.current=n},[n]),e.useEffect(()=>{b.current=r},[r]),e.useEffect(()=>()=>{I.current!==null&&window.clearTimeout(I.current)},[]);const o=e.useMemo(()=>`translate(${n.x}px, ${n.y}px) scale(${r})`,[n.x,n.y,r]),c=e.useMemo(()=>Math.round(r*100),[r]),d=e.useCallback(s=>{if(!s){I.current!==null&&(window.clearTimeout(I.current),I.current=null),u(!1);return}u(!0),I.current!==null&&window.clearTimeout(I.current),I.current=window.setTimeout(()=>{u(!1),I.current=null},oe)},[]),T=e.useCallback((s,p,w,k=b.current)=>{const S=X.current;if(S.maxX<=S.minX||S.maxY<=S.minY)return{x:nt(s.x,-p,p),y:nt(s.y,-w,w)};const Y=p-S.maxX*k,v=-S.minX*k,_=w-S.maxY*k,B=-S.minY*k,ot=Y>v?(Y+v)/2:nt(s.x,Y,v),J=_>B?(_+B)/2:nt(s.y,_,B);return{x:ot,y:J}},[]),E=e.useCallback((s,p,w,k)=>{const S=b.current,Y=y.current,v=nt(s,ut,lt),_=v/S,B=T({x:p.x-(p.x-Y.x)*_,y:p.y-(p.y-Y.y)*_},w,k,v);a(v),i(B)},[T]),A=e.useCallback((s,p,w,k)=>{d(!1);const S=k??{x:p/2,y:w/2};E(b.current*s,S,p,w)},[d,E]),G=e.useCallback((s,p)=>{if(s&&p){A(1.2,s,p);return}a(w=>nt(w+.1,ut,lt))},[A]),Z=e.useCallback((s,p)=>{if(s&&p){A(1/1.2,s,p);return}a(w=>nt(w-.1,ut,lt))},[A]),W=e.useCallback(()=>{d(!0),i({x:0,y:0}),a(1)},[d]),$=e.useCallback((s,p,w,k)=>{if(d(!0),s.size===0){i({x:0,y:0}),a(1);return}const S=k?.nodeWidth??280,Y=k?.nodeHeight??100,v=Array.from(s.entries()),_=Math.min(...v.map(([,et])=>et.x)),B=Math.min(...v.map(([,et])=>et.y)),ot=Math.max(...v.map(([,et])=>et.x+S)),J=Math.max(...v.map(([et,mt])=>mt.y+(k?.measuredHeights?.get(et)??Y))),F=Math.max(1,ot-_),Q=Math.max(1,J-B),tt=Math.max(1,p-Dt*2),ht=Math.max(1,w-Dt*2),st=nt(Math.min(tt/F,ht/Q),ut,lt),dt=(p-F*st)/2-_*st,pt=(w-Q*st)/2-B*st;a(st),i(T({x:dt,y:pt},p,w,st))},[T,d]),l=e.useCallback((s,p)=>{if(M.current.set(s,p),M.current.size===2){const[w,k]=Array.from(M.current.values());C.current={distance:Math.hypot(w.x-k.x,w.y-k.y),zoom:b.current,pan:y.current,midpoint:{x:(w.x+k.x)/2,y:(w.y+k.y)/2}},z.current=null;return}z.current={start:p,panStart:y.current}},[]),P=e.useCallback((s,p,w,k)=>{if(M.current.has(s)&&M.current.set(s,p),M.current.size===2&&C.current){d(!1);const[v,_]=Array.from(M.current.values()),ot=Math.hypot(v.x-_.x,v.y-_.y)/Math.max(1,C.current.distance),J={x:(v.x+_.x)/2,y:(v.y+_.y)/2},F=nt(C.current.zoom*ot,ut,lt),Q=F/C.current.zoom,tt=T({x:J.x-(C.current.midpoint.x-C.current.pan.x)*Q,y:J.y-(C.current.midpoint.y-C.current.pan.y)*Q},w,k);a(F),i(tt);return}const S=z.current;if(!S)return;d(!1);const Y={x:S.panStart.x+(p.x-S.start.x),y:S.panStart.y+(p.y-S.start.y)};i(T(Y,w,k))},[T,d]),x=e.useCallback(s=>{if(M.current.delete(s),M.current.size<2&&(C.current=null),M.current.size===1){const[p]=Array.from(M.current.values());z.current={start:p,panStart:y.current};return}M.current.size===0&&(z.current=null)},[]),U=e.useCallback((s,p,w,k)=>{d(!1);const S={x:y.current.x-s,y:y.current.y-p};i(T(S,w,k))},[T,d]),O=e.useCallback((s,p,w,k)=>{const S=s<0?1.1:.9;d(!1),E(b.current*S,p,w,k)},[d,E]),V=e.useCallback(s=>{X.current=s},[]),q=e.useCallback((s,p,w,k,S)=>{if(se(s.target))return;const Y=s.metaKey||s.ctrlKey;if(s.key==="Escape"){s.preventDefault(),W();return}if(Y){if(s.key==="="||s.key==="+"){s.preventDefault(),A(1.2,p,w);return}if(s.key==="-"){s.preventDefault(),A(1/1.2,p,w);return}if(s.key==="0"){s.preventDefault(),W();return}(s.key==="f"||s.key==="F")&&s.shiftKey&&(s.preventDefault(),$(k,p,w,S))}},[$,W,A]);return{pan:n,zoom:r,zoomPercent:c,transform:o,transitioning:f,zoomIn:G,zoomOut:Z,resetView:W,fitToGraph:$,setAnimate:d,onPointerDown:l,onPointerMove:P,onPointerUp:x,onWheelPan:U,onWheelZoom:O,handleKeyDown:q,setGraphBounds:V}}function ae(n){const{upstreamMap:i,downstreamMap:r}=e.useMemo(()=>{const f=new Map,u=new Map;for(const y of n)f.set(y.id,new Set(y.dependencies??[])),u.has(y.id)||u.set(y.id,new Set);for(const y of n)for(const b of y.dependencies??[])u.has(b)||u.set(b,new Set),u.get(b)?.add(y.id);return{upstreamMap:f,downstreamMap:u}},[n]);return{getChain:e.useCallback(f=>{if(!i.has(f)&&!r.has(f))return new Set;const u=new Set([f]),y=(b,I)=>{const z=[b],M=new Set([b]);for(;z.length>0;){const C=z.shift();if(!C)continue;const X=I.get(C);if(X)for(const o of X)M.has(o)||(M.add(o),u.add(o),z.push(o))}};return y(f,i),y(f,r),u},[r,i])}}const Mt="fusion-plugin-dependency-graph:positions";function ft(n){if(!n||typeof n!="object")return!1;const i=n;return typeof i.x=="number"&&Number.isFinite(i.x)&&typeof i.y=="number"&&Number.isFinite(i.y)}function ce(n){const i=Yt(Mt,n);if(!i)return{};try{const r=JSON.parse(i);if(!r||typeof r!="object")return{};const a={};for(const[f,u]of Object.entries(r))ft(u)&&(a[f]=u);return a}catch{return{}}}function ue(n,i,r){const a={};for(const[f,u]of Object.entries(n))i.has(f)&&ft(u)&&(a[f]=u);_t(Mt,JSON.stringify(a),r)}function le(n){jt(Mt,n)}function de(n,i,r){const a={};for(const[f,u]of Object.entries(n))r.has(f)&&ft(u)&&(a[f]=u);for(const[f,u]of Object.entries(i))r.has(f)&&ft(u)&&(a[f]=u);return a}function fe(n,i){const r={};for(const[a,f]of Object.entries(n))i.has(a)&&(r[a]=f);return r}function he({projectId:n,visibleTaskIds:i}){const[r,a]=e.useState(null);e.useEffect(()=>{a(ce(n))},[n]);const f=e.useCallback(y=>{ue(y,i,n),a(fe(y,i))},[n,i]),u=e.useCallback(()=>{le(n),a(null)},[n]);return{savedPositions:r,persistPositions:f,clearSavedPositions:u}}const ct=280,rt=100,pe=768,Rt=4;function me({tasks:n,projectId:i,columnFlagsByTaskId:r,onOpenTaskDetail:a,onOpenDetail:f,addToast:u,globalPaused:y,onUpdateTask:b,onArchiveTask:I,onUnarchiveTask:z,onDeleteTask:M,onRetryTask:C,onOpenDetailWithTab:X,taskStuckTimeoutMs:o,onOpenMission:c,onMoveTask:d,lastFetchTimeMs:T}){const E=e.useRef(null),A=e.useRef(null),G=e.useRef(!1),Z=e.useRef(new Map),[W,$]=e.useState(null),[l,P]=e.useState(null),[x,U]=e.useState({width:0,height:0}),[O,V]=e.useState(new Map),q=e.useMemo(()=>ee(n),[n]),s=re(q),{getChain:p}=ae(q),w=W??l,k=e.useMemo(()=>w?p(w):new Set,[w,p]),S=e.useMemo(()=>{const t=x.width||(typeof window<"u"?window.innerWidth:0);return(x.height||(typeof window<"u"?window.innerHeight:0))>t||t<pe?"horizontal":"vertical"},[x.height,x.width]),Y=e.useMemo(()=>({nodeWidth:ct,nodeHeight:rt,horizontalGap:40,verticalGap:80,orientation:S,measuredHeights:O}),[O,S]),v=e.useMemo(()=>kt(s,Y),[s,Y]),_=e.useMemo(()=>new Set(q.map(t=>t.id)),[q]),{savedPositions:B,persistPositions:ot,clearSavedPositions:J}=he({projectId:i,visibleTaskIds:_}),[F,Q]=e.useState(v),[tt,ht]=e.useState(!1);e.useEffect(()=>{const t={};for(const[m,D]of v.entries())t[m]=D;const h=B?de(t,B,_):t;Q(new Map(Object.entries(h)))},[v,B,_]),e.useEffect(()=>{const t=E.current;if(!t)return;const h=(D,N)=>{U(g=>g.width===D&&g.height===N?g:{width:D,height:N})};if(typeof ResizeObserver>"u"){h(t.clientWidth||(typeof window<"u"?window.innerWidth:0),t.clientHeight||(typeof window<"u"?window.innerHeight:0));return}h(t.clientWidth,t.clientHeight);const m=new ResizeObserver(D=>{const N=D[0];N&&h(N.contentRect.width,N.contentRect.height)});return m.observe(t),()=>m.disconnect()},[]),e.useEffect(()=>{const t=E.current;if(!t)return;const h=new Set(s.nodes.map(g=>g.task.id)),m=new Map;for(const g of h){const R=t.querySelector(`[data-testid="graph-task-node-${g}"]`);R&&m.set(g,R)}Z.current=m,V(g=>{let R=!1;const j=new Map;for(const[K,at]of g.entries()){if(!h.has(K)){R=!0;continue}j.set(K,at)}return R?j:g});const D=(g,R)=>{V(j=>{const K=j.get(g);if(K!==void 0&&Math.abs(K-R)<1)return j;const at=new Map(j);return at.set(g,R),at})};for(const[g,R]of m.entries())D(g,R.offsetHeight||rt);if(typeof ResizeObserver>"u")return;const N=new ResizeObserver(g=>{for(const R of g){const j=R.target,K=Array.from(m.entries()).find(([,at])=>at===j)?.[0];K&&D(K,j.offsetHeight||rt)}});for(const g of m.values())N.observe(g);return()=>N.disconnect()},[s.nodes,F,x.height,x.width]);const{transform:st,zoom:dt,transitioning:pt,zoomIn:et,zoomOut:mt,resetView:It,fitToGraph:gt,onPointerDown:Ht,onPointerMove:zt,onPointerUp:bt,onWheelPan:Et,onWheelZoom:Ot,handleKeyDown:Nt,setGraphBounds:Pt}=ie(),L=e.useMemo(()=>{const t=Array.from(F.values());if(t.length===0)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};const h=Math.min(...t.map(g=>g.x)),m=Math.min(...t.map(g=>g.y)),D=Math.max(...t.map(g=>g.x+ct)),N=Math.max(...Array.from(F.entries()).map(([g,R])=>R.y+(O.get(g)??rt)));return{minX:h,minY:m,maxX:D,maxY:N,width:Math.max(0,D-h),height:Math.max(0,N-m)}},[O,F]),it=e.useMemo(()=>{if(F.size===0)return F;const t=new Map;for(const[h,m]of F.entries())t.set(h,{x:m.x-L.minX,y:m.y-L.minY});return t},[L.minX,L.minY,F]);e.useEffect(()=>{Pt({minX:0,minY:0,maxX:L.width,maxY:L.height})},[L.height,L.width,Pt]);const Tt=e.useMemo(()=>Array.from(it.keys()).sort().join("|"),[it]),yt=e.useMemo(()=>[Tt,x.width,x.height,L.width,L.height,Array.from(O.entries()).sort(([t],[h])=>t.localeCompare(h)).map(([t,h])=>`${t}:${Math.round(h)}`).join("|")].join("::"),[L.height,L.width,Tt,O,x.height,x.width]),Ct=e.useRef(null);e.useEffect(()=>{if(q.length===0||it.size===0)return;const t=E.current;if(!t)return;const h=t.clientWidth||x.width,m=t.clientHeight||x.height;if(h===0||m===0||Ct.current===yt)return;let D=0,N=0;const g=()=>{const R=E.current;if(!R)return;const j=R.clientWidth||x.width,K=R.clientHeight||x.height;j===0||K===0||(gt(it,j,K,{nodeWidth:ct,nodeHeight:rt,measuredHeights:O}),Ct.current=yt)};return typeof requestAnimationFrame=="function"?D=requestAnimationFrame(()=>{N=requestAnimationFrame(g)}):g(),()=>{D&&cancelAnimationFrame(D),N&&cancelAnimationFrame(N)}},[q.length,yt,gt,O,it,x.height,x.width]);const St=e.useCallback(()=>{J();const t=kt(s,Y);Q(t)},[J,s,Y]),At=e.useCallback(()=>{const t={};for(const[h,m]of F.entries())t[h]=m;ot(t)},[ot,F]);return H.jsxs("section",{className:"dependency-graph","data-testid":"dependency-graph",children:[H.jsx("div",{ref:E,className:"dependency-graph__viewport",onPointerDown:t=>{tt||(A.current={x:t.clientX,y:t.clientY},G.current=!1,Ht(t.pointerId,{x:t.clientX,y:t.clientY}))},onPointerMove:t=>{if(tt)return;const h=E.current;if(!h)return;const m=A.current;if(m){const D=Math.abs(t.clientX-m.x),N=Math.abs(t.clientY-m.y);(D>Rt||N>Rt)&&(G.current=!0)}zt(t.pointerId,{x:t.clientX,y:t.clientY},h.clientWidth,h.clientHeight)},onPointerUp:t=>{tt||bt(t.pointerId),A.current=null},onPointerCancel:t=>{tt||bt(t.pointerId),A.current=null,G.current=!1},onWheel:t=>{t.preventDefault();const h=E.current;if(h){if(t.ctrlKey||t.metaKey){const m=h.getBoundingClientRect();Ot(t.deltaY,{x:t.clientX-m.left,y:t.clientY-m.top},h.clientWidth,h.clientHeight);return}Et(t.deltaX,t.deltaY,h.clientWidth,h.clientHeight)}},onKeyDown:t=>{const h=E.current;h&&Nt(t,h.clientWidth,h.clientHeight,it,{nodeWidth:ct,nodeHeight:rt,measuredHeights:O})},tabIndex:0,onClick:()=>{G.current||tt||P(null)},children:q.length===0?H.jsx("div",{className:"dependency-graph__empty",children:"No active tasks to display in graph view."}):H.jsxs("div",{className:`graph-canvas-transform${pt?" graph-canvas-transform--animate":""}`,style:{transform:st,width:`${L.width}px`,height:`${L.height}px`},children:[H.jsx(Qt,{edges:s.edges,positions:it,nodeWidth:ct,nodeHeight:rt,nodeHeights:O,highlightedEdgeIds:k.size>0?new Set(s.edges.filter(t=>k.has(t.source)&&k.has(t.target)).map(t=>`${t.source}->${t.target}`)):void 0}),H.jsx("div",{className:"dependency-graph__nodes-layer",children:s.nodes.map(t=>{const h=it.get(t.task.id);return h?H.jsx(Kt,{task:t.task,projectId:i,taskColumnFlags:r?.get(t.task.id),isSelected:l===t.task.id,style:{minHeight:`${rt}px`,left:`${h.x}px`,top:`${h.y}px`},position:h,scale:dt,onNodePositionChange:(m,D)=>{Q(N=>{const g={x:D.x+L.minX,y:D.y+L.minY},R=N.get(m);if(R&&R.x===g.x&&R.y===g.y)return N;const j=new Map(N);return j.set(m,g),j})},onNodeDragStateChange:ht,onNodeDragEnd:At,isHighlighted:k.size>0&&k.has(t.task.id),isDimmed:k.size>0&&!k.has(t.task.id),onOpenDetail:f??(m=>a?.(m.id)),addToast:u??(()=>{}),globalPaused:y,onUpdateTask:b,onArchiveTask:I,onUnarchiveTask:z,onDeleteTask:M,onRetryTask:C,onOpenDetailWithTab:X,taskStuckTimeoutMs:o,onOpenMission:c,onMoveTask:d,lastFetchTimeMs:T,onMouseEnter:()=>$(t.task.id),onMouseLeave:()=>$(null),onClick:m=>{m.stopPropagation(),G.current=!1,P(D=>D===t.task.id?null:t.task.id)}},t.task.id):null})})]})}),H.jsx(Vt,{zoom:dt,onZoomIn:()=>{const t=E.current;t&&et(t.clientWidth,t.clientHeight)},onZoomOut:()=>{const t=E.current;t&&mt(t.clientWidth,t.clientHeight)},onFitToGraph:()=>{St();const t=E.current;if(!t)return;const h=kt(s,Y),m=new Map,D=Array.from(h.values()),N=D.length>0?Math.min(...D.map(R=>R.x)):0,g=D.length>0?Math.min(...D.map(R=>R.y)):0;for(const[R,j]of h.entries())m.set(R,{x:j.x-N,y:j.y-g});gt(m,t.clientWidth,t.clientHeight,{nodeWidth:ct,nodeHeight:rt,measuredHeights:O})},onResetView:()=>{St(),It()}})]})}function Te({context:n}){return e.createElement(me,{tasks:n?.tasks??[],projectId:n?.projectId,columnFlagsByTaskId:n?.columnFlagsByTaskId,onOpenDetail:n?.openTaskDetail})}export{me as DependencyGraph,Te as DependencyGraphDashboardView,Te as default};
|