gsd-pi 2.53.0-dev.a67436f → 2.54.0-dev.16631ca

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/cli.js +19 -19
  2. package/dist/headless-ui.d.ts +27 -1
  3. package/dist/headless-ui.js +203 -13
  4. package/dist/headless.js +60 -3
  5. package/dist/resources/extensions/bg-shell/bg-shell-lifecycle.js +2 -2
  6. package/dist/resources/extensions/bg-shell/utilities.js +34 -5
  7. package/dist/resources/extensions/gsd/auto/phases.js +10 -1
  8. package/dist/resources/extensions/gsd/auto-dispatch.js +1 -1
  9. package/dist/resources/extensions/gsd/auto-model-selection.js +17 -1
  10. package/dist/resources/extensions/gsd/auto-prompts.js +9 -0
  11. package/dist/resources/extensions/gsd/bootstrap/register-extension.js +18 -5
  12. package/dist/web/standalone/.next/BUILD_ID +1 -1
  13. package/dist/web/standalone/.next/app-path-routes-manifest.json +22 -22
  14. package/dist/web/standalone/.next/build-manifest.json +3 -3
  15. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  16. package/dist/web/standalone/.next/react-loadable-manifest.json +1 -1
  17. package/dist/web/standalone/.next/server/app/_global-error.html +2 -2
  18. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  19. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  20. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  21. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  22. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  23. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  24. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  25. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  26. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  27. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  28. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  29. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  30. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  31. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  32. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  33. package/dist/web/standalone/.next/server/app/api/projects/route.js +1 -1
  34. package/dist/web/standalone/.next/server/app/api/switch-root/route.js +1 -1
  35. package/dist/web/standalone/.next/server/app/index.html +1 -1
  36. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  37. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  38. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  39. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  40. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  41. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  42. package/dist/web/standalone/.next/server/app-paths-manifest.json +22 -22
  43. package/dist/web/standalone/.next/server/chunks/2229.js +1 -1
  44. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  45. package/dist/web/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  46. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  47. package/dist/web/standalone/.next/server/pages/500.html +2 -2
  48. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  49. package/dist/web/standalone/.next/static/chunks/4024.82f2e2a838908338.js +9 -0
  50. package/dist/web/standalone/.next/static/chunks/{webpack-bca0e732db0dcec3.js → webpack-70adf6e3be5479ce.js} +1 -1
  51. package/package.json +1 -1
  52. package/packages/pi-coding-agent/dist/core/model-registry.d.ts +1 -1
  53. package/packages/pi-coding-agent/dist/core/model-registry.d.ts.map +1 -1
  54. package/packages/pi-coding-agent/dist/core/model-registry.js.map +1 -1
  55. package/packages/pi-coding-agent/dist/modes/interactive/components/provider-manager.d.ts +2 -0
  56. package/packages/pi-coding-agent/dist/modes/interactive/components/provider-manager.d.ts.map +1 -1
  57. package/packages/pi-coding-agent/dist/modes/interactive/components/provider-manager.js +14 -2
  58. package/packages/pi-coding-agent/dist/modes/interactive/components/provider-manager.js.map +1 -1
  59. package/packages/pi-coding-agent/package.json +1 -1
  60. package/packages/pi-coding-agent/src/core/model-registry.ts +1 -1
  61. package/packages/pi-coding-agent/src/modes/interactive/components/provider-manager.ts +16 -2
  62. package/pkg/package.json +1 -1
  63. package/src/resources/extensions/bg-shell/bg-shell-lifecycle.ts +2 -2
  64. package/src/resources/extensions/bg-shell/utilities.ts +39 -4
  65. package/src/resources/extensions/gsd/auto/phases.ts +14 -2
  66. package/src/resources/extensions/gsd/auto-dispatch.ts +1 -1
  67. package/src/resources/extensions/gsd/auto-model-selection.ts +21 -1
  68. package/src/resources/extensions/gsd/auto-prompts.ts +15 -0
  69. package/src/resources/extensions/gsd/bootstrap/register-extension.ts +19 -6
  70. package/src/resources/extensions/gsd/tests/auto-model-selection.test.ts +139 -0
  71. package/src/resources/extensions/gsd/tests/journal-integration.test.ts +55 -0
  72. package/src/resources/extensions/gsd/tests/plan-milestone-queue-context.test.ts +48 -0
  73. package/src/resources/extensions/gsd/tests/register-extension-guard.test.ts +59 -0
  74. package/dist/web/standalone/.next/static/chunks/4024.87fd909ae0110f50.js +0 -9
  75. /package/dist/web/standalone/.next/static/{YO-PWFRitlHM-L-dotlmm → 8yiPxQ52ue_s6qdrrAxsH}/_buildManifest.js +0 -0
  76. /package/dist/web/standalone/.next/static/{YO-PWFRitlHM-L-dotlmm → 8yiPxQ52ue_s6qdrrAxsH}/_ssgManifest.js +0 -0
@@ -0,0 +1,9 @@
1
+ "use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4024],{4024:(e,t,s)=>{s.r(t),s.d(t,{GSDAppShell:()=>o3});var r=s(95155),a=s(5772),n=s(12115),i=s(33210),o=s(29857),l=s(12651),d=s(20232),c=s(16950),u=s(51900),m=s(36999),x=s(92972),h=s(98401),p=s(8434),g=s(1806),f=s(56572),b=s(38798),v=s(93219),j=s(89123),y=s(79270),N=s(31025),w=s(89363),k=s(41313),S=s(89626),C=s(66088),A=s(21362),T=s(48368),R=s(2318),E=s(6296),P=s(33e3),_=s(30125),I=s(50070),$=s(29483),D=s(29722),F=s(622);function L(...e){return(0,F.QP)((0,D.$)(e))}function M({...e}){return(0,r.jsx)($.bL,{"data-slot":"dialog",...e})}function q({...e}){return(0,r.jsx)($.ZL,{"data-slot":"dialog-portal",...e})}function O({className:e,...t}){return(0,r.jsx)($.hJ,{"data-slot":"dialog-overlay",className:L("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function U({className:e,children:t,showCloseButton:s=!0,...a}){return(0,r.jsxs)(q,{"data-slot":"dialog-portal",children:[(0,r.jsx)(O,{}),(0,r.jsxs)($.UC,{"data-slot":"dialog-content",className:L("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...a,children:[t,s&&(0,r.jsxs)($.bm,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[(0,r.jsx)(i.A,{}),(0,r.jsx)("span",{className:"sr-only",children:"Close"})]})]})]})}function z({className:e,...t}){return(0,r.jsx)("div",{"data-slot":"dialog-header",className:L("flex flex-col gap-2 text-center sm:text-left",e),...t})}function B({className:e,...t}){return(0,r.jsx)("div",{"data-slot":"dialog-footer",className:L("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function G({className:e,...t}){return(0,r.jsx)($.hE,{"data-slot":"dialog-title",className:L("text-lg leading-none font-semibold",e),...t})}function W({className:e,...t}){return(0,r.jsx)($.VY,{"data-slot":"dialog-description",className:L("text-muted-foreground text-sm",e),...t})}var K=s(42442),H=s(18460);let V=(0,H.F)("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function J({className:e,variant:t,size:s,asChild:a=!1,...n}){let i=a?K.DX:"button";return(0,r.jsx)(i,{"data-slot":"button",className:L(V({variant:t,size:s,className:e})),...n})}var Y=s(70460);let Q=new Map([{name:"settings",description:"Open settings menu"},{name:"model",description:"Select model (opens selector UI)"},{name:"scoped-models",description:"Enable/disable models for Ctrl+P cycling"},{name:"export",description:"Export session to HTML file"},{name:"share",description:"Share session as a secret GitHub gist"},{name:"copy",description:"Copy last agent message to clipboard"},{name:"name",description:"Set session display name"},{name:"session",description:"Show session info and stats"},{name:"changelog",description:"Show changelog entries"},{name:"hotkeys",description:"Show all keyboard shortcuts"},{name:"fork",description:"Create a new fork from a previous message"},{name:"tree",description:"Navigate session tree (switch branches)"},{name:"provider",description:"Manage provider configuration"},{name:"login",description:"Login with OAuth provider"},{name:"logout",description:"Logout from OAuth provider"},{name:"new",description:"Start a new session"},{name:"compact",description:"Manually compact the session context"},{name:"resume",description:"Resume a different session"},{name:"reload",description:"Reload extensions, skills, prompts, and themes"},{name:"thinking",description:"Set thinking level (off/minimal/low/medium/high/xhigh)"},{name:"edit-mode",description:"Toggle edit mode (standard/hashline)"},{name:"terminal",description:"Run a shell command directly (e.g. /terminal ping -c3 1.1.1.1)"},{name:"quit",description:"Quit pi"}].map(e=>[e.name,e.description])),X=new Set(Q.keys()),Z=new Map([["settings","settings"],["model","model"],["thinking","thinking"],["git","git"],["resume","resume"],["name","name"],["fork","fork"],["compact","compact"],["login","login"],["logout","logout"],["session","session"],["export","export"]]),ee=new Map([["status","gsd-status"],["visualize","gsd-visualize"],["forensics","gsd-forensics"],["doctor","gsd-doctor"],["skill-health","gsd-skill-health"],["knowledge","gsd-knowledge"],["capture","gsd-capture"],["triage","gsd-triage"],["quick","gsd-quick"],["history","gsd-history"],["undo","gsd-undo"],["inspect","gsd-inspect"],["prefs","gsd-prefs"],["config","gsd-config"],["hooks","gsd-hooks"],["mode","gsd-mode"],["steer","gsd-steer"],["export","gsd-export"],["cleanup","gsd-cleanup"],["queue","gsd-queue"]]),et=new Set(["auto","next","stop","pause","skip","discuss","run-hook","migrate","remote"]),es=`Available /gsd subcommands:
2
+
3
+ Workflow: next \xb7 auto \xb7 stop \xb7 pause \xb7 skip \xb7 queue \xb7 quick \xb7 capture \xb7 triage
4
+ Diagnostics: status \xb7 visualize \xb7 forensics \xb7 doctor \xb7 skill-health \xb7 inspect
5
+ Context: knowledge \xb7 history \xb7 undo \xb7 discuss
6
+ Settings: prefs \xb7 config \xb7 hooks \xb7 mode \xb7 steer
7
+ Advanced: export \xb7 cleanup \xb7 run-hook \xb7 migrate \xb7 remote
8
+
9
+ Type /gsd <subcommand> to run. Use /gsd help for this message.`;function er(e){return e.isStreaming?"follow_up":"prompt"}function ea(e,t={}){let s=e.trim(),r=function(e){if(!e.startsWith("/"))return null;let t=e.slice(1).trim();if(!t)return null;let s=t.search(/\s/);return -1===s?{name:t,args:""}:{name:t.slice(0,s),args:t.slice(s+1).trim()}}(s);if("/clear"===s)return{kind:"local",input:s,commandName:"clear",action:"clear_terminal"};if("/refresh"===s)return{kind:"local",input:s,commandName:"refresh",action:"refresh_workspace"};if("/state"===s)return{kind:"rpc",input:s,commandName:"state",command:{type:"get_state"}};if("/new-session"===s)return{kind:"rpc",input:s,commandName:"new",command:{type:"new_session"}};if(!r)return{kind:"prompt",input:s,slashCommandName:null,command:{type:er(t),message:s}};if("new"===r.name)return{kind:"rpc",input:s,commandName:"new",command:{type:"new_session"}};if("gsd"===r.name)return function(e,t,s){let r=t.trim(),a=r.search(/\s/),n=-1===a?r:r.slice(0,a),i=-1===a?"":r.slice(a+1).trim();if(!n)return{kind:"prompt",input:e,slashCommandName:"gsd",command:{type:er(s),message:e}};if("help"===n)return{kind:"local",input:e,commandName:"gsd",action:"gsd_help"};if("visualize"===n)return{kind:"view-navigate",input:e,commandName:"gsd",view:"visualize"};let o=ee.get(n);return o?{kind:"surface",input:e,commandName:"gsd",surface:o,args:i}:(et.has(n),{kind:"prompt",input:e,slashCommandName:"gsd",command:{type:er(s),message:e}})}(s,r.args,t);let a=Z.get(r.name);if(a)return{kind:"surface",input:s,commandName:r.name,surface:a,args:r.args};if(X.has(r.name)){var n,i;let e;return i=n=r.name,e=Q.get(i)??"Browser handling is reserved for this built-in command.",{kind:"reject",input:s,commandName:n,reason:`/${n} is a built-in pi command (${e}) that is not available in the browser yet.`,guidance:"It was blocked instead of falling through to the model."}}return{kind:"prompt",input:s,slashCommandName:r.name,command:{type:er(t),message:s}}}function en(e){switch(e.kind){case"surface":return{type:"system",message:`/${e.commandName} is reserved for browser-native handling and was not sent to the model.`};case"reject":return{type:"error",message:`${e.reason} ${e.guidance}`.trim()};default:return null}}let ei=["off","minimal","low","medium","high","xhigh"];function eo(){return{phase:"idle",data:null,error:null,lastLoadedAt:null}}function el(){return{forensics:eo(),doctor:{phase:"idle",data:null,error:null,lastLoadedAt:null,fixPending:!1,lastFixResult:null,lastFixError:null},skillHealth:eo()}}function ed(){return{knowledge:eo(),captures:eo(),resolveRequest:{pending:!1,lastError:null,lastResult:null}}}function ec(){return{history:eo(),inspect:eo(),hooks:eo(),exportData:eo(),undo:eo(),cleanup:eo(),steer:eo()}}let eu=new Set(["settings","login","logout"]),em={set_steering_mode:"steeringMode",set_follow_up_mode:"followUpMode",set_auto_compaction:"autoCompaction",set_auto_retry:"autoRetry",abort_retry:"abortRetry"};function ex(e={}){return{scope:null,projectCwd:null,projectSessionsDir:null,activeSessionPath:null,query:"",sortMode:"threaded",nameFilter:"all",totalSessions:0,returnedSessions:0,sessions:[],loaded:!1,error:null,...e}}function eh(){return{pending:!1,sessionPath:null,result:null,error:null}}function ep(){return{pending:!1,result:null,error:null}}function eg(){return{steeringMode:ep(),followUpMode:ep(),autoCompaction:ep(),autoRetry:ep(),abortRetry:ep()}}function ef(){return{pending:!1,loaded:!1,result:null,error:null}}function eb(){return{phase:"idle",pending:!1,loaded:!1,stale:!1,diagnostics:null,error:null,lastLoadedAt:null,lastInvalidatedAt:null,lastFailureAt:null}}function ev(e){return ei.includes(e??"")}function ej(e){switch(e.surface){case"model":return"model";case"thinking":return"thinking";case"settings":return e.onboardingLocked?"auth":"general";case"git":return"git";case"login":case"logout":return"auth";case"resume":return"resume";case"name":return"name";case"fork":return"fork";case"session":case"export":return"session";case"compact":return"compact";case"gsd-status":return"gsd-status";case"gsd-visualize":return"gsd-visualize";case"gsd-forensics":return"gsd-forensics";case"gsd-doctor":return"gsd-doctor";case"gsd-skill-health":return"gsd-skill-health";case"gsd-knowledge":return"gsd-knowledge";case"gsd-capture":return"gsd-capture";case"gsd-triage":return"gsd-triage";case"gsd-quick":return"gsd-quick";case"gsd-history":return"gsd-history";case"gsd-undo":return"gsd-undo";case"gsd-inspect":return"gsd-inspect";case"gsd-prefs":return"gsd-prefs";case"gsd-config":return"gsd-config";case"gsd-hooks":return"gsd-hooks";case"gsd-mode":return"gsd-mode";case"gsd-steer":return"gsd-steer";case"gsd-export":return"gsd-export";case"gsd-cleanup":return"gsd-cleanup";case"gsd-queue":return"gsd-queue";default:return null}}function ey(e){return{kind:"settings",section:e}}function eN(e){let t=e.args?.trim()||void 0;return{kind:"model",provider:e.currentModel?.provider,modelId:e.currentModel?.modelId,query:t}}function ew(e){let t=e.args?.trim().toLowerCase()||"";return{kind:"thinking",level:ev(t)?t:ev(e.currentThinkingLevel)?e.currentThinkingLevel:"off"}}function ek(e){return{kind:"auth",providerId:(e.args?.trim()||void 0)??e.preferredProviderId??void 0,intent:"login"===e.surface?"login":"logout"===e.surface?"logout":"manage"}}function eS(e){return{kind:"resume",sessionPath:function(e,t){if(!e?.length)return;let s=t?.trim().toLowerCase();if(!s)return e.find(e=>!e.isActive)?.path??e[0]?.path;let r=e.find(e=>[e.id,e.name,e.path].filter(Boolean).map(e=>e.toLowerCase()).includes(s));return r?r.path:e.find(e=>[e.id,e.name,e.path].filter(Boolean).map(e=>e.toLowerCase()).some(e=>e.includes(s)))?.path}(e.resumableSessions,e.args)}}function eC(e){return{kind:"fork",entryId:e.args?.trim()||void 0}}function eA(e){return{kind:"session",outputPath:e.args?.trim()||void 0}}function eT(e){return{kind:"compact",customInstructions:e.args?.trim()??""}}function eR(e,t,s=e.selectedTarget){let r="switch_session"===t?{pending:!0,sessionPath:s?.kind==="resume"?s.sessionPath??null:null,result:null,error:null}:e.resumeRequest,a="rename_session"===t?{pending:!0,sessionPath:s?.kind==="name"?s.sessionPath??null:null,result:null,error:null}:e.renameRequest,n=em[t],i=n?{...e.settingsRequests,[n]:{pending:!0,result:null,error:null}}:e.settingsRequests;return{...e,pendingAction:t,selectedTarget:s,lastError:null,lastResult:null,gitSummary:"load_git_summary"===t?{...e.gitSummary,pending:!0,error:null}:e.gitSummary,recovery:"load_recovery_diagnostics"===t?{...e.recovery,pending:!0,error:null,phase:e.recovery.loaded?e.recovery.phase:"loading"}:e.recovery,sessionBrowser:"load_session_browser"===t?{...e.sessionBrowser,error:null}:e.sessionBrowser,resumeRequest:r,renameRequest:a,settingsRequests:i}}function eE(e,t){let s=void 0===t.selectedTarget?e.selectedTarget:t.selectedTarget,r=(s?.kind==="resume"?s.sessionPath:void 0)??e.resumeRequest.sessionPath,a=(s?.kind==="name"?s.sessionPath:void 0)??e.renameRequest.sessionPath,n=em[t.action],i=n?{...e.settingsRequests,[n]:{pending:!1,result:t.success?t.message:null,error:t.success?null:t.message}}:e.settingsRequests;return{...e,pendingAction:null,selectedTarget:s,availableModels:t.availableModels??e.availableModels,forkMessages:t.forkMessages??e.forkMessages,sessionStats:void 0===t.sessionStats?e.sessionStats:t.sessionStats,lastCompaction:void 0===t.lastCompaction?e.lastCompaction:t.lastCompaction,gitSummary:void 0===t.gitSummary?e.gitSummary:{...t.gitSummary,pending:!1,loaded:t.gitSummary.loaded||t.success},recovery:t.recovery??e.recovery,sessionBrowser:t.sessionBrowser??e.sessionBrowser,resumeRequest:"switch_session"===t.action?{pending:!1,sessionPath:r??null,result:t.success?t.message:null,error:t.success?null:t.message}:e.resumeRequest,renameRequest:"rename_session"===t.action?{pending:!1,sessionPath:a??null,result:t.success?t.message:null,error:t.success?null:t.message}:e.renameRequest,settingsRequests:i,lastError:t.success?null:t.message,lastResult:t.success?t.message:null}}let eP="gsd-auth-token",e_=null;function eI(){if(null!==e_)return e_;let e=window.location.hash;if(e){let t=e.match(/token=([a-fA-F0-9]+)/);if(t){e_=t[1];try{localStorage.setItem(eP,e_)}catch{}return window.history.replaceState(null,"",window.location.pathname+window.location.search),e_}}try{let e=localStorage.getItem(eP);if(e)return e_=e}catch{}return null}async function e$(e,t){let s=eI();if(!s)return new Response(JSON.stringify({error:"No auth token available"}),{status:401,headers:{"Content-Type":"application/json"}});let r=new Headers(t?.headers);return r.has("Authorization")||r.set("Authorization",`Bearer ${s}`),fetch(e,{...t,headers:r})}function eD(e){let t=eI();if(!t)return e;let s=e.includes("?")?"&":"?";return`${e}${s}_token=${t}`}window.addEventListener("storage",e=>{e.key===eP&&e.newValue&&(e_=e.newValue)});let eF=new Set(["settings","model","thinking","git","resume","name","fork","compact","login","logout","session","export","gsd-status","gsd-visualize","gsd-forensics","gsd-doctor","gsd-skill-health","gsd-knowledge","gsd-capture","gsd-triage","gsd-quick","gsd-history","gsd-undo","gsd-inspect","gsd-prefs","gsd-config","gsd-hooks","gsd-mode","gsd-steer","gsd-export","gsd-cleanup","gsd-queue"]);function eL(e,t){return{id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,type:e,content:t,timestamp:function(e=new Date){return e.toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}()}}function eM(e,t){return[...e,t].slice(-250)}function eq(e){return!!(e?.activeSessionId||e?.sessionState?.sessionId)}function eO(e){return e instanceof Error?e.message:String(e)}function eU(e){if("failed"===e.phase)return{type:"error",message:`Bridge failed${e.lastError?.message?` — ${e.lastError.message}`:""}`};if("starting"===e.phase)return{type:"system",message:"Bridge starting for the current project…"};if("ready"===e.phase){let t=e1(e);return{type:"success",message:t?`Live bridge ready — attached to ${t}`:"Live bridge ready — session attachment pending"}}return{type:"system",message:"Bridge idle"}}let ez=new Set(["running","awaiting_browser_auth","awaiting_input"]),eB=new Set(["succeeded","failed","cancelled"]);function eG(e,t){return e.required.providers.find(e=>e.id===t)?.label??t}function eW(e,t){if(!e)return null;let s={...e,bridge:t};return{...s,resumableSessions:e7(s.resumableSessions,s)}}function eK(e,t){return e?.bridge.sessionState?eW(e,{...e.bridge,sessionState:{...e.bridge.sessionState,...t}}):e}function eH(e,t){return e?{...e,onboarding:t,onboardingNeeded:t.locked}:null}function eV(e){return"failed"===e.bridgeAuthRefresh.phase?{type:"error",message:e.bridgeAuthRefresh.error?`Bridge auth refresh failed — ${e.bridgeAuthRefresh.error}`:"Bridge auth refresh failed after setup"}:"pending"===e.bridgeAuthRefresh.phase?{type:"system",message:"Credentials saved — refreshing bridge auth before the workspace unlocks…"}:e.lastValidation?.status==="failed"?{type:"error",message:`Credential validation failed — ${e.lastValidation.message}`}:e.locked||e.lastValidation?.status!=="succeeded"?e.activeFlow?.status==="awaiting_browser_auth"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in is waiting for browser confirmation`}:e.activeFlow?.status==="awaiting_input"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in needs one more input step`}:e.activeFlow?.status==="cancelled"?{type:"system",message:`${e.activeFlow.providerLabel} sign-in was cancelled`}:e.activeFlow?.status==="failed"?{type:"error",message:e.activeFlow.error?`${e.activeFlow.providerLabel} sign-in failed — ${e.activeFlow.error}`:`${e.activeFlow.providerLabel} sign-in failed`}:"required_setup"===e.lockReason?{type:"system",message:"Onboarding is still required before model-backed prompts will run"}:null:{type:"success",message:`${eG(e,e.lastValidation.providerId)} is ready — workspace unlocked`}}function eJ(e){let t=[eL("system",`GSD web workspace attached to ${e.project.cwd}`),eL("system",`Workspace scope: ${eZ(e.workspace)}`)],s=eU(e.bridge);t.push(eL(s.type,s.message)),e.bridge.lastError&&t.push(eL("error",`Bridge error: ${e.bridge.lastError.message}`));let r=eV(e.onboarding);return r&&t.push(eL(r.type,r.message)),t}function eY(e,t=3){if(!e)return"—";let s=e.split(/[\\/]/).filter(Boolean);if(s.length<=t)return e.startsWith("/")?`/${s.join("/")}`:s.join("/");let r=s.slice(-t).join("/");return`…/${r}`}function eQ(e){return!Number.isFinite(e)||e<=0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e))}function eX(e){return!Number.isFinite(e)||e<=0?"$0.00":`$${e.toFixed(2)}`}function eZ(e){if(!e)return"Project scope pending";let t=[e.active.milestoneId,e.active.sliceId,e.active.taskId].filter(Boolean).join("/");return t?`${t} — ${e.active.phase}`:`project — ${e.active.phase}`}function e0(e){if(!e?.active.milestoneId||!e.active.sliceId)return null;let t=e.milestones.find(t=>t.id===e.active.milestoneId),s=t?.slices.find(t=>t.id===e.active.sliceId);return s?.branch??null}function e1(e){if(!e?.sessionState&&!e?.activeSessionId)return null;let t=e.sessionState?.sessionName?.trim();return t||(e.activeSessionId?`session ${e.activeSessionId}`:e.sessionState?.sessionId??null)}function e5(e){let t=e?.sessionState?.model;return t&&(t.id||t.providerId||t.provider)||"model pending"}function e2(e){let t=e?.sessionState?.model;return t?{provider:t.provider??t.providerId,modelId:t.id}:null}function e3(e){if(!e)return null;if(e.required.satisfiedBy?.providerId)return e.required.satisfiedBy.providerId;let t=e.required.providers.find(e=>!e.configured&&e.recommended);if(t)return t.id;let s=e.required.providers.find(e=>!e.configured);return s?s.id:e.required.providers[0]?.id??null}function e4(e,t){return{...e,pending:!1,loaded:!1,error:t}}function e8(e,t){return{...e,phase:"error",pending:!1,stale:!0,error:t,lastFailureAt:new Date().toISOString()}}function e6(e){return e?.bridge.activeSessionFile??e?.bridge.sessionState?.sessionFile??null}function e7(e,t){let s=e6(t),r=t?.bridge.sessionState?.sessionName?.trim()||void 0;return e.map(e=>{let t=s?e.path===s:e.isActive;return{...e,isActive:t,...t&&r?{name:r}:{}}})}function e9(e,t){return{...e,activeSessionPath:e6(t),sessions:e7(e.sessions,t)}}function te(e,t,s){return{...e,activeSessionPath:s.isActive?t:e.activeSessionPath,sessions:e.sessions.map(e=>e.path===t?{...e,...s}:s.isActive?{...e,isActive:!1}:e)}}function tt(e){let t=e.boot?.onboarding;return t?.bridgeAuthRefresh.phase==="failed"&&t.bridgeAuthRefresh.error?t.bridgeAuthRefresh.error:t?.lastValidation?.status==="failed"?t.lastValidation.message:e.lastBridgeError?.message??e.lastClientError}function ts(e){if("loading"===e.bootStatus)return{label:"Loading workspace",tone:"info"};if("error"===e.bootStatus)return{label:"Boot failed",tone:"danger"};let t=function(e){if("loading"===e.bootStatus||!e.boot)return{phase:"loading",label:"Loading setup state",detail:"Resolving the current project, bridge, and onboarding contract…",tone:"info"};let t=e.boot.onboarding;return t.activeFlow?.status==="awaiting_browser_auth"?{phase:"awaiting_browser_auth",label:"Continue sign-in in your browser",detail:`${t.activeFlow.providerLabel} is waiting for browser confirmation before the workspace can unlock.`,tone:"info"}:t.activeFlow?.status==="awaiting_input"?{phase:"awaiting_input",label:"One more sign-in step is required",detail:t.activeFlow.prompt?.message??`${t.activeFlow.providerLabel} needs one more input step.`,tone:"info"}:"bridge_refresh_pending"===t.lockReason?{phase:"refreshing",label:"Refreshing bridge auth",detail:"Credentials validated. The live bridge is restarting onto the new auth view before the shell unlocks.",tone:"info"}:"bridge_refresh_failed"===t.lockReason?{phase:"failure",label:"Setup completed, but the shell is still locked",detail:t.bridgeAuthRefresh.error??"The bridge could not reload auth after setup.",tone:"danger"}:t.lastValidation?.status==="failed"?{phase:"failure",label:"Credential validation failed",detail:t.lastValidation.message,tone:"danger"}:"saving_api_key"===e.onboardingRequestState?{phase:"validating",label:"Validating credentials",detail:"Checking the provider key and saving it only if validation succeeds.",tone:"info"}:"starting_provider_flow"===e.onboardingRequestState||"submitting_provider_flow_input"===e.onboardingRequestState?{phase:"running_flow",label:"Advancing provider sign-in",detail:"The onboarding flow is running and will update here as soon as the next step is ready.",tone:"info"}:t.locked?{phase:"locked",label:"Required setup needed",detail:"Choose a required provider, validate it here, and the workspace will unlock without restarting the host.",tone:"warning"}:{phase:"ready",label:"Workspace unlocked",detail:t.lastValidation?.status==="succeeded"?`${eG(t,t.lastValidation.providerId)} is ready and the workspace is live.`:"Required setup is satisfied and the shell is ready for live commands.",tone:"success"}}(e);if("ready"!==t.phase)return{label:t.label,tone:t.tone};if(e.boot?.bridge.phase==="failed")return{label:"Bridge failed",tone:"danger"};switch(e.connectionState){case"connected":return{label:"Bridge connected",tone:"success"};case"connecting":return{label:"Connecting stream",tone:"info"};case"reconnecting":return{label:"Reconnecting stream",tone:"warning"};case"disconnected":return{label:"Stream disconnected",tone:"warning"};case"error":return{label:"Stream error",tone:"danger"};default:return{label:"Workspace idle",tone:"muted"}}}function tr(){return{status:"idle",stale:!1,reloadCount:0,lastRequestedAt:null,lastSuccessAt:null,lastFailureAt:null,lastFailure:null,invalidatedAt:null,invalidationReason:null,invalidationSource:null}}function ta(){return{visible:!1,tone:"healthy",label:"Recovery summary pending",detail:"Waiting for the first live workspace snapshot.",validationCount:0,retryInProgress:!1,retryAttempt:0,autoRetryEnabled:!1,isCompacting:!1,currentUnitId:null,freshness:"idle",entrypointLabel:"Inspect recovery",lastError:null}}function tn(e){return{...e,status:"refreshing",lastRequestedAt:new Date().toISOString(),lastFailure:null}}function ti(e,t,s){return{...e,status:e.lastSuccessAt?"stale":e.status,stale:!0,invalidatedAt:new Date().toISOString(),invalidationReason:t,invalidationSource:s}}function to(e){return{...e,status:"fresh",stale:!1,reloadCount:e.reloadCount+1,lastSuccessAt:new Date().toISOString(),lastFailureAt:null,lastFailure:null}}function tl(e,t){return{...e,status:"error",stale:!0,lastFailureAt:new Date().toISOString(),lastFailure:t}}function td(e){return e.live.workspace??e.boot?.workspace??null}function tc(e){return e.live.auto??e.boot?.auto??null}function tu(e){return e.live.resumableSessions.length>0?e.live.resumableSessions:e.boot?.resumableSessions??[]}function tm(e){let t=e.boot?.bridge??null,s=td(e),r=tc(e),a=s?.validationIssues.length??0,n=!!t?.sessionState?.retryInProgress,i=t?.sessionState?.retryAttempt??0,o=!!t?.sessionState?.autoRetryEnabled,l=!!t?.sessionState?.isCompacting,d=e.live.freshness.recovery,c="error"===d.status?"error":d.stale?"stale":d.lastSuccessAt?"fresh":"idle",u=t?.lastError?{message:t.lastError.message,phase:t.lastError.phase,at:t.lastError.at}:null,m="healthy",x="Recovery summary healthy",h="No retry, compaction, bridge, or validation recovery signals are active.";return s||r||t?(u||"error"===c?(m="danger",x="Recovery attention required",h=u?.message??d.lastFailure??"A targeted live refresh failed."):a>0?(m="warning",x=`Recovery summary: ${a} validation issue${1===a?"":"s"}`,h="Workspace validation surfaced issues that may need doctor or audit follow-up."):n?(m="warning",x=`Recovery retry active (attempt ${Math.max(1,i)})`,h="The live bridge is retrying the current unit after a transient failure."):l?(m="warning",x="Recovery compaction active",h="The live session is compacting context before continuing."):"stale"===c&&(m="warning",x="Recovery summary stale",h=d.invalidationReason?`Waiting for a targeted refresh after ${d.invalidationReason.replaceAll("_"," ")}.`:"Waiting for the next targeted refresh."),{visible:!0,tone:m,label:x,detail:h,validationCount:a,retryInProgress:n,retryAttempt:i,autoRetryEnabled:o,isCompacting:l,currentUnitId:r?.currentUnit?.id??null,freshness:c,entrypointLabel:"danger"===m||"warning"===m?"Inspect recovery":"Review recovery",lastError:u}):ta()}function tx(e,t){if(!t)return e;let s=new URL(e,"http://localhost");return s.searchParams.set("project",t),s.pathname+s.search}class th{constructor(e){this.projectCwd=e,this.state={bootStatus:"idle",connectionState:"idle",boot:null,live:{auto:null,workspace:null,resumableSessions:[],recoverySummary:ta(),freshness:{auto:tr(),workspace:tr(),recovery:tr(),resumableSessions:tr(),gitSummary:tr(),sessionBrowser:tr(),sessionStats:tr()},softBootRefreshCount:0,targetedRefreshCount:0},terminalLines:[eL("system","Preparing the live GSD workspace…")],lastClientError:null,lastBridgeError:null,sessionAttached:!1,lastEventType:null,commandInFlight:null,lastSlashCommandOutcome:null,commandSurface:{open:!1,activeSurface:null,source:null,section:null,args:"",pendingAction:null,selectedTarget:null,lastError:null,lastResult:null,availableModels:[],forkMessages:[],sessionStats:null,lastCompaction:null,gitSummary:ef(),recovery:eb(),diagnostics:el(),knowledgeCaptures:ed(),settingsData:eo(),remainingCommands:ec(),sessionBrowser:ex(),resumeRequest:eh(),renameRequest:eh(),settingsRequests:eg()},onboardingRequestState:"idle",onboardingRequestProviderId:null,pendingUiRequests:[],streamingAssistantText:"",streamingThinkingText:"",liveTranscript:[],liveThinkingTranscript:[],completedToolExecutions:[],activeToolExecution:null,currentTurnSegments:[],completedTurnSegments:[],chatUserMessages:[],statusTexts:{},widgetContents:{},titleOverride:null,editorTextBuffer:null},this.listeners=new Set,this.bootPromise=null,this.eventSource=null,this.onboardingPollTimer=null,this.started=!1,this.disposed=!1,this.lastBridgeDigest=null,this.lastStreamState="idle",this.commandTimeoutTimer=null,this.lastBootRefreshAt=0,this.visibilityHandler=null,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.start=()=>{this.started||this.disposed||(this.started=!0,"u">typeof document&&(this.visibilityHandler=()=>{"visible"===document.visibilityState&&Date.now()-this.lastBootRefreshAt>=3e4&&this.refreshBoot({soft:!0})},document.addEventListener("visibilitychange",this.visibilityHandler)),this.refreshBoot())},this.dispose=()=>{this.disposed=!0,this.started=!1,this.stopOnboardingPoller(),this.closeEventStream(),this.clearCommandTimeout(),this.visibilityHandler&&"u">typeof document&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null)},this.disconnectSSE=()=>{this.closeEventStream()},this.reconnectSSE=()=>{this.disposed||(this.ensureEventStream(),this.refreshBoot({soft:!0}))},this.clearTerminalLines=()=>{let e=this.state.boot?eJ(this.state.boot):[eL("system","Terminal cleared")];this.patchState({terminalLines:e})},this.consumeEditorTextBuffer=()=>{let e=this.state.editorTextBuffer;return null!==e&&this.patchState({editorTextBuffer:null}),e},this.openCommandSurface=(e,t={})=>{var s,r;let a,n,i=tu(this.state);this.patchState({commandSurface:(s=this.state.commandSurface,a=ej(r={surface:e,source:t.source??"surface",args:t.args??"",selectedTarget:t.selectedTarget,onboardingLocked:this.state.boot?.onboarding.locked,currentModel:e2(this.state.boot?.bridge),currentThinkingLevel:this.state.boot?.bridge.sessionState?.thinkingLevel??null,preferredProviderId:e3(this.state.boot?.onboarding),resumableSessions:i.map(e=>({id:e.id,path:e.path,name:e.name,isActive:e.isActive})),currentSessionPath:this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null,currentSessionName:this.state.boot?.bridge.sessionState?.sessionName??null,projectCwd:this.state.boot?.project.cwd??null,projectSessionsDir:this.state.boot?.project.sessionsDir??null}),{...s,open:!0,activeSurface:r.surface,source:r.source,section:a,args:r.args?.trim()??"",pendingAction:null,selectedTarget:function(e){if(void 0!==e.selectedTarget)return e.selectedTarget;let t=ej(e);if(!t)return null;if("settings"===e.surface)return ey(t);if("model"===e.surface)return eN(e);if("thinking"===e.surface)return ew(e);if(eu.has(e.surface))return ek(e);if("resume"===e.surface)return eS(e);if("name"===e.surface){let t;return t=e.args?.trim(),{kind:"name",sessionPath:e.currentSessionPath??void 0,name:void 0!==t&&t.length>0?t:e.currentSessionName?.trim()??""}}if("fork"===e.surface)return eC(e);if("session"===e.surface||"export"===e.surface)return eA(e);if("compact"===e.surface)return eT(e);if(e.surface?.startsWith("gsd-")){let t=e.surface.slice(4);return{kind:"gsd",surface:e.surface,subcommand:t,args:e.args??""}}return ey(t)}(r),lastError:null,lastResult:null,sessionStats:null,forkMessages:[],lastCompaction:null,gitSummary:ef(),recovery:eb(),diagnostics:el(),knowledgeCaptures:ed(),settingsData:eo(),remainingCommands:ec(),sessionBrowser:(n="resume"===r.surface?r.args?.trim()??"":"",ex({activeSessionPath:r.currentSessionPath??null,projectCwd:r.projectCwd??null,projectSessionsDir:r.projectSessionsDir??null,query:n,sortMode:n?"relevance":"threaded"})),resumeRequest:eh(),renameRequest:eh(),settingsRequests:eg()})})},this.closeCommandSurface=()=>{this.patchState({commandSurface:{...this.state.commandSurface,open:!1,pendingAction:null}})},this.setCommandSurfaceSection=e=>{let t=tu(this.state);this.patchState({commandSurface:function(e,t,s={}){let r={surface:e.activeSurface??"settings",source:e.source??"surface",args:e.args,...s},a=e.selectedTarget?.kind==="resume"||e.selectedTarget?.kind==="name"?e.selectedTarget.sessionPath:void 0,n=e.selectedTarget?.kind==="name"?e.selectedTarget.name:void 0,i=e.selectedTarget;return"model"===t?i=eN(r):"thinking"===t?i=ew(r):"general"===t||"session-behavior"===t||"queue"===t||"compaction"===t||"retry"===t||"recovery"===t||"git"===t||"admin"===t?i=ey(t):"auth"===t?i=ek({...r,surface:"logout"===e.activeSurface?"logout":"login"===e.activeSurface?"login":"settings"}):"resume"===t?i={kind:"resume",sessionPath:a??eS(r).sessionPath}:"name"===t?i={kind:"name",sessionPath:a??r.currentSessionPath??void 0,name:n??r.currentSessionName?.trim()??""}:"fork"===t?i=eC(r):"session"===t?i=eA(r):"compact"===t&&(i=eT(r)),{...e,section:t,selectedTarget:i}}(this.state.commandSurface,e,{onboardingLocked:this.state.boot?.onboarding.locked,currentModel:e2(this.state.boot?.bridge),currentThinkingLevel:this.state.boot?.bridge.sessionState?.thinkingLevel??null,preferredProviderId:e3(this.state.boot?.onboarding),resumableSessions:t.map(e=>({id:e.id,path:e.path,name:e.name,isActive:e.isActive})),currentSessionPath:this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null,currentSessionName:this.state.boot?.bridge.sessionState?.sessionName??null,projectCwd:this.state.boot?.project.cwd??null,projectSessionsDir:this.state.boot?.project.sessionsDir??null})})},this.selectCommandSurfaceTarget=e=>{var t;let s;this.patchState({commandSurface:(t=this.state.commandSurface,s="settings"===e.kind?e.section:"model"===e.kind?"model":"thinking"===e.kind?"thinking":"auth"===e.kind?"auth":"resume"===e.kind?"resume":"name"===e.kind?"name":"fork"===e.kind?"fork":"session"===e.kind?"session":"compact",{...t,section:s,selectedTarget:e,lastError:null,lastResult:null})})},this.loadGitSummary=async()=>{let e={...this.state.commandSurface.gitSummary,pending:!0,error:null},t={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:tn(this.state.live.freshness.gitSummary)}};this.patchState({live:{...t,recoverySummary:tm({boot:this.state.boot,live:t})},commandSurface:eR({...this.state.commandSurface,gitSummary:e},"load_git_summary")});try{let t=await e$(this.buildUrl("/api/git"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await t.json().catch(()=>null),r=s&&"object"==typeof s&&("repo"===s.kind||"not_repo"===s.kind)&&s.project&&"object"==typeof s.project&&"current_project"===s.project.scope&&"string"==typeof s.project.cwd&&("not_repo"===s.kind?"string"==typeof s.message:"string"==typeof s.project?.repoRoot&&"boolean"==typeof s.hasChanges&&"boolean"==typeof s.hasConflicts&&!!s.counts&&"object"==typeof s.counts&&!!Array.isArray(s.changedFiles)&&"number"==typeof s.truncatedFileCount&&"number"==typeof s.counts.changed&&"number"==typeof s.counts.staged&&"number"==typeof s.counts.dirty&&"number"==typeof s.counts.untracked&&"number"==typeof s.counts.conflicts)?s:null;if(!t.ok||!r){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Current-project git summary failed with ${t.status}`,a=e4(e,r),n={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:tl(this.state.live.freshness.gitSummary,r)}};return this.patchState({live:{...n,recoverySummary:tm({boot:this.state.boot,live:n})},commandSurface:eE({...this.state.commandSurface,gitSummary:a},{action:"load_git_summary",success:!1,message:r,gitSummary:a})}),null}let a={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:to(this.state.live.freshness.gitSummary)}};return this.patchState({live:{...a,recoverySummary:tm({boot:this.state.boot,live:a})},commandSurface:eE(this.state.commandSurface,{action:"load_git_summary",success:!0,message:"",gitSummary:{pending:!1,loaded:!0,result:r,error:null}})}),r}catch(a){let t=eO(a),s=e4(e,t),r={...this.state.live,freshness:{...this.state.live.freshness,gitSummary:tl(this.state.live.freshness.gitSummary,t)}};return this.patchState({live:{...r,recoverySummary:tm({boot:this.state.boot,live:r})},commandSurface:eE({...this.state.commandSurface,gitSummary:s},{action:"load_git_summary",success:!1,message:t,gitSummary:s})}),null}},this.loadRecoveryDiagnostics=async()=>{var e;let t={...e=this.state.commandSurface.recovery,pending:!0,error:null,phase:e.loaded?e.phase:"loading"},s={...this.state.live,freshness:{...this.state.live.freshness,recovery:tn(this.state.live.freshness.recovery)}};this.patchState({live:{...s,recoverySummary:tm({boot:this.state.boot,live:s})},commandSurface:eR({...this.state.commandSurface,recovery:t},"load_recovery_diagnostics")});try{let e=await e$(this.buildUrl("/api/recovery"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await e.json().catch(()=>null),r=s&&"object"==typeof s&&("ready"===s.status||"unavailable"===s.status)&&"string"==typeof s.loadedAt&&s.project&&"string"==typeof s.project.cwd&&s.summary&&"string"==typeof s.summary.label&&"string"==typeof s.summary.detail&&s.bridge&&"string"==typeof s.bridge.phase&&s.validation&&"number"==typeof s.validation.total&&s.doctor&&"number"==typeof s.doctor.total&&s.interruptedRun&&"boolean"==typeof s.interruptedRun.available&&s.actions&&Array.isArray(s.actions.browser)&&Array.isArray(s.actions.commands)?s:null;if(!e.ok||!r){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Recovery diagnostics failed with ${e.status}`,a=e8(t,r),n={...this.state.live,freshness:{...this.state.live.freshness,recovery:tl(this.state.live.freshness.recovery,r)}};return this.patchState({lastClientError:r,live:{...n,recoverySummary:tm({boot:this.state.boot,live:n})},commandSurface:eE({...this.state.commandSurface,recovery:a},{action:"load_recovery_diagnostics",success:!1,message:r,recovery:a})}),null}let a={...{phase:"ready"===r.status?"ready":"unavailable",pending:!1,loaded:!0,stale:!1,diagnostics:r,error:null,lastLoadedAt:r.loadedAt,lastInvalidatedAt:null,lastFailureAt:null},lastInvalidatedAt:this.state.commandSurface.recovery.lastInvalidatedAt},n={...this.state.live,freshness:{...this.state.live.freshness,recovery:to(this.state.live.freshness.recovery)}};return this.patchState({lastClientError:null,live:{...n,recoverySummary:tm({boot:this.state.boot,live:n})},commandSurface:eE({...this.state.commandSurface,recovery:a},{action:"load_recovery_diagnostics",success:!0,message:"ready"===r.status?"Recovery diagnostics refreshed":"Recovery diagnostics are currently unavailable",recovery:a})}),r}catch(a){let e=eO(a),s=e8(t,e),r={...this.state.live,freshness:{...this.state.live.freshness,recovery:tl(this.state.live.freshness.recovery,e)}};return this.patchState({lastClientError:e,live:{...r,recoverySummary:tm({boot:this.state.boot,live:r})},commandSurface:eE({...this.state.commandSurface,recovery:s},{action:"load_recovery_diagnostics",success:!1,message:e,recovery:s})}),null}},this.loadForensicsDiagnostics=async()=>{this.patchDiagnosticsPhaseState("forensics",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/forensics"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Forensics request failed with ${e.status}`;return this.patchDiagnosticsPhaseState("forensics",{phase:"error",error:s}),null}return this.patchDiagnosticsPhaseState("forensics",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchDiagnosticsPhaseState("forensics",{phase:"error",error:e}),null}},this.loadDoctorDiagnostics=async e=>{this.patchDoctorState({phase:"loading",error:null});try{let t=e?`/api/doctor?scope=${encodeURIComponent(e)}`:"/api/doctor",s=await e$(t,{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Doctor request failed with ${s.status}`;return this.patchDoctorState({phase:"error",error:e}),null}return this.patchDoctorState({phase:"loaded",data:r,lastLoadedAt:new Date().toISOString()}),r}catch(t){let e=eO(t);return this.patchDoctorState({phase:"error",error:e}),null}},this.applyDoctorFixes=async e=>{this.patchDoctorState({fixPending:!0,lastFixError:null,lastFixResult:null});try{let t=await e$(this.buildUrl("/api/doctor"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e?{scope:e}:{})}),s=await t.json().catch(()=>null);if(!t.ok||!s){let e=s?.error??`Doctor fix request failed with ${t.status}`;return this.patchDoctorState({fixPending:!1,lastFixError:e}),null}return this.patchDoctorState({fixPending:!1,lastFixResult:s}),this.loadDoctorDiagnostics(e),s}catch(t){let e=eO(t);return this.patchDoctorState({fixPending:!1,lastFixError:e}),null}},this.loadSkillHealthDiagnostics=async()=>{this.patchDiagnosticsPhaseState("skillHealth",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/skill-health"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Skill health request failed with ${e.status}`;return this.patchDiagnosticsPhaseState("skillHealth",{phase:"error",error:s}),null}return this.patchDiagnosticsPhaseState("skillHealth",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchDiagnosticsPhaseState("skillHealth",{phase:"error",error:e}),null}},this.loadKnowledgeData=async()=>{this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/knowledge"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Knowledge request failed with ${e.status}`;return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"error",error:s}),null}return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchKnowledgeCapturesPhaseState("knowledge",{phase:"error",error:e}),null}},this.loadCapturesData=async()=>{this.patchKnowledgeCapturesPhaseState("captures",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/captures"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Captures request failed with ${e.status}`;return this.patchKnowledgeCapturesPhaseState("captures",{phase:"error",error:s}),null}return this.patchKnowledgeCapturesPhaseState("captures",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchKnowledgeCapturesPhaseState("captures",{phase:"error",error:e}),null}},this.loadSettingsData=async()=>{this.patchSettingsPhaseState({phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/settings-data"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Settings request failed with ${e.status}`;return this.patchSettingsPhaseState({phase:"error",error:s}),null}return this.patchSettingsPhaseState({phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchSettingsPhaseState({phase:"error",error:e}),null}},this.loadHistoryData=async()=>{this.patchRemainingCommandsPhaseState("history",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/history"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`History request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("history",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("history",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("history",{phase:"error",error:e}),null}},this.loadInspectData=async()=>{this.patchRemainingCommandsPhaseState("inspect",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/inspect"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Inspect request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("inspect",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("inspect",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("inspect",{phase:"error",error:e}),null}},this.loadHooksData=async()=>{this.patchRemainingCommandsPhaseState("hooks",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/hooks"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Hooks request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("hooks",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("hooks",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("hooks",{phase:"error",error:e}),null}},this.loadExportData=async e=>{this.patchRemainingCommandsPhaseState("exportData",{phase:"loading",error:null});try{let t=e?`/api/export-data?format=${encodeURIComponent(e)}`:"/api/export-data",s=await e$(t,{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Export request failed with ${s.status}`;return this.patchRemainingCommandsPhaseState("exportData",{phase:"error",error:e}),null}return this.patchRemainingCommandsPhaseState("exportData",{phase:"loaded",data:r,lastLoadedAt:new Date().toISOString()}),r}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("exportData",{phase:"error",error:e}),null}},this.loadUndoInfo=async()=>{this.patchRemainingCommandsPhaseState("undo",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/undo"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Undo info request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("undo",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("undo",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("undo",{phase:"error",error:e}),null}},this.loadCleanupData=async()=>{this.patchRemainingCommandsPhaseState("cleanup",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/cleanup"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Cleanup data request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("cleanup",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("cleanup",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("cleanup",{phase:"error",error:e}),null}},this.loadSteerData=async()=>{this.patchRemainingCommandsPhaseState("steer",{phase:"loading",error:null});try{let e=await e$(this.buildUrl("/api/steer"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Steer data request failed with ${e.status}`;return this.patchRemainingCommandsPhaseState("steer",{phase:"error",error:s}),null}return this.patchRemainingCommandsPhaseState("steer",{phase:"loaded",data:t,lastLoadedAt:new Date().toISOString()}),t}catch(t){let e=eO(t);return this.patchRemainingCommandsPhaseState("steer",{phase:"error",error:e}),null}},this.executeUndoAction=async()=>{try{let e=await e$(this.buildUrl("/api/undo"),{method:"POST",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t){let s=t?.error??`Undo action failed with ${e.status}`;return{success:!1,message:s}}return this.loadUndoInfo(),t}catch(e){return{success:!1,message:eO(e)}}},this.executeCleanupAction=async(e,t)=>{try{let s=await e$(this.buildUrl("/api/cleanup"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({branches:e,snapshots:t})}),r=await s.json().catch(()=>null);if(!s.ok||!r){let e=r?.error??`Cleanup action failed with ${s.status}`;return{deletedBranches:0,prunedSnapshots:0,message:e}}return this.loadCleanupData(),r}catch(e){return{deletedBranches:0,prunedSnapshots:0,message:eO(e)}}},this.resolveCaptureAction=async e=>{this.patchKnowledgeCapturesState({resolveRequest:{pending:!0,lastError:null,lastResult:null}});try{let t=await e$(this.buildUrl("/api/captures"),{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>null);if(!t.ok||!s){let e=s?.error??`Capture resolve failed with ${t.status}`;return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:e,lastResult:null}}),null}return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:null,lastResult:s}}),this.loadCapturesData(),s}catch(t){let e=eO(t);return this.patchKnowledgeCapturesState({resolveRequest:{pending:!1,lastError:e,lastResult:null}}),null}},this.updateSessionBrowserState=e=>{this.patchState({commandSurface:{...this.state.commandSurface,sessionBrowser:{...this.state.commandSurface.sessionBrowser,...e,error:null},lastError:null,lastResult:null}})},this.loadSessionBrowser=async(e={})=>{let t={...this.state.commandSurface.sessionBrowser,...e,error:null},s={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:tn(this.state.live.freshness.sessionBrowser)}};this.patchState({live:{...s,recoverySummary:tm({boot:this.state.boot,live:s})},commandSurface:eR({...this.state.commandSurface,sessionBrowser:t},"load_session_browser")});let r=new URLSearchParams;t.query.trim()&&r.set("query",t.query.trim()),r.set("sortMode",t.sortMode),r.set("nameFilter",t.nameFilter);try{let e=await e$(this.buildUrl(`/api/session/browser?${r.toString()}`),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),s=await e.json().catch(()=>null),a=function(e){if(!e||"object"!=typeof e)return null;let t=e.project,s=e.query;if(!t||!s||!Array.isArray(e.sessions)||"current_project"!==t.scope||"string"!=typeof t.cwd||"string"!=typeof t.sessionsDir||"string"!=typeof s.query||"string"!=typeof s.sortMode||"string"!=typeof s.nameFilter)return null;let r=e.sessions.filter(e=>"string"==typeof e?.id&&"string"==typeof e?.path&&"string"==typeof e?.cwd&&"string"==typeof e?.createdAt&&"string"==typeof e?.modifiedAt&&"number"==typeof e?.messageCount&&"string"==typeof e?.firstMessage&&"boolean"==typeof e?.isActive&&"number"==typeof e?.depth&&"boolean"==typeof e?.isLastInThread&&Array.isArray(e?.ancestorHasNextSibling));return{scope:t.scope,projectCwd:t.cwd,projectSessionsDir:t.sessionsDir,activeSessionPath:"string"==typeof t.activeSessionPath?t.activeSessionPath:null,query:s.query,sortMode:s.sortMode,nameFilter:s.nameFilter,totalSessions:Number(e.totalSessions??r.length),returnedSessions:Number(e.returnedSessions??r.length),sessions:r,loaded:!0,error:null}}(s);if(!e.ok||!a){let r=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Current-project session browser failed with ${e.status}`,a={...t,error:r},n={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:tl(this.state.live.freshness.sessionBrowser,r)}};return this.patchState({live:{...n,recoverySummary:tm({boot:this.state.boot,live:n})},commandSurface:eE({...this.state.commandSurface,sessionBrowser:a},{action:"load_session_browser",success:!1,message:r,sessionBrowser:a})}),null}let n=e9(a,this.state.boot),i=this.state.commandSurface.selectedTarget,o=n.sessions.find(e=>!e.isActive)?.path??n.sessions[0]?.path,l=n.sessions.find(e=>e.path===n.activeSessionPath)??n.sessions[0],d=i;if(i?.kind==="resume"||"resume"===this.state.commandSurface.section){let e=i?.kind==="resume"&&i.sessionPath&&n.sessions.some(e=>e.path===i.sessionPath)?i.sessionPath:o;d={kind:"resume",sessionPath:e}}else if(i?.kind==="name"||"name"===this.state.commandSurface.section){let e=i?.kind==="name"&&i.sessionPath?n.sessions.find(e=>e.path===i.sessionPath)??l:l;d={kind:"name",sessionPath:e?.path,name:i?.kind==="name"&&i.sessionPath===e?.path?i.name:e?.name??""}}let c={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:to(this.state.live.freshness.sessionBrowser)}};return this.patchState({live:{...c,recoverySummary:tm({boot:this.state.boot,live:c})},commandSurface:eE({...this.state.commandSurface,sessionBrowser:n},{action:"load_session_browser",success:!0,message:"",selectedTarget:d,sessionBrowser:n})}),n}catch(a){let e=eO(a),s={...t,error:e},r={...this.state.live,freshness:{...this.state.live.freshness,sessionBrowser:tl(this.state.live.freshness.sessionBrowser,e)}};return this.patchState({live:{...r,recoverySummary:tm({boot:this.state.boot,live:r})},commandSurface:eE({...this.state.commandSurface,sessionBrowser:s},{action:"load_session_browser",success:!1,message:e,sessionBrowser:s})}),null}},this.renameSessionFromSurface=async(e,t)=>{let s=this.state.commandSurface.selectedTarget,r=t??(s?.kind==="name"?s.name:""),a=r.trim(),n={kind:"name",sessionPath:e,name:r};if(!a)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"rename_session",success:!1,message:"Session name cannot be empty",selectedTarget:n})}),null;this.patchState({commandSurface:eR(this.state.commandSurface,"rename_session",n)});try{let t=await e$(this.buildUrl("/api/session/manage"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({action:"rename",sessionPath:e,name:a})}),s=await t.json().catch(()=>null);if(!t.ok||!s||"object"!=typeof s||!0!==s.success){let e=s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error?s.error:`Session rename failed with ${t.status}`;return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"rename_session",success:!1,message:e,selectedTarget:n})}),null}let r=function(e,t,s){if(!e)return null;let r=e6(e)===t&&e.bridge.sessionState?{...e.bridge,sessionState:{...e.bridge.sessionState,sessionName:s}}:e.bridge,a={...e,bridge:r};return{...a,resumableSessions:e7(a.resumableSessions.map(e=>e.path===t?{...e,name:s}:e),a)}}(this.state.boot,s.sessionPath,s.name),i=e9(te(this.state.commandSurface.sessionBrowser,s.sessionPath,{name:s.name,...s.isActiveSession?{isActive:!0}:{}}),r),o={kind:"name",sessionPath:s.sessionPath,name:s.name},l={...this.state.live,resumableSessions:e7(tu(this.state).map(e=>e.path===s.sessionPath?{...e,name:s.name}:e),r)};return this.patchState({...r?{boot:r}:{},live:{...l,recoverySummary:tm({boot:r,live:l})},commandSurface:eE({...this.state.commandSurface,sessionBrowser:i},{action:"rename_session",success:!0,message:`Session name set: ${s.name}`,selectedTarget:o,sessionBrowser:i})}),s}catch(t){let e=eO(t);return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"rename_session",success:!1,message:e,selectedTarget:n})}),null}},this.loadAvailableModels=async()=>{this.patchState({commandSurface:eR(this.state.commandSurface,"loading_models")});let e=await this.sendCommand({type:"get_available_models"},{appendInputLine:!1,appendResponseLine:!1});if(!e||!1===e.success){let t=e?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"loading_models",success:!1,message:`Couldn't load models — ${t}`})}),[]}let t=function(e,t){let s=e&&"object"==typeof e&&"models"in e&&Array.isArray(e.models)?e.models:[],r=[];for(let e of s){let s="string"==typeof e.provider?e.provider:"string"==typeof e.providerId?e.providerId:void 0,a="string"==typeof e.id?e.id:void 0;s&&a&&r.push({provider:s,modelId:a,name:"string"==typeof e.name?e.name:void 0,reasoning:!!e.reasoning,isCurrent:s===t?.provider&&a===t?.modelId})}return r.sort((e,t)=>Number(t.isCurrent)-Number(e.isCurrent)||e.provider.localeCompare(t.provider)||e.modelId.localeCompare(t.modelId))}(e.data,e2(this.state.boot?.bridge)),s=this.state.commandSurface.selectedTarget,r=s?.kind==="model"?s:t[0]?{kind:"model",provider:t[0].provider,modelId:t[0].modelId}:s;return this.patchState({commandSurface:{...this.state.commandSurface,pendingAction:null,lastError:null,availableModels:t,selectedTarget:r??null}}),t},this.applyModelSelection=async(e,t)=>{let s={kind:"model",provider:e,modelId:t};this.patchState({commandSurface:eR(this.state.commandSurface,"set_model",s)});let r=await this.sendCommand({type:"set_model",provider:e,modelId:t},{appendInputLine:!1,appendResponseLine:!1});if(!r||!1===r.success){let e=r?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"set_model",success:!1,message:e,selectedTarget:s})}),r}let a=this.state.boot?.bridge.sessionState?{...this.state.boot.bridge,sessionState:{...this.state.boot.bridge.sessionState,model:r.data}}:null,n=this.state.commandSurface.availableModels.map(s=>({...s,isCurrent:s.provider===e&&s.modelId===t}));return this.patchState({...a&&this.state.boot?{boot:eW(this.state.boot,a)}:{},commandSurface:eE(this.state.commandSurface,{action:"set_model",success:!0,message:`Model set to ${e}/${t}`,selectedTarget:s,availableModels:n})}),r},this.applyThinkingLevel=async e=>{let t={kind:"thinking",level:e};this.patchState({commandSurface:eR(this.state.commandSurface,"set_thinking_level",t)});let s=await this.sendCommand({type:"set_thinking_level",level:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"set_thinking_level",success:!1,message:e,selectedTarget:t})}),s}let r=this.state.boot?.bridge.sessionState?{...this.state.boot.bridge,sessionState:{...this.state.boot.bridge.sessionState,thinkingLevel:e}}:null;return this.patchState({...r&&this.state.boot?{boot:eW(this.state.boot,r)}:{},commandSurface:eE(this.state.commandSurface,{action:"set_thinking_level",success:!0,message:`Thinking level set to ${e}`,selectedTarget:t})}),s},this.setSteeringModeFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:eR(this.state.commandSurface,"set_steering_mode",t)});let s=await this.sendCommand({type:"set_steering_mode",mode:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"set_steering_mode",success:!1,message:e,selectedTarget:t})}),s}let r=eK(this.state.boot,{steeringMode:e});return this.patchState({...r?{boot:r}:{},commandSurface:eE(this.state.commandSurface,{action:"set_steering_mode",success:!0,message:`Steering mode set to ${e}`,selectedTarget:t})}),s},this.setFollowUpModeFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:eR(this.state.commandSurface,"set_follow_up_mode",t)});let s=await this.sendCommand({type:"set_follow_up_mode",mode:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"set_follow_up_mode",success:!1,message:e,selectedTarget:t})}),s}let r=eK(this.state.boot,{followUpMode:e});return this.patchState({...r?{boot:r}:{},commandSurface:eE(this.state.commandSurface,{action:"set_follow_up_mode",success:!0,message:`Follow-up mode set to ${e}`,selectedTarget:t})}),s},this.setAutoCompactionFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:eR(this.state.commandSurface,"set_auto_compaction",t)});let s=await this.sendCommand({type:"set_auto_compaction",enabled:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"set_auto_compaction",success:!1,message:e,selectedTarget:t})}),s}let r=eK(this.state.boot,{autoCompactionEnabled:e});return this.patchState({...r?{boot:r}:{},commandSurface:eE(this.state.commandSurface,{action:"set_auto_compaction",success:!0,message:`Auto-compaction ${e?"enabled":"disabled"}`,selectedTarget:t})}),s},this.setAutoRetryFromSurface=async e=>{let t=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:eR(this.state.commandSurface,"set_auto_retry",t)});let s=await this.sendCommand({type:"set_auto_retry",enabled:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"set_auto_retry",success:!1,message:e,selectedTarget:t})}),s}let r=eK(this.state.boot,{autoRetryEnabled:e});return this.patchState({...r?{boot:r}:{},commandSurface:eE(this.state.commandSurface,{action:"set_auto_retry",success:!0,message:`Auto-retry ${e?"enabled":"disabled"}`,selectedTarget:t})}),s},this.abortRetryFromSurface=async()=>{let e=this.state.commandSurface.selectedTarget;this.patchState({commandSurface:eR(this.state.commandSurface,"abort_retry",e)});let t=await this.sendCommand({type:"abort_retry"},{appendInputLine:!1,appendResponseLine:!1});if(!t||!1===t.success){let s=t?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"abort_retry",success:!1,message:s,selectedTarget:e})}),t}return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"abort_retry",success:!0,message:"Retry cancellation requested. Live retry state will update when the bridge confirms the abort.",selectedTarget:e})}),t},this.switchSessionFromSurface=async e=>{var t;let s,r={kind:"resume",sessionPath:e};this.patchState({commandSurface:eR(this.state.commandSurface,"switch_session",r)});let a=await this.sendCommand({type:"switch_session",sessionPath:e},{appendInputLine:!1,appendResponseLine:!1});if(!a||!1===a.success){let e=a?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"switch_session",success:!1,message:e,selectedTarget:r})}),a}if(a.data&&"object"==typeof a.data&&"cancelled"in a.data&&a.data.cancelled)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"switch_session",success:!1,message:"Session switch was cancelled before the browser changed sessions.",selectedTarget:r})}),a;let n=this.state.commandSurface.sessionBrowser.sessions.find(t=>t.path===e)?.name??this.state.boot?.resumableSessions.find(t=>t.path===e)?.name,i=function(e,t,s){if(!e)return null;let r=e.resumableSessions.find(e=>e.path===t),a={...e.bridge,activeSessionFile:t,activeSessionId:r?.id??e.bridge.activeSessionId,sessionState:e.bridge.sessionState?{...e.bridge.sessionState,sessionFile:t,sessionId:r?.id??e.bridge.sessionState.sessionId,sessionName:s??r?.name??e.bridge.sessionState.sessionName}:e.bridge.sessionState},n={...e,bridge:a};return{...n,resumableSessions:e7(n.resumableSessions.map(e=>({...e,isActive:e.path===t})),n)}}(this.state.boot,e,n),o=e9(te(this.state.commandSurface.sessionBrowser,e,{isActive:!0,...n?{name:n}:{}}),i),l={...this.state.live,resumableSessions:e7(tu(this.state).map(t=>({...t,isActive:t.path===e,...t.path===e&&n?{name:n}:{}})),i)};return this.patchState({...i?{boot:i}:{},live:{...l,recoverySummary:tm({boot:i,live:l})},commandSurface:eE({...this.state.commandSurface,sessionBrowser:o},{action:"switch_session",success:!0,message:`Switched to ${(t=i??this.state.boot,s=t?.resumableSessions.find(t=>t.path===e),s?.name?.trim()?s.name.trim():s?.id?s.id:eY(e))}`,selectedTarget:r,sessionBrowser:o})}),a},this.loadSessionStats=async()=>{var e;let t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:tn(this.state.live.freshness.sessionStats)}};this.patchState({live:{...t,recoverySummary:tm({boot:this.state.boot,live:t})},commandSurface:eR(this.state.commandSurface,"load_session_stats")});let s=await this.sendCommand({type:"get_session_stats"},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error",t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:tl(this.state.live.freshness.sessionStats,e)}};return this.patchState({live:{...t,recoverySummary:tm({boot:this.state.boot,live:t})},commandSurface:eE(this.state.commandSurface,{action:"load_session_stats",success:!1,message:`Couldn't load session details — ${e}`,sessionStats:null})}),null}let r=(e=s.data)&&"object"==typeof e?"string"!=typeof e.sessionId?null:{sessionFile:"string"==typeof e.sessionFile?e.sessionFile:void 0,sessionId:e.sessionId,userMessages:Number(e.userMessages??0),assistantMessages:Number(e.assistantMessages??0),toolCalls:Number(e.toolCalls??0),toolResults:Number(e.toolResults??0),totalMessages:Number(e.totalMessages??0),tokens:{input:Number(e.tokens?.input??0),output:Number(e.tokens?.output??0),cacheRead:Number(e.tokens?.cacheRead??0),cacheWrite:Number(e.tokens?.cacheWrite??0),total:Number(e.tokens?.total??0)},cost:Number(e.cost??0)}:null;if(!r){let e="Session details response was missing the expected fields.",t={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:tl(this.state.live.freshness.sessionStats,e)}};return this.patchState({live:{...t,recoverySummary:tm({boot:this.state.boot,live:t})},commandSurface:eE(this.state.commandSurface,{action:"load_session_stats",success:!1,message:e,sessionStats:null})}),null}let a={...this.state.live,freshness:{...this.state.live.freshness,sessionStats:to(this.state.live.freshness.sessionStats)}};return this.patchState({live:{...a,recoverySummary:tm({boot:this.state.boot,live:a})},commandSurface:eE(this.state.commandSurface,{action:"load_session_stats",success:!0,message:`Loaded session details for ${r.sessionId}`,sessionStats:r})}),r},this.exportSessionFromSurface=async e=>{let t=e?.trim()||void 0,s={kind:"session",outputPath:t};this.patchState({commandSurface:eR(this.state.commandSurface,"export_html",s)});let r=await this.sendCommand(t?{type:"export_html",outputPath:t}:{type:"export_html"},{appendInputLine:!1,appendResponseLine:!1});if(!r||!1===r.success){let e=r?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"export_html",success:!1,message:`Couldn't export this session — ${e}`,selectedTarget:s})}),r}let a=r.data&&"object"==typeof r.data&&"path"in r.data&&"string"==typeof r.data.path?r.data.path:"the generated file";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"export_html",success:!0,message:`Session exported to ${a}`,selectedTarget:s})}),r},this.loadForkMessages=async()=>{var e;this.patchState({commandSurface:eR(this.state.commandSurface,"load_fork_messages")});let t=await this.sendCommand({type:"get_fork_messages"},{appendInputLine:!1,appendResponseLine:!1});if(!t||!1===t.success){let e=t?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"load_fork_messages",success:!1,message:`Couldn't load fork points — ${e}`,forkMessages:[]})}),[]}let s=((e=t.data)&&"object"==typeof e&&"messages"in e&&Array.isArray(e.messages)?e.messages:[]).map(e=>{let t="string"==typeof e.entryId?e.entryId:void 0,s="string"==typeof e.text?e.text:void 0;return t&&s?{entryId:t,text:s}:null}).filter(e=>null!==e),r=this.state.commandSurface.selectedTarget,a=r?.kind==="fork"&&r.entryId?r:s[0]?{kind:"fork",entryId:s[0].entryId}:r;return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"load_fork_messages",success:!0,message:s.length>0?`Loaded ${s.length} fork points.`:"No fork points are available yet.",selectedTarget:a??null,forkMessages:s})}),s},this.forkSessionFromSurface=async e=>{let t={kind:"fork",entryId:e};this.patchState({commandSurface:eR(this.state.commandSurface,"fork_session",t)});let s=await this.sendCommand({type:"fork",entryId:e},{appendInputLine:!1,appendResponseLine:!1});if(!s||!1===s.success){let e=s?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"fork_session",success:!1,message:`Couldn't create a fork — ${e}`,selectedTarget:t})}),s}if(s.data&&"object"==typeof s.data&&"cancelled"in s.data&&s.data.cancelled)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"fork_session",success:!1,message:"Fork creation was cancelled before a new session was created.",selectedTarget:t})}),s;let r=s.data&&"object"==typeof s.data&&"text"in s.data&&"string"==typeof s.data.text?s.data.text.trim():"";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"fork_session",success:!0,message:r?`Forked from “${r.slice(0,120)}${r.length>120?"…":""}”`:"Created a forked session.",selectedTarget:t})}),s},this.compactSessionFromSurface=async e=>{var t;let s=e?.trim()??"",r={kind:"compact",customInstructions:s};this.patchState({commandSurface:eR(this.state.commandSurface,"compact_session",r)});let a=await this.sendCommand(s?{type:"compact",customInstructions:s}:{type:"compact"},{appendInputLine:!1,appendResponseLine:!1});if(!a||!1===a.success){let e=a?.error??this.state.lastClientError??"Unknown error";return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"compact_session",success:!1,message:`Couldn't compact the session — ${e}`,selectedTarget:r,lastCompaction:null})}),a}let n=(t=a.data)&&"object"==typeof t?"string"!=typeof t.summary||"string"!=typeof t.firstKeptEntryId?null:{summary:t.summary,firstKeptEntryId:t.firstKeptEntryId,tokensBefore:Number(t.tokensBefore??0),details:t.details}:null;return n?this.patchState({commandSurface:eE(this.state.commandSurface,{action:"compact_session",success:!0,message:`Compacted ${n.tokensBefore.toLocaleString()} tokens into a fresh summary${s?" with custom instructions":""}.`,selectedTarget:r,lastCompaction:n})}):this.patchState({commandSurface:eE(this.state.commandSurface,{action:"compact_session",success:!1,message:"Compaction finished but the browser could not read the compaction result.",selectedTarget:r,lastCompaction:null})}),a},this.saveApiKeyFromSurface=async(e,t)=>{let s={kind:"auth",providerId:e,intent:"manage"};this.patchState({commandSurface:eR(this.state.commandSurface,"save_api_key",s)});let r=await this.saveApiKey(e,t),a=r?eG(r,e):e;return r?(r.lastValidation?.status==="failed"?this.patchState({commandSurface:eE(this.state.commandSurface,{action:"save_api_key",success:!1,message:r.lastValidation.message,selectedTarget:s})}):"failed"===r.bridgeAuthRefresh.phase?this.patchState({commandSurface:eE(this.state.commandSurface,{action:"save_api_key",success:!1,message:r.bridgeAuthRefresh.error??`${a} credentials validated but bridge auth refresh failed`,selectedTarget:s})}):this.patchState({commandSurface:eE(this.state.commandSurface,{action:"save_api_key",success:!0,message:`${a} credentials validated and saved.`,selectedTarget:s})}),r):(this.patchState({commandSurface:eE(this.state.commandSurface,{action:"save_api_key",success:!1,message:this.state.lastClientError??`${a} setup failed`,selectedTarget:s})}),null)},this.startProviderFlowFromSurface=async e=>{let t={kind:"auth",providerId:e,intent:"login"};this.patchState({commandSurface:eR(this.state.commandSurface,"start_provider_flow",t)});let s=await this.startProviderFlow(e),r=s?eG(s,e):e;return s?(this.patchState({commandSurface:eE(this.state.commandSurface,{action:"start_provider_flow",success:!0,message:`${r} sign-in started. Continue in the auth section.`,selectedTarget:t})}),s):(this.patchState({commandSurface:eE(this.state.commandSurface,{action:"start_provider_flow",success:!1,message:this.state.lastClientError??`${r} sign-in failed to start`,selectedTarget:t})}),null)},this.submitProviderFlowInputFromSurface=async(e,t)=>{let s=this.state.boot?.onboarding.activeFlow?.providerId??void 0,r={kind:"auth",providerId:s,intent:"login"};this.patchState({commandSurface:eR(this.state.commandSurface,"submit_provider_flow_input",r)});let a=await this.submitProviderFlowInput(e,t),n=a?.activeFlow?.providerLabel??(s&&a?eG(a,s):s)??"Provider";if(!a)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:this.state.lastClientError??`${n} sign-in failed`,selectedTarget:r})}),null;if(a.activeFlow?.status==="failed")return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:a.activeFlow.error??`${n} sign-in failed`,selectedTarget:r})}),a;if("failed"===a.bridgeAuthRefresh.phase)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"submit_provider_flow_input",success:!1,message:a.bridgeAuthRefresh.error??`${n} sign-in completed but bridge auth refresh failed`,selectedTarget:r})}),a;let i=a.activeFlow&&["running","awaiting_browser_auth","awaiting_input"].includes(a.activeFlow.status)?`${n} sign-in advanced. Complete the remaining step in this panel.`:`${n} sign-in complete.`;return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"submit_provider_flow_input",success:!0,message:i,selectedTarget:r})}),a},this.cancelProviderFlowFromSurface=async e=>{let t=this.state.boot?.onboarding.activeFlow?.providerId??void 0,s={kind:"auth",providerId:t,intent:"login"};this.patchState({commandSurface:eR(this.state.commandSurface,"cancel_provider_flow",s)});let r=await this.cancelProviderFlow(e),a=r?.activeFlow?.providerLabel??(t&&r?eG(r,t):t)??"Provider";return r?(this.patchState({commandSurface:eE(this.state.commandSurface,{action:"cancel_provider_flow",success:!0,message:`${a} sign-in cancelled.`,selectedTarget:s})}),r):(this.patchState({commandSurface:eE(this.state.commandSurface,{action:"cancel_provider_flow",success:!1,message:this.state.lastClientError??`${a} sign-in cancellation failed`,selectedTarget:s})}),null)},this.logoutProviderFromSurface=async e=>{let t={kind:"auth",providerId:e,intent:"logout"};this.patchState({commandSurface:eR(this.state.commandSurface,"logout_provider",t)});let s=await this.logoutProvider(e),r=s?eG(s,e):e;if(!s)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"logout_provider",success:!1,message:this.state.lastClientError??`${r} logout failed`,selectedTarget:t})}),null;if("failed"===s.bridgeAuthRefresh.phase)return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"logout_provider",success:!1,message:s.bridgeAuthRefresh.error??`${r} logout completed but bridge auth refresh failed`,selectedTarget:t})}),s;let a=s.required.providers.find(t=>t.id===e),n=a?.configured?`${r} saved credentials were removed, but ${a.configuredVia} auth still keeps the provider available.`:s.locked?`${r} logged out — required setup is needed again.`:`${r} logged out.`;return this.patchState({commandSurface:eE(this.state.commandSurface,{action:"logout_provider",success:!0,message:n,selectedTarget:t})}),s},this.respondToUiRequest=async(e,t)=>{this.patchState({commandInFlight:"extension_ui_response"});try{let s=await e$(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({type:"extension_ui_response",id:e,...t})});if(!s.ok){let e=await s.json().catch(()=>({error:`HTTP ${s.status}`}));throw Error(e.error??`extension_ui_response failed with ${s.status}`)}this.patchState({pendingUiRequests:this.state.pendingUiRequests.filter(t=>t.id!==e)})}catch(t){let e=eO(t);this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`UI response failed — ${e}`))})}finally{this.patchState({commandInFlight:null})}},this.dismissUiRequest=async e=>{this.patchState({commandInFlight:"extension_ui_response"});try{let t=await e$(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({type:"extension_ui_response",id:e,cancelled:!0})});if(!t.ok){let e=await t.json().catch(()=>({error:`HTTP ${t.status}`}));throw Error(e.error??`extension_ui_response cancel failed with ${t.status}`)}this.patchState({pendingUiRequests:this.state.pendingUiRequests.filter(t=>t.id!==e)})}catch(t){let e=eO(t);this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`UI dismiss failed — ${e}`))})}finally{this.patchState({commandInFlight:null})}},this.sendSteer=async e=>{await this.sendCommand({type:"steer",message:e})},this.sendAbort=async()=>{await this.sendCommand({type:"abort"})},this.pushChatUserMessage=e=>{this.patchState({chatUserMessages:[...this.state.chatUserMessages,e]})},this.submitInput=async(e,t)=>{let s=e.trim();if(!s)return null;let r=ea(s,{isStreaming:this.state.boot?.bridge.sessionState?.isStreaming});switch(this.patchState({lastSlashCommandOutcome:s.startsWith("/")?r:null}),r.kind){case"prompt":case"rpc":{let e=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),a=e&&e.length>0?{...r.command,images:e}:r.command;return await this.sendCommand(a,{displayInput:s}),r}case"local":if("clear_terminal"===r.action)return this.clearTerminalLines(),r;if("refresh_workspace"===r.action)return await this.refreshBoot(),r;return"gsd_help"===r.action&&this.patchState({terminalLines:eM(eM(this.state.terminalLines,eL("input",s)),eL("system",es))}),r;case"surface":{if(eF.has(r.surface))return this.patchState({terminalLines:eM(this.state.terminalLines,eL("input",s))}),this.openCommandSurface(r.surface,{source:"slash",args:r.args}),r;let e=en(r),t=eM(this.state.terminalLines,eL("input",s));return e&&(t=eM(t,eL(e.type,e.message))),this.patchState({terminalLines:t}),r}case"reject":{let e=en(r),t=eM(this.state.terminalLines,eL("input",s));return e&&(t=eM(t,eL(e.type,e.message))),this.patchState({terminalLines:t}),r}case"view-navigate":return this.patchState({terminalLines:eM(this.state.terminalLines,eL("system",`Navigating to ${r.view} view`))}),window.dispatchEvent(new CustomEvent("gsd:navigate-view",{detail:{view:r.view}})),r}},this.refreshBoot=async(e={})=>{if(this.bootPromise)return await this.bootPromise;this.lastBootRefreshAt=Date.now();let t=!!(e.soft&&this.state.boot);this.bootPromise=(async()=>{t?this.patchState({lastClientError:null}):this.patchState({bootStatus:"loading",connectionState:"connected"===this.state.connectionState?"connected":"connecting",lastClientError:null});try{let e=await e$(this.buildUrl("/api/boot"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok){if(401===e.status)return void this.patchState({bootStatus:"unauthenticated",connectionState:"error"});throw Error(`Boot request failed with ${e.status}`)}let s=await e.json(),r=eW(s,s.bridge)??s,a=function(e,t,s={}){let r={...e,auto:t.auto,workspace:t.workspace,resumableSessions:t.resumableSessions,freshness:{...e.freshness,auto:to(e.freshness.auto),workspace:to(e.freshness.workspace),recovery:to(e.freshness.recovery),resumableSessions:to(e.freshness.resumableSessions)},softBootRefreshCount:e.softBootRefreshCount+ +!!s.soft};return r.recoverySummary=tm({boot:t,live:r}),r}(this.state.live,r,{soft:t});this.lastBridgeDigest=null,this.lastBridgeDigest=[r.bridge.phase,r.bridge.activeSessionId,r.bridge.lastError?.at,r.bridge.lastError?.message].join("::"),this.patchState({bootStatus:"ready",boot:r,live:a,connectionState:r.onboarding.locked?"idle":this.eventSource?this.state.connectionState:"connecting",lastBridgeError:r.bridge.lastError,sessionAttached:eq(r.bridge),lastClientError:null,...t?{}:{terminalLines:eJ(r)}}),r.onboarding.locked?this.closeEventStream():this.ensureEventStream()}catch(s){let e=eO(s);if(t)return void this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Workspace refresh failed — ${e}`))});this.patchState({bootStatus:"error",connectionState:"error",lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Boot failed — ${e}`))})}})().finally(()=>{this.bootPromise=null}),await this.bootPromise},this.refreshOnboarding=async()=>{this.patchState({onboardingRequestState:"refreshing",onboardingRequestProviderId:null,lastClientError:null});try{return await this.fetchOnboardingState()}catch(t){let e=eO(t);return this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Onboarding refresh failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.saveApiKey=async(e,t)=>{this.patchState({onboardingRequestState:"saving_api_key",onboardingRequestProviderId:e,lastClientError:null});try{let s=await this.postOnboardingAction({action:"save_api_key",providerId:e,apiKey:t});return await this.syncAfterOnboardingMutation(s),s}catch(t){let e=eO(t);return this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Credential setup failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.startProviderFlow=async e=>{this.patchState({onboardingRequestState:"starting_provider_flow",onboardingRequestProviderId:e,lastClientError:null});try{let t=await this.postOnboardingAction({action:"start_provider_flow",providerId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=eO(t);return this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Provider sign-in failed to start — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.submitProviderFlowInput=async(e,t)=>{this.patchState({onboardingRequestState:"submitting_provider_flow_input",onboardingRequestProviderId:this.state.boot?.onboarding.activeFlow?.providerId??null,lastClientError:null});try{let s=await this.postOnboardingAction({action:"continue_provider_flow",flowId:e,input:t});return await this.syncAfterOnboardingMutation(s),s}catch(t){let e=eO(t);return this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Provider sign-in input failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.cancelProviderFlow=async e=>{this.patchState({onboardingRequestState:"cancelling_provider_flow",onboardingRequestProviderId:this.state.boot?.onboarding.activeFlow?.providerId??null,lastClientError:null});try{let t=await this.postOnboardingAction({action:"cancel_provider_flow",flowId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=eO(t);return this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Provider sign-in cancellation failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.logoutProvider=async e=>{this.patchState({onboardingRequestState:"logging_out_provider",onboardingRequestProviderId:e,lastClientError:null});try{let t=await this.postOnboardingAction({action:"logout_provider",providerId:e});return await this.syncAfterOnboardingMutation(t),t}catch(t){let e=eO(t);return this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Provider logout failed — ${e}`))}),null}finally{this.patchState({onboardingRequestState:"idle",onboardingRequestProviderId:null})}},this.sendCommand=async(e,t={})=>{this.clearCommandTimeout();let s={commandInFlight:e.type};!1!==t.appendInputLine&&(s.terminalLines=eM(this.state.terminalLines,eL("input",t.displayInput??("string"==typeof e.message?e.message:`/${e.type}`)))),this.patchState(s),this.commandTimeoutTimer=setTimeout(()=>{this.state.commandInFlight&&this.patchState({commandInFlight:null,lastClientError:"Command timed out — controls re-enabled",terminalLines:eM(this.state.terminalLines,eL("error","Command timed out — controls re-enabled"))})},9e4);try{let s=await e$(this.buildUrl("/api/session/command"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),r=await s.json();if("ok"in r)return null;if("get_state"===r.command&&r.success&&this.state.boot){let e={...this.state.boot.bridge,sessionState:r.data,activeSessionId:r.data.sessionId,activeSessionFile:r.data.sessionFile??this.state.boot.bridge.activeSessionFile,lastCommandType:"get_state",updatedAt:new Date().toISOString()};this.patchState({boot:eW(this.state.boot,e),lastBridgeError:e.lastError,sessionAttached:eq(e)})}return"onboarding_locked"===r.code&&r.details?.onboarding&&this.state.boot&&this.patchState({boot:function(e,t){var s;return e?eH(e,(s=e.onboarding,{...s,...t,required:{...s.required,...t.required??{},providers:t.required?.providers??s.required.providers},optional:{...s.optional,...t.optional??{},sections:t.optional?.sections??s.optional.sections},bridgeAuthRefresh:{...s.bridgeAuthRefresh,...t.bridgeAuthRefresh??{}}})):null}(this.state.boot,r.details.onboarding)}),this.patchState({...!1===t.appendResponseLine?{}:{terminalLines:eM(this.state.terminalLines,function(e){if(!e.success)return eL("error",`Command failed (${e.command}) — ${e.error??"unknown error"}`);switch(e.command){case"get_state":return eL("success","Session state refreshed");case"new_session":return eL("success","Started a new session");case"prompt":return eL("success","Prompt accepted by the live bridge");case"follow_up":return eL("success","Follow-up queued on the live bridge");default:return eL("success",`Command accepted (${e.command})`)}}(r))},lastBridgeError:r.success?this.state.lastBridgeError:this.state.boot?.bridge.lastError??this.state.lastBridgeError}),r}catch(s){let t=eO(s);return this.patchState({lastClientError:t,terminalLines:eM(this.state.terminalLines,eL("error",`Command failed (${e.type}) — ${t}`))}),{type:"response",command:e.type,success:!1,error:t}}finally{this.clearCommandTimeout(),this.patchState({commandInFlight:null})}}}buildUrl(e){return tx(e,this.projectCwd)}patchDiagnosticsPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,diagnostics:{...this.state.commandSurface.diagnostics,[e]:{...this.state.commandSurface.diagnostics[e],...t}}}})}patchDoctorState(e){this.patchState({commandSurface:{...this.state.commandSurface,diagnostics:{...this.state.commandSurface.diagnostics,doctor:{...this.state.commandSurface.diagnostics.doctor,...e}}}})}patchKnowledgeCapturesState(e){this.patchState({commandSurface:{...this.state.commandSurface,knowledgeCaptures:{...this.state.commandSurface.knowledgeCaptures,...e}}})}patchKnowledgeCapturesPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,knowledgeCaptures:{...this.state.commandSurface.knowledgeCaptures,[e]:{...this.state.commandSurface.knowledgeCaptures[e],...t}}}})}patchSettingsPhaseState(e){this.patchState({commandSurface:{...this.state.commandSurface,settingsData:{...this.state.commandSurface.settingsData,...e}}})}patchRemainingCommandsPhaseState(e,t){this.patchState({commandSurface:{...this.state.commandSurface,remainingCommands:{...this.state.commandSurface.remainingCommands,[e]:{...this.state.commandSurface.remainingCommands[e],...t}}}})}async refreshBootAfterCurrentSettles(e={}){if(this.bootPromise)try{await this.bootPromise}catch{}await this.refreshBoot(e)}invalidateLiveFreshness(e,t,s){let r={...this.state.live.freshness};e.includes("auto")&&(r.auto=ti(r.auto,t,s)),e.includes("workspace")&&(r.workspace=ti(r.workspace,t,s),r.gitSummary=ti(r.gitSummary,t,s)),e.includes("recovery")&&(r.recovery=ti(r.recovery,t,s),r.sessionStats=ti(r.sessionStats,t,s)),e.includes("resumable_sessions")&&(r.resumableSessions=ti(r.resumableSessions,t,s),r.sessionBrowser=ti(r.sessionBrowser,t,s),r.sessionStats=ti(r.sessionStats,t,s));let a={...this.state.live,freshness:r};return{...a,recoverySummary:tm({boot:this.state.boot,live:a})}}refreshOpenCommandSurfacesForInvalidation(e){if(e.domains.includes("workspace")&&this.state.commandSurface.open&&"git"===this.state.commandSurface.section&&"load_git_summary"!==this.state.commandSurface.pendingAction&&this.loadGitSummary(),e.domains.includes("recovery")&&this.state.commandSurface.open&&"recovery"===this.state.commandSurface.section&&"load_recovery_diagnostics"!==this.state.commandSurface.pendingAction&&this.loadRecoveryDiagnostics(),e.domains.includes("resumable_sessions")&&(this.state.commandSurface.open&&("resume"===this.state.commandSurface.section||"name"===this.state.commandSurface.section)&&"load_session_browser"!==this.state.commandSurface.pendingAction&&this.loadSessionBrowser(),this.state.commandSurface.open&&"session"===this.state.commandSurface.section)){let e=this.state.boot?.bridge.activeSessionFile??this.state.boot?.bridge.sessionState?.sessionFile??null;this.patchState({commandSurface:{...this.state.commandSurface,sessionStats:this.state.commandSurface.sessionStats&&this.state.commandSurface.sessionStats.sessionFile===e?this.state.commandSurface.sessionStats:null}}),"load_session_stats"!==this.state.commandSurface.pendingAction&&this.loadSessionStats()}}async reloadLiveState(e,t){let s=e.filter(e=>"auto"===e||"workspace"===e||"resumable_sessions"===e);if(0===s.length){let e={...this.state.live,freshness:{...this.state.live.freshness,recovery:to(this.state.live.freshness.recovery)}};this.patchState({live:{...e,recoverySummary:tm({boot:this.state.boot,live:e})}});return}let r={...this.state.live.freshness};s.includes("auto")&&(r.auto=tn(r.auto)),s.includes("workspace")&&(r.workspace=tn(r.workspace)),s.includes("resumable_sessions")&&(r.resumableSessions=tn(r.resumableSessions)),r.recovery=tn(r.recovery);let a={...this.state.live,freshness:r,targetedRefreshCount:this.state.live.targetedRefreshCount+1};this.patchState({live:{...a,recoverySummary:tm({boot:this.state.boot,live:a})}});let n=new URLSearchParams;for(let e of s)n.append("domain",e);try{let e=await e$(this.buildUrl(`/api/live-state?${n.toString()}`),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),t=await e.json().catch(()=>null);if(!e.ok||!t)throw Error(t?.error??`Live state request failed with ${e.status}`);let r=this.state.boot,a={...this.state.live,freshness:{...this.state.live.freshness}};if(s.includes("auto")&&t.auto&&(a.auto=t.auto,a.freshness.auto=to(a.freshness.auto),r=r?{...r,auto:t.auto}:r),s.includes("workspace")&&t.workspace&&(a.workspace=t.workspace,a.freshness.workspace=to(a.freshness.workspace),r=r?{...r,workspace:t.workspace}:r),s.includes("resumable_sessions")&&t.resumableSessions){let e=e7(t.resumableSessions,r);a.resumableSessions=e,a.freshness.resumableSessions=to(a.freshness.resumableSessions),r=r?{...r,resumableSessions:e}:r}a.freshness.recovery=to(a.freshness.recovery),a.recoverySummary=tm({boot:r,live:a}),this.patchState({...r?{boot:r}:{},live:a})}catch(a){let e=eO(a),r={...this.state.live,freshness:{...this.state.live.freshness,auto:s.includes("auto")?tl(this.state.live.freshness.auto,e):this.state.live.freshness.auto,workspace:s.includes("workspace")?tl(this.state.live.freshness.workspace,e):this.state.live.freshness.workspace,resumableSessions:s.includes("resumable_sessions")?tl(this.state.live.freshness.resumableSessions,e):this.state.live.freshness.resumableSessions,recovery:tl(this.state.live.freshness.recovery,e)}};this.patchState({lastClientError:e,live:{...r,recoverySummary:tm({boot:this.state.boot,live:r})},terminalLines:eM(this.state.terminalLines,eL("error",`Live refresh failed (${t}) — ${e}`))})}}handleLiveStateInvalidation(e){var t;this.patchState({live:this.invalidateLiveFreshness(e.domains,e.reason,e.source),commandSurface:e.domains.includes("recovery")?{...this.state.commandSurface,recovery:(t=this.state.commandSurface.recovery).loaded||t.error?{...t,stale:!0,lastInvalidatedAt:new Date().toISOString()}:t}:this.state.commandSurface}),this.refreshOpenCommandSurfacesForInvalidation(e),this.reloadLiveState(e.domains,e.reason)}clearCommandTimeout(){this.commandTimeoutTimer&&(clearTimeout(this.commandTimeoutTimer),this.commandTimeoutTimer=null)}async fetchOnboardingState(e=!1){let t=this.state.boot?.onboarding.activeFlow?.status??null,s=await e$(this.buildUrl("/api/onboarding"),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}}),r=await s.json();if(!s.ok||!r.onboarding)throw Error(r.error??`Onboarding request failed with ${s.status}`);return this.applyOnboardingState(r.onboarding),t&&ez.has(t)&&r.onboarding.activeFlow&&eB.has(r.onboarding.activeFlow.status)?await this.syncAfterOnboardingMutation(r.onboarding):e||this.appendOnboardingSummaryLine(r.onboarding),r.onboarding}async postOnboardingAction(e){let t=await e$(this.buildUrl("/api/onboarding"),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)}),s=await t.json();if(!s.onboarding)throw Error(s.error??`Onboarding action failed with ${t.status}`);return this.applyOnboardingState(s.onboarding),s.onboarding}applyOnboardingState(e){this.state.boot&&this.patchState({boot:eH(this.state.boot,e)})}async syncAfterOnboardingMutation(e){this.applyOnboardingState(e),this.appendOnboardingSummaryLine(e),(e.lastValidation?.status==="succeeded"||"idle"!==e.bridgeAuthRefresh.phase)&&this.refreshBootAfterCurrentSettles({soft:!0})}appendOnboardingSummaryLine(e){let t=eV(e);if(!t)return;let s=this.state.terminalLines.at(-1);(s?.type!==t.type||s.content!==t.message)&&this.patchState({terminalLines:eM(this.state.terminalLines,eL(t.type,t.message))})}emit(){for(let e of this.listeners)e()}patchState(e){this.state={...this.state,...e},this.syncOnboardingPoller(),this.emit()}syncOnboardingPoller(){if(this.disposed)return void this.stopOnboardingPoller();let e=this.state.boot?.onboarding.activeFlow?.status,t=!!(e&&ez.has(e));if(t&&!this.onboardingPollTimer){this.onboardingPollTimer=setInterval(()=>{"idle"===this.state.onboardingRequestState&&this.fetchOnboardingState(!0).catch(e=>{let t=eO(e);this.patchState({lastClientError:t})})},1500);return}t||this.stopOnboardingPoller()}stopOnboardingPoller(){this.onboardingPollTimer&&(clearInterval(this.onboardingPollTimer),this.onboardingPollTimer=null)}ensureEventStream(){if(this.eventSource||this.disposed||this.state.boot?.onboarding.locked)return;let e=new EventSource(eD(this.buildUrl("/api/session/events")));this.eventSource=e,e.onopen=()=>{let e=this.lastStreamState,t="reconnecting"===e||"disconnected"===e||"error"===e;t&&this.patchState({terminalLines:eM(this.state.terminalLines,eL("success","Live event stream reconnected"))}),this.lastStreamState="connected",this.patchState({connectionState:"connected",lastClientError:null}),t&&this.refreshBoot({soft:!0})},e.onmessage=e=>{try{let t=JSON.parse(e.data);if(null===t||"object"!=typeof t||"string"!=typeof t.type)return void this.patchState({lastClientError:"Malformed event received from stream",terminalLines:eM(this.state.terminalLines,eL("error","Malformed event received from stream"))});this.handleEvent(t)}catch(t){let e=eO(t);this.patchState({lastClientError:e,terminalLines:eM(this.state.terminalLines,eL("error",`Failed to parse stream event — ${e}`))})}},e.onerror=()=>{let e="connected"===this.lastStreamState?"reconnecting":"error";e!==this.lastStreamState?this.patchState({connectionState:e,terminalLines:eM(this.state.terminalLines,eL("reconnecting"===e?"system":"error","reconnecting"===e?"Live event stream disconnected — retrying…":"Live event stream failed before connection was established"))}):this.patchState({connectionState:e}),this.lastStreamState=e}}closeEventStream(){this.eventSource?.close(),this.eventSource=null}handleEvent(e){if(this.patchState({lastEventType:e.type}),"bridge_status"===e.type)return void this.recordBridgeStatus(e.bridge);"live_state_invalidation"===e.type&&this.handleLiveStateInvalidation(e),this.routeLiveInteractionEvent(e);let t=function(e){switch(e.type){case"bridge_status":return eU(e.bridge);case"live_state_invalidation":return{type:"system",message:`[Live] Refreshing ${Array.isArray(e.domains)?e.domains.join(", "):"state"} after ${String(e.reason).replaceAll("_"," ")}`};case"agent_start":return{type:"system",message:"[Agent] Run started"};case"agent_end":return{type:"success",message:"[Agent] Run finished"};case"turn_start":return{type:"system",message:"[Agent] Turn started"};case"turn_end":return{type:"success",message:"[Agent] Turn complete"};case"tool_execution_start":return{type:"output",message:`[Tool] ${"string"==typeof e.toolName?e.toolName:"tool"} started`};case"tool_execution_end":return{type:e.isError?"error":"success",message:`[Tool] ${"string"==typeof e.toolName?e.toolName:"tool"} ${e.isError?"failed":"completed"}`};case"auto_compaction_start":return{type:"system",message:"[Auto] Compaction started"};case"auto_compaction_end":return{type:e.aborted?"error":"success",message:e.aborted?"[Auto] Compaction aborted":"[Auto] Compaction finished"};case"auto_retry_start":return{type:"system",message:`[Auto] Retry ${String(e.attempt)}/${String(e.maxAttempts)} scheduled`};case"auto_retry_end":return{type:e.success?"success":"error",message:e.success?"[Auto] Retry recovered the run":"[Auto] Retry exhausted"};case"extension_ui_request":{let t="title"in e&&"string"==typeof e.title&&e.title.trim().length>0?e.title:"message"in e&&"string"==typeof e.message&&e.message.trim().length>0?e.message:e.method;return{type:"notifyType"in e&&"error"===e.notifyType?"error":"system",message:`[UI] ${t}`}}case"extension_error":return{type:"error",message:`[Extension] ${e.error}`};default:return null}}(e);t&&this.patchState({terminalLines:eM(this.state.terminalLines,eL(t.type,t.message))})}routeLiveInteractionEvent(e){switch(e.type){case"extension_ui_request":this.handleExtensionUiRequest(e);break;case"message_update":this.handleMessageUpdate(e);break;case"agent_end":case"turn_end":this.handleTurnBoundary();break;case"tool_execution_start":this.handleToolExecutionStart(e);break;case"tool_execution_end":this.handleToolExecutionEnd(e)}}handleExtensionUiRequest(e){switch(e.method){case"select":case"confirm":case"input":case"editor":this.patchState({pendingUiRequests:[...this.state.pendingUiRequests,e]});break;case"notify":break;case"setStatus":if("setStatus"===e.method){let t={...this.state.statusTexts};void 0===e.statusText?delete t[e.statusKey]:t[e.statusKey]=e.statusText,this.patchState({statusTexts:t})}break;case"setWidget":if("setWidget"===e.method){let t={...this.state.widgetContents};void 0===e.widgetLines?delete t[e.widgetKey]:t[e.widgetKey]={lines:e.widgetLines,placement:e.widgetPlacement},this.patchState({widgetContents:t})}break;case"setTitle":if("setTitle"===e.method){let t=e.title.trim();this.patchState({titleOverride:t||null})}break;case"set_editor_text":"set_editor_text"===e.method&&this.patchState({editorTextBuffer:e.text})}}handleMessageUpdate(e){let t=e.assistantMessageEvent;t&&("text_delta"===t.type&&"string"==typeof t.delta?(this.state.streamingThinkingText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"thinking",content:this.state.streamingThinkingText}],streamingThinkingText:""}),this.patchState({streamingAssistantText:this.state.streamingAssistantText+t.delta})):"thinking_delta"===t.type&&"string"==typeof t.delta?(this.state.streamingAssistantText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"text",content:this.state.streamingAssistantText}],streamingAssistantText:""}),this.patchState({streamingThinkingText:this.state.streamingThinkingText+t.delta})):"thinking_end"===t.type&&this.state.streamingThinkingText.length>0&&this.patchState({currentTurnSegments:[...this.state.currentTurnSegments,{kind:"thinking",content:this.state.streamingThinkingText}],streamingThinkingText:""}))}handleTurnBoundary(){let e=[];this.state.streamingThinkingText.length>0&&e.push({kind:"thinking",content:this.state.streamingThinkingText}),this.state.streamingAssistantText.length>0&&e.push({kind:"text",content:this.state.streamingAssistantText});let t=e.length>0?[...this.state.currentTurnSegments,...e]:this.state.currentTurnSegments,s=t.filter(e=>"text"===e.kind).map(e=>e.content).join("");if(s.length>0||t.length>0){let e=[...this.state.liveTranscript,s],r=[...this.state.liveThinkingTranscript,""],a=[...this.state.completedTurnSegments,t],n=e.length>100?e.length-100:0;this.patchState({liveTranscript:n>0?e.slice(n):e,liveThinkingTranscript:n>0?r.slice(n):r,completedTurnSegments:n>0?a.slice(n):a,streamingAssistantText:"",streamingThinkingText:"",currentTurnSegments:[],completedToolExecutions:[]})}else this.state.streamingThinkingText.length>0?this.patchState({streamingThinkingText:"",currentTurnSegments:[],completedToolExecutions:[]}):this.patchState({currentTurnSegments:[],completedToolExecutions:[]})}handleToolExecutionStart(e){let t=[];this.state.streamingThinkingText.length>0&&t.push({kind:"thinking",content:this.state.streamingThinkingText}),this.state.streamingAssistantText.length>0&&t.push({kind:"text",content:this.state.streamingAssistantText}),this.patchState({activeToolExecution:{id:e.toolCallId,name:e.toolName,args:e.args},...t.length>0?{currentTurnSegments:[...this.state.currentTurnSegments,...t],streamingAssistantText:"",streamingThinkingText:""}:{}})}handleToolExecutionEnd(e){let t=this.state.activeToolExecution;if(t){let s={id:t.id,name:t.name,args:t.args??{},result:{content:e.result?.content,details:e.result?.details,isError:e.isError}},r=[...this.state.completedToolExecutions,s];this.patchState({activeToolExecution:null,completedToolExecutions:r.length>50?r.slice(r.length-50):r,currentTurnSegments:[...this.state.currentTurnSegments,{kind:"tool",tool:s}]})}else this.patchState({activeToolExecution:null})}recordBridgeStatus(e){let t=[e.phase,e.activeSessionId,e.lastError?.at,e.lastError?.message].join("::"),s=t!==this.lastBridgeDigest;this.lastBridgeDigest=t;let r=eW(this.state.boot,e),a={...this.state.live,resumableSessions:e7(this.state.live.resumableSessions,r)},n={...a,recoverySummary:tm({boot:r,live:a})},i={boot:r,live:n,lastBridgeError:e.lastError,sessionAttached:eq(e),commandSurface:{...this.state.commandSurface,sessionBrowser:e9(this.state.commandSurface.sessionBrowser,r)}};if(s){let t=eU(e);i.terminalLines=eM(this.state.terminalLines,eL(t.type,t.message))}this.patchState(i)}}let tp=(0,n.createContext)(null);function tg({children:e,store:t}){let[s]=(0,n.useState)(()=>new th),a=t??s;return(0,n.useEffect)(()=>{if(!t)return a.start(),()=>a.dispose()},[a,t]),(0,r.jsx)(tp.Provider,{value:a,children:e})}function tf(){let e=(0,n.useContext)(tp);if(!e)throw Error("useWorkspaceStore must be used within GSDWorkspaceProvider");return e}function tb(){let e=tf();return(0,n.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}function tv(){let e=tf();return{sendCommand:e.sendCommand,submitInput:e.submitInput,clearTerminalLines:e.clearTerminalLines,consumeEditorTextBuffer:e.consumeEditorTextBuffer,refreshBoot:e.refreshBoot,refreshOnboarding:e.refreshOnboarding,openCommandSurface:e.openCommandSurface,closeCommandSurface:e.closeCommandSurface,setCommandSurfaceSection:e.setCommandSurfaceSection,selectCommandSurfaceTarget:e.selectCommandSurfaceTarget,loadGitSummary:e.loadGitSummary,loadRecoveryDiagnostics:e.loadRecoveryDiagnostics,loadForensicsDiagnostics:e.loadForensicsDiagnostics,loadDoctorDiagnostics:e.loadDoctorDiagnostics,applyDoctorFixes:e.applyDoctorFixes,loadSkillHealthDiagnostics:e.loadSkillHealthDiagnostics,loadKnowledgeData:e.loadKnowledgeData,loadCapturesData:e.loadCapturesData,loadSettingsData:e.loadSettingsData,loadHistoryData:e.loadHistoryData,loadInspectData:e.loadInspectData,loadHooksData:e.loadHooksData,loadExportData:e.loadExportData,loadUndoInfo:e.loadUndoInfo,loadCleanupData:e.loadCleanupData,loadSteerData:e.loadSteerData,executeUndoAction:e.executeUndoAction,executeCleanupAction:e.executeCleanupAction,resolveCaptureAction:e.resolveCaptureAction,updateSessionBrowserState:e.updateSessionBrowserState,loadSessionBrowser:e.loadSessionBrowser,renameSessionFromSurface:e.renameSessionFromSurface,loadAvailableModels:e.loadAvailableModels,applyModelSelection:e.applyModelSelection,applyThinkingLevel:e.applyThinkingLevel,setSteeringModeFromSurface:e.setSteeringModeFromSurface,setFollowUpModeFromSurface:e.setFollowUpModeFromSurface,setAutoCompactionFromSurface:e.setAutoCompactionFromSurface,setAutoRetryFromSurface:e.setAutoRetryFromSurface,abortRetryFromSurface:e.abortRetryFromSurface,switchSessionFromSurface:e.switchSessionFromSurface,loadSessionStats:e.loadSessionStats,exportSessionFromSurface:e.exportSessionFromSurface,loadForkMessages:e.loadForkMessages,forkSessionFromSurface:e.forkSessionFromSurface,compactSessionFromSurface:e.compactSessionFromSurface,saveApiKey:e.saveApiKey,saveApiKeyFromSurface:e.saveApiKeyFromSurface,startProviderFlow:e.startProviderFlow,startProviderFlowFromSurface:e.startProviderFlowFromSurface,submitProviderFlowInput:e.submitProviderFlowInput,submitProviderFlowInputFromSurface:e.submitProviderFlowInputFromSurface,cancelProviderFlow:e.cancelProviderFlow,cancelProviderFlowFromSurface:e.cancelProviderFlowFromSurface,logoutProvider:e.logoutProvider,logoutProviderFromSurface:e.logoutProviderFromSurface,respondToUiRequest:e.respondToUiRequest,dismissUiRequest:e.dismissUiRequest,sendSteer:e.sendSteer,sendAbort:e.sendAbort,pushChatUserMessage:e.pushChatUserMessage}}function tj(e,t){let s=ea(e,{isStreaming:t?.sessionState?.isStreaming});if("prompt"===s.kind||"rpc"===s.kind)return s.command;throw Error(`buildPromptCommand cannot serialize ${s.input||e} because browser dispatch resolved it to ${s.kind}; use submitInput() instead.`)}function ty(e,t){return e.slices.length>0&&e.slices.every(e=>e.done)?"done":t.milestoneId===e.id||e.slices.some(e=>e.done)?"in-progress":"pending"}function tN(e,t,s){return t.done?"done":s.milestoneId===e&&s.sliceId===t.id?"in-progress":"pending"}function tw(e,t,s,r){return s.done?"done":r.milestoneId===e&&r.sliceId===t&&r.taskId===s.id?"in-progress":"pending"}function tk(e){let t,{phase:s,autoActive:r,autoPaused:a,onboardingLocked:n,commandInFlight:i,bootStatus:o,hasMilestones:l,projectDetectionKind:d}=e;if(d&&"active-gsd"!==d&&"empty-gsd"!==d)return{primary:null,secondaries:[],disabled:!0,disabledReason:"Project setup pending",isNewMilestone:!1};let c=!1;null!==i?(c=!0,t="Command in progress"):"ready"!==o?(c=!0,t="Workspace not ready"):n&&(c=!0,t="Setup required");let u=null,m=[],x=!1;return r&&!a?u={label:"Stop Auto",command:"/gsd stop",variant:"destructive"}:a?u={label:"Resume Auto",command:"/gsd auto",variant:"default"}:("complete"===s?(u={label:"New Milestone",command:"/gsd",variant:"default"},x=!0):u="planning"===s?{label:"Plan",command:"/gsd",variant:"default"}:"executing"===s||"summarizing"===s?{label:"Start Auto",command:"/gsd auto",variant:"default"}:"pre-planning"!==s||l?{label:"Continue",command:"/gsd",variant:"default"}:{label:"Initialize Project",command:"/gsd",variant:"default"},"/gsd next"===u.command||x||m.push({label:"Step",command:"/gsd next"})),{primary:u,secondaries:m,disabled:c,disabledReason:t,isNewMilestone:x}}let tS="gsd-user-mode",tC="expert",tA=new Set;function tT(e){return tA.add(e),()=>{tA.delete(e)}}function tR(){let e=localStorage.getItem(tS);return"expert"===e||"vibe-coder"===e?e:tC}function tE(){return tC}function tP(e){window.dispatchEvent(new CustomEvent("gsd:navigate-view",{detail:{view:e}}))}function t_({dispatch:e}){e().catch(e=>{console.error("[workflow-action] dispatch failed:",e)}),tP("vibe-coder"===tR()?"chat":"power")}class tI{getActiveStore(){return this.activeProjectCwd?this.stores.get(this.activeProjectCwd)??null:null}getActiveProjectCwd(){return this.activeProjectCwd}switchProject(e){if(this.activeProjectCwd&&this.activeProjectCwd!==e){let e=this.stores.get(this.activeProjectCwd);e&&e.disconnectSSE()}let t=this.stores.get(e);return t?t.reconnectSSE():(t=new th(e),this.stores.set(e,t),t.start()),this.activeProjectCwd=e,this.notify(),t}disposeAll(){for(let e of this.stores.values())e.dispose();this.stores.clear(),this.activeProjectCwd=null,this.notify()}closeProject(e){let t=this.stores.get(e);if(t){if(t.dispose(),this.stores.delete(e),this.activeProjectCwd===e){let e=Array.from(this.stores.keys());if(e.length>0){let t=this.stores.get(e[0]);this.activeProjectCwd=e[0],t.reconnectSSE()}else this.activeProjectCwd=null}this.notify()}}getProjectCount(){return this.stores.size}getActiveProjectPaths(){return Array.from(this.stores.keys())}notify(){for(let e of this.listeners)e()}constructor(){this.stores=new Map,this.activeProjectCwd=null,this.listeners=new Set,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getSnapshot=()=>this.activeProjectCwd}}let t$=(0,n.createContext)(null);function tD({children:e}){let[t]=(0,n.useState)(()=>new tI);return(0,n.useEffect)(()=>()=>t.disposeAll(),[t]),(0,r.jsx)(t$.Provider,{value:t,children:e})}function tF(){let e=(0,n.useContext)(t$);if(!e)throw Error("useProjectStoreManager must be used within ProjectStoreManagerProvider");return e}function tL({className:e,...t}){return(0,r.jsx)("div",{"data-slot":"skeleton",className:L("bg-accent animate-pulse rounded-md",e),...t})}let tM=({status:e})=>"done"===e?(0,r.jsx)(l.A,{className:"h-4 w-4 shrink-0 text-success"}):"in-progress"===e?(0,r.jsx)(d.A,{className:"h-4 w-4 shrink-0 text-warning"}):(0,r.jsx)(c.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"});function tq({activeView:e,onViewChange:t,isConnecting:s=!1}){let{openCommandSurface:a}=tv(),i=tF(),o=(0,n.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),[l,d]=(0,n.useState)(!1),{theme:c,setTheme:S}=(0,Y.D)(),C="light"===c?u.A:"dark"===c?m.A:x.A,A=[{id:"dashboard",label:"Dashboard",icon:h.A},{id:"power",label:"Power Mode",icon:p.A},{id:"chat",label:"Chat",icon:g.A},{id:"roadmap",label:"Roadmap",icon:f.A},{id:"files",label:"Files",icon:b.A},{id:"activity",label:"Activity",icon:v.A},{id:"visualize",label:"Visualize",icon:j.A}];return(0,r.jsxs)("div",{className:"flex w-12 flex-col items-center gap-1 border-r border-border bg-sidebar py-3",children:[A.map(a=>(0,r.jsx)("button",{onClick:()=>t(a.id),disabled:s,className:L("flex h-10 w-10 items-center justify-center rounded-md transition-colors",s?"cursor-not-allowed text-muted-foreground/50":e===a.id?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),title:s?"Connecting…":a.label,children:(0,r.jsx)(a.icon,{className:"h-5 w-5"})},a.id)),(0,r.jsxs)("div",{className:"mt-auto flex flex-col gap-1",children:[(0,r.jsx)("button",{onClick:()=>window.dispatchEvent(new CustomEvent("gsd:open-projects")),disabled:s,className:L("flex h-10 w-10 items-center justify-center rounded-md transition-colors",s?"cursor-not-allowed text-muted-foreground/50":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),title:s?"Connecting…":"Projects",children:(0,r.jsx)(y.A,{className:"h-5 w-5"})}),(0,r.jsx)("button",{className:L("flex h-10 w-10 items-center justify-center rounded-md text-muted-foreground transition-colors",s?"cursor-not-allowed opacity-30":"hover:bg-accent/50 hover:text-foreground"),title:"Git",disabled:s,onClick:()=>!s&&a("git",{source:"sidebar"}),"data-testid":"sidebar-git-button",children:(0,r.jsx)(N.A,{className:"h-5 w-5"})}),(0,r.jsx)("button",{className:L("flex h-10 w-10 items-center justify-center rounded-md text-muted-foreground transition-colors",s?"cursor-not-allowed opacity-30":"hover:bg-accent/50 hover:text-foreground"),title:"Settings",disabled:s,onClick:()=>!s&&a("settings",{source:"sidebar"}),"data-testid":"sidebar-settings-button",children:(0,r.jsx)(w.A,{className:"h-5 w-5"})}),(0,r.jsx)("button",{className:L("flex h-10 w-10 items-center justify-center rounded-md text-muted-foreground transition-colors",s?"cursor-not-allowed opacity-30":"hover:bg-accent/50 hover:text-foreground"),title:`Theme: ${"light"===c?"Light":"dark"===c?"Dark":"System"}`,disabled:s,onClick:()=>!s&&void("system"===c?S("light"):"light"===c?S("dark"):S("system")),"data-testid":"sidebar-theme-toggle",children:(0,r.jsx)(C,{className:"h-5 w-5"})}),(0,r.jsx)("button",{className:L("flex h-10 w-10 items-center justify-center rounded-md text-muted-foreground transition-colors",s?"cursor-not-allowed opacity-30":"hover:bg-destructive/15 hover:text-destructive"),title:"Exit",disabled:s,onClick:()=>!s&&d(!0),"data-testid":"sidebar-signoff-button",children:(0,r.jsx)(k.A,{className:"h-5 w-5"})}),(0,r.jsx)(tO,{open:l,onOpenChange:d,projectCount:i.getProjectCount(),activeProjectCwd:o,onCloseProject:e=>{i.closeProject(e),t("dashboard"),d(!1)},onStopServer:async()=>{await e$("/api/shutdown",{method:"POST"}).catch(()=>{}),setTimeout(()=>{try{window.close()}catch{}setTimeout(()=>{window.location.href="about:blank"},300)},400)}})]})]})}function tO({open:e,onOpenChange:t,projectCount:s,activeProjectCwd:a,onCloseProject:n,onStopServer:i}){let o=s>1,l=a?a.split("/").pop()??a:null;return o?(0,r.jsx)(M,{open:e,onOpenChange:t,children:(0,r.jsxs)(U,{className:"sm:max-w-md",children:[(0,r.jsxs)(z,{children:[(0,r.jsx)(G,{children:"Close project or stop server?"}),(0,r.jsxs)(W,{children:["You have ",s," projects open. You can close just the current project or stop the entire server."]})]}),(0,r.jsxs)("div",{className:"flex flex-col gap-2 py-2",children:[a&&(0,r.jsxs)(J,{variant:"outline",className:"h-auto justify-start gap-3 px-4 py-3 text-left",onClick:()=>n(a),children:[(0,r.jsx)(y.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsxs)("div",{className:"text-sm font-medium",children:["Close ",l]}),(0,r.jsx)("div",{className:"text-xs text-muted-foreground",children:"Disconnect this project and switch to another"})]})]}),(0,r.jsxs)(J,{variant:"outline",className:"h-auto justify-start gap-3 px-4 py-3 text-left border-destructive/30 hover:bg-destructive/10 hover:text-destructive",onClick:i,children:[(0,r.jsx)(k.A,{className:"h-4 w-4 shrink-0"}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("div",{className:"text-sm font-medium",children:"Stop server"}),(0,r.jsxs)("div",{className:"text-xs text-muted-foreground",children:["Shut down all ",s," projects and close the tab"]})]})]})]}),(0,r.jsx)(B,{children:(0,r.jsx)(J,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"})})]})}):(0,r.jsx)(M,{open:e,onOpenChange:t,children:(0,r.jsxs)(U,{className:"sm:max-w-md",children:[(0,r.jsxs)(z,{children:[(0,r.jsx)(G,{children:"Stop the GSD web server?"}),(0,r.jsxs)(W,{children:["This will shut down the server process and close this tab. Run"," ",(0,r.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"gsd --web"})," again to restart."]})]}),(0,r.jsxs)(B,{children:[(0,r.jsx)(J,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),(0,r.jsx)(J,{variant:"destructive",onClick:i,children:"Stop server"})]})]})})}function tU({isConnecting:e=!1,width:t,onCollapse:s}){let a,i=tb(),{openCommandSurface:o,setCommandSurfaceSection:l,sendCommand:c}=tv(),[u,m]=(0,n.useState)([]),[x,h]=(0,n.useState)([]),p=td(i),g=(0,n.useMemo)(()=>p?.milestones??[],[p?.milestones]),f=p?.active,b=tc(i),v=i.live.recoverySummary,j=p?.validationIssues.length??0,y=eZ(p),N=i.boot?.project.cwd??null,w=i.boot?.bridge??null,k=tk({phase:p?.active.phase??"pre-planning",autoActive:b?.active??!1,autoPaused:b?.paused??!1,onboardingLocked:i.boot?.onboarding.locked??!1,commandInFlight:i.commandInFlight,bootStatus:i.bootStatus,hasMilestones:g.length>0,projectDetectionKind:i.boot?.projectDetection?.kind??null}),I=e=>{t_({dispatch:()=>c(tj(e,w))})},$=f?.milestoneId&&!u.includes(f.milestoneId)?[...u,f.milestoneId]:u,D=f?.milestoneId&&f.sliceId?(a=`${f.milestoneId}-${f.sliceId}`,x.includes(a)?x:[...x,a]):x,F=new Map(g.map(e=>[e.id,ty(e,f??{})]));return(0,r.jsxs)("div",{className:"flex flex-col bg-sidebar",style:{width:t??256,flexShrink:0},children:[e&&(0,r.jsxs)("div",{className:"flex-1 overflow-y-auto px-1.5 py-1",children:[(0,r.jsx)("div",{className:"px-2 py-1.5",children:(0,r.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Milestones"})}),(0,r.jsx)("div",{className:"space-y-0.5 px-1",children:[1,2].map(e=>(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 px-2 py-1.5",children:[(0,r.jsx)(tL,{className:"h-4 w-4 shrink-0 rounded"}),(0,r.jsx)(tL,{className:"h-4 w-4 shrink-0 rounded-full"}),(0,r.jsx)(tL,{className:L("h-4",1===e?"w-40":"w-32")})]}),1===e&&(0,r.jsx)("div",{className:"ml-4 space-y-0.5",children:[1,2,3].map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-1.5 px-2 py-1.5",children:[(0,r.jsx)(tL,{className:"h-4 w-4 shrink-0 rounded"}),(0,r.jsx)(tL,{className:"h-4 w-4 shrink-0 rounded-full"}),(0,r.jsx)(tL,{className:L("h-3.5",1===e?"w-32":2===e?"w-28":"w-24")})]},e))})]},e))})]}),!e&&(0,r.jsxs)("div",{className:"flex-1 overflow-y-auto px-1.5 py-1",children:[(0,r.jsxs)("div",{className:"flex items-start justify-between px-2 py-1.5",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Milestones"}),(0,r.jsx)("div",{className:"mt-1 text-xs text-foreground","data-testid":"sidebar-current-scope",children:y})]}),s&&(0,r.jsx)("button",{onClick:s,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",title:"Collapse sidebar",children:(0,r.jsx)(S.A,{className:"h-3.5 w-3.5"})})]}),"error"===i.bootStatus&&0===g.length&&(0,r.jsx)("div",{className:"px-3 py-2 text-xs text-destructive",children:"Workspace boot failed before the explorer could load."}),"ready"===i.bootStatus&&0===g.length&&(0,r.jsx)("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:"No milestones found for this project."}),g.map(e=>{let t=$.includes(e.id),s=f?.milestoneId===e.id,a=F.get(e.id)??"pending";return(0,r.jsxs)("div",{children:[(0,r.jsxs)("button",{onClick:()=>{var t;return t=e.id,void m(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},className:L("flex w-full items-center gap-1.5 px-2 py-1.5 text-sm transition-colors hover:bg-accent/50",s&&"bg-accent/30"),children:[t?(0,r.jsx)(C.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,r.jsx)(A.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,r.jsx)(tM,{status:a}),(0,r.jsxs)("span",{className:L("truncate","pending"===a&&"text-muted-foreground"),children:[e.id,": ",e.title]})]}),t&&(0,r.jsx)("div",{className:"ml-4",children:e.slices.map(t=>{let s=`${e.id}-${t.id}`,a=D.includes(s),n=tN(e.id,t,f??{}),i=f?.milestoneId===e.id&&f.sliceId===t.id;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("button",{onClick:()=>{h(e=>e.includes(s)?e.filter(e=>e!==s):[...e,s])},className:L("flex w-full items-center gap-1.5 px-2 py-1.5 text-sm transition-colors hover:bg-accent/50",i&&"bg-accent/20"),children:[a?(0,r.jsx)(C.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):(0,r.jsx)(A.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,r.jsx)(tM,{status:n}),(0,r.jsxs)("span",{className:L("truncate text-[13px]","pending"===n&&"text-muted-foreground"),children:[t.id,": ",t.title]})]}),a&&(0,r.jsxs)("div",{className:"ml-5",children:[t.branch&&(0,r.jsx)("div",{className:"px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground",children:t.branch}),t.tasks.map(a=>{let n=tw(e.id,t.id,a,f??{}),o=!!(a.planPath||a.summaryPath);return(0,r.jsxs)("button",{type:"button",onClick:()=>(e=>{if(!e||!N)return;let t=`${N}/.gsd/`;if(!e.startsWith(t))return;let s=e.slice(t.length);window.dispatchEvent(new CustomEvent("gsd:open-file",{detail:{root:"gsd",path:s}}))})(a.summaryPath??a.planPath),disabled:!o,className:L("flex w-full items-center gap-1.5 px-2 py-1 text-xs transition-colors",o?"cursor-pointer hover:bg-accent/50":"cursor-default opacity-70",f?.taskId===a.id&&i&&"bg-accent/10"),children:[(0,r.jsx)(T.A,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),(0,r.jsx)(tM,{status:n}),(0,r.jsxs)("span",{className:L("truncate text-left","pending"===n&&"text-muted-foreground"),children:[a.id,": ",a.title]})]},`${s}-${a.id}`)})]})]},s)})})]},e.id)})]}),!e&&(0,r.jsx)("div",{className:"border-t border-border px-3 py-2.5",children:(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md border border-border bg-background px-3 py-2 text-xs",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsxs)("div",{className:"font-medium text-foreground","data-testid":"sidebar-validation-count",children:[j," validation issue",1===j?"":"s"]}),(0,r.jsx)("div",{className:"truncate text-muted-foreground",children:v.label})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>{o("settings",{source:"sidebar"}),l("recovery")},className:"inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md border border-border bg-card px-2.5 text-[11px] font-medium text-foreground transition-colors hover:bg-accent","data-testid":"sidebar-recovery-summary-entrypoint",children:[(0,r.jsx)(R.A,{className:"h-3.5 w-3.5"}),"Recovery"]})]})}),!e&&k.primary&&(0,r.jsx)("div",{className:"border-t border-border px-3 py-2.5",children:(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)("button",{onClick:()=>{k.primary&&I(k.primary.command)},disabled:k.disabled,className:L("inline-flex h-9 flex-1 items-center justify-center gap-2 rounded-md px-3 text-sm font-medium transition-colors","destructive"===k.primary.variant?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-primary text-primary-foreground hover:bg-primary/90",k.disabled&&"cursor-not-allowed opacity-50"),title:k.disabledReason,children:[i.commandInFlight?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):k.isNewMilestone?(0,r.jsx)(P.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(d.A,{className:"h-3.5 w-3.5"}),k.primary.label]}),k.secondaries.map(e=>(0,r.jsx)("button",{onClick:()=>I(e.command),disabled:k.disabled,className:L("inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border bg-background transition-colors hover:bg-accent",k.disabled&&"cursor-not-allowed opacity-50"),title:e.label,children:(0,r.jsx)(_.A,{className:"h-3.5 w-3.5"})},e.command))]})})]})}function tz({onExpand:e}){let t=tb(),{sendCommand:s}=tv(),a=td(t),n=a?.milestones??[],i=tc(t),o=t.boot?.bridge??null,l=tk({phase:a?.active.phase??"pre-planning",autoActive:i?.active??!1,autoPaused:i?.paused??!1,onboardingLocked:t.boot?.onboarding.locked??!1,commandInFlight:t.commandInFlight,bootStatus:t.bootStatus,hasMilestones:n.length>0,projectDetectionKind:t.boot?.projectDetection?.kind??null});return(0,r.jsxs)("div",{className:"flex h-full w-10 flex-col items-center border-l border-border bg-sidebar py-3",children:[(0,r.jsx)("button",{onClick:e,className:"flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",title:"Expand milestone sidebar",children:(0,r.jsx)(I.A,{className:"h-4 w-4"})}),l.primary&&(0,r.jsx)("div",{className:"mt-auto pb-0.5",children:(0,r.jsx)("button",{onClick:()=>{if(l.primary){var e;e=l.primary.command,t_({dispatch:()=>s(tj(e,o))})}},disabled:l.disabled,className:L("flex h-8 w-8 items-center justify-center rounded-md transition-colors","destructive"===l.primary.variant?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-primary text-primary-foreground hover:bg-primary/90",l.disabled&&"cursor-not-allowed opacity-50"),title:l.disabledReason??l.primary.label,children:t.commandInFlight?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}):l.isNewMilestone?(0,r.jsx)(P.A,{className:"h-4 w-4"}):(0,r.jsx)(d.A,{className:"h-4 w-4"})})})]})}function tB({activeView:e,onViewChange:t,isConnecting:s=!1,mobile:a=!1}){return a?(0,r.jsx)(tG,{activeView:e,onViewChange:t,isConnecting:s}):(0,r.jsx)("div",{className:"flex h-full",children:(0,r.jsx)(tq,{activeView:e,onViewChange:t,isConnecting:s})})}function tG({activeView:e,onViewChange:t,isConnecting:s=!1}){let{openCommandSurface:a}=tv(),{theme:n,setTheme:i}=(0,Y.D)(),o="light"===n?u.A:"dark"===n?m.A:x.A,l=[{id:"dashboard",label:"Dashboard",icon:h.A},{id:"power",label:"Power Mode",icon:p.A},{id:"chat",label:"Chat",icon:g.A},{id:"roadmap",label:"Roadmap",icon:f.A},{id:"files",label:"Files",icon:b.A},{id:"activity",label:"Activity",icon:v.A},{id:"visualize",label:"Visualize",icon:j.A}];return(0,r.jsxs)("div",{className:"flex h-full flex-col bg-sidebar pt-14","data-testid":"mobile-nav-panel",children:[(0,r.jsx)("div",{className:"flex-1 overflow-y-auto px-2 py-2",children:l.map(a=>(0,r.jsxs)("button",{onClick:()=>t(a.id),disabled:s,className:L("flex w-full items-center gap-3 rounded-md px-3 py-3 text-sm font-medium transition-colors min-h-[44px]",s?"cursor-not-allowed text-muted-foreground/50":e===a.id?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"),children:[(0,r.jsx)(a.icon,{className:"h-5 w-5 shrink-0"}),a.label]},a.id))}),(0,r.jsxs)("div",{className:"border-t border-border px-2 py-2 space-y-1",children:[(0,r.jsxs)("button",{onClick:()=>window.dispatchEvent(new CustomEvent("gsd:open-projects")),disabled:s,className:"flex w-full items-center gap-3 rounded-md px-3 py-3 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground transition-colors min-h-[44px]",children:[(0,r.jsx)(y.A,{className:"h-5 w-5 shrink-0"}),"Projects"]}),(0,r.jsxs)("button",{onClick:()=>!s&&a("git",{source:"sidebar"}),disabled:s,className:"flex w-full items-center gap-3 rounded-md px-3 py-3 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground transition-colors min-h-[44px]",children:[(0,r.jsx)(N.A,{className:"h-5 w-5 shrink-0"}),"Git"]}),(0,r.jsxs)("button",{onClick:()=>!s&&a("settings",{source:"sidebar"}),disabled:s,className:"flex w-full items-center gap-3 rounded-md px-3 py-3 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground transition-colors min-h-[44px]",children:[(0,r.jsx)(w.A,{className:"h-5 w-5 shrink-0"}),"Settings"]}),(0,r.jsxs)("button",{onClick:()=>!s&&void("system"===n?i("light"):"light"===n?i("dark"):i("system")),disabled:s,className:"flex w-full items-center gap-3 rounded-md px-3 py-3 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground transition-colors min-h-[44px]",children:[(0,r.jsx)(o,{className:"h-5 w-5 shrink-0"}),"Theme: ","light"===n?"Light":"dark"===n?"Dark":"System"]})]})]})}var tW=s(30234),tK=s(51914),tH=s(42804);let tV=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function tJ(e){if(!tV.has(e.type)){let t=`Unsupported image type: ${e.type||"unknown"}. Accepted: JPEG, PNG, GIF, WebP.`;return console.warn("[image-utils] validation failed:",t),{valid:!1,error:t}}if(e.size>0x1400000){let t=(e.size/1048576).toFixed(1),s=`Image too large (${t} MB). Maximum: 20 MB.`;return console.warn("[image-utils] validation failed:",s),{valid:!1,error:s}}return{valid:!0}}async function tY(e,t){var s,r;let a=.75*e.length;if(("image/gif"===t||"image/webp"===t)&&a<=4718592)return{data:e,mimeType:t};let n=await (s=e,r=t,new Promise((e,t)=>{let a=new Image;a.onload=()=>e(a),a.onerror=()=>t(Error("Failed to decode image")),a.src=`data:${r};base64,${s}`})),i=n.width>2e3||n.height>2e3;if(!i&&!(a>4718592))return{data:e,mimeType:t};let o="image/gif"===t||"image/webp"===t?"image/jpeg":t,l=n.width,d=n.height;if(i){let e=Math.min(2e3/n.width,2e3/n.height);l=Math.round(n.width*e),d=Math.round(n.height*e)}let c=document.createElement("canvas");c.width=l,c.height=d;let u=c.getContext("2d");if(!u)throw Error("Canvas 2D context not available");u.drawImage(n,0,0,l,d);let m=c.toDataURL(o,"image/jpeg"===o?.85:void 0).split(",")[1],x=.75*m.length;if(x>4718592)throw Error(`Image still exceeds 4.5 MB after resize (${(x/1048576).toFixed(1)} MB). Try a smaller image.`);return{data:m,mimeType:o}}async function tQ(e){let t=tJ(e);if(!t.valid)throw Error(t.error);return tY(await new Promise((t,s)=>{let r=new FileReader;r.onload=()=>{let e=new Uint8Array(r.result),s="";for(let t=0;t<e.length;t++)s+=String.fromCharCode(e[t]);t(btoa(s))},r.onerror=()=>s(Error("Failed to read image file")),r.readAsArrayBuffer(e)}),e.type)}let tX=/Get Shit Done v\d+\.\d+\.\d+/i;function tZ(e,t){if(0===t)return 0;let s=0;for(let r=0;r<e.length;r+=1)if("\n"===e[r]&&(s+=1)===t)return r+1;return null}function t0(e){return!e||0===e.trim().length}function t1(e){return!!e&&/[█╔╗╚╝║═]/.test(e)}function t5(e,t){if(!t)return e;let s=new URL(e,"http://localhost");return s.searchParams.set("project",t),s.pathname+s.search}function t2(e,t,s){return new URL(t5(e,s),t)}s(82407);let t3={background:"#0a0a0a",foreground:"#e4e4e7",cursor:"#e4e4e7",cursorAccent:"#0a0a0a",selectionBackground:"#27272a",selectionForeground:"#e4e4e7",black:"#18181b",red:"#ef4444",green:"#22c55e",yellow:"#eab308",blue:"#3b82f6",magenta:"#a855f7",cyan:"#06b6d4",white:"#e4e4e7",brightBlack:"#52525b",brightRed:"#f87171",brightGreen:"#4ade80",brightYellow:"#facc15",brightBlue:"#60a5fa",brightMagenta:"#c084fc",brightCyan:"#22d3ee",brightWhite:"#fafafa"},t4={background:"#f5f5f5",foreground:"#1a1a1a",cursor:"#1a1a1a",cursorAccent:"#f5f5f5",selectionBackground:"#d4d4d8",selectionForeground:"#1a1a1a",black:"#1a1a1a",red:"#dc2626",green:"#16a34a",yellow:"#a16207",blue:"#2563eb",magenta:"#9333ea",cyan:"#0891b2",white:"#e4e4e7",brightBlack:"#71717a",brightRed:"#ef4444",brightGreen:"#22c55e",brightYellow:"#92400e",brightBlue:"#3b82f6",brightMagenta:"#a855f7",brightCyan:"#06b6d4",brightWhite:"#fafafa"};function t8(e,t){if(!e||!t)return null;let s=e.getBoundingClientRect();return s.width<180||s.height<120||t.cols<20||t.rows<8?null:{cols:t.cols,rows:t.rows}}async function t6(e,t,s,r){if("u">typeof document&&"fonts"in document)try{await Promise.race([document.fonts.ready,new Promise(e=>setTimeout(e,1e3))])}catch{}for(let a=0;a<12;a++){if(r()||(await new Promise(e=>{requestAnimationFrame(()=>e())}),r()))return null;try{s?.fit()}catch{}let a=t8(e,t);if(a)return a;await new Promise(e=>setTimeout(e,50))}return t8(e,t)}function t7({sessionId:e,visible:t,command:a,commandArgs:i,isDark:o,fontSize:l,hideInitialGsdHeader:d=!1,projectCwd:c,onConnectionChange:u}){let m=(0,n.useRef)(null),x=(0,n.useRef)(null),h=(0,n.useRef)(null),p=(0,n.useRef)(null),g=(0,n.useRef)([]),f=(0,n.useRef)(!1),b=(0,n.useRef)(null),v=(0,n.useRef)(u),j=(0,n.useRef)(!d),y=(0,n.useRef)(""),N=(i??[]).join("\0"),[w,k]=(0,n.useState)(!1),S=(0,n.useCallback)((t,s)=>{b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{e$(t5("/api/terminal/resize",c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e,cols:t,rows:s})})},100)},[c,e]),C=(0,n.useCallback)(async()=>{if(!f.current){for(f.current=!0;g.current.length>0;){let t=g.current.shift();try{await e$(t5("/api/terminal/input",c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e,data:t})})}catch{g.current.unshift(t);break}}f.current=!1}},[c,e]),A=(0,n.useCallback)(e=>{g.current.push(e),C()},[C]);(0,n.useEffect)(()=>{v.current=u},[u]),(0,n.useEffect)(()=>{j.current=!d,y.current=""},[d,e]),(0,n.useEffect)(()=>{x.current&&(x.current.options.theme=o?t3:t4)},[o]),(0,n.useEffect)(()=>{if(x.current){x.current.options.fontSize=l??13;try{h.current?.fit(),x.current&&S(x.current.cols,x.current.rows)}catch{}}},[l,S]),(0,n.useEffect)(()=>{if(t&&h.current&&x.current){let e=setTimeout(()=>{try{h.current?.fit(),x.current&&S(x.current.cols,x.current.rows)}catch{}},50);return()=>clearTimeout(e)}},[t,S]),(0,n.useEffect)(()=>{if(!m.current)return;let t=!1,r=null,n=null,u=null;return(async()=>{let[{Terminal:g},{FitAddon:f}]=await Promise.all([s.e(3888).then(s.bind(s,8422)),s.e(3606).then(s.bind(s,63606))]);if(t)return;if(r=new g({cursorBlink:!0,cursorStyle:"bar",fontSize:l??13,fontFamily:"'SF Mono', 'Cascadia Code', 'Fira Code', Menlo, Monaco, 'Courier New', monospace",lineHeight:1.35,letterSpacing:0,theme:o?t3:t4,allowProposedApi:!0,scrollback:1e4,convertEol:!1}),n=new f,r.loadAddon(n),r.open(m.current),x.current=r,h.current=n,await t6(m.current,r,n,()=>t),t)return;r.onData(e=>A(e)),r.onBinary(e=>A(e));let b=t2("/api/terminal/stream",window.location.origin,c);for(let t of(b.searchParams.set("id",e),a&&b.searchParams.set("command",a),i??[]))b.searchParams.append("arg",t);let N=new EventSource(eD(b.toString()));p.current=N,N.onmessage=e=>{try{let s=JSON.parse(e.data);if("connected"===s.type)v.current(!0),t6(m.current,r,n,()=>t).then(e=>{e&&S(e.cols,e.rows)});else if("output"===s.type&&s.data){let e=s.data;if(d&&!j.current){y.current+=e;let t=function(e){let{plainText:t,rawOffsetsByPlainIndex:s}=function(e){let t="",s=[0];for(let r=0;r<e.length;){let a=e[r];if("\x1b"===a){let t=e[r+1];if("["===t){for(r+=2;r<e.length&&!/[A-~]/.test(e[r]);)r+=1;r<e.length&&(r+=1);continue}if("]"===t){for(r+=2;r<e.length;){if("\x07"===e[r]){r+=1;break}if("\x1b"===e[r]&&"\\"===e[r+1]){r+=2;break}r+=1}continue}if("P"===t||"^"===t||"_"===t||"X"===t){for(r+=2;r<e.length;){if("\x1b"===e[r]&&"\\"===e[r+1]){r+=2;break}r+=1}continue}r+=t?2:1;continue}if("\r"===a){r+=1;continue}r+=1,s[(t+=a).length]=r}return{plainText:t,rawOffsetsByPlainIndex:s}}(e);if(!t)return{status:"needs-more",text:""};let r=t.split("\n"),a=r.find(e=>!t0(e));if(a&&!t1(a))return{status:"passthrough",text:e};let n=r.findIndex(e=>tX.test(e));if(-1===n)return r.length>=16||t.length>=4096?{status:"passthrough",text:e}:{status:"needs-more",text:""};if(n<6)return{status:"passthrough",text:e};let i=r.slice(n-6,n);if(6!==i.length||!i.every(t1))return{status:"passthrough",text:e};let o=tZ(t,n+1);if(null===o)return{status:"needs-more",text:""};let l=o,d=n+1;for(;t0(r[d]);){let e=tZ(t,d+1);if(null===e)break;l=e,d+=1}let c=s[l]??e.length;return{status:"matched",text:e.slice(c)}}(y.current);if("needs-more"===t.status)return;j.current=!0,y.current="",e=t.text}e&&(r?.write(e),k(!0))}}catch{}},N.onerror=()=>v.current(!1),(u=new ResizeObserver(()=>{if(!t)try{n?.fit(),r&&S(r.cols,r.rows)}catch{}})).observe(m.current)})(),()=>{t=!0,b.current&&clearTimeout(b.current),p.current?.close(),p.current=null,u?.disconnect(),r?.dispose(),x.current=null,h.current=null}},[e,a,i,N,l,d,o,c,A,S]);let T=(0,n.useRef)(null),R=(0,n.useCallback)(()=>{x.current?.focus()},[]);return(0,n.useEffect)(()=>{let e=T.current;if(!e)return;let t=e=>{"Enter"!==e.key||!e.shiftKey||e.ctrlKey||e.altKey||e.metaKey||(e.preventDefault(),e.stopPropagation(),A("\n"))};return e.addEventListener("keydown",t,!0),()=>e.removeEventListener("keydown",t,!0)},[A]),(0,n.useEffect)(()=>{if(t){let e=setTimeout(()=>x.current?.focus(),80);return()=>clearTimeout(e)}},[t]),(0,r.jsxs)("div",{ref:T,className:L("relative h-full w-full bg-terminal",!t&&"hidden"),onClick:R,children:[!w&&(0,r.jsxs)("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-terminal",children:[(0,r.jsx)(E.A,{className:"h-5 w-5 animate-spin text-muted-foreground"}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:a?"Starting GSD…":"Connecting…"})]}),(0,r.jsx)("div",{ref:m,className:"h-full w-full",style:{padding:"8px 4px 4px 8px"}})]})}let t9=new Set(["image/jpeg","image/png","image/gif","image/webp"]);async function se(e,t,s){let r,a=tJ(e);if(!a.valid)return void console.warn("[terminal-upload] validation failed:",a.error);let n=new FormData;n.append("file",e);try{let e=await e$(t5("/api/terminal/upload",s),{method:"POST",body:n}),t=await e.json();if(!e.ok||!t.path)return void console.error("[terminal-upload] upload failed:",t.error??`HTTP ${e.status}`);r=t.path}catch(e){console.error("[terminal-upload] upload request failed:",e);return}try{let e=await e$(t5("/api/terminal/input",s),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t,data:`@${r} `})});if(!e.ok){let t=await e.json().catch(()=>({}));console.error("[terminal-upload] inject failed:",t.error??`HTTP ${e.status}`)}}catch(e){console.error("[terminal-upload] inject request failed:",e)}}function st({className:e,command:t,commandArgs:s,sessionPrefix:a,hideSidebar:o=!1,fontSize:l,hideInitialGsdHeader:d=!1,projectCwd:c}){let{resolvedTheme:u}=(0,Y.D)(),m="light"!==u,x=a??(t?"gsd-default":"default"),h=function(e){if(!e?.trim())return"zsh";let t=e.trim().split(/\s+/)[0]||e,s=t.replace(/\\/g,"/").split("/");return s[s.length-1]||t}(t),[p,g]=(0,n.useState)([{id:x,label:h,connected:!1}]),[f,b]=(0,n.useState)(x),[v,j]=(0,n.useState)(!1),y=(0,n.useRef)(null);(0,n.useEffect)(()=>{let e=y.current;if(!e)return;let t=0,s=e=>{e.preventDefault(),e.stopPropagation(),1===(t+=1)&&j(!0)},r=e=>{e.preventDefault(),e.stopPropagation()},a=e=>{e.preventDefault(),e.stopPropagation(),(t-=1)<=0&&(t=0,j(!1))},n=e=>{if(e.preventDefault(),e.stopPropagation(),t=0,j(!1),!f)return;let s=Array.from(e.dataTransfer?.files??[]).find(e=>t9.has(e.type));s&&se(s,f,c)};return e.addEventListener("dragenter",s,!0),e.addEventListener("dragover",r,!0),e.addEventListener("dragleave",a,!0),e.addEventListener("drop",n,!0),()=>{e.removeEventListener("dragenter",s,!0),e.removeEventListener("dragover",r,!0),e.removeEventListener("dragleave",a,!0),e.removeEventListener("drop",n,!0)}},[f,c]),(0,n.useEffect)(()=>{let e=y.current;if(!e)return;let t=e=>{if(!e.clipboardData)return;let t=Array.from(e.clipboardData.files).find(e=>t9.has(e.type));t&&(e.preventDefault(),e.stopPropagation(),f&&se(t,f,c))};return e.addEventListener("paste",t,!0),()=>e.removeEventListener("paste",t,!0)},[f,c]);let N=(0,n.useCallback)(async()=>{try{let e=await e$(t5("/api/terminal/sessions",c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{command:t}:{})}),s=await e.json(),r={id:s.id,label:h,connected:!1};g(e=>[...e,r]),b(s.id)}catch{}},[t,h,c]),w=(0,n.useCallback)(e=>{if(p.length<=1)return;let t=t2("/api/terminal/sessions",window.location.origin,c);t.searchParams.set("id",e),e$(t.toString(),{method:"DELETE"});let s=p.filter(t=>t.id!==e);g(s),f===e&&b(s[s.length-1]?.id??x)},[p,f,x,c]),k=(0,n.useCallback)((e,t)=>{g(s=>s.map(s=>s.id===e?{...s,connected:t}:s))},[]);return(0,r.jsxs)("div",{className:L("flex bg-terminal",e),children:[(0,r.jsxs)("div",{ref:y,className:"relative flex-1 min-w-0",children:[p.map(e=>(0,r.jsx)(t7,{sessionId:e.id,visible:e.id===f,command:t,commandArgs:e.id===x?s:void 0,isDark:m,fontSize:l,hideInitialGsdHeader:d,projectCwd:c,onConnectionChange:t=>k(e.id,t)},e.id)),v&&(0,r.jsxs)("div",{className:"absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 bg-background backdrop-blur-sm border-2 border-dashed border-primary rounded-md pointer-events-none",children:[(0,r.jsx)(tW.A,{className:"h-8 w-8 text-primary"}),(0,r.jsx)("span",{className:"text-sm font-medium text-primary",children:"Drop image here"})]})]}),!o&&(0,r.jsxs)("div",{className:"flex w-[34px] flex-shrink-0 flex-col border-l border-border/50 bg-terminal",children:[(0,r.jsx)("button",{onClick:N,className:"flex h-[30px] w-full items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground",title:"New terminal",children:(0,r.jsx)(tK.A,{className:"h-3 w-3"})}),(0,r.jsx)("div",{className:"h-px bg-border/50"}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto",children:p.map((e,t)=>(0,r.jsxs)("button",{onClick:()=>b(e.id),className:L("group relative flex h-[30px] w-full items-center justify-center transition-colors",e.id===f?"bg-accent text-accent-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"),title:`${e.label} ${t+1}`,children:[e.id===f&&(0,r.jsx)("div",{className:"absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-full bg-muted-foreground"}),(0,r.jsxs)("div",{className:"relative flex items-center",children:[(0,r.jsx)(tH.A,{className:"h-3 w-3"}),(0,r.jsx)("span",{className:L("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full border border-terminal",e.connected?"bg-success":"bg-muted-foreground/40")})]}),p.length>1&&(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),w(e.id)},className:"absolute -right-0.5 -top-0.5 z-10 hidden h-3.5 w-3.5 items-center justify-center rounded-full bg-accent text-muted-foreground hover:bg-destructive/20 hover:text-destructive group-hover:flex",title:"Kill terminal",children:(0,r.jsx)(i.A,{className:"h-2 w-2"})})]},e.id))})]})]})}var ss=s(84980),sr=s(76498),sa=s(53961),sn=s(67514);function si(){return(0,r.jsxs)("div",{className:"rounded-md border border-border bg-card",children:[(0,r.jsx)("div",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("h2",{className:"text-sm font-semibold",children:"Current Slice"})}),(0,r.jsx)("div",{className:"space-y-3 p-4",children:[1,2,3].map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)(tL,{className:"h-4 w-4 shrink-0 rounded-full"}),(0,r.jsx)(tL,{className:L("h-4",1===e?"w-48":2===e?"w-40":"w-36")})]},e))})]})}function so(){return(0,r.jsxs)("div",{className:"rounded-md border border-border bg-card",children:[(0,r.jsx)("div",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("h2",{className:"text-sm font-semibold",children:"Recent Activity"})}),(0,r.jsx)("div",{className:"divide-y divide-border",children:[1,2,3,4].map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[(0,r.jsx)(tL,{className:"h-3 w-16 shrink-0"}),(0,r.jsx)(tL,{className:"h-1.5 w-1.5 shrink-0 rounded-full"}),(0,r.jsx)(tL,{className:L("h-4 flex-1",e%3==0?"max-w-xs":e%3==1?"max-w-sm":"max-w-md")})]},e))})]})}function sl(e){switch(e){case"complete":case"completed":return{label:"Complete",tone:"success"};case"executing":return{label:"Executing",tone:"active"};case"in-progress":return{label:"In Progress",tone:"active"};case"planning":return{label:"Planning",tone:"info"};case"pre-planning":return{label:"Pre-planning",tone:"muted"};case"summarizing":return{label:"Summarizing",tone:"info"};case"blocked":return{label:"Blocked",tone:"warning"};case"needs-discussion":return{label:"Discussion",tone:"warning"};case"replanning-slice":return{label:"Replanning",tone:"info"};case"completing-milestone":return{label:"Completing",tone:"info"};case"evaluating-gates":return{label:"Evaluating Gates",tone:"info"};default:return{label:e,tone:"muted"}}}let sd={success:"bg-success/15 text-success",active:"bg-primary/15 text-primary",warning:"bg-warning/15 text-warning",info:"bg-info/15 text-info",muted:"bg-muted text-muted-foreground"},sc={success:"bg-success",active:"bg-primary",warning:"bg-warning",info:"bg-info",muted:"bg-muted-foreground/50"};function su(e){return e.replace(/([MST])0*(\d+)/g,"$1$2")}function sm(e){let t=e.match(/^(.+?)\s*—\s*(.+)$/);return t?{scopeId:su(t[1].trim()),phase:t[2].trim()}:{scopeId:su(e.trim()),phase:null}}function sx({label:e,size:t="md",className:s}){let{scopeId:a,phase:n}=sm(e);if("Project scope pending"===a)return(0,r.jsx)("span",{className:L("text-muted-foreground",sh(t),s),children:"Scope pending…"});let i=n?sl(n):null;return(0,r.jsxs)("span",{className:L("inline-flex items-center gap-2",s),children:[(0,r.jsx)("span",{className:L("font-semibold tracking-tight","sm"===t?"text-sm":"text-lg"),children:a}),i&&(0,r.jsx)("span",{className:L("inline-flex shrink-0 items-center rounded-full px-2 font-medium leading-snug",sd[i.tone],sh(t),"sm"===t?"py-px":"py-0.5"),children:i.label})]})}function sh(e){return"sm"===e?"text-[10px]":"text-[11px]"}function sp({label:e,className:t}){let{scopeId:s,phase:a}=sm(e);if("Project scope pending"===s)return(0,r.jsx)("span",{className:L("text-muted-foreground",t),children:"Scope pending…"});let n=a?sl(a):null,i=n?sc[n.tone]:"bg-muted-foreground/50";return(0,r.jsxs)("span",{className:L("inline-flex items-center gap-1.5",t),children:[(0,r.jsx)("span",{className:L("h-1.5 w-1.5 shrink-0 rounded-full",i)}),(0,r.jsx)("span",{children:s}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-border",children:"\xb7"}),(0,r.jsx)("span",{children:n.label})]})]})}var sg=s(42129),sf=s(25344),sb=s(86901),sv=s(24642),sj=s(48274),sy=s(21628);function sN({icon:e,label:t}){return(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1 text-xs text-muted-foreground",children:[e,t]})}function sw({signals:e}){let t=[];return(e.hasGitRepo&&t.push({icon:(0,r.jsx)(N.A,{className:"h-3 w-3"}),label:"Git repository"}),e.hasPackageJson&&t.push({icon:(0,r.jsx)(sv.A,{className:"h-3 w-3"}),label:"Node.js project"}),e.fileCount>0&&t.push({icon:(0,r.jsx)(sj.A,{className:"h-3 w-3"}),label:`${e.fileCount} file${1===e.fileCount?"":"s"}`}),0===t.length)?null:(0,r.jsx)("div",{className:"flex flex-wrap gap-2",children:t.map(e=>(0,r.jsx)(sN,{icon:e.icon,label:e.label},e.label))})}function sk({detection:e,onCommand:t,onSwitchView:s,disabled:a=!1}){let n=function(e){switch(e.kind){case"brownfield":return{icon:(0,r.jsx)(sg.A,{className:"h-8 w-8 text-foreground",strokeWidth:1.5}),headline:"Existing project detected",body:"GSD will map your codebase and ask a few questions about what you want to build. From there it generates structured milestones and deliverable slices.",primaryLabel:"Map & Initialize",primaryCommand:"/gsd",secondary:{label:"Browse files first",action:"files-view"}};case"v1-legacy":return{icon:(0,r.jsx)(sf.A,{className:"h-8 w-8 text-foreground",strokeWidth:1.5}),headline:"GSD v1 project found",body:"This project has a .planning/ folder from an earlier GSD version. Migration converts your existing planning data into the new .gsd/ format.",detail:"Your original files will be preserved — migration creates the new structure alongside them.",primaryLabel:"Migrate to v2",primaryCommand:"/gsd migrate",secondary:{label:"Start fresh instead",action:"command",command:"/gsd"}};case"blank":return{icon:(0,r.jsx)(sb.A,{className:"h-8 w-8 text-foreground",strokeWidth:1.5}),headline:"Start a new project",body:"This folder is empty. GSD will ask what you want to build, then generate a structured plan — milestones broken into deliverable slices with risk-ordered execution.",primaryLabel:"Start Project Setup",primaryCommand:"/gsd"};default:return{icon:(0,r.jsx)(b.A,{className:"h-8 w-8 text-foreground",strokeWidth:1.5}),headline:"Set up your project",body:"Run the GSD wizard to get started.",primaryLabel:"Get Started",primaryCommand:"/gsd"}}}(e),i="brownfield"===e.kind||"v1-legacy"===e.kind;return(0,r.jsx)("div",{className:"flex h-full items-center justify-center p-8",children:(0,r.jsxs)("div",{className:"w-full max-w-lg",children:[(0,r.jsx)("div",{className:"mb-6 flex h-16 w-16 items-center justify-center rounded-xl border border-border bg-card",children:n.icon}),(0,r.jsx)("h2",{className:"text-2xl font-bold tracking-tight text-foreground",children:n.headline}),(0,r.jsx)("p",{className:"mt-3 text-sm leading-relaxed text-muted-foreground",children:n.body}),n.detail&&(0,r.jsx)("p",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:n.detail}),i&&(0,r.jsx)("div",{className:"mt-5",children:(0,r.jsx)(sw,{signals:e.signals})}),(0,r.jsxs)("div",{className:"mt-8 flex items-center gap-3",children:[(0,r.jsxs)("button",{onClick:()=>t(n.primaryCommand),disabled:a,className:L("inline-flex items-center gap-2 rounded-md bg-foreground px-5 py-2.5 text-sm font-medium text-background transition-colors hover:bg-foreground/90",a&&"cursor-not-allowed opacity-50"),children:[n.primaryLabel,(0,r.jsx)(sy.A,{className:"h-3.5 w-3.5"})]}),n.secondary&&(0,r.jsx)("button",{onClick:()=>{"files-view"===n.secondary.action?s("files"):n.secondary.command&&t(n.secondary.command)},disabled:a,className:L("inline-flex items-center gap-1.5 rounded-md border border-border bg-background px-4 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-accent",a&&"cursor-not-allowed opacity-50"),children:n.secondary.label})]}),"blank"===e.kind&&(0,r.jsxs)("div",{className:"mt-8 rounded-lg border border-border/50 bg-card/50 p-4",children:[(0,r.jsx)("p",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"What happens next"}),(0,r.jsx)("ul",{className:"mt-2.5 space-y-2",children:["A few questions about what you're building","Codebase analysis and context gathering","Structured milestone and slice generation"].map((e,t)=>(0,r.jsxs)("li",{className:"flex items-start gap-2.5 text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border border-border text-[10px] font-medium text-muted-foreground",children:t+1}),e]},t))})]}),"brownfield"===e.kind&&(0,r.jsxs)("div",{className:"mt-8 rounded-lg border border-border/50 bg-card/50 p-4",children:[(0,r.jsx)("p",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"What happens next"}),(0,r.jsx)("ul",{className:"mt-2.5 space-y-2",children:["GSD scans your codebase and asks about your goals","You discuss scope, constraints, and priorities","A milestone with risk-ordered slices is generated"].map((e,t)=>(0,r.jsxs)("li",{className:"flex items-start gap-2.5 text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border border-border text-[10px] font-medium text-muted-foreground",children:t+1}),e]},t))})]})]})})}function sS({label:e,value:t,subtext:s,icon:a}){return(0,r.jsx)("div",{className:"rounded-md border border-border bg-card p-4",children:(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("p",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:e}),null===t?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(tL,{className:"mt-2 h-7 w-20"}),(0,r.jsx)(tL,{className:"mt-1.5 h-3 w-16"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"mt-1 truncate text-2xl font-semibold tracking-tight",children:t}),s&&(0,r.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:s})]})]}),(0,r.jsx)("div",{className:"shrink-0 rounded-md bg-accent p-2 text-muted-foreground",children:a})]})})}function sC({onSwitchView:e,onExpandTerminal:t}={}){let s,a=tb(),{sendCommand:n}=tv(),i=a.boot,o=td(a),u=tc(a),m=i?.bridge??null,x=a.live.freshness,h=u?.elapsed??0,p=u?.totalCost??0,g=u?.totalTokens??0,f=u?.rtkSavings??null,b=u?.rtkEnabled===!0,j=function(e){if(!e?.active.milestoneId||!e.active.sliceId)return null;let t=e.milestones.find(t=>t.id===e.active.milestoneId);return t?.slices.find(t=>t.id===e.active.sliceId)??null}(o),y=j?.tasks.filter(e=>e.done).length??0,w=j?.tasks.length??0,k=w>0?Math.round(y/w*100):0,S=eZ(o),C=e0(o),A=u?.active??!1,T=u?.currentUnit?.id??S,R=x.auto.stale?"stale":x.auto.status;tk({phase:o?.active.phase??"pre-planning",autoActive:u?.active??!1,autoPaused:u?.paused??!1,onboardingLocked:i?.onboarding.locked??!1,commandInFlight:a.commandInFlight,bootStatus:a.bootStatus,hasMilestones:(o?.milestones.length??0)>0,projectDetectionKind:i?.projectDetection?.kind??null});let E=(a.terminalLines??[]).slice(-6),P="idle"===a.bootStatus||"loading"===a.bootStatus,_=P?null:eQ(f?.savedTokens??0),I=P?null:f&&f.commands>0?`${Math.round(f.savingsPct)}% saved • ${f.commands} cmd${1===f.commands?"":"s"}`:"Waiting for shell usage",$=i?.projectDetection;return!P&&$&&"active-gsd"!==$.kind&&"empty-gsd"!==$.kind?(0,r.jsx)("div",{className:"flex h-full flex-col overflow-hidden",children:(0,r.jsx)(sk,{detection:$,onCommand:e=>{t_({dispatch:()=>n(tj(e,m))})},onSwitchView:t=>e?.(t),disabled:!!a.commandInFlight||i?.onboarding.locked})}):(0,r.jsxs)("div",{className:"flex h-full flex-col overflow-hidden",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between border-b border-border px-3 py-2 md:px-6 md:py-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,r.jsx)("h1",{className:"text-base md:text-lg font-semibold shrink-0",children:"Dashboard"}),!P&&S&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"hidden sm:inline text-lg font-thin text-muted-foreground select-none",children:"/"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:(0,r.jsx)(sx,{label:S,size:"sm"})})]}),P&&(0,r.jsx)(tL,{className:"h-4 w-40"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 md:gap-3","data-testid":"dashboard-action-bar",children:[P?(0,r.jsx)(r.Fragment,{children:(0,r.jsx)(tL,{className:"h-8 w-40 rounded-md"})}):null,!P&&(0,r.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border bg-card px-3 py-1.5 text-sm",children:[(0,r.jsx)("span",{className:L("h-2 w-2 rounded-full",A?"animate-pulse bg-success":"bg-muted-foreground/50")}),(0,r.jsx)("span",{className:"font-medium",children:A?"Auto Mode Active":"Auto Mode Inactive"})]}),!P&&C&&(0,r.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,r.jsx)(N.A,{className:"h-4 w-4"}),(0,r.jsx)("span",{className:"font-mono",children:C})]})]})]}),(0,r.jsxs)("div",{className:"flex-1 overflow-y-auto p-3 md:p-6",children:[(0,r.jsxs)("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-5",children:[(0,r.jsx)("div",{className:"rounded-md border border-border bg-card p-4","data-testid":"dashboard-current-unit",children:(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("p",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Current Unit"}),P?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(tL,{className:"mt-2 h-7 w-20"}),(0,r.jsx)(tL,{className:"mt-1.5 h-3 w-16"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"mt-2",children:(0,r.jsx)(sx,{label:T})}),(0,r.jsxs)("p",{className:"mt-1.5 text-xs text-muted-foreground","data-testid":"dashboard-current-unit-freshness",children:["Auto freshness: ",R]})]})]}),(0,r.jsx)("div",{className:"shrink-0 rounded-md bg-accent p-2 text-muted-foreground",children:(0,r.jsx)(v.A,{className:"h-5 w-5"})})]})}),(0,r.jsx)(sS,{label:"Elapsed Time",value:P?null:function(e){if(!e||e<1e3)return"0m";let t=Math.floor(e/6e4),s=Math.floor(t/60),r=t%60;return s>0?`${s}h ${r}m`:`${r}m`}(h),icon:(0,r.jsx)(ss.A,{className:"h-5 w-5"})}),(0,r.jsx)(sS,{label:"Total Cost",value:P?null:eX(p),icon:(0,r.jsx)(sr.A,{className:"h-5 w-5"})}),(0,r.jsx)(sS,{label:"Tokens Used",value:P?null:eQ(g),icon:(0,r.jsx)(sa.A,{className:"h-5 w-5"})}),b&&(0,r.jsx)(sS,{label:"RTK Saved",value:_,subtext:I,icon:(0,r.jsx)(sn.A,{className:"h-5 w-5"})})]}),(0,r.jsx)("div",{className:"mt-6",children:P?(0,r.jsx)(si,{}):(0,r.jsxs)("div",{className:"flex flex-col rounded-md border border-border bg-card",children:[(0,r.jsxs)("div",{className:"border-b border-border px-4 py-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("h2",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Current Slice"}),j?(0,r.jsxs)("p",{className:"mt-0.5 truncate text-sm font-medium text-foreground",children:[j.id," — ",j.title]}):(0,r.jsx)("p",{className:"mt-0.5 text-sm text-muted-foreground",children:"No active slice"})]}),j&&w>0&&(0,r.jsxs)("div",{className:"shrink-0 text-right",children:[(0,r.jsx)("span",{className:"text-2xl font-bold tabular-nums leading-none",children:k}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"%"})]})]}),j&&w>0&&(0,r.jsxs)("div",{className:"mt-3",children:[(0,r.jsx)("div",{className:"h-1 w-full overflow-hidden rounded-full bg-accent",children:(0,r.jsx)("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${k}%`,backgroundColor:(s=Math.max(0,Math.min(100,k)),`oklch(0.65 0.16 ${(25+s/100*120).toFixed(1)})`)}})}),(0,r.jsxs)("p",{className:"mt-1.5 text-xs text-muted-foreground",children:[y," of ",w," tasks complete"]})]})]}),(0,r.jsx)("div",{className:"flex-1 p-3",children:j&&j.tasks.length>0?(0,r.jsx)("div",{className:"space-y-0.5",children:j.tasks.map(e=>{let t=tw(o.active.milestoneId,j.id,e,o.active);return(0,r.jsxs)("div",{className:L("flex items-center gap-2.5 rounded px-2 py-1.5 transition-colors","in-progress"===t&&"bg-accent"),children:[function(e){switch(e){case"done":return(0,r.jsx)(l.A,{className:"h-4 w-4 text-muted-foreground"});case"in-progress":return(0,r.jsx)(d.A,{className:"h-4 w-4 text-foreground"});case"pending":return(0,r.jsx)(c.A,{className:"h-4 w-4 text-muted-foreground"})}}(t),(0,r.jsxs)("span",{className:L("min-w-0 flex-1 truncate text-xs","done"===t&&"text-muted-foreground line-through decoration-muted-foreground/40","pending"===t&&"text-muted-foreground","in-progress"===t&&"font-medium text-foreground"),children:[(0,r.jsx)("span",{className:"font-mono text-muted-foreground",children:e.id}),(0,r.jsx)("span",{className:"mx-1.5 text-border",children:"\xb7"}),e.title]}),"in-progress"===t&&(0,r.jsx)("span",{className:"shrink-0 rounded-sm bg-foreground/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:"active"})]},e.id)})}):(0,r.jsx)("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:"No active slice or no tasks defined yet."})})]})}),P?(0,r.jsx)("div",{className:"mt-6",children:(0,r.jsx)(so,{})}):(0,r.jsxs)("div",{className:"mt-6 rounded-md border border-border bg-card",children:[(0,r.jsx)("div",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("h2",{className:"text-sm font-semibold",children:"Recent Activity"})}),E.length>0?(0,r.jsx)("div",{className:"divide-y divide-border",children:E.map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[(0,r.jsx)("span",{className:"w-16 flex-shrink-0 font-mono text-xs text-muted-foreground",children:e.timestamp}),(0,r.jsx)("span",{className:L("h-1.5 w-1.5 flex-shrink-0 rounded-full",function(e){switch(e){case"success":return"bg-success";case"error":return"bg-destructive";default:return"bg-foreground/50"}}(e.type))}),(0,r.jsx)("span",{className:"truncate text-sm",children:e.content})]},e.id))}):(0,r.jsx)("div",{className:"px-4 py-4 text-sm text-muted-foreground",children:"No activity yet."})]})]})]})}var sA=s(41585);let sT=({status:e,size:t="default"})=>{let s="large"===t?"h-5 w-5":"h-4 w-4";return"done"===e?(0,r.jsx)(l.A,{className:L(s,"text-success")}):"in-progress"===e?(0,r.jsx)(d.A,{className:L(s,"text-warning")}):(0,r.jsx)(c.A,{className:L(s,"text-muted-foreground")})},sR=({risk:e})=>(0,r.jsxs)("span",{className:L("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium uppercase","high"===e&&"bg-destructive/20 text-destructive","medium"===e&&"bg-warning/20 text-warning","low"===e&&"bg-muted text-muted-foreground"),children:["high"===e&&(0,r.jsx)(sA.A,{className:"h-2.5 w-2.5"}),e]});function sE(){let e=tb(),t=td(e),s=t?.milestones??[],a=t?.active??{},n=e.live.freshness.workspace.stale?"stale":e.live.freshness.workspace.status;return(0,r.jsxs)("div",{className:"flex h-full flex-col overflow-hidden",children:[(0,r.jsxs)("div",{className:"border-b border-border px-6 py-3",children:[(0,r.jsx)("h1",{className:"text-lg font-semibold",children:"Roadmap"}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"Project milestone structure with slices and dependencies"}),(0,r.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground","data-testid":"roadmap-workspace-freshness",children:["Workspace freshness: ",n]})]}),(0,r.jsxs)("div",{className:"flex-1 overflow-y-auto p-6",children:["loading"===e.bootStatus&&(0,r.jsx)("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loading workspace…"}),"ready"===e.bootStatus&&0===s.length&&(0,r.jsxs)("div",{className:"py-8 text-center text-sm text-muted-foreground",children:["No milestones found. Create a milestone with ",(0,r.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:"/gsd"})," to get started."]}),(0,r.jsx)("div",{className:"space-y-6",children:s.map(e=>{let t=ty(e,a),s=e.slices.filter(e=>e.done).length,n=e.slices.reduce((e,t)=>e+t.tasks.length,0),i=e.slices.reduce((e,t)=>e+t.tasks.filter(e=>e.done).length,0);return(0,r.jsxs)("div",{className:"rounded-md border border-border bg-card",children:[(0,r.jsxs)("div",{className:L("flex items-center gap-3 border-b border-border px-4 py-3","in-progress"===t&&"bg-accent/30"),children:[(0,r.jsx)(sT,{status:t,size:"large"}),(0,r.jsx)("div",{className:"flex-1",children:(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.id}),(0,r.jsx)(A.A,{className:"h-3 w-3 text-muted-foreground"}),(0,r.jsx)("span",{className:"font-semibold",children:e.title})]})}),(0,r.jsxs)("div",{className:"text-right",children:[(0,r.jsxs)("div",{className:"text-sm font-medium",children:[s,"/",e.slices.length," slices"]}),(0,r.jsxs)("div",{className:"text-xs text-muted-foreground",children:[i,"/",n," tasks"]})]})]}),(0,r.jsx)("div",{className:"divide-y divide-border",children:e.slices.map(t=>{let s=tN(e.id,t,a),n=t.tasks.filter(e=>e.done).length,i=t.tasks.length;return(0,r.jsxs)("div",{className:L("flex items-center gap-3 px-4 py-2.5","in-progress"===s&&"bg-accent/20","pending"===s&&"opacity-70"),children:[(0,r.jsx)("div",{className:"w-4"}),(0,r.jsx)(sT,{status:s}),(0,r.jsx)("div",{className:"flex-1",children:(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:t.id}),(0,r.jsx)("span",{className:"text-sm",children:t.title}),t.risk&&(0,r.jsx)(sR,{risk:t.risk}),t.depends&&t.depends.length>0&&(0,r.jsxs)("span",{className:"text-[10px] text-muted-foreground",children:["depends on ",t.depends.join(", ")]})]})}),(0,r.jsxs)("div",{className:"flex items-center gap-4",children:[(0,r.jsx)("div",{className:"w-24",children:(0,r.jsx)("div",{className:"h-1 w-full rounded-full bg-accent",children:(0,r.jsx)("div",{className:"h-full rounded-full bg-foreground/70 transition-all",style:{width:i>0?`${n/i*100}%`:"0%"}})})}),(0,r.jsxs)("span",{className:"w-12 text-right text-xs text-muted-foreground",children:[n,"/",i]})]})]},`${e.id}-${t.id}`)})})]},e.id)})})]})]})}var sP=s(78916),s_=s(93631),sI=s(63393),s$=s(49387),sD=s(67635),sF=s(13986),sL=s(68459),sM=s(49619),sq=s(13545),sO=s(55243),sU=s(57518);function sz({className:e,...t}){return(0,r.jsx)(sU.bL,{"data-slot":"tabs",className:L("flex flex-col gap-2",e),...t})}function sB({className:e,...t}){return(0,r.jsx)(sU.B8,{"data-slot":"tabs-list",className:L("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function sG({className:e,...t}){return(0,r.jsx)(sU.l9,{"data-slot":"tabs-trigger",className:L("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function sW({className:e,...t}){return(0,r.jsx)(sU.UC,{"data-slot":"tabs-content",className:L("flex-1 outline-none",e),...t})}var sK=s(37206),sH=s(8175),sV=s(32638),sJ=s(60740),sY=s(89561);let sQ=(0,sK.default)(()=>s.e(5326).then(s.bind(s,15326)),{loadableGenerated:{webpack:()=>[null]},ssr:!1,loading:()=>(0,r.jsx)("div",{className:"flex h-full min-h-[120px] items-center justify-center",children:(0,r.jsx)(E.A,{className:"h-5 w-5 animate-spin text-muted-foreground"})})}),sX=[{tag:[sV._A.comment,sV._A.lineComment,sV._A.blockComment],color:"#6a737d"},{tag:[sV._A.keyword],color:"#ff7b72"},{tag:[sV._A.operator],color:"#79c0ff"},{tag:[sV._A.string,sV._A.special(sV._A.string)],color:"#a5d6ff"},{tag:[sV._A.number,sV._A.bool,sV._A.null],color:"#79c0ff"},{tag:[sV._A.variableName],color:"#c9d1d9"},{tag:[sV._A.definition(sV._A.variableName)],color:"#d2a8ff"},{tag:[sV._A.function(sV._A.variableName)],color:"#d2a8ff"},{tag:[sV._A.typeName,sV._A.className],color:"#ffa657"},{tag:[sV._A.propertyName],color:"#79c0ff"},{tag:[sV._A.definition(sV._A.propertyName)],color:"#c9d1d9"},{tag:[sV._A.bracket],color:"#8b949e"},{tag:[sV._A.punctuation],color:"#8b949e"},{tag:[sV._A.tagName],color:"#7ee787"},{tag:[sV._A.attributeName],color:"#79c0ff"},{tag:[sV._A.attributeValue],color:"#a5d6ff"},{tag:[sV._A.regexp],color:"#7ee787"},{tag:[sV._A.escape],color:"#79c0ff"},{tag:[sV._A.meta],color:"#8b949e"}],sZ=[{tag:[sV._A.comment,sV._A.lineComment,sV._A.blockComment],color:"#6a737d"},{tag:[sV._A.keyword],color:"#cf222e"},{tag:[sV._A.operator],color:"#0550ae"},{tag:[sV._A.string,sV._A.special(sV._A.string)],color:"#0a3069"},{tag:[sV._A.number,sV._A.bool,sV._A.null],color:"#0550ae"},{tag:[sV._A.variableName],color:"#24292f"},{tag:[sV._A.definition(sV._A.variableName)],color:"#8250df"},{tag:[sV._A.function(sV._A.variableName)],color:"#8250df"},{tag:[sV._A.typeName,sV._A.className],color:"#953800"},{tag:[sV._A.propertyName],color:"#0550ae"},{tag:[sV._A.definition(sV._A.propertyName)],color:"#24292f"},{tag:[sV._A.bracket],color:"#57606a"},{tag:[sV._A.punctuation],color:"#57606a"},{tag:[sV._A.tagName],color:"#116329"},{tag:[sV._A.attributeName],color:"#0550ae"},{tag:[sV._A.attributeValue],color:"#0a3069"},{tag:[sV._A.regexp],color:"#116329"},{tag:[sV._A.escape],color:"#0550ae"},{tag:[sV._A.meta],color:"#57606a"}],s0=(0,sH.a)({theme:"dark",settings:{background:"oklch(0.09 0 0)",foreground:"oklch(0.9 0 0)",caret:"oklch(0.9 0 0)",selection:"oklch(0.2 0 0)",lineHighlight:"oklch(0.12 0 0)",gutterBackground:"oklch(0.09 0 0)",gutterForeground:"oklch(0.42 0 0)",gutterBorder:"transparent"},styles:sX}),s1=(0,sH.a)({theme:"light",settings:{background:"oklch(0.98 0 0)",foreground:"oklch(0.15 0 0)",caret:"oklch(0.15 0 0)",selection:"oklch(0.9 0 0)",lineHighlight:"oklch(0.96 0 0)",gutterBackground:"oklch(0.98 0 0)",gutterForeground:"oklch(0.55 0 0)",gutterBorder:"transparent"},styles:sZ}),s5={typescript:"ts",tsx:"tsx",javascript:"js",jsx:"jsx",bash:"bash",sh:"sh",zsh:"sh",json:"json",jsonc:"json",yaml:"yaml",toml:"toml",markdown:"markdown",mdx:"markdown",html:"html",xml:"xml",css:"css",scss:"scss",less:"less",python:"py",ruby:"rb",rust:"rs",go:"go",java:"java",kotlin:"kt",swift:"swift",c:"c",cpp:"cpp",csharp:"cs",php:"php",sql:"sql",graphql:null,dockerfile:null,makefile:null,lua:"lua",r:"r",latex:"tex",diff:"diff",viml:null,dotenv:null,fish:null,ini:"ini"};function s2({value:e,onChange:t,language:s,fontSize:a,className:i}){let{resolvedTheme:o}=(0,Y.D)(),l=(0,n.useMemo)(()=>{if(!s)return null;let e=s5[s];return null==e?null:(0,sJ.rI)(e)},[s]),d=(0,n.useMemo)(()=>sY.Lz.theme({"&":{fontSize:`${a}px`},".cm-gutters":{fontSize:`${a}px`}}),[a]),c=(0,n.useMemo)(()=>{let e=[d];return l&&e.push(l),e},[d,l]);return(0,r.jsx)(sQ,{value:e,onChange:t,theme:"light"!==o?s0:s1,extensions:c,height:"100%",basicSetup:{lineNumbers:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,foldGutter:!0,bracketMatching:!0,closeBrackets:!0,autocompletion:!1,tabSize:2},className:L("overflow-hidden rounded-md border",i)})}let s3="gsd-editor-font-size",s4="editor-font-size-changed";function s8(){let[e,t]=(0,n.useState)(()=>{try{let e=localStorage.getItem(s3);if(e){let t=Number(e);if(Number.isFinite(t)&&t>=8&&t<=24)return t}}catch{}return 14}),s=(0,n.useCallback)(e=>{let s=Math.max(8,Math.min(24,Math.round(e)));t(s);try{localStorage.setItem(s3,String(s))}catch{}window.dispatchEvent(new CustomEvent(s4,{detail:s}))},[]);return(0,n.useEffect)(()=>{let e=e=>{if(e.key!==s3)return;let s=Number(e.newValue);Number.isFinite(s)&&s>=8&&s<=24&&t(s)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,n.useEffect)(()=>{let e=e=>{let s=e.detail;Number.isFinite(s)&&s>=8&&s<=24&&t(s)};return window.addEventListener(s4,e),()=>window.removeEventListener(s4,e)},[]),[e,s]}let s6={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",mjs:"javascript",cjs:"javascript",json:"json",jsonc:"jsonc",md:"markdown",mdx:"mdx",css:"css",scss:"scss",less:"less",html:"html",htm:"html",xml:"xml",svg:"xml",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",sql:"sql",graphql:"graphql",gql:"graphql",dockerfile:"dockerfile",makefile:"makefile",lua:"lua",vim:"viml",r:"r",tex:"latex",diff:"diff",ini:"ini",conf:"ini",env:"dotenv"},s7={Dockerfile:"dockerfile",Makefile:"makefile",Containerfile:"dockerfile",Justfile:"makefile",Rakefile:"ruby",Gemfile:"ruby",".env":"dotenv",".env.local":"dotenv",".env.example":"dotenv",".eslintrc":"json",".prettierrc":"json","tsconfig.json":"jsonc","jsconfig.json":"jsonc"};function s9(e){let t=e.split("/").pop()??"";if(s7[t])return s7[t];let s=t.includes(".")?t.split(".").pop()?.toLowerCase():null;return s&&s6[s]?s6[s]:null}function re(e){let t=e.split(".").pop()?.toLowerCase();return"md"===t||"mdx"===t}let rt=null;async function rs(){return rt||(rt=Promise.all([s.e(8921),s.e(4447)]).then(s.bind(s,24447)).then(e=>e.createHighlighter({themes:["github-dark-default","github-light-default"],langs:["typescript","tsx","javascript","jsx","json","jsonc","markdown","mdx","css","scss","less","html","xml","yaml","toml","bash","python","ruby","rust","go","java","kotlin","swift","c","cpp","csharp","php","sql","graphql","dockerfile","makefile","lua","diff","ini","dotenv"]})).catch(e=>{throw rt=null,e})),rt}function rr({content:e,filepath:t,shikiTheme:s="github-dark-default"}){let[a,i]=(0,n.useState)(null),[o,l]=(0,n.useState)(!1),d=(0,n.useRef)(null),c=s9(t);return((0,n.useEffect)(()=>{let t=!1;if(!c){let e=window.setTimeout(()=>{l(!0)},0);return()=>window.clearTimeout(e)}return rs().then(r=>{if(!t){try{let t=r.codeToHtml(e,{lang:c,theme:s});i(t)}catch{i(null)}l(!0)}}).catch(()=>{t||l(!0)}),()=>{t=!0}},[e,c,s]),o)?a?(0,r.jsx)("div",{ref:d,className:"file-viewer-code overflow-x-auto text-sm leading-relaxed",dangerouslySetInnerHTML:{__html:a}}):(0,r.jsx)(ra,{content:e}):(0,r.jsxs)("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin mr-2"}),"Highlighting…"]})}function ra({content:e}){let t=(0,n.useMemo)(()=>e.split("\n"),[e]),s=String(t.length).length;return(0,r.jsx)("div",{className:"overflow-x-auto text-sm leading-relaxed font-mono",children:(0,r.jsx)("table",{className:"border-collapse",children:(0,r.jsx)("tbody",{children:t.map((e,t)=>(0,r.jsxs)("tr",{className:"hover:bg-accent/20",children:[(0,r.jsx)("td",{className:"select-none pr-4 text-right text-muted-foreground align-top",style:{minWidth:`${s+1}ch`},children:t+1}),(0,r.jsx)("td",{className:"whitespace-pre text-muted-foreground",children:e||" "})]},t))})})})}function rn({content:e,filepath:t,shikiTheme:a="github-dark-default"}){let[i,o]=(0,n.useState)(null),[l,d]=(0,n.useState)(!1);return((0,n.useEffect)(()=>{let t=!1;return Promise.all([Promise.all([s.e(4846),s.e(8921),s.e(4417)]).then(s.bind(s,4417)),Promise.all([s.e(4846),s.e(2397)]).then(s.bind(s,32397)),rs()]).then(([s,n,i])=>{if(t)return;let l=s.default,c=n.default;o((0,r.jsx)(l,{remarkPlugins:[c],components:{code({className:e,children:t,...s}){let n=/language-(\w+)/.exec(e||""),o=String(t).replace(/\n$/,"");if(n)try{let e=i.codeToHtml(o,{lang:n[1],theme:a});return(0,r.jsx)("div",{className:"file-viewer-code my-3 rounded-md overflow-x-auto text-sm",dangerouslySetInnerHTML:{__html:e}})}catch{}return e||String(t).includes("\n")?(0,r.jsx)("pre",{className:"my-3 overflow-x-auto rounded-md bg-[#0d1117] p-4 text-sm",children:(0,r.jsx)("code",{children:t})}):(0,r.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-sm font-mono",...s,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),table:({children:e})=>(0,r.jsx)("div",{className:"my-4 overflow-x-auto",children:(0,r.jsx)("table",{className:"min-w-full border-collapse border border-border text-sm",children:e})}),th:({children:e})=>(0,r.jsx)("th",{className:"border border-border bg-muted/50 px-3 py-2 text-left font-medium",children:e}),td:({children:e})=>(0,r.jsx)("td",{className:"border border-border px-3 py-2",children:e}),a:({href:e,children:t})=>(0,r.jsx)("a",{href:e,className:"text-info hover:underline",target:"_blank",rel:"noopener noreferrer",children:t}),img:({src:e,alt:t})=>(0,r.jsxs)("span",{className:"my-2 block rounded border border-border bg-muted/50 px-3 py-2 text-xs text-muted-foreground italic",children:["\uD83D\uDDBC ",t||("string"==typeof e?e:"")||"image"]})},children:e})),d(!0)}).catch(()=>{t||d(!0)}),()=>{t=!0}},[e,t,a]),l)?i?(0,r.jsx)("div",{className:"markdown-body",children:i}):(0,r.jsx)(ra,{content:e}):(0,r.jsxs)("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin mr-2"}),"Rendering…"]})}function ri({before:e,after:t,onDismiss:s}){let a=(0,n.useMemo)(()=>(function(e,t){let s=e.split("\n"),r=t.split("\n"),a=[],n=s.length,i=r.length;if(n+i>5e3)return s.forEach((e,t)=>a.push({type:"remove",lineNum:t+1,text:e})),r.forEach((e,t)=>a.push({type:"add",lineNum:t+1,text:e})),a;let o=n+i,l=new Int32Array(2*o+1),d=[];e:for(let e=0;e<=o;e++){let t=new Int32Array(l);d.push(t);for(let t=-e;t<=e;t+=2){let a,d=(a=t===-e||t!==e&&l[t-1+o]<l[t+1+o]?l[t+1+o]:l[t-1+o]+1)-t;for(;a<n&&d<i&&s[a]===r[d];)a++,d++;if(l[t+o]=a,a>=n&&d>=i)break e}}let c=[],u=n,m=i;for(let e=d.length-1;e>=0;e--){let t,s=d[e],r=u-m;t=r===-e||r!==e&&s[r-1+o]<s[r+1+o]?r+1:r-1;let a=s[t+o],n=a-t;for(;u>a&&m>n;)u--,m--,c.push({type:"context",oldIdx:u,newIdx:m});e>0&&(u===a?(m--,c.push({type:"add",oldIdx:u,newIdx:m})):(u--,c.push({type:"remove",oldIdx:u,newIdx:m})))}c.reverse();let x=new Set;c.forEach((e,t)=>{if("context"!==e.type)for(let e=Math.max(0,t-3);e<=Math.min(c.length-1,t+3);e++)x.add(e)});let h=-1;for(let e=0;e<c.length;e++){if(!x.has(e))continue;h>=0&&e-h>1&&a.push({type:"context",lineNum:null,text:"\xb7\xb7\xb7"});let t=c[e];"context"===t.type?a.push({type:"context",lineNum:t.newIdx+1,text:r[t.newIdx]}):"remove"===t.type?a.push({type:"remove",lineNum:t.oldIdx+1,text:s[t.oldIdx]}):a.push({type:"add",lineNum:t.newIdx+1,text:r[t.newIdx]}),h=e}return a})(e,t),[e,t]);return(0,r.jsx)("div",{className:"flex-1 overflow-y-auto font-mono text-sm leading-relaxed",children:(0,r.jsx)("table",{className:"w-full border-collapse",children:(0,r.jsx)("tbody",{children:a.map((e,t)=>(0,r.jsxs)("tr",{className:L("add"===e.type&&"bg-emerald-500/10","remove"===e.type&&"bg-red-500/10"),children:[(0,r.jsx)("td",{className:"select-none w-[1ch] pl-2 pr-1 text-center align-top",children:"add"===e.type?(0,r.jsx)("span",{className:"text-emerald-400/80",children:"+"}):"remove"===e.type?(0,r.jsx)("span",{className:"text-red-400/80",children:"−"}):null}),(0,r.jsx)("td",{className:L("select-none pr-3 text-right align-top min-w-[3ch]","add"===e.type?"text-emerald-400/40":"remove"===e.type?"text-red-400/40":"text-muted-foreground/50"),children:e.lineNum??""}),(0,r.jsx)("td",{className:L("whitespace-pre pr-4","add"===e.type&&"text-emerald-300","remove"===e.type&&"text-red-300 line-through decoration-red-400/30","context"===e.type&&"\xb7\xb7\xb7"===e.text&&"text-muted-foreground/50 text-center italic","context"===e.type&&"\xb7\xb7\xb7"!==e.text&&"text-muted-foreground"),children:e.text||" "})]},t))})})})}function ro({content:e,filepath:t,fontSize:s,shikiTheme:a}){return(0,r.jsx)("div",{style:s?{fontSize:s}:void 0,children:re(t)?(0,r.jsx)(rn,{content:e,filepath:t,shikiTheme:a}):(0,r.jsx)(rr,{content:e,filepath:t,shikiTheme:a})})}function rl({content:e,filepath:t,className:s,root:a,path:o,onSave:l,diff:d,onDismissDiff:c,agentOpened:u}){let m=void 0!==a&&void 0!==o&&void 0!==l,[x,h]=(0,n.useState)(e),[p,g]=(0,n.useState)(!1),[f,b]=(0,n.useState)(null);(0,n.useEffect)(()=>{h(e)},[e]);let v=x!==e,[j]=s8(),{resolvedTheme:y}=(0,Y.D)(),N="light"===y?"github-light-default":"github-dark-default",w=s9(t),k=(0,n.useCallback)(async()=>{if(l&&v&&!p){g(!0),b(null);try{await l(x)}catch(e){b(e instanceof Error?e.message:"Failed to save")}finally{g(!1)}}},[l,v,p,x]);return((0,n.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key&&(e.preventDefault(),k())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[k]),m)?d?(0,r.jsxs)("div",{className:L("flex flex-1 flex-col overflow-hidden min-h-0",s),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 border-b border-border px-4 h-9",children:[(0,r.jsx)("span",{className:"text-sm font-medium font-mono truncate",children:t}),(0,r.jsx)("span",{className:"ml-2 rounded-full bg-emerald-500/15 px-2 py-0.5 text-[10px] font-medium text-emerald-400 uppercase tracking-wide",children:"Changed"}),(0,r.jsx)("div",{className:"ml-auto flex items-center gap-2",children:(0,r.jsxs)("button",{onClick:c,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-accent transition-colors",children:[(0,r.jsx)(i.A,{className:"h-3 w-3"}),"Dismiss"]})})]}),(0,r.jsx)(ri,{before:d.before,after:d.after,onDismiss:c})]}):re(t)?(0,r.jsxs)(sz,{defaultValue:u?"edit":"view",className:L("flex flex-1 flex-col overflow-hidden min-h-0",s),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 border-b border-border px-4 h-9",children:[(0,r.jsx)("span",{className:"text-sm font-medium font-mono truncate mr-2",children:t}),(0,r.jsxs)(sB,{className:"h-7 bg-transparent p-0 ml-auto",children:[(0,r.jsx)(sG,{value:"view",className:"h-6 rounded-md px-2 text-xs data-[state=active]:bg-muted",children:"View"}),(0,r.jsx)(sG,{value:"edit",className:"h-6 rounded-md px-2 text-xs data-[state=active]:bg-muted",children:"Edit"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[f&&(0,r.jsx)("span",{className:"text-xs text-destructive max-w-[200px] truncate",title:f,children:f}),(0,r.jsxs)("button",{onClick:k,disabled:!v||p,className:L("inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors",v&&!p?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed opacity-50"),children:[p?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(sO.A,{className:"h-3 w-3"}),"Save"]})]})]}),(0,r.jsx)(sW,{value:"view",className:"flex-1 overflow-y-auto p-4 mt-0",style:{fontSize:j},children:(0,r.jsx)(ro,{content:e,filepath:t,fontSize:j,shikiTheme:N})}),(0,r.jsx)(sW,{value:"edit",className:"flex-1 overflow-hidden mt-0 min-h-0",children:(0,r.jsx)(s2,{value:x,onChange:h,language:w,fontSize:j,className:"h-full border-0 rounded-none"})})]},u?"agent-edit":"normal"):(0,r.jsxs)("div",{className:L("flex flex-1 flex-col overflow-hidden min-h-0",s),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 border-b border-border px-4 h-9",children:[(0,r.jsx)("span",{className:"text-sm font-medium font-mono truncate",children:t}),(0,r.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:[f&&(0,r.jsx)("span",{className:"text-xs text-destructive max-w-[200px] truncate",title:f,children:f}),(0,r.jsxs)("button",{onClick:k,disabled:!v||p,className:L("inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors",v&&!p?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed opacity-50"),children:[p?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(sO.A,{className:"h-3 w-3"}),"Save"]})]})]}),(0,r.jsx)(s2,{value:x,onChange:h,language:w,fontSize:j,className:"flex-1 min-h-0 border-0 rounded-none"})]}):(0,r.jsx)("div",{className:L("flex-1 overflow-y-auto p-4",s),style:{fontSize:j},children:(0,r.jsx)(ro,{content:e,filepath:t,fontSize:j,shikiTheme:N})})}var rd=s(92564),rc=s(36201),ru=s(34152),rm=s(37595),rx=s(77314),rh=s(50538),rp=s(34530),rg=s(37618),rf=s(15282),rb=s(55711),rv=s(97810),rj=s(64479),ry=s(21283),rN=s(41730),rw=s(92451),rk=s(94514),rS=s(15411),rC=s(7915),rA=s(6755),rT=s(60285),rR=s(3926),rE=s(10762);function rP({className:e,type:t,...s}){return(0,r.jsx)("input",{type:t,"data-slot":"input",className:L("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...s})}var r_=s(45828);function rI({delayDuration:e=0,...t}){return(0,r.jsx)(r_.Kq,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function r$({...e}){return(0,r.jsx)(rI,{children:(0,r.jsx)(r_.bL,{"data-slot":"tooltip",...e})})}function rD({...e}){return(0,r.jsx)(r_.l9,{"data-slot":"tooltip-trigger",...e})}function rF({className:e,sideOffset:t=0,children:s,...a}){return(0,r.jsx)(r_.ZL,{children:(0,r.jsxs)(r_.UC,{"data-slot":"tooltip-content",sideOffset:t,className:L("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...a,children:[s,(0,r.jsx)(r_.i3,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}var rL=s(67198);function rM({...e}){return(0,r.jsx)(rL.bL,{"data-slot":"popover",...e})}function rq({...e}){return(0,r.jsx)(rL.l9,{"data-slot":"popover-trigger",...e})}function rO({className:e,align:t="center",sideOffset:s=4,...a}){return(0,r.jsx)(rL.ZL,{children:(0,r.jsx)(rL.UC,{"data-slot":"popover-content",align:t,sideOffset:s,className:L("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...a})})}let rU="gsd-terminal-font-size",rz="terminal-font-size-changed";function rB(){let[e,t]=(0,n.useState)(()=>{try{let e=localStorage.getItem(rU);if(e){let t=Number(e);if(Number.isFinite(t)&&t>=8&&t<=24)return t}}catch{}return 13}),s=(0,n.useCallback)(e=>{let s=Math.max(8,Math.min(24,Math.round(e)));t(s);try{localStorage.setItem(rU,String(s))}catch{}window.dispatchEvent(new CustomEvent(rz,{detail:s}))},[]);return(0,n.useEffect)(()=>{let e=e=>{if(e.key!==rU)return;let s=Number(e.newValue);Number.isFinite(s)&&s>=8&&s<=24&&t(s)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,n.useEffect)(()=>{let e=e=>{let s=e.detail;Number.isFinite(s)&&s>=8&&s<=24&&t(s)};return window.addEventListener(rz,e),()=>window.removeEventListener(rz,e)},[]),[e,s]}var rG=s(41463);let rW=[{label:"Discuss",command:"/gsd discuss",icon:rd.A,description:"Start guided milestone/slice discussion",category:"workflow",disabledDuringAuto:!0},{label:"Next",command:"/gsd next",icon:d.A,description:"Execute next task, then pause",category:"workflow"},{label:"Auto",command:"/gsd auto",icon:sa.A,description:"Run all queued units continuously",category:"workflow"},{label:"Stop",command:"/gsd stop",icon:rc.A,description:"Stop auto-mode gracefully",category:"workflow"},{label:"Pause",command:"/gsd pause",icon:ru.A,description:"Pause auto-mode (preserves state)",category:"workflow"},{label:"Status",command:"/gsd status",icon:j.A,description:"Show progress dashboard",category:"visibility"},{label:"Visualize",command:"/gsd visualize",icon:rm.A,description:"Interactive TUI (progress, deps, metrics, timeline)",category:"visibility"},{label:"Queue",command:"/gsd queue",icon:rx.A,description:"Show queued/dispatched units and execution order",category:"visibility"},{label:"History",command:"/gsd history",icon:rh.A,description:"View execution history with cost/phase/model details",category:"visibility"},{label:"Steer",command:"/gsd steer",icon:rp.A,description:"Apply user override to active work",category:"correction"},{label:"Capture",command:"/gsd capture",icon:rg.A,description:"Quick-capture a thought to CAPTURES.md",category:"correction"},{label:"Triage",command:"/gsd triage",icon:rf.A,description:"Classify and route pending captures",category:"correction",disabledDuringAuto:!0},{label:"Skip",command:"/gsd skip",icon:_.A,description:"Prevent a unit from auto-mode dispatch",category:"correction"},{label:"Undo",command:"/gsd undo",icon:rb.A,description:"Revert last completed unit",category:"correction"},{label:"Knowledge",command:"/gsd knowledge",icon:rv.A,description:"Add rule, pattern, or lesson to KNOWLEDGE.md",category:"knowledge"},{label:"Mode",command:"/gsd mode",icon:rj.A,description:"Set workflow mode (solo/team)",category:"config"},{label:"Prefs",command:"/gsd prefs",icon:w.A,description:"Manage preferences (global/project)",category:"config"},{label:"Doctor",command:"/gsd doctor",icon:ry.A,description:"Diagnose and repair .gsd/ state",category:"maintenance"},{label:"Export",command:"/gsd export",icon:rN.A,description:"Export milestone/slice results (JSON or Markdown)",category:"maintenance"},{label:"Cleanup",command:"/gsd cleanup",icon:sL.A,description:"Remove merged branches or snapshots",category:"maintenance"},{label:"Remote",command:"/gsd remote",icon:rw.A,description:"Control remote auto-mode (Slack/Discord)",category:"maintenance"}],rK=rW.slice(0,3),rH=rW.slice(3),rV={workflow:"Workflow",visibility:"Visibility",correction:"Course Correction",knowledge:"Knowledge",config:"Configuration",maintenance:"Maintenance"};function rJ({className:e}){let t=tb(),{sendCommand:s}=tv(),a=t.boot?.bridge??null,i=(0,n.useCallback)(e=>{s(tj(e,a))},[s,a]);return(0,r.jsxs)("div",{className:L("flex h-full flex-col overflow-hidden bg-background",e),children:[(0,r.jsx)(rY,{onPrimaryAction:i,onSecondaryAction:i}),(0,r.jsx)(an,{sessionId:"gsd-main",command:"gsd",className:"flex-1",onOpenAction:e=>i(e.command)})]})}function rY({onPrimaryAction:e,onSecondaryAction:t}){let s=tb(),a=s.boot,n=a?.workspace??null,i=a?.auto??null,o=tk({phase:n?.active.phase??"pre-planning",autoActive:i?.active??!1,autoPaused:i?.paused??!1,onboardingLocked:a?.onboarding.locked??!1,commandInFlight:s.commandInFlight,bootStatus:s.bootStatus,hasMilestones:(n?.milestones.length??0)>0,projectDetectionKind:a?.projectDetection?.kind??null}),l=(()=>{if("ready"!==s.bootStatus)return s.bootStatus;let e=n?.active.phase;return e?i?.active&&!i?.paused?"auto":i?.paused?"paused":e:"idle"})();return(0,r.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-card px-4 py-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(g.A,{className:"h-4 w-4 text-muted-foreground"}),(0,r.jsx)("span",{className:"font-medium",children:"Chat Mode"}),(0,r.jsx)("span",{className:"rounded-full border border-border bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground uppercase tracking-wide",children:l})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2","data-testid":"chat-mode-action-bar",children:[o.primary&&(0,r.jsxs)("button",{"data-testid":"chat-primary-action",onClick:()=>{o.primary&&e(o.primary.command)},disabled:o.disabled,className:L("inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium transition-colors","destructive"===o.primary.variant?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-primary text-primary-foreground hover:bg-primary/90",o.disabled&&"cursor-not-allowed opacity-50"),title:o.disabledReason,children:[s.commandInFlight?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):o.isNewMilestone?(0,r.jsx)(P.A,{className:"h-3 w-3"}):(0,r.jsx)(d.A,{className:"h-3 w-3"}),o.primary.label]}),o.secondaries.map(e=>(0,r.jsx)("button",{"data-testid":`chat-secondary-action-${e.command}`,onClick:()=>t(e.command),disabled:o.disabled,className:L("inline-flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1 text-xs font-medium transition-colors hover:bg-accent",o.disabled&&"cursor-not-allowed opacity-50"),title:o.disabledReason,children:e.label},e.command)),s.commandInFlight&&(0,r.jsx)("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"})})]})]})}let rQ=null;function rX({content:e}){let[t,a]=(0,n.useState)(null),[i,o]=(0,n.useState)(!1),l=r2();return((0,n.useEffect)(()=>{let t=!1;return Promise.all([Promise.all([s.e(4846),s.e(8921),s.e(4417)]).then(s.bind(s,4417)),Promise.all([s.e(4846),s.e(2397)]).then(s.bind(s,32397)),(!rQ&&(rQ=Promise.all([s.e(8921),s.e(4447)]).then(s.bind(s,24447)).then(e=>e.createHighlighter({themes:["github-dark-default","github-light-default"],langs:["typescript","tsx","javascript","jsx","json","jsonc","markdown","mdx","css","scss","less","html","xml","yaml","toml","bash","python","ruby","rust","go","java","kotlin","swift","c","cpp","csharp","php","sql","graphql","dockerfile","makefile","lua","diff","ini","dotenv"]})).catch(e=>{throw rQ=null,e})),rQ)]).then(([s,n,i])=>{if(t)return;console.debug("[ChatBubble] markdown modules loaded");let d=s.default,c=n.default,u=l?"github-dark-default":"github-light-default";a((0,r.jsx)(d,{remarkPlugins:[c],components:{code({className:e,children:t,...s}){let a=/language-(\w+)/.exec(e||""),n=String(t).replace(/\n$/,"");if(a)try{let e=i.codeToHtml(n,{lang:a[1],theme:u});return(0,r.jsx)("div",{className:"chat-code-block my-3 rounded-xl overflow-x-auto text-sm shadow-sm border border-border/50",dangerouslySetInnerHTML:{__html:e}})}catch{}return e||String(t).includes("\n")?(0,r.jsx)("pre",{className:L("my-3 overflow-x-auto rounded-xl p-4 text-sm border border-border/50",l?"bg-[#0d1117]":"bg-[#f6f8fa]"),children:(0,r.jsx)("code",{className:"font-mono",children:t})}):(0,r.jsx)("code",{className:"rounded-md bg-muted px-1.5 py-0.5 text-[0.85em] font-mono text-foreground",...s,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),table:({children:e})=>(0,r.jsx)("div",{className:"my-4 overflow-x-auto rounded-lg border border-border",children:(0,r.jsx)("table",{className:"min-w-full border-collapse text-sm",children:e})}),th:({children:e})=>(0,r.jsx)("th",{className:"border-b border-border bg-muted/50 px-3 py-2 text-left text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:e}),td:({children:e})=>(0,r.jsx)("td",{className:"border-b border-border/50 px-3 py-2 text-sm last:border-0",children:e}),a:({href:e,children:t})=>(0,r.jsx)("a",{href:e,className:"text-info underline underline-offset-2 hover:text-info transition-colors",target:"_blank",rel:"noopener noreferrer",children:t}),h1:({children:e})=>(0,r.jsx)("h1",{className:"mt-4 mb-2 text-base font-semibold text-foreground first:mt-0",children:e}),h2:({children:e})=>(0,r.jsx)("h2",{className:"mt-3 mb-1.5 text-sm font-semibold text-foreground first:mt-0",children:e}),h3:({children:e})=>(0,r.jsx)("h3",{className:"mt-2 mb-1 text-sm font-medium text-foreground first:mt-0",children:e}),ul:({children:e})=>(0,r.jsx)("ul",{className:"my-2 ml-4 list-disc space-y-0.5 text-sm [&>li]:text-foreground",children:e}),ol:({children:e})=>(0,r.jsx)("ol",{className:"my-2 ml-4 list-decimal space-y-0.5 text-sm [&>li]:text-foreground",children:e}),blockquote:({children:e})=>(0,r.jsx)("blockquote",{className:"my-3 border-l-2 border-primary/40 pl-3 text-sm text-muted-foreground italic",children:e}),hr:()=>(0,r.jsx)("hr",{className:"my-4 border-border/50"}),p:({children:e})=>(0,r.jsx)("p",{className:"mb-2 text-sm leading-relaxed last:mb-0 text-foreground",children:e}),img:({alt:e,src:t})=>(0,r.jsxs)("span",{className:"my-2 block rounded-lg border border-border bg-muted/50 px-3 py-2 text-xs text-muted-foreground italic",children:["\uD83D\uDDBC ",e||t||"image"]})},children:e})),o(!0)}).catch(()=>{t||o(!0)}),()=>{t=!0}},[e,l]),i&&t)?(0,r.jsx)("div",{className:"chat-markdown min-w-0",children:t}):(0,r.jsx)("span",{className:"whitespace-pre-wrap text-sm leading-relaxed text-foreground",children:e})}function rZ({prompt:e,onSubmit:t}){let[s,a]=(0,n.useState)(e.selectedIndex??0),[i,o]=(0,n.useState)(!1),l=(0,n.useRef)(null);(0,n.useEffect)(()=>{console.log("[TuiSelectPrompt] mounted kind=select label=%s",e.label),l.current?.focus()},[e.label]);let d=(0,n.useCallback)(e=>{let r=e-s,n="";r>0?n="\x1b[B".repeat(r):r<0&&(n="\x1b[A".repeat(Math.abs(r))),console.log("[TuiSelectPrompt] submit delta=%d keystrokes=%j",r,n+="\r"),a(e),o(!0),t(n)},[s,t]),c=(0,n.useCallback)(t=>{i||("ArrowUp"===t.key?(t.preventDefault(),a(e=>Math.max(0,e-1))):"ArrowDown"===t.key?(t.preventDefault(),a(t=>Math.min(e.options.length-1,t+1))):"Enter"===t.key&&(t.preventDefault(),d(s)))},[i,s,e.options.length,d]);if(i){let t=e.options[s]??"";return(0,r.jsxs)("div",{"data-testid":"tui-prompt-submitted",className:"mt-2 flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium",children:t})]})}return(0,r.jsxs)("div",{ref:l,"data-testid":"tui-select-prompt",tabIndex:0,onKeyDown:c,className:"mt-2 rounded-xl border border-border bg-background p-1.5 shadow-sm outline-none focus-visible:ring-1 focus-visible:ring-border","aria-label":`Select: ${e.label}`,role:"listbox","aria-activedescendant":`tui-select-option-${s}`,children:[e.label&&(0,r.jsx)("p",{className:"mb-1.5 px-2 text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:e.label}),e.options.map((t,a)=>{let n=a===s,i=e.descriptions?.[a];return(0,r.jsxs)("button",{id:`tui-select-option-${a}`,"data-testid":`tui-select-option-${a}`,role:"option","aria-selected":n,onClick:()=>d(a),className:L("flex w-full items-start gap-2 rounded-lg px-3 py-1.5 text-left text-sm transition-colors",n?"bg-primary/15 text-primary font-medium":"text-foreground hover:bg-muted"),children:[(0,r.jsx)("span",{className:"mt-0.5 flex h-4 w-4 flex-shrink-0 items-center justify-center",children:n?(0,r.jsx)(rk.A,{className:"h-3 w-3 text-primary"}):(0,r.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/30"})}),(0,r.jsxs)("span",{className:"min-w-0",children:[(0,r.jsx)("span",{className:"block",children:t}),i&&(0,r.jsx)("span",{className:"mt-0.5 block text-xs font-normal text-muted-foreground",children:i})]})]},a)})]})}function r0({prompt:e,onSubmit:t}){let[s,a]=(0,n.useState)(""),[i,o]=(0,n.useState)(!1),l=(0,n.useRef)(null);(0,n.useEffect)(()=>{console.log("[TuiTextPrompt] mounted kind=text label=%s",e.label),l.current?.focus()},[e.label]);let d=(0,n.useCallback)(()=>{i||(console.log("[TuiTextPrompt] submitted label=%s",e.label),o(!0),t(s+"\r"))},[i,s,e.label,t]),c=(0,n.useCallback)(e=>{"Enter"===e.key&&(e.preventDefault(),d())},[d]);return i?(0,r.jsxs)("div",{"data-testid":"tui-prompt-submitted",className:"mt-2 flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium",children:"✓ Submitted"})]}):(0,r.jsxs)("div",{"data-testid":"tui-text-prompt",className:"mt-2 rounded-xl border border-border bg-background p-3 shadow-sm",children:[e.label&&(0,r.jsx)("p",{className:"mb-2 text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:e.label}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{ref:l,value:s,onChange:e=>a(e.target.value),onKeyDown:c,placeholder:"Type your answer…",className:"flex-1 h-8 text-sm","aria-label":e.label||"Text input"}),(0,r.jsx)("button",{onClick:d,disabled:!s.trim(),className:L("flex h-8 items-center justify-center rounded-lg px-3 text-xs font-medium transition-all",s.trim()?"bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 shadow-sm":"bg-muted text-muted-foreground cursor-not-allowed"),children:"Submit"})]})]})}function r1({prompt:e,onSubmit:t}){let[s,a]=(0,n.useState)(""),[i,o]=(0,n.useState)(!1),[l,d]=(0,n.useState)(!1),c=(0,n.useRef)(null);(0,n.useEffect)(()=>{console.log("[TuiPasswordPrompt] mounted kind=password label=%s",e.label),c.current?.focus()},[e.label]);let u=(0,n.useCallback)(()=>{i||(console.log("[TuiPasswordPrompt] submitted label=%s",e.label),o(!0),t(s+"\r"))},[i,s,e.label,t]),m=(0,n.useCallback)(e=>{"Enter"===e.key&&(e.preventDefault(),u())},[u]);if(i){let t=e.label||"Value";return(0,r.jsxs)("div",{"data-testid":"tui-prompt-submitted",className:"mt-2 flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsxs)("span",{className:"font-medium",children:[t," — entered ✓"]})]})}return(0,r.jsxs)("div",{"data-testid":"tui-password-prompt",className:"mt-2 rounded-xl border border-border bg-background p-3 shadow-sm",children:[e.label&&(0,r.jsx)("p",{className:"mb-2 text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:e.label}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsxs)("div",{className:"relative flex-1",children:[(0,r.jsx)(rP,{ref:c,type:l?"text":"password",value:s,onChange:e=>a(e.target.value),onKeyDown:m,placeholder:"Enter value…",className:"h-8 pr-9 text-sm","aria-label":e.label||"Password input",autoComplete:"off"}),(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),tabIndex:-1,"aria-label":l?"Hide input":"Show input",className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-muted-foreground transition-colors",children:l?(0,r.jsx)(rS.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(rC.A,{className:"h-3.5 w-3.5"})})]}),(0,r.jsx)("button",{onClick:u,disabled:!s,className:L("flex h-8 items-center justify-center rounded-lg px-3 text-xs font-medium transition-all",s?"bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 shadow-sm":"bg-muted text-muted-foreground cursor-not-allowed"),children:"Submit"})]}),(0,r.jsx)("p",{className:"mt-1.5 text-[10px] text-muted-foreground",children:"Value is transmitted securely and not stored in chat history."})]})}function r5(){return(0,r.jsx)("span",{"aria-hidden":"true",className:"ml-0.5 inline-block h-3.5 w-0.5 translate-y-0.5 rounded-full bg-current opacity-70",style:{animation:"chat-cursor 1s ease-in-out infinite"}})}function r2(){let[e,t]=(0,n.useState)(()=>"u">typeof document&&document.documentElement.classList.contains("dark"));return(0,n.useEffect)(()=>{if("u"<typeof document)return;let e=document.documentElement,s=new MutationObserver(()=>{t(e.classList.contains("dark"))});return s.observe(e,{attributes:!0,attributeFilter:["class"]}),()=>s.disconnect()},[]),e}function r3({className:e}){let t=r2();return(0,r.jsx)(a.default,{src:t?"/logo-icon-white.svg":"/logo-icon-black.svg",alt:"",width:24,height:32,unoptimized:!0,className:L("h-4 w-auto",e)})}function r4({content:e,isStreaming:t}){let[s,a]=(0,n.useState)(!1),i=(0,n.useRef)(null),o=e.split("\n").filter(e=>e.trim()),l=o.slice(-5),d=o.length>5;return(0,n.useEffect)(()=>{s&&t&&i.current&&(i.current.scrollTop=i.current.scrollHeight)},[s,t,e]),(0,r.jsx)("div",{className:"mb-3",children:(0,r.jsxs)("button",{onClick:()=>a(e=>!e),className:L("group w-full rounded-xl border px-3.5 py-2.5 text-left transition-all","border-border/50 bg-muted/50 hover:bg-muted/50"),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[t?(0,r.jsxs)("span",{className:"relative flex h-2 w-2 flex-shrink-0",children:[(0,r.jsx)("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-muted-foreground/30"}),(0,r.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-muted-foreground/50"})]}):(0,r.jsx)("span",{className:"flex h-4 w-4 flex-shrink-0 items-center justify-center rounded bg-muted-foreground/10",children:(0,r.jsx)("span",{className:"text-[9px] text-muted-foreground",children:"\uD83D\uDCAD"})}),(0,r.jsx)("span",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:t?"Thinking…":"Thought process"}),d&&!s&&(0,r.jsxs)("span",{className:"ml-1 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:[o.length," lines"]}),(0,r.jsx)("span",{className:"ml-auto flex-shrink-0",children:s?(0,r.jsx)(C.A,{className:"h-3 w-3 text-muted-foreground transition-transform"}):(0,r.jsx)(A.A,{className:"h-3 w-3 text-muted-foreground transition-transform group-hover:text-muted-foreground"})})]}),!s&&(0,r.jsxs)("div",{className:"mt-2 space-y-0.5 border-l-2 border-muted-foreground/10 pl-3",children:[l.map((e,t)=>(0,r.jsx)("p",{className:"text-[12px] leading-relaxed text-muted-foreground line-clamp-1",children:e},t)),t&&(0,r.jsx)(r5,{})]}),s&&(0,r.jsxs)("div",{ref:i,className:"mt-2 max-h-[400px] overflow-y-auto overscroll-contain rounded-lg border border-border/50 bg-background/50 p-3 text-[12px] leading-[1.7] text-muted-foreground whitespace-pre-wrap scrollbar-thin scrollbar-thumb-border scrollbar-track-transparent",children:[e,t&&(0,r.jsx)(r5,{})]})]})})}function r8({message:e,onSubmitPrompt:t,isThinking:s}){if("system"===e.role)return(0,r.jsx)("div",{className:"flex items-center justify-center py-1",children:(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground italic px-3",children:e.content})});if("user"===e.role)return(0,r.jsx)("div",{className:"flex justify-end",children:(0,r.jsxs)("div",{className:"max-w-[72%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-sm text-primary-foreground shadow-sm",children:[e.images&&e.images.length>0&&(0,r.jsx)("div",{className:"flex gap-1.5 mb-2 flex-wrap",children:e.images.map((e,t)=>(0,r.jsx)(a.default,{src:`data:${e.mimeType};base64,${e.data}`,alt:`Attached image ${t+1}`,width:32,height:32,unoptimized:!0,className:"h-8 w-8 rounded object-cover border border-primary-foreground/20"},t))}),(0,r.jsx)("span",{className:"whitespace-pre-wrap leading-relaxed",children:e.content}),!e.complete&&(0,r.jsx)(r5,{})]})});let n=e.prompt?.kind==="select"&&!e.complete&&null!=t,i=e.prompt?.kind==="text"&&!e.complete&&null!=t,o=e.prompt?.kind==="password"&&!e.complete&&null!=t,l=n||i||o;return(0,r.jsxs)("div",{className:"flex justify-start gap-3",children:[(0,r.jsx)("div",{className:"mt-1 flex-shrink-0 flex h-7 w-7 items-center justify-center rounded-full bg-card border border-border",children:(0,r.jsx)(r3,{className:"h-3.5 w-auto"})}),(0,r.jsxs)("div",{className:"max-w-[82%] min-w-0 rounded-2xl rounded-tl-md border border-border bg-card px-4 py-3 shadow-sm",children:[s&&!e.content&&(0,r.jsxs)("div",{className:"flex items-center gap-2 py-1",children:[(0,r.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,r.jsx)("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-muted-foreground/30"}),(0,r.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-muted-foreground/50"})]}),(0,r.jsx)("span",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"Thinking…"})]}),e.content&&(0,r.jsx)(rX,{content:e.content}),!e.complete&&!l&&(0,r.jsx)(r5,{}),n&&(0,r.jsx)(rZ,{prompt:e.prompt,onSubmit:t}),i&&(0,r.jsx)(r0,{prompt:e.prompt,onSubmit:t}),o&&(0,r.jsx)(r1,{prompt:e.prompt,onSubmit:t})]})]})}function r6({onSendInput:e,connected:t,onOpenAction:s}){let o=tb().boot?.auto?.active??!1,[l,d]=(0,n.useState)(""),[c,u]=(0,n.useState)(!1),[m,x]=(0,n.useState)([]),[h,p]=(0,n.useState)(!1),[g,f]=(0,n.useState)(null),b=(0,n.useRef)(null),v=(0,n.useRef)(0);(0,n.useEffect)(()=>()=>{m.forEach(e=>URL.revokeObjectURL(e.previewUrl))},[]);let j=(0,n.useCallback)(async e=>{f(null);let t=e.filter(e=>e.type.startsWith("image/"));if(0===t.length)return;x(e=>(5-e.length<=0&&f("Maximum 5 images per message"),e));let s=m.length,r=t.slice(0,5-s);r.length<t.length&&f("Maximum 5 images per message");let a=[];for(let e of r)try{let t=await tQ(e),s=URL.createObjectURL(e);a.push({id:`img-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,data:t.data,mimeType:t.mimeType,previewUrl:s})}catch(e){console.warn("[chat-input] image processing failed:",e instanceof Error?e.message:e),f(e instanceof Error?e.message:"Failed to process image")}a.length>0&&x(e=>{let t=[...e,...a];return t.length>5?(t.slice(5).forEach(e=>URL.revokeObjectURL(e.previewUrl)),f("Maximum 5 images per message"),t.slice(0,5)):t})},[m.length]),y=(0,n.useCallback)(e=>{x(t=>{let s=t.find(t=>t.id===e);return s&&URL.revokeObjectURL(s.previewUrl),t.filter(t=>t.id!==e)}),f(null)},[]),N=(0,n.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),p(!1),v.current=0,j(Array.from(e.dataTransfer.files))},[j]),w=(0,n.useCallback)(e=>{e.preventDefault(),e.stopPropagation()},[]),k=(0,n.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),v.current+=1,p(!0)},[]),S=(0,n.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),v.current-=1,v.current<=0&&(v.current=0,p(!1))},[]),C=(0,n.useCallback)(e=>{let t=e.clipboardData?.files;if(t&&t.length>0){let s=Array.from(t).filter(e=>e.type.startsWith("image/"));s.length>0&&(e.preventDefault(),j(s))}},[j]),A=(0,n.useCallback)(()=>{!l.trim()&&0===m.length||t&&(e(l+"\r",m.length>0?m:void 0),d(""),x([]),f(null),b.current&&(b.current.style.height="auto"))},[l,t,e,m]),T=(0,n.useCallback)(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),A())},[A]),R=(0,n.useCallback)(e=>{d(e.target.value);let t=e.target;t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,160)}px`},[]),E=l.trim().length>0||m.length>0,P=(0,n.useMemo)(()=>(function(e){let t=new Map;for(let s of e){let e=t.get(s.category);e||(e=[],t.set(s.category,e)),e.push(s)}return Array.from(t.entries()).map(([e,t])=>({category:e,label:rV[e],items:t}))})(rH),[]);return(0,r.jsx)("div",{className:"flex-shrink-0 border-t border-border bg-card px-4 py-3 backdrop-blur-sm",children:(0,r.jsxs)("div",{className:"flex items-end gap-2",onDrop:N,onDragOver:w,onDragEnter:k,onDragLeave:S,children:[(0,r.jsxs)("div",{className:L("flex flex-1 flex-col rounded-xl border bg-background transition-colors",t?"border-border focus-within:ring-1 focus-within:ring-border/30":"border-border/50 opacity-80",h&&t&&"border-primary/60 ring-2 ring-primary/20 bg-primary/5"),children:[m.length>0&&(0,r.jsxs)("div",{className:"flex items-center gap-2 px-3 pt-2.5 pb-1 flex-wrap",children:[m.map(e=>(0,r.jsxs)("div",{className:"relative group flex-shrink-0",children:[(0,r.jsx)(a.default,{src:e.previewUrl,alt:"Pending image",width:48,height:48,unoptimized:!0,className:"h-12 w-12 rounded-lg object-cover border border-border/50"}),(0,r.jsx)("button",{onClick:()=>y(e.id),"aria-label":"Remove image",className:"absolute -top-1.5 -right-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-destructive-foreground text-[10px] opacity-0 group-hover:opacity-100 transition-opacity shadow-sm",children:(0,r.jsx)(i.A,{className:"h-2.5 w-2.5"})})]},e.id)),g&&(0,r.jsx)("span",{className:"text-[10px] text-muted-foreground italic",children:g})]}),(0,r.jsxs)("div",{className:"flex items-end gap-2",children:[(0,r.jsx)("textarea",{ref:b,value:l,onChange:R,onKeyDown:T,onPaste:C,disabled:!t,rows:1,"aria-label":"Send message",placeholder:t?"Message…":"Connecting…",className:"min-h-[40px] flex-1 resize-none bg-transparent px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground",style:{height:"40px",maxHeight:"160px",overflowY:"auto"}}),(0,r.jsxs)("div",{className:"flex flex-shrink-0 items-end pb-1.5 pr-1.5 gap-1",children:[!t&&(0,r.jsx)("span",{className:"px-2 py-1 text-[10px] font-medium text-muted-foreground uppercase tracking-wide",children:"Disconnected"}),(0,r.jsx)("button",{onClick:A,disabled:!t||!E,"aria-label":"Send",className:L("flex h-7 w-7 items-center justify-center rounded-lg transition-all",E&&t?"bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:scale-95":"bg-muted text-muted-foreground cursor-not-allowed"),children:(0,r.jsx)(rA.A,{className:"h-3.5 w-3.5"})})]})]})]}),s&&(0,r.jsxs)(rI,{delayDuration:300,children:[rK.map(e=>{let t=e.icon,a=e.disabledDuringAuto&&o;return(0,r.jsxs)(r$,{children:[(0,r.jsx)(rD,{asChild:!0,children:(0,r.jsxs)("button",{onClick:()=>s(e),disabled:a,"aria-label":e.description,className:L("flex flex-shrink-0 items-center justify-center gap-1.5 rounded-xl border border-border bg-background px-3 py-2.5 text-xs font-medium text-foreground transition-colors hover:bg-accent",a&&"cursor-not-allowed opacity-40"),children:[(0,r.jsx)(t,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.label]})}),(0,r.jsxs)(rF,{side:"top",sideOffset:6,children:[(0,r.jsx)("p",{className:"font-medium",children:e.label}),(0,r.jsx)("p",{className:"text-[10px] opacity-80",children:a?"Disabled while auto-mode is running":e.description})]})]},e.command)}),(0,r.jsxs)(rM,{open:c,onOpenChange:u,children:[(0,r.jsxs)(r$,{children:[(0,r.jsx)(rD,{asChild:!0,children:(0,r.jsx)(rq,{asChild:!0,children:(0,r.jsx)("button",{"aria-label":"More GSD commands",className:L("flex flex-shrink-0 items-center justify-center rounded-xl border border-border bg-background p-2.5 text-foreground transition-colors hover:bg-accent",c&&"bg-accent"),children:(0,r.jsx)(rT.A,{className:"h-4 w-4 text-muted-foreground"})})})}),!c&&(0,r.jsx)(rF,{side:"top",sideOffset:6,children:"More commands"})]}),(0,r.jsx)(rO,{side:"top",align:"end",sideOffset:8,className:"w-64 max-h-[420px] overflow-y-auto rounded-xl border border-border bg-popover p-2 shadow-lg",children:P.map((e,t)=>(0,r.jsxs)("div",{children:[t>0&&(0,r.jsx)("div",{className:"my-1.5 border-t border-border/50"}),(0,r.jsx)("p",{className:"px-2 py-1 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:e.label}),e.items.map(e=>{let t=e.icon,a=e.disabledDuringAuto&&o;return(0,r.jsxs)(r$,{children:[(0,r.jsx)(rD,{asChild:!0,children:(0,r.jsxs)("button",{onClick:()=>{a||(u(!1),s(e))},disabled:a,className:L("flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left text-sm text-foreground transition-colors hover:bg-accent",a&&"cursor-not-allowed opacity-40"),children:[(0,r.jsx)(t,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}),(0,r.jsx)("span",{className:"flex-1 truncate",children:e.label})]})}),(0,r.jsxs)(rF,{side:"left",sideOffset:8,children:[(0,r.jsx)("p",{className:"font-medium",children:e.label}),(0,r.jsx)("p",{className:"text-[10px] opacity-80",children:a?"Disabled while auto-mode is running":e.description})]})]},e.command)})]},e.category))})]})]})]})})}function r7({connected:e,runningLabel:t,notice:s,primaryAction:a,onPrimaryAction:n}){let i=e&&!!t;return(0,r.jsxs)("div",{className:"flex flex-1 flex-col items-center justify-center text-center py-16",children:[(0,r.jsx)("div",{className:"flex h-12 w-12 items-center justify-center rounded-full border border-border bg-card",children:i?(0,r.jsx)(E.A,{className:"h-5 w-5 animate-spin text-muted-foreground"}):(0,r.jsx)(g.A,{className:"h-6 w-6 text-muted-foreground"})}),(0,r.jsxs)("div",{className:"mt-3 space-y-1",children:[(0,r.jsx)("p",{className:"text-sm font-medium text-foreground",children:"Chat Mode"}),i?(0,r.jsxs)("p",{className:"max-w-xs text-xs text-muted-foreground",children:["Running ",t,"…"]}):s?(0,r.jsx)("p",{className:"max-w-xs text-xs text-muted-foreground",children:s}):e?a&&n?(0,r.jsx)("div",{className:"mt-4",children:(0,r.jsxs)("button",{onClick:n,className:"inline-flex items-center gap-2 rounded-xl border border-border bg-background px-5 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-accent active:scale-[0.98]",children:[(0,r.jsx)(a.icon,{className:"h-4 w-4 text-muted-foreground"}),a.label]})}):(0,r.jsx)("p",{className:"max-w-xs text-xs text-muted-foreground",children:"Connected — waiting for GSD output…"}):(0,r.jsx)("p",{className:"max-w-xs text-xs text-muted-foreground",children:"Connecting to GSD session…"})]})]})}function r9({request:e}){let{respondToUiRequest:t,dismissUiRequest:s}=tv(),a="extension_ui_response"===tb().commandInFlight,i=(0,n.useCallback)(s=>{t(e.id,s)},[t,e.id]),o=(0,n.useCallback)(()=>{s(e.id)},[s,e.id]);return(0,r.jsxs)("div",{className:"flex justify-start gap-3","data-testid":"inline-ui-request","data-request-id":e.id,children:[(0,r.jsx)("div",{className:"mt-1 flex-shrink-0 flex h-7 w-7 items-center justify-center rounded-full bg-card border border-border",children:(0,r.jsx)(r3,{className:"h-3.5 w-auto"})}),(0,r.jsxs)("div",{className:"max-w-[82%] min-w-0 rounded-2xl rounded-tl-md border border-border bg-card px-4 py-3 shadow-sm",children:[e.title&&(0,r.jsx)("p",{className:"mb-2.5 text-sm font-medium text-foreground",children:e.title}),"select"===e.method&&(0,r.jsx)(ae,{request:e,onSubmit:i,disabled:a}),"confirm"===e.method&&(0,r.jsx)(at,{request:e,onSubmit:i,onDismiss:o,disabled:a}),"input"===e.method&&(0,r.jsx)(as,{request:e,onSubmit:i,disabled:a}),"editor"===e.method&&(0,r.jsx)(ar,{request:e,onSubmit:i,disabled:a})]})]})}function ae({request:e,onSubmit:t,disabled:s}){let a=!!e.allowMultiple,[i,o]=(0,n.useState)(""),[l,d]=(0,n.useState)(new Set),[c,u]=(0,n.useState)(!1),m=(0,n.useCallback)(()=>{u(!0),t({value:a?Array.from(l):i})},[a,i,l,t]);if(c)return(0,r.jsxs)("div",{className:"flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium",children:a?`${l.size} selected`:i})]});let x=a?l.size>0:""!==i;return(0,r.jsxs)("div",{className:"space-y-1.5",children:[e.options.map((e,t)=>{if(a){let a=l.has(e);return(0,r.jsxs)("button",{onClick:()=>{let t=new Set(l);a?t.delete(e):t.add(e),d(t)},disabled:s,className:L("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm transition-colors",a?"bg-primary/15 text-primary font-medium":"text-foreground hover:bg-muted"),children:[(0,r.jsx)("span",{className:"flex h-4 w-4 flex-shrink-0 items-center justify-center rounded border border-border",children:a&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-primary"})}),(0,r.jsx)("span",{children:e})]},t)}let n=i===e;return(0,r.jsxs)("button",{onClick:()=>o(e),disabled:s,className:L("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm transition-colors",n?"bg-primary/15 text-primary font-medium":"text-foreground hover:bg-muted"),children:[(0,r.jsx)("span",{className:"flex h-4 w-4 flex-shrink-0 items-center justify-center",children:n?(0,r.jsx)(rk.A,{className:"h-3 w-3 text-primary"}):(0,r.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/30"})}),(0,r.jsx)("span",{children:e})]},t)}),(0,r.jsx)("button",{onClick:m,disabled:s||!x,className:L("mt-2 flex w-full items-center justify-center rounded-lg px-3 py-2 text-xs font-medium transition-all",x&&!s?"bg-primary text-primary-foreground hover:bg-primary/90 active:scale-[0.98] shadow-sm":"bg-muted text-muted-foreground cursor-not-allowed"),children:a?`Submit (${l.size})`:"Submit"})]})}function at({request:e,onSubmit:t,onDismiss:s,disabled:a}){let[i,o]=(0,n.useState)(null);return null!==i?(0,r.jsxs)("div",{className:"flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium",children:i?"Confirmed":"Cancelled"})]}):(0,r.jsxs)("div",{className:"space-y-2.5",children:[(0,r.jsx)("p",{className:"text-sm text-foreground leading-relaxed",children:e.message}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)("button",{onClick:()=>{o(!0),t({value:!0})},disabled:a,className:"flex-1 rounded-lg bg-primary px-3 py-2 text-xs font-medium text-primary-foreground hover:bg-primary/90 active:scale-[0.98] shadow-sm transition-all",children:"Confirm"}),(0,r.jsx)("button",{onClick:()=>{o(!1),s()},disabled:a,className:"flex-1 rounded-lg border border-border bg-background px-3 py-2 text-xs font-medium text-foreground hover:bg-accent transition-colors",children:"Cancel"})]})]})}function as({request:e,onSubmit:t,disabled:s}){let[a,i]=(0,n.useState)(""),[o,l]=(0,n.useState)(!1),d=(0,n.useRef)(null);if((0,n.useEffect)(()=>{d.current?.focus()},[]),o)return(0,r.jsxs)("div",{className:"flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium",children:"Submitted"})]});let c=()=>{a.trim()&&!s&&(l(!0),t({value:a}))};return(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{ref:d,value:a,onChange:e=>i(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),c())},placeholder:e.placeholder||"Type your answer…",disabled:s,className:"flex-1 h-8 text-sm"}),(0,r.jsx)("button",{onClick:c,disabled:s||!a.trim(),className:L("flex h-8 items-center justify-center rounded-lg px-3 text-xs font-medium transition-all",a.trim()&&!s?"bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 shadow-sm":"bg-muted text-muted-foreground cursor-not-allowed"),children:"Submit"})]})}function ar({request:e,onSubmit:t,disabled:s}){let[a,i]=(0,n.useState)(e.prefill||""),[o,l]=(0,n.useState)(!1);return o?(0,r.jsxs)("div",{className:"flex items-center gap-1.5 rounded-lg bg-primary/10 px-3 py-2 text-sm text-primary",children:[(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,r.jsx)("span",{className:"font-medium",children:"Submitted"})]}):(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("textarea",{value:a,onChange:e=>i(e.target.value),disabled:s,className:"w-full min-h-[120px] rounded-lg border border-border bg-background px-3 py-2 text-sm font-mono focus:outline-none focus:ring-1 focus:ring-border/30 resize-y",autoFocus:!0}),(0,r.jsx)("button",{onClick:()=>{l(!0),t({value:a})},disabled:s,className:"flex w-full items-center justify-center rounded-lg bg-primary px-3 py-2 text-xs font-medium text-primary-foreground hover:bg-primary/90 active:scale-[0.98] shadow-sm transition-all",children:"Submit"})]})}function aa({tool:e}){let[t,s]=(0,n.useState)(!1),a="string"==typeof e.args?.path?e.args.path:"string"==typeof e.args?.file_path?e.args.file_path:null,i=a?a.startsWith(rG.env.HOME??"/Users")?"~"+a.slice((rG.env.HOME??"").length):a:null,o=e.result?.isError??!1,l=e.result?.details?.diff,d="edit"===e.name?(0,r.jsx)(rR.A,{className:"h-3.5 w-3.5"}):"write"===e.name?(0,r.jsx)(s_.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(rE.A,{className:"h-3.5 w-3.5"}),c="edit"===e.name?"Edit":"write"===e.name?"Write":"bash"===e.name?"$":e.name,u="bash"===e.name&&"string"==typeof e.args?.command?e.args.command:null,m=e.result?.content?.filter(e=>"text"===e.type&&e.text).map(e=>e.text).join("\n")??"";return(0,r.jsxs)("div",{className:"flex justify-start gap-3",children:[(0,r.jsx)("div",{className:"w-7 flex-shrink-0"}),(0,r.jsx)("div",{className:"max-w-[82%] min-w-0 w-full",children:(0,r.jsxs)("button",{onClick:()=>s(e=>!e),className:L("w-full rounded-lg border px-3 py-2 text-left text-xs transition-colors",o?"border-destructive/30 bg-destructive/5 hover:bg-destructive/10":"border-border/50 bg-muted/50 hover:bg-muted/50"),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:L("flex-shrink-0",o?"text-destructive":"text-muted-foreground"),children:d}),(0,r.jsx)("span",{className:L("font-mono font-medium",o?"text-destructive":"text-muted-foreground"),children:c}),i&&(0,r.jsx)("span",{className:"truncate font-mono text-info/80",children:i}),u&&!i&&(0,r.jsx)("span",{className:"truncate font-mono text-muted-foreground",children:u.length>60?u.slice(0,60)+"…":u}),(0,r.jsx)("span",{className:"ml-auto flex-shrink-0 text-muted-foreground",children:t?(0,r.jsx)(C.A,{className:"h-3 w-3"}):(0,r.jsx)(A.A,{className:"h-3 w-3"})})]}),t&&l&&(0,r.jsx)("div",{className:"mt-2 overflow-x-auto rounded-md border border-border/50 bg-background p-2 font-mono text-[11px] leading-relaxed",children:l.split("\n").map((e,t)=>{let s=e.startsWith("+"),a=e.startsWith("-"),n=e.startsWith(" ");return(0,r.jsx)("div",{className:L("whitespace-pre",s&&"bg-success/10 text-success",a&&"bg-destructive/10 text-destructive",n&&"text-muted-foreground",!s&&!a&&!n&&"text-muted-foreground"),children:e},t)})}),t&&!l&&m&&(0,r.jsx)("div",{className:"mt-2 max-h-[200px] overflow-y-auto rounded-md border border-border/50 bg-background p-2 font-mono text-[11px] leading-relaxed text-muted-foreground whitespace-pre-wrap",children:m.length>2e3?m.slice(0,2e3)+"\n…":m}),t&&o&&m&&(0,r.jsx)("div",{className:"mt-2 rounded-md border border-destructive/20 bg-destructive/5 p-2 text-[11px] text-destructive whitespace-pre-wrap",children:m})]})})]})}function an({className:e,onOpenAction:t}){let s=tb(),{submitInput:a,sendCommand:i,pushChatUserMessage:o}=tv(),[l]=rB(),c="connected"===s.connectionState,u=s.boot?.bridge.sessionState?.isStreaming??!1,m=s.boot?.bridge??null,x=tk({phase:s.boot?.workspace?.active.phase??"pre-planning",autoActive:s.boot?.auto?.active??!1,autoPaused:s.boot?.auto?.paused??!1,onboardingLocked:s.boot?.onboarding.locked??!1,commandInFlight:s.commandInFlight,bootStatus:s.bootStatus,hasMilestones:(s.boot?.workspace?.milestones.length??0)>0,projectDetectionKind:s.boot?.projectDetection?.kind??null}),h=(0,n.useMemo)(()=>{if(!x.primary||x.disabled)return null;let e=s.boot?.workspace?.active.phase??"pre-planning",t=s.boot?.auto?.active??!1,r=s.boot?.auto?.paused??!1;return t&&!r?{label:"Stop Auto",icon:rc.A}:r?{label:"Resume Auto",icon:d.A}:"complete"===e?{label:"New Milestone",icon:P.A}:"planning"===e?{label:"Plan",icon:d.A}:"executing"===e||"summarizing"===e?{label:"Start Auto",icon:sa.A}:"pre-planning"===e?{label:"Initialize Project",icon:d.A}:{label:"Continue",icon:d.A}},[x,s.boot?.workspace?.active.phase,s.boot?.auto?.active,s.boot?.auto?.paused]),p=(0,n.useCallback)(()=>{x.primary&&i(tj(x.primary.command,m))},[x,i,m]),g=(0,n.useCallback)((e,t)=>{let s=e.replace(/\r$/,"").trim();(s||t&&0!==t.length)&&(o({id:"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`msg-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",content:s,complete:!0,timestamp:Date.now(),images:t?.map(e=>({data:e.data,mimeType:e.mimeType}))}),a(s,t))},[a,o]),f=(0,n.useMemo)(()=>{let e=[],t=s.liveTranscript,r=s.completedTurnSegments,a=s.chatUserMessages;for(let s=0;s<Math.max(a.length,t.length);s++)if(s<a.length&&e.push({kind:"message",message:a[s]}),s<r.length&&r[s].length>0)for(let t of r[s])"thinking"===t.kind?e.push({kind:"thinking",content:t.content,id:`turn-${s}-thinking-${e.length}`}):"text"===t.kind?e.push({kind:"message",message:{id:`turn-${s}-text-${e.length}`,role:"assistant",content:t.content,complete:!0,timestamp:s+1}}):"tool"===t.kind&&e.push({kind:"tool",tool:t.tool});else s<t.length&&t[s].trim()&&e.push({kind:"message",message:{id:`transcript-${s}`,role:"assistant",content:t[s],complete:!0,timestamp:s+1}});for(let t of s.currentTurnSegments)"thinking"===t.kind?e.push({kind:"thinking",content:t.content,id:`current-thinking-${e.length}`}):"text"===t.kind?e.push({kind:"message",message:{id:`current-text-${e.length}`,role:"assistant",content:t.content,complete:!0,timestamp:Date.now()}}):"tool"===t.kind&&e.push({kind:"tool",tool:t.tool});for(let t of(s.activeToolExecution&&e.push({kind:"active-tool",tool:s.activeToolExecution}),s.streamingThinkingText.length>0&&e.push({kind:"streaming-thinking",content:s.streamingThinkingText}),s.streamingAssistantText.length>0&&e.push({kind:"streaming-message",content:s.streamingAssistantText,isThinking:!1}),0===s.streamingThinkingText.length&&0===s.streamingAssistantText.length&&!s.activeToolExecution&&u&&0===s.currentTurnSegments.length&&e.push({kind:"streaming-message",content:"",isThinking:!0}),s.pendingUiRequests))e.push({kind:"ui-request",request:t});return e},[s.liveTranscript,s.completedTurnSegments,s.currentTurnSegments,s.streamingAssistantText,s.streamingThinkingText,s.activeToolExecution,s.pendingUiRequests,s.chatUserMessages,u]),b=(0,n.useCallback)(e=>{a(e.replace(/\r$/,""))},[a]),v=0===f.length&&!u,j=(0,n.useRef)(null),y=(0,n.useRef)(!0),N=(0,n.useCallback)(()=>{let e=j.current;e&&(y.current=e.scrollHeight-e.scrollTop-e.clientHeight<100)},[]);return(0,n.useEffect)(()=>{let e=j.current;e&&y.current&&(e.scrollTop=e.scrollHeight)},[f]),(0,r.jsxs)("div",{"data-testid":"chat-pane-store-driven",className:L("flex flex-col overflow-hidden",e),children:[(0,r.jsx)("div",{className:"flex flex-1 flex-col overflow-hidden",children:v?(0,r.jsx)(r7,{connected:c,runningLabel:u?"responding":void 0,primaryAction:h,onPrimaryAction:p}):(0,r.jsxs)("div",{ref:j,onScroll:N,className:"flex-1 overflow-y-auto px-4 py-4 space-y-4",style:13!==l?{fontSize:`${l}px`}:void 0,children:[f.map((e,t)=>{switch(e.kind){case"message":return(0,r.jsx)(r8,{message:e.message,onSubmitPrompt:b},e.message.id);case"thinking":return(0,r.jsxs)("div",{className:"flex justify-start gap-3",children:[(0,r.jsx)("div",{className:"w-7 flex-shrink-0"}),(0,r.jsx)("div",{className:"max-w-[82%] min-w-0",children:(0,r.jsx)(r4,{content:e.content,isStreaming:!1})})]},e.id);case"streaming-thinking":return(0,r.jsxs)("div",{className:"flex justify-start gap-3",children:[(0,r.jsx)("div",{className:"w-7 flex-shrink-0"}),(0,r.jsx)("div",{className:"max-w-[82%] min-w-0",children:(0,r.jsx)(r4,{content:e.content,isStreaming:!0})})]},"streaming-thinking");case"streaming-message":return(0,r.jsx)(r8,{message:{id:"streaming-current",role:"assistant",content:e.content,complete:!1,timestamp:Date.now()},isThinking:e.isThinking},"streaming-message");case"tool":return(0,r.jsx)(aa,{tool:e.tool},e.tool.id);case"active-tool":return(0,r.jsxs)("div",{className:"flex justify-start gap-3",children:[(0,r.jsx)("div",{className:"w-7 flex-shrink-0"}),(0,r.jsx)("div",{className:"max-w-[82%] min-w-0",children:(0,r.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-border/50 bg-muted/50 px-3.5 py-2",children:[(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin text-muted-foreground"}),(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.tool.name}),!!e.tool.args?.path&&(0,r.jsx)("span",{className:"font-mono text-xs text-info/80 truncate",children:String(e.tool.args?.path)})]})})]},`active-${e.tool.id}`);case"ui-request":return(0,r.jsx)(r9,{request:e.request},e.request.id)}}),(0,r.jsx)("div",{className:"h-2"})]})}),(0,r.jsx)(r6,{onSendInput:g,connected:c,onOpenAction:t})]})}let ai=null;function ao(e,t){return`gsd-files-expanded:${t}:${e}`}function al(e,t){if(!e)return new Set;try{let s=sessionStorage.getItem(ao(e,t));if(s)return new Set(JSON.parse(s))}catch{}return new Set}function ad(e,t,s){if(e)try{sessionStorage.setItem(ao(e,t),JSON.stringify([...s]))}catch{}}function ac({name:e,isFolder:t,isOpen:s}){return t?s?(0,r.jsx)(sg.A,{className:"h-4 w-4 text-muted-foreground"}):(0,r.jsx)(b.A,{className:"h-4 w-4 text-muted-foreground"}):e.endsWith(".md")?(0,r.jsx)(T.A,{className:"h-4 w-4 text-muted-foreground"}):e.endsWith(".json")||e.endsWith(".ts")||e.endsWith(".tsx")||e.endsWith(".js")||e.endsWith(".jsx")?(0,r.jsx)(sj.A,{className:"h-4 w-4 text-muted-foreground"}):(0,r.jsx)(sP.A,{className:"h-4 w-4 text-muted-foreground"})}function au({menu:e,onClose:t,onNewFile:s,onNewFolder:a,onRename:i,onDelete:o,onCopyPath:l,onDuplicate:d}){let c=(0,n.useRef)(null);(0,n.useEffect)(()=>{let e=e=>{c.current&&!c.current.contains(e.target)&&t()},s=e=>{"Escape"===e.key&&t()};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[t]);let[u,m]=(0,n.useState)({x:e.x,y:e.y});(0,n.useEffect)(()=>{if(!c.current)return;let t=c.current.getBoundingClientRect(),{x:s,y:r}=e;s+t.width>window.innerWidth&&(s=window.innerWidth-t.width-8),r+t.height>window.innerHeight&&(r=window.innerHeight-t.height-8),s<0&&(s=8),r<0&&(r=8),m({x:s,y:r})},[e]);let x="directory"===e.type?e.path:e.parentPath,h=[{label:"New File",icon:(0,r.jsx)(s_.A,{className:"h-3.5 w-3.5"}),action:()=>{s(x),t()}},{label:"New Folder",icon:(0,r.jsx)(sI.A,{className:"h-3.5 w-3.5"}),action:()=>{a(x),t()}},{label:"Rename",icon:(0,r.jsx)(s$.A,{className:"h-3.5 w-3.5"}),action:()=>{i(e.path),t()},separator:!0},{label:"Duplicate",icon:(0,r.jsx)(sD.A,{className:"h-3.5 w-3.5"}),action:()=>{d(e.path),t()}},{label:"Copy Path",icon:(0,r.jsx)(sF.A,{className:"h-3.5 w-3.5"}),action:()=>{l(e.path),t()},separator:!0},{label:"Delete",icon:(0,r.jsx)(sL.A,{className:"h-3.5 w-3.5"}),action:()=>{o(e.path,e.type),t()},destructive:!0}];return(0,r.jsx)("div",{ref:c,className:"fixed z-50 min-w-[160px] rounded-md border border-border bg-popover py-1 shadow-lg animate-in fade-in-0 zoom-in-95",style:{left:u.x,top:u.y},children:h.map((e,t)=>(0,r.jsxs)("div",{children:[e.separator&&t>0&&(0,r.jsx)("div",{className:"my-1 h-px bg-border"}),(0,r.jsxs)("button",{onClick:e.action,className:L("flex w-full items-center gap-2 px-3 py-1.5 text-xs transition-colors",e.destructive?"text-destructive hover:bg-destructive/10":"text-popover-foreground hover:bg-accent"),children:[e.icon,e.label]})]},t))})}function am({defaultValue:e,onCommit:t,onCancel:s,depth:a,icon:i}){let o=(0,n.useRef)(null);return(0,n.useEffect)(()=>{let t=o.current;if(!t)return;t.focus();let s=e.lastIndexOf(".");s>0?t.setSelectionRange(0,s):t.select()},[e]),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 px-2 py-0.5",style:{paddingLeft:`${12*a+8}px`},children:[i,(0,r.jsx)("input",{ref:o,defaultValue:e,onKeyDown:e=>{if("Enter"===e.key){e.preventDefault();let r=o.current?.value.trim();r&&r.length>0?t(r):s()}"Escape"===e.key&&(e.preventDefault(),s())},onBlur:()=>{let e=o.current?.value.trim();e&&e.length>0?t(e):s()},className:"flex-1 bg-transparent text-sm outline-none border border-ring rounded px-1 py-0.5 text-foreground",spellCheck:!1})]})}function ax({node:e,depth:t,parentPath:s,selectedPath:a,expandedPaths:i,renamingPath:o,creatingIn:l,onToggleDir:d,onSelectFile:c,onMoveFile:u,onContextMenu:m,onRenameCommit:x,onRenameCancel:h,onCreateCommit:p,onCreateCancel:g}){let f=s?`${s}/${e.name}`:e.name,v="directory"===e.type&&i.has(f),[j,y]=(0,n.useState)(!1),N=o===f,w=l&&l.parentDir===f&&"directory"===e.type&&v;return N?(0,r.jsx)("div",{"data-tree-item":!0,children:(0,r.jsx)(am,{defaultValue:e.name,onCommit:e=>x(f,e),onCancel:h,depth:t,icon:(0,r.jsx)(ac,{name:e.name,isFolder:"directory"===e.type,isOpen:v})})}):(0,r.jsxs)("div",{"data-tree-item":!0,children:[(0,r.jsxs)("button",{onClick:()=>{"directory"===e.type?d(f):c(f)},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),m(t,f,e.type,s)},draggable:!0,onDragStart:e=>{e.dataTransfer.setData("text/x-tree-path",f),e.dataTransfer.effectAllowed="move"},onDragOver:t=>{"directory"!==e.type||(t.dataTransfer.types.includes("text/x-tree-path")?"pending":null)&&(t.preventDefault(),t.dataTransfer.dropEffect="move",y(!0))},onDragLeave:()=>{y(!1)},onDrop:t=>{if(y(!1),"directory"!==e.type)return;t.preventDefault();let s=t.dataTransfer.getData("text/x-tree-path");!s||s===f||f.startsWith(s+"/")||(s.includes("/")?s.substring(0,s.lastIndexOf("/")):"")!==f&&u(s,f)},className:L("flex w-full items-center gap-1.5 px-2 py-1 text-sm hover:bg-accent/50 transition-colors",a===f&&"file"===e.type&&"bg-accent",j&&"bg-accent/70 outline outline-1 outline-ring"),style:{paddingLeft:`${12*t+8}px`},children:["directory"===e.type&&(v?(0,r.jsx)(C.A,{className:"h-3 w-3 text-muted-foreground"}):(0,r.jsx)(A.A,{className:"h-3 w-3 text-muted-foreground"})),(0,r.jsx)(ac,{name:e.name,isFolder:"directory"===e.type,isOpen:v}),(0,r.jsx)("span",{className:"truncate",children:e.name})]}),v&&e.children&&(0,r.jsxs)("div",{children:[w&&(0,r.jsx)(am,{defaultValue:"directory"===l.type?"new-folder":"new-file",onCommit:e=>p(f,e,l.type),onCancel:g,depth:t+1,icon:"directory"===l.type?(0,r.jsx)(b.A,{className:"h-4 w-4 text-muted-foreground"}):(0,r.jsx)(sP.A,{className:"h-4 w-4 text-muted-foreground"})}),e.children.map((e,s)=>(0,r.jsx)(ax,{node:e,depth:t+1,parentPath:f,selectedPath:a,expandedPaths:i,renamingPath:o,creatingIn:l,onToggleDir:d,onSelectFile:c,onMoveFile:u,onContextMenu:m,onRenameCommit:x,onRenameCancel:h,onCreateCommit:p,onCreateCancel:g},s))]})]})}function ah(e,t){return`${e}:${t}`}function ap(e){return"gsd"===e.root?`.gsd/${e.path}`:e.path}function ag(){let e=tb(),t=e.boot?.project.cwd,[s,a]=(0,n.useState)("gsd"),[o,l]=(0,n.useState)("tree"),[d,c]=(0,n.useState)(null),[u,m]=(0,n.useState)(null),[x,h]=(0,n.useState)(!0),[p,g]=(0,n.useState)(null),[f,v]=(0,n.useState)(256),j=(0,n.useRef)(!1),y=(0,n.useRef)(0),N=(0,n.useRef)(0);(0,n.useEffect)(()=>{let e=e=>{if(!j.current)return;let t=e.clientX-y.current;v(Math.max(180,Math.min(480,N.current+t)))},t=()=>{j.current&&(j.current=!1,document.body.style.cursor="",document.body.style.userSelect="")};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[]);let w=(0,n.useCallback)(e=>{j.current=!0,y.current=e.clientX,N.current=f,document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[f]),[k,S]=(0,n.useState)(()=>al(t,"gsd")),[C,A]=(0,n.useState)(()=>al(t,"project")),T=(0,n.useRef)(!1);(0,n.useEffect)(()=>{t&&!T.current&&(T.current=!0,S(al(t,"gsd")),A(al(t,"project")))},[t]);let R="gsd"===s?k:C,P="gsd"===s?S:A,[_,I]=(0,n.useState)([]),[$,D]=(0,n.useState)(null),[F,M]=(0,n.useState)(!1),[q,O]=(0,n.useState)(null),[U,z]=(0,n.useState)(null),[B,G]=(0,n.useState)(null),[W,K]=(0,n.useState)(null),H=_.find(e=>e.key===$)??null,V=H?.path??null,J="gsd"===s?d:u,Y="gsd"===s?null!==d:null!==u,Q=(0,n.useCallback)(async e=>{try{h(!0),g(null);let s=await e$(tx(`/api/files?root=${e}`,t));if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error||`Failed to fetch files (${s.status})`)}let r=(await s.json()).tree??[];"gsd"===e?c(r):m(r)}catch(e){g(e instanceof Error?e.message:"Failed to fetch files")}finally{h(!1)}},[t]);(0,n.useEffect)(()=>{Y||Q(s)},[s,Y,Q]),(0,n.useEffect)(()=>{Q("gsd")},[Q]);let X=(0,n.useCallback)(async(e,s)=>{let r=ah(e,s);I(t=>t.find(e=>e.key===r)?t:[...t,{key:r,root:e,path:s,content:null,loading:!0,error:null}]),D(r),a(e);let n=s.split("/");("gsd"===e?S:A)(s=>{let r=new Set(s);for(let e=1;e<n.length;e++)r.add(n.slice(0,e).join("/"));return ad(t,e,r),r}),I(e=>{let t=e.find(e=>e.key===r);return t&&t.content,e});try{let a=await e$(tx(`/api/files?root=${e}&path=${encodeURIComponent(s)}`,t));if(!a.ok){let e=(await a.json().catch(()=>({}))).error||`Failed to fetch file (${a.status})`;I(t=>t.map(t=>t.key===r?{...t,loading:!1,error:e}:t));return}let n=await a.json();I(e=>e.map(e=>e.key===r?{...e,content:n.content??null,loading:!1,error:null}:e))}catch(t){let e=t instanceof Error?t.message:"Failed to fetch file content";I(t=>t.map(t=>t.key===r?{...t,loading:!1,error:e}:t))}},[t]),Z=(0,n.useCallback)((e,t)=>{t?.stopPropagation(),I(t=>{let s=t.findIndex(t=>t.key===e),r=t.filter(t=>t.key!==e);if(e===$)if(0===r.length)D(null);else{let e=Math.min(s,r.length-1);D(r[e].key)}return r})},[$]),ee=(0,n.useCallback)(async(e,t)=>{"gsd"!==e||d?"project"!==e||u||Q("project"):Q("gsd"),await X(e,t)},[d,u,Q,X]),et=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!et.current&&ai){et.current=!0;let{root:e,path:t}=ai;ai=null,ee(e,t)}},[ee]),(0,n.useEffect)(()=>{let e=e=>{let t=e.detail;t?.root&&t?.path&&(ai=null,ee(t.root,t.path))};return window.addEventListener("gsd:open-file",e),()=>window.removeEventListener("gsd:open-file",e)},[ee]);let es=(0,n.useCallback)(e=>{P(r=>{let a=new Set(r);return a.has(e)?a.delete(e):a.add(e),ad(t,s,a),a})},[P,t,s]),er=e=>{a(e)},ea=(0,n.useCallback)(async e=>{await X(s,e)},[s,X]),en=(0,n.useCallback)(async(e,r)=>{let a=e.split("/").pop()??e,n=r?`${r}/${a}`:a;try{let r=await e$(tx("/api/files",t),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:n,root:s})});if(!r.ok){let e=await r.json().catch(()=>({}));console.error("Move failed:",e.error||r.statusText);return}let a=ah(s,e);if(I(t=>t.map(t=>{if(t.key===a){let e=ah(s,n);return{...t,key:e,path:n}}if(t.root===s&&t.path.startsWith(e+"/")){let r=n+t.path.slice(e.length);return{...t,key:ah(s,r),path:r}}return t})),$?.startsWith(`${s}:${e}`))if($===`${s}:${e}`)D(ah(s,n));else{let t=$.slice(`${s}:${e}`.length);D(ah(s,n+t))}await Q(s)}catch(e){console.error("Move failed:",e)}},[s,$,Q,t]),ei=(0,n.useCallback)((e,t,s,r)=>{O({x:e.clientX,y:e.clientY,path:t,type:s,parentPath:r})},[]),eo=(0,n.useCallback)(()=>{O(null)},[]),el=(0,n.useCallback)(e=>{e&&("gsd"===s?S:A)(r=>{let a=new Set(r),n=e.split("/");for(let e=1;e<=n.length;e++)a.add(n.slice(0,e).join("/"));return ad(t,s,a),a}),G({parentDir:e,type:"file"})},[s,t]),ed=(0,n.useCallback)(e=>{e&&("gsd"===s?S:A)(r=>{let a=new Set(r),n=e.split("/");for(let e=1;e<=n.length;e++)a.add(n.slice(0,e).join("/"));return ad(t,s,a),a}),G({parentDir:e,type:"directory"})},[s,t]),ec=(0,n.useCallback)(async(e,r,a)=>{let n=e?`${e}/${r}`:r;try{let e=await e$(tx("/api/files",t),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n,type:a,root:s})});if(!e.ok){let t=await e.json().catch(()=>({}));console.error("Create failed:",t.error||e.statusText);return}await Q(s),"file"===a&&await X(s,n)}catch(e){console.error("Create failed:",e)}finally{G(null)}},[s,Q,X,t]),eu=(0,n.useCallback)(()=>{G(null)},[]),em=(0,n.useCallback)(e=>{z(e)},[]),ex=(0,n.useCallback)(async(e,r)=>{let a=e.includes("/")?e.substring(0,e.lastIndexOf("/")):"",n=a?`${a}/${r}`:r;if(n===e)return void z(null);try{let r=await e$(tx("/api/files",t),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:n,root:s})});if(!r.ok){let e=await r.json().catch(()=>({}));console.error("Rename failed:",e.error||r.statusText);return}let a=ah(s,e);if(I(t=>t.map(t=>{if(t.key===a)return{...t,key:ah(s,n),path:n};if(t.root===s&&t.path.startsWith(e+"/")){let r=n+t.path.slice(e.length);return{...t,key:ah(s,r),path:r}}return t})),$===`${s}:${e}`)D(ah(s,n));else if($?.startsWith(`${s}:${e}/`)){let t=$.slice(`${s}:${e}`.length);D(ah(s,n+t))}await Q(s)}catch(e){console.error("Rename failed:",e)}finally{z(null)}},[s,$,Q,t]),eh=(0,n.useCallback)(()=>{z(null)},[]),ep=(0,n.useCallback)((e,t)=>{K({path:e,type:t})},[]),eg=(0,n.useCallback)(async()=>{if(!W)return;let{path:e,type:r}=W;try{let r=await fetch(tx(`/api/files?root=${s}&path=${encodeURIComponent(e)}`,t),{method:"DELETE"});if(!r.ok){let e=await r.json().catch(()=>({}));console.error("Delete failed:",e.error||r.statusText);return}I(t=>{let r=t.filter(t=>t.root!==s||!(t.path===e||t.path.startsWith(e+"/")));return $&&(r.some(e=>e.key===$)||D(r.length>0?r[r.length-1].key:null)),r}),await Q(s)}catch(e){console.error("Delete failed:",e)}finally{K(null)}},[W,s,$,Q,t]),ef=(0,n.useCallback)(()=>{K(null)},[]),eb=(0,n.useCallback)(e=>{let t="gsd"===s?`.gsd/${e}`:e;navigator.clipboard.writeText(t)},[s]),ev=(0,n.useCallback)(async e=>{try{let r,a=await e$(tx(`/api/files?root=${s}&path=${encodeURIComponent(e)}`,t));if(!a.ok)return;let n=await a.json();if("string"!=typeof n.content)return;let i=e.split("/").pop()??e,o=e.includes("/")?e.substring(0,e.lastIndexOf("/")):"",l=i.lastIndexOf(".");r=l>0?`${i.substring(0,l)}-copy${i.substring(l)}`:`${i}-copy`;let d=o?`${o}/${r}`:r,c=await e$(tx("/api/files",t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:d,content:n.content,root:s})});if(!c.ok){let e=await c.json().catch(()=>({}));console.error("Duplicate failed:",e.error||c.statusText);return}await Q(s),await X(s,d)}catch(e){console.error("Duplicate failed:",e)}},[s,Q,X,t]),ej=(0,n.useCallback)(async e=>{if(!H)return;let{root:s,path:r,key:a}=H,n=await e$(tx("/api/files",t),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,content:e,root:s})});if(!n.ok)throw Error((await n.json().catch(()=>({}))).error||`Save failed (${n.status})`);let i=await e$(tx(`/api/files?root=${s}&path=${encodeURIComponent(r)}`,t));if(i.ok){let e=await i.json();I(t=>t.map(t=>t.key===a?{...t,content:e.content??null}:t))}},[H,t]),ey=(0,n.useRef)(!1);(0,n.useEffect)(()=>{ey.current||!d||_.length>0||et.current||d.some(e=>"STATE.md"===e.name&&"file"===e.type)&&(ey.current=!0,X("gsd","STATE.md"))},[d,_.length,X]);let eN=(0,n.useRef)(0),ew=e.completedToolExecutions,ek=e.activeToolExecution,eS=(0,n.useRef)(null);return(0,n.useEffect)(()=>{if(ew.length<=eN.current)return;let e=ew.slice(eN.current);for(let s of(eN.current=ew.length,e)){if("edit"!==s.name&&"write"!==s.name)continue;let e="string"==typeof s.args?.path?s.args.path:null;if(!e)continue;let r=".gsd/",a="project",n=e;t&&n.startsWith(t)&&(n=n.slice(t.length)).startsWith("/")&&(n=n.slice(1)),n.startsWith(r)&&(a="gsd",n=n.slice(r.length));let i=ah(a,n),o=_.find(e=>e.key===i),l=o?.content??null;(async()=>{try{let e=await e$(tx(`/api/files?root=${a}&path=${encodeURIComponent(n)}`,t));if(!e.ok)return;let s=(await e.json()).content??null;if(null!==s){let e=null!==l&&l!==s?{before:l,after:s}:null;I(t=>t.find(e=>e.key===i)?t.map(t=>t.key===i?{...t,content:s,loading:!1,error:null,diff:e,agentOpened:!0}:t):[...t,{key:i,root:a,path:n,content:s,loading:!1,error:null,diff:e,agentOpened:!0}]),D(i),e&&(eS.current&&clearTimeout(eS.current),eS.current=setTimeout(()=>{I(e=>e.map(e=>e.key===i?{...e,diff:null}:e))},8e3))}}catch{}})()}},[ew,t,_]),(0,n.useMemo)(()=>ek&&("edit"===ek.name||"write"===ek.name)&&"string"==typeof ek.args?.path?ek.args.path:null,[ek]),(0,r.jsxs)("div",{className:"flex h-full",children:[(0,r.jsxs)("div",{className:"flex-shrink-0 border-r border-border overflow-hidden flex flex-col",style:{width:f},children:[(0,r.jsxs)("div",{className:"flex border-b border-border flex-shrink-0",children:[(0,r.jsx)("button",{onClick:()=>{l("tree"),er("gsd")},className:L("flex-1 px-3 py-2 text-xs font-medium transition-colors","tree"===o&&"gsd"===s?"border-b-2 border-foreground text-foreground":"text-muted-foreground hover:text-foreground"),children:"GSD"}),(0,r.jsx)("button",{onClick:()=>{l("tree"),er("project")},className:L("flex-1 px-3 py-2 text-xs font-medium transition-colors","tree"===o&&"project"===s?"border-b-2 border-foreground text-foreground":"text-muted-foreground hover:text-foreground"),children:"Project"}),(0,r.jsxs)("button",{onClick:()=>l("agent"),className:L("flex-1 px-3 py-2 text-xs font-medium transition-colors flex items-center justify-center gap-1.5","agent"===o?"border-b-2 border-foreground text-foreground":"text-muted-foreground hover:text-foreground"),children:[(0,r.jsx)(sM.A,{className:"h-3 w-3"}),"Agent"]})]}),"agent"===o?(0,r.jsx)("div",{className:"flex-1 overflow-hidden flex flex-col min-h-0",children:(0,r.jsx)(an,{className:"flex-1 min-h-0"})}):(0,r.jsx)("div",{className:L("flex-1 overflow-y-auto py-2",F&&"bg-accent/30"),onDragOver:e=>{e.target.closest("[data-tree-item]")||e.dataTransfer.types.includes("text/x-tree-path")&&(e.preventDefault(),e.dataTransfer.dropEffect="move",M(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||M(!1)},onDrop:e=>{if(M(!1),e.target.closest("[data-tree-item]"))return;e.preventDefault();let t=e.dataTransfer.getData("text/x-tree-path");!t||t.includes("/")&&en(t,"")},onContextMenu:e=>{e.target.closest("[data-tree-item]")||(e.preventDefault(),O({x:e.clientX,y:e.clientY,path:"",type:"directory",parentPath:""}))},children:x&&!Y?(0,r.jsxs)("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin mr-2"}),"Loading…"]}):p&&!Y?(0,r.jsxs)("div",{className:"flex items-center justify-center py-8 text-destructive text-xs px-3",children:[(0,r.jsx)(sq.A,{className:"h-4 w-4 mr-2 shrink-0"}),p]}):J&&0===J.length?(0,r.jsx)("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-xs",children:"gsd"===s?"No .gsd/ files found":"No files found"}):J?(0,r.jsxs)(r.Fragment,{children:[B&&""===B.parentDir&&(0,r.jsx)(am,{defaultValue:"directory"===B.type?"new-folder":"new-file",onCommit:e=>ec("",e,B.type),onCancel:eu,depth:0,icon:"directory"===B.type?(0,r.jsx)(b.A,{className:"h-4 w-4 text-muted-foreground"}):(0,r.jsx)(sP.A,{className:"h-4 w-4 text-muted-foreground"})}),J.map((e,t)=>(0,r.jsx)(ax,{node:e,depth:0,parentPath:"",selectedPath:V,expandedPaths:R,renamingPath:U,creatingIn:B,onToggleDir:es,onSelectFile:ea,onMoveFile:en,onContextMenu:ei,onRenameCommit:ex,onRenameCancel:eh,onCreateCommit:ec,onCreateCancel:eu},`${s}-${t}`))]}):null})]}),(0,r.jsx)("div",{className:"relative flex items-stretch",style:{flexShrink:0},children:(0,r.jsx)("div",{className:"absolute left-[-3px] top-0 bottom-0 w-[7px] cursor-col-resize z-10 hover:bg-muted-foreground/20 transition-colors",onMouseDown:w})}),(0,r.jsxs)("div",{className:"flex-1 overflow-hidden flex flex-col min-h-0",children:[_.length>0&&(0,r.jsx)("div",{className:"flex border-b border-border flex-shrink-0 overflow-x-auto bg-background",children:_.map(e=>(0,r.jsxs)("button",{onClick:()=>{D(e.key),a(e.root)},className:L("group flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium border-r border-border transition-colors shrink-0 max-w-[180px]",e.key===$?"bg-accent/50 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-accent/20"),children:[(0,r.jsx)("span",{className:"truncate",title:ap(e),children:e.path.split("/").pop()??e.path}),(0,r.jsx)("span",{role:"button",tabIndex:0,onClick:t=>Z(e.key,t),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),Z(e.key))},className:"ml-0.5 rounded p-0.5 opacity-0 group-hover:opacity-100 hover:bg-accent transition-opacity",children:(0,r.jsx)(i.A,{className:"h-3 w-3"})})]},e.key))}),H?(0,r.jsx)(r.Fragment,{children:H.loading?(0,r.jsxs)("div",{className:"flex flex-1 items-center justify-center text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin mr-2"}),"Loading…"]}):H.error?(0,r.jsxs)("div",{className:"flex flex-1 items-center justify-center text-destructive",children:[(0,r.jsx)(sq.A,{className:"h-4 w-4 mr-2"}),H.error]}):null!==H.content?(0,r.jsx)(rl,{content:H.content,filepath:ap(H),root:H.root,path:H.path,onSave:ej,diff:H.diff??void 0,agentOpened:H.agentOpened,onDismissDiff:()=>{I(e=>e.map(e=>e.key===H.key?{...e,diff:null,agentOpened:!1}:e))}}):(0,r.jsx)("div",{className:"flex flex-1 items-center justify-center text-muted-foreground italic",children:"No preview available"})}):(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:"Select a file to view"})]}),q&&(0,r.jsx)(au,{menu:q,onClose:eo,onNewFile:el,onNewFolder:ed,onRename:em,onDelete:ep,onCopyPath:eb,onDuplicate:ev}),W&&(0,r.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 animate-in fade-in-0",children:(0,r.jsxs)("div",{className:"w-full max-w-sm rounded-lg border border-border bg-popover p-4 shadow-lg animate-in zoom-in-95",children:[(0,r.jsxs)("h3",{className:"text-sm font-medium text-popover-foreground",children:["Delete ","directory"===W.type?"folder":"file","?"]}),(0,r.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Are you sure you want to delete"," ",(0,r.jsx)("span",{className:"font-mono font-medium text-popover-foreground",children:W.path.split("/").pop()}),"?","directory"===W.type&&" This will delete all contents."," ","This cannot be undone."]}),(0,r.jsxs)("div",{className:"mt-4 flex justify-end gap-2",children:[(0,r.jsx)("button",{onClick:ef,className:"rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground hover:bg-accent transition-colors",children:"Cancel"}),(0,r.jsx)("button",{onClick:eg,className:"rounded-md bg-destructive px-3 py-1.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors",children:"Delete"})]})]})})]})}function af({type:e}){let t="h-4 w-4";switch(e){case"system":return(0,r.jsx)(ss.A,{className:L(t,"text-info")});case"success":return(0,r.jsx)(l.A,{className:L(t,"text-success")});case"error":return(0,r.jsx)(sq.A,{className:L(t,"text-destructive")});case"output":return(0,r.jsx)(rE.A,{className:L(t,"text-foreground")});case"input":return(0,r.jsx)(d.A,{className:L(t,"text-warning")});default:return(0,r.jsx)(ss.A,{className:L(t,"text-muted-foreground")})}}function ab(){let e=[...tb().terminalLines??[]].reverse();return(0,r.jsxs)("div",{className:"flex h-full flex-col overflow-hidden",children:[(0,r.jsxs)("div",{className:"border-b border-border px-6 py-3",children:[(0,r.jsx)("h1",{className:"text-lg font-semibold",children:"Activity Log"}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"Execution history and git operations"})]}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto",children:0===e.length?(0,r.jsx)("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No activity yet. Events will appear here once the workspace is active."}):(0,r.jsxs)("div",{className:"relative px-6 py-4",children:[(0,r.jsx)("div",{className:"absolute left-10 top-6 bottom-6 w-px bg-border"}),(0,r.jsx)("div",{className:"space-y-4",children:e.map(e=>(0,r.jsxs)("div",{className:"relative flex gap-4",children:[(0,r.jsx)("div",{className:"relative z-10 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border border-border bg-card",children:(0,r.jsx)(af,{type:e.type})}),(0,r.jsx)("div",{className:"flex-1 pt-0.5",children:(0,r.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,r.jsx)("div",{children:(0,r.jsx)("p",{className:"text-sm font-medium",children:e.content})}),(0,r.jsx)("span",{className:"flex-shrink-0 font-mono text-xs text-muted-foreground",children:e.timestamp})]})})]},e.id))})]})})]})}window.addEventListener("gsd:open-file",e=>{let t=e.detail;t?.root&&t?.path&&(ai={root:t.root,path:t.path})});var av=s(33024),aj=s(6962),ay=s(45187),aN=s(9199);function aw(e){let t=Number(e)||0;return t<.01?`$${t.toFixed(4)}`:t<1?`$${t.toFixed(3)}`:`$${t.toFixed(2)}`}function ak(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(2)}M`}function aS(e){let t=Math.round(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60),r=t%60;if(s<60)return r>0?`${s}m ${r}s`:`${s}m`;let a=Math.floor(s/60),n=s%60;return n>0?`${a}h ${n}m`:`${a}h`}let aC=[{value:"progress",label:"Progress",Icon:av.A},{value:"deps",label:"Dependencies",Icon:N.A},{value:"metrics",label:"Metrics",Icon:j.A},{value:"timeline",label:"Timeline",Icon:ss.A},{value:"agent",label:"Agent",Icon:sM.A},{value:"changes",label:"Changes",Icon:v.A},{value:"export",label:"Export",Icon:aj.A}];function aA(e){switch(e){case"complete":case"done":return(0,r.jsx)(l.A,{className:"h-4 w-4 shrink-0 text-success"});case"active":return(0,r.jsx)(d.A,{className:"h-4 w-4 shrink-0 text-info"});case"pending":return(0,r.jsx)(c.A,{className:"h-4 w-4 shrink-0 text-muted-foreground/50"})}}function aT({risk:e}){return(0,r.jsx)("span",{className:L("inline-flex items-center rounded border px-2 py-0.5 text-[11px] font-semibold uppercase tracking-widest","high"===e?"bg-destructive/15 text-destructive border-destructive/25 ring-destructive/10":"medium"===e?"bg-warning/15 text-warning border-warning/25 ring-warning/10":"bg-success/15 text-success border-success/25 ring-success/10"),children:e})}function aR(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function aE({children:e}){return(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)("div",{className:"h-3.5 w-0.5 rounded-full bg-foreground/25"}),(0,r.jsx)("h3",{className:"text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:e})]})}function aP({message:e,icon:t=sq.A}){return(0,r.jsxs)("div",{className:"flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed border-border py-16 text-center",children:[(0,r.jsx)("div",{className:"rounded-full border border-border bg-muted/50 p-4",children:(0,r.jsx)(t,{className:"h-6 w-6 text-muted-foreground"})}),(0,r.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:e})]})}function a_({label:e,value:t,sub:s,accent:a}){return(0,r.jsxs)("div",{className:L("relative overflow-hidden rounded-xl border bg-gradient-to-br to-transparent p-5",{sky:"from-info/8 border-info/20",emerald:"from-success/8 border-success/20",amber:"from-warning/8 border-warning/20",default:"from-transparent border-border"}[a??"default"]),children:[(0,r.jsx)("p",{className:"text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:e}),(0,r.jsx)("p",{className:"mt-2 text-2xl font-bold tabular-nums leading-none tracking-tight",children:t}),s&&(0,r.jsx)("p",{className:"mt-1.5 text-xs text-muted-foreground",children:s})]})}function aI({value:e,max:t,color:s="sky",animated:a=!1}){let n=t>0?Math.max(1,e/t*100):0;return(0,r.jsx)("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:(0,r.jsx)("div",{className:L("h-full rounded-full transition-all duration-700",{sky:"bg-info",emerald:"bg-success",amber:"bg-warning"}[s],a&&"animate-pulse"),style:{width:`${n}%`}})})}function a$({data:e}){if(0===e.milestones.length)return(0,r.jsx)(aP,{message:"No milestones defined yet.",icon:av.A});let t=e.milestones.flatMap(e=>e.slices),s={low:0,medium:0,high:0};for(let e of t)"high"===e.risk?s.high++:"medium"===e.risk?s.medium++:s.low++;return(0,r.jsxs)("div",{className:"space-y-6",children:[t.length>0&&(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Risk Heatmap"}),(0,r.jsx)("div",{className:"mt-5 space-y-3",children:e.milestones.filter(e=>e.slices.length>0).map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-4",children:[(0,r.jsx)("span",{className:"w-16 shrink-0 font-mono text-xs font-medium text-muted-foreground",children:e.id}),(0,r.jsx)("div",{className:"flex flex-wrap gap-1.5",children:e.slices.map(e=>(0,r.jsx)("div",{title:`${e.id}: ${e.title} (${e.risk})`,className:L("h-6 w-6 rounded cursor-default transition-transform hover:scale-125","high"===e.risk?"bg-destructive":"medium"===e.risk?"bg-warning":"bg-success")},e.id))})]},e.id))}),(0,r.jsxs)("div",{className:"mt-5 flex items-center gap-5 text-xs text-muted-foreground",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"h-3 w-3 rounded-sm bg-success"}),"Low (",s.low,")"]}),(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"h-3 w-3 rounded-sm bg-warning"}),"Medium (",s.medium,")"]}),(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"h-3 w-3 rounded-sm bg-destructive"}),"High (",s.high,")"]})]})]}),(0,r.jsx)("div",{className:"space-y-4",children:e.milestones.map(e=>(0,r.jsxs)("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-muted/50 px-5 py-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[aA(e.status),(0,r.jsx)("span",{className:"font-mono text-xs font-semibold text-muted-foreground",children:e.id}),(0,r.jsx)("span",{className:"text-sm font-semibold",children:e.title})]}),(0,r.jsx)("span",{className:L("rounded-md px-2.5 py-1 text-xs font-semibold uppercase tracking-wider","complete"===e.status?"bg-success/15 text-success":"active"===e.status?"bg-info/15 text-info":"bg-muted text-muted-foreground"),children:e.status})]}),"pending"===e.status&&e.dependsOn.length>0&&(0,r.jsxs)("div",{className:"px-5 py-2.5 text-xs text-muted-foreground border-b border-border/50",children:["Depends on ",e.dependsOn.join(", ")]}),e.slices.length>0&&(0,r.jsx)("div",{className:"divide-y divide-border/50",children:e.slices.map(e=>{let t=e.tasks.filter(e=>e.done).length,s=e.done?"done":e.active?"active":"pending";return(0,r.jsxs)("div",{className:"px-5 py-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[aA(s),(0,r.jsx)("span",{className:"font-mono text-xs font-medium text-muted-foreground",children:e.id}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:e.title}),(0,r.jsxs)("div",{className:"flex shrink-0 items-center gap-2.5",children:[e.depends.length>0&&(0,r.jsxs)("span",{className:"text-xs text-muted-foreground",children:["deps: ",e.depends.join(", ")]}),e.tasks.length>0&&(0,r.jsxs)("span",{className:"font-mono text-xs font-medium text-muted-foreground",children:[t,"/",e.tasks.length]}),(0,r.jsx)(aT,{risk:e.risk})]})]}),(e.active||e.tasks.some(e=>e.active))&&e.tasks.length>0&&(0,r.jsx)("div",{className:"ml-7 mt-3 space-y-1",children:e.tasks.map(e=>(0,r.jsxs)("div",{className:L("flex items-center gap-2.5 rounded-lg px-3 py-2 transition-colors",e.active?"bg-info/8 border border-info/20":"hover:bg-muted/50"),children:[e.done?aA("done"):e.active?aA("active"):aA("pending"),(0,r.jsx)("span",{className:"font-mono text-xs font-medium text-muted-foreground",children:e.id}),(0,r.jsx)("span",{className:L("text-sm",e.done&&"text-muted-foreground line-through",e.active&&"font-semibold text-info",!e.done&&!e.active&&"text-muted-foreground"),children:e.title}),e.active&&(0,r.jsx)("span",{className:"ml-auto rounded-md bg-info/15 px-2 py-0.5 text-[11px] font-bold uppercase tracking-wider text-info",children:"running"})]},e.id))})]},e.id)})})]},e.id))})]})}function aD({data:e}){let t,s=e.criticalPath,a=e.milestones.find(e=>"active"===e.status),n=e.milestones.filter(e=>e.dependsOn.length>0);return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Milestone Dependencies"}),(0,r.jsx)("div",{className:"mt-5",children:0===n.length?(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"No milestone dependencies configured."}):(0,r.jsx)("div",{className:"flex flex-col gap-3",children:n.flatMap(e=>e.dependsOn.map(t=>(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{className:"rounded-lg border border-info/25 bg-info/10 px-3 py-1.5 font-mono text-sm font-semibold text-info",children:t}),(0,r.jsx)(sy.A,{className:"h-4 w-4 text-muted-foreground"}),(0,r.jsx)("span",{className:"rounded-lg border border-border bg-muted/50 px-3 py-1.5 font-mono text-sm font-medium",children:e.id}),(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:e.title})]},`${t}-${e.id}`)))})})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Slice Dependencies — Active Milestone"}),(0,r.jsx)("div",{className:"mt-5",children:a?0===(t=a.slices.filter(e=>e.depends.length>0)).length?(0,r.jsxs)("p",{className:"text-sm text-muted-foreground",children:["No slice dependencies in ",a.id,"."]}):(0,r.jsx)("div",{className:"flex flex-col gap-3",children:t.flatMap(e=>e.depends.map(t=>(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{className:"rounded-lg border border-info/25 bg-info/10 px-3 py-1.5 font-mono text-sm font-semibold text-info",children:t}),(0,r.jsx)(sy.A,{className:"h-4 w-4 text-muted-foreground"}),(0,r.jsx)("span",{className:"rounded-lg border border-border bg-muted/50 px-3 py-1.5 font-mono text-sm font-medium",children:e.id}),(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:e.title})]},`${t}-${e.id}`)))}):(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"No active milestone."})})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Critical Path"}),(0,r.jsx)("div",{className:"mt-5",children:0===s.milestonePath.length?(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"No critical path data."}):(0,r.jsxs)("div",{className:"space-y-7",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:"Milestone Chain"}),(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:s.milestonePath.map((e,t)=>(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-1.5 font-mono text-sm font-bold text-destructive",children:e}),t<s.milestonePath.length-1&&(0,r.jsx)(A.A,{className:"h-4 w-4 text-muted-foreground"})]},e))})]}),Object.keys(s.milestoneSlack).length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:"Milestone Slack"}),(0,r.jsx)("div",{className:"flex flex-col gap-2",children:e.milestones.filter(e=>!s.milestonePath.includes(e.id)).map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-4 rounded-lg bg-muted/50 px-4 py-2.5",children:[(0,r.jsx)("span",{className:"w-16 font-mono text-sm font-semibold",children:e.id}),(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:e.title}),(0,r.jsxs)("span",{className:"ml-auto font-mono text-xs text-muted-foreground",children:["slack: ",s.milestoneSlack[e.id]??0]})]},e.id))})]}),s.slicePath.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:"Slice Critical Path"}),(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:s.slicePath.map((e,t)=>(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"rounded-lg border border-warning/30 bg-warning/10 px-3 py-1.5 font-mono text-sm font-semibold text-warning",children:e}),t<s.slicePath.length-1&&(0,r.jsx)(A.A,{className:"h-4 w-4 text-muted-foreground"})]},e))}),a&&(0,r.jsx)("div",{className:"mt-3 space-y-2",children:s.slicePath.map(e=>a.slices.find(t=>t.id===e)).filter(e=>null!=e&&!e.done&&!e.active).map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-2.5 rounded-lg border border-warning/20 bg-warning/8 px-4 py-2.5 text-sm text-warning",children:[(0,r.jsx)(sA.A,{className:"h-4 w-4 shrink-0"}),(0,r.jsx)("span",{className:"font-mono font-semibold",children:e.id}),(0,r.jsx)("span",{children:"is on the critical path but not yet started"})]},e.id))})]}),Object.keys(s.sliceSlack).length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:"Slice Slack"}),(0,r.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(s.sliceSlack).map(([e,t])=>(0,r.jsxs)("span",{className:"rounded-lg border border-border bg-muted/50 px-3 py-1.5 font-mono text-xs text-muted-foreground",children:[e,": ",t]},e))})]})]})})]})]})}function aF({data:e}){if(!e.totals)return(0,r.jsx)(aP,{message:"No metrics data available.",icon:j.A});let t=e.totals;return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[(0,r.jsx)(a_,{label:"Execution Units",value:String(t.units),accent:"default"}),(0,r.jsx)(a_,{label:"Total Cost",value:aw(t.cost),accent:"emerald"}),(0,r.jsx)(a_,{label:"Duration",value:aS(t.duration),accent:"sky"}),(0,r.jsx)(a_,{label:"Total Tokens",value:ak(t.tokens.total),sub:`${ak(t.tokens.input)} in \xb7 ${ak(t.tokens.output)} out`,accent:"amber"})]}),e.byPhase.length>0&&(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Cost by Phase"}),(0,r.jsx)("div",{className:"mt-5 space-y-5",children:e.byPhase.map(e=>{let s=t.cost>0?e.cost/t.cost*100:0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,r.jsx)("span",{className:"text-sm font-semibold",children:e.phase}),(0,r.jsxs)("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"font-mono font-medium text-foreground",children:aw(e.cost)}),(0,r.jsxs)("span",{children:[s.toFixed(1),"%"]}),(0,r.jsxs)("span",{children:[ak(e.tokens.total)," tok"]}),(0,r.jsxs)("span",{children:[e.units," units"]})]})]}),(0,r.jsx)(aI,{value:s,max:100,color:"sky"})]},e.phase)})})]}),e.byModel.length>0&&(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Cost by Model"}),(0,r.jsx)("div",{className:"mt-5 space-y-5",children:e.byModel.map(e=>{let s=t.cost>0?e.cost/t.cost*100:0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,r.jsx)("span",{className:"font-mono text-sm font-medium",children:e.model}),(0,r.jsxs)("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"font-mono font-medium text-foreground",children:aw(e.cost)}),(0,r.jsxs)("span",{children:[s.toFixed(1),"%"]}),(0,r.jsxs)("span",{children:[ak(e.tokens.total)," tok"]}),(0,r.jsxs)("span",{children:[e.units," units"]})]})]}),(0,r.jsx)(aI,{value:s,max:100,color:"emerald"})]},e.model)})})]}),e.bySlice.length>0&&(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Cost by Slice"}),(0,r.jsx)("div",{className:"mt-5 overflow-x-auto",children:(0,r.jsxs)("table",{className:"w-full text-sm",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border text-left text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:[(0,r.jsx)("th",{className:"pb-3 pr-5",children:"Slice"}),(0,r.jsx)("th",{className:"pb-3 pr-5 text-right",children:"Units"}),(0,r.jsx)("th",{className:"pb-3 pr-5 text-right",children:"Cost"}),(0,r.jsx)("th",{className:"pb-3 pr-5 text-right",children:"Duration"}),(0,r.jsx)("th",{className:"pb-3 text-right",children:"Tokens"})]})}),(0,r.jsx)("tbody",{className:"divide-y divide-border/50",children:e.bySlice.map(e=>(0,r.jsxs)("tr",{className:"transition-colors hover:bg-muted/50",children:[(0,r.jsx)("td",{className:"py-3 pr-5 font-mono text-xs font-semibold",children:e.sliceId}),(0,r.jsx)("td",{className:"py-3 pr-5 text-right tabular-nums text-muted-foreground",children:e.units}),(0,r.jsx)("td",{className:"py-3 pr-5 text-right tabular-nums font-medium",children:aw(e.cost)}),(0,r.jsx)("td",{className:"py-3 pr-5 text-right tabular-nums text-muted-foreground",children:aS(e.duration)}),(0,r.jsx)("td",{className:"py-3 text-right tabular-nums text-muted-foreground",children:ak(e.tokens.total)})]},e.sliceId))})]})})]}),e.bySlice.length>=2&&(0,r.jsx)(aL,{data:e,totals:t})]})}function aL({data:e,totals:t}){let s=e.bySlice.filter(e=>e.sliceId.includes("/"));if(s.length<2)return null;let a=s.reduce((e,t)=>e+t.cost,0)/s.length,n=a*e.remainingSliceCount,i=t.cost+n,o=t.duration>0?t.cost/(t.duration/36e5):0;return(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Projections"}),(0,r.jsxs)("div",{className:"mt-5 grid grid-cols-2 gap-4 sm:grid-cols-4",children:[(0,r.jsx)(a_,{label:"Avg / Slice",value:aw(a)}),(0,r.jsx)(a_,{label:"Projected Remaining",value:aw(n),sub:`${e.remainingSliceCount} slices left`}),(0,r.jsx)(a_,{label:"Projected Total",value:aw(i)}),o>0&&(0,r.jsx)(a_,{label:"Burn Rate",value:`${aw(o)}/hr`})]}),i>2*t.cost&&e.remainingSliceCount>0&&(0,r.jsxs)("div",{className:"mt-4 flex items-center gap-2.5 rounded-lg border border-warning/20 bg-warning/8 px-4 py-3 text-sm text-warning",children:[(0,r.jsx)(sA.A,{className:"h-4 w-4 shrink-0"}),"Projected total ",aw(i)," exceeds 2\xd7 current spend"]})]})}function aM({data:e}){let t=[...e.units].sort((e,t)=>e.startedAt-t.startedAt).slice(-30),s=t.some(e=>!e.finishedAt||0===e.finishedAt),[a,i]=(0,n.useState)(()=>Date.now());(0,n.useEffect)(()=>{if(!s)return;let e=window.setInterval(()=>{i(Date.now())},1e3);return()=>window.clearInterval(e)},[s]);let o=s?a:0,c=(0,n.useCallback)(e=>(e.finishedAt||o)-e.startedAt,[o]);if(0===e.units.length)return(0,r.jsx)(aP,{message:"No execution history yet.",icon:ss.A});let u=Math.max(...t.map(c),1);return(0,r.jsx)("div",{className:"space-y-4",children:(0,r.jsxs)("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:[(0,r.jsxs)("div",{className:"border-b border-border bg-muted/50 px-6 py-4",children:[(0,r.jsx)(aE,{children:"Execution Timeline"}),(0,r.jsxs)("p",{className:"mt-1.5 text-xs text-muted-foreground",children:["Showing ",t.length," of ",e.units.length," units — most recent first"]})]}),(0,r.jsxs)("div",{className:"grid grid-cols-[3.5rem_1.5rem_5rem_8rem_1fr_4.5rem_5rem] items-center gap-3 border-b border-border/50 px-6 py-2.5 text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:[(0,r.jsx)("span",{children:"Time"}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{children:"Type"}),(0,r.jsx)("span",{children:"ID"}),(0,r.jsx)("span",{children:"Duration"}),(0,r.jsx)("span",{className:"text-right",children:"Time"}),(0,r.jsx)("span",{className:"text-right",children:"Cost"})]}),(0,r.jsx)("div",{className:"divide-y divide-border/40",children:[...t].reverse().map((e,t)=>{let s=c(e),a=!e.finishedAt||0===e.finishedAt;return(0,r.jsxs)("div",{className:"grid grid-cols-[3.5rem_1.5rem_5rem_8rem_1fr_4.5rem_5rem] items-center gap-3 px-6 py-3.5 transition-colors hover:bg-muted/50",children:[(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:aR(e.startedAt)}),a?(0,r.jsx)(d.A,{className:"h-3.5 w-3.5 shrink-0 text-info"}):(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 shrink-0 text-success"}),(0,r.jsx)("span",{className:"truncate text-xs font-medium",children:e.type}),(0,r.jsx)("span",{className:"truncate font-mono text-xs text-muted-foreground",children:e.id}),(0,r.jsx)("div",{className:"hidden sm:block",children:(0,r.jsx)(aI,{value:s/u*100,max:100,color:"sky",animated:a})}),(0,r.jsx)("span",{className:"text-right font-mono text-xs tabular-nums text-muted-foreground",children:aS(s)}),(0,r.jsx)("span",{className:"text-right font-mono text-xs tabular-nums font-medium",children:aw(e.cost)})]},`${e.id}-${e.startedAt}-${t}`)})})]})})}function aq({data:e}){let t=e.agentActivity;if(!t)return(0,r.jsx)(aP,{message:"No agent activity data available.",icon:sM.A});let s=t.completedUnits,a=Math.max(s,t.totalSlices),n=a>0?Math.min(100,Math.round(s/a*100)):0;return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("div",{className:"flex items-center gap-4",children:[(0,r.jsxs)("div",{className:L("relative flex h-10 w-10 items-center justify-center rounded-full",t.active?"bg-success/15":"bg-muted"),children:[t.active&&(0,r.jsx)("div",{className:"absolute inset-0 animate-ping rounded-full bg-success/20"}),(0,r.jsx)("div",{className:L("h-3 w-3 rounded-full",t.active?"bg-success":"bg-muted-foreground/30")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xl font-bold",children:t.active?"Active":"Idle"}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:t.active?"Agent is running":"Waiting for next task"})]})]}),t.active&&(0,r.jsxs)("div",{className:"text-right",children:[(0,r.jsx)("p",{className:"font-mono text-lg font-bold",children:aS(t.elapsed)}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:"elapsed"})]})]}),t.currentUnit&&(0,r.jsxs)("div",{className:"mt-5 flex items-center gap-3 rounded-xl border border-info/20 bg-info/8 px-5 py-3.5",children:[(0,r.jsx)(d.A,{className:"h-4 w-4 shrink-0 text-info"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:"Currently executing"}),(0,r.jsxs)("p",{className:"mt-0.5 font-mono text-sm font-semibold text-info",children:[t.currentUnit.type," — ",t.currentUnit.id]})]})]})]}),a>0&&(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsxs)("div",{className:"mb-4 flex items-center justify-between",children:[(0,r.jsx)(aE,{children:"Completion Progress"}),(0,r.jsxs)("span",{className:"font-mono text-sm text-muted-foreground",children:[s," / ",a," slices"]})]}),(0,r.jsx)(aI,{value:s,max:a,color:"emerald"}),(0,r.jsxs)("div",{className:"mt-3 flex items-center justify-between text-xs text-muted-foreground",children:[(0,r.jsxs)("span",{children:[n,"% complete"]}),(0,r.jsxs)("span",{children:[a-s," remaining"]})]})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[(0,r.jsx)(a_,{label:"Completion Rate",value:t.completionRate>0?`${t.completionRate.toFixed(1)}/hr`:"—",accent:"sky"}),(0,r.jsx)(a_,{label:"Session Cost",value:aw(t.sessionCost),accent:"emerald"}),(0,r.jsx)(a_,{label:"Session Tokens",value:ak(t.sessionTokens),accent:"amber"}),(0,r.jsx)(a_,{label:"Completed",value:String(t.completedUnits)})]}),e.units.filter(e=>e.finishedAt>0).length>0&&(0,r.jsxs)("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:[(0,r.jsx)("div",{className:"border-b border-border bg-muted/50 px-6 py-4",children:(0,r.jsx)(aE,{children:"Recent Completed Units"})}),(0,r.jsx)("div",{className:"divide-y divide-border/40",children:e.units.filter(e=>e.finishedAt>0).slice(-5).reverse().map((e,t)=>(0,r.jsxs)("div",{className:"flex items-center gap-4 px-6 py-4 transition-colors hover:bg-muted/50",children:[(0,r.jsx)("span",{className:"w-12 font-mono text-xs text-muted-foreground",children:aR(e.startedAt)}),(0,r.jsx)(l.A,{className:"h-4 w-4 shrink-0 text-success"}),(0,r.jsx)("span",{className:"flex-1 truncate text-sm font-medium",children:e.type}),(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.id}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:aS(e.finishedAt-e.startedAt)}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums font-semibold",children:aw(e.cost)})]},`${e.id}-${t}`))})]})]})}function aO({data:e}){let t=e.changelog.entries;if(0===t.length)return(0,r.jsx)(aP,{message:"No completed slices yet.",icon:v.A});let s=[...t].reverse();return(0,r.jsx)("div",{className:"space-y-4",children:s.map((e,t)=>(0,r.jsxs)("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-muted/50 px-6 py-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)(l.A,{className:"h-4 w-4 shrink-0 text-success"}),(0,r.jsxs)("span",{className:"font-mono text-xs font-bold text-success",children:[e.milestoneId,"/",e.sliceId]}),(0,r.jsx)("span",{className:"text-sm font-semibold",children:e.title})]}),e.completedAt&&(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:function(e){let t=Date.now()-new Date(e).getTime();if(t<6e4)return"just now";let s=Math.floor(t/6e4);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}(e.completedAt)})]}),(0,r.jsxs)("div",{className:"px-6 py-5 space-y-5",children:[e.oneLiner&&(0,r.jsxs)("p",{className:"text-sm text-muted-foreground italic leading-relaxed border-l-2 border-muted pl-4",children:["“",e.oneLiner,"”"]}),e.filesModified.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-muted-foreground",children:"Files Modified"}),(0,r.jsx)("div",{className:"space-y-2",children:e.filesModified.map((e,t)=>(0,r.jsxs)("div",{className:"flex items-start gap-3 rounded-lg bg-muted/50 px-4 py-2.5",children:[(0,r.jsx)(l.A,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-success/70"}),(0,r.jsx)("span",{className:"font-mono text-xs font-medium text-muted-foreground",children:e.path}),e.description&&(0,r.jsxs)("span",{className:"ml-1 text-xs text-muted-foreground",children:["— ",e.description]})]},t))})]})]})]},`${e.milestoneId}-${e.sliceId}-${t}`))})}function aU({data:e}){let t=(0,n.useCallback)((e,t,s)=>{let r=new Blob([e],{type:s}),a=URL.createObjectURL(r),n=document.createElement("a");n.href=a,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(a)},[]),s=(0,n.useCallback)(()=>{let t=[];for(let s of(t.push("# GSD Workflow Report"),t.push(""),t.push(`Generated: ${new Date().toISOString()}`),t.push(`Phase: ${e.phase}`),t.push(""),t.push("## Milestones"),t.push(""),e.milestones)){let e="complete"===s.status?"✓":"active"===s.status?"▸":"○";for(let r of(t.push(`### ${e} ${s.id}: ${s.title} (${s.status})`),s.dependsOn.length>0&&t.push(`Depends on: ${s.dependsOn.join(", ")}`),t.push(""),s.slices)){let e=r.done?"✓":r.active?"▸":"○";for(let s of(t.push(`- ${e} **${r.id}**: ${r.title} [risk: ${r.risk}]`),r.tasks)){let e=s.done?"✓":s.active?"▸":"○";t.push(` - ${e} ${s.id}: ${s.title}`)}}t.push("")}if(e.totals&&(t.push("## Metrics Summary"),t.push(""),t.push("| Metric | Value |"),t.push("|--------|-------|"),t.push(`| Units | ${e.totals.units} |`),t.push(`| Total Cost | ${aw(e.totals.cost)} |`),t.push(`| Duration | ${aS(e.totals.duration)} |`),t.push(`| Tokens | ${ak(e.totals.tokens.total)} |`),t.push("")),e.criticalPath.milestonePath.length>0&&(t.push("## Critical Path"),t.push(""),t.push(`Milestone: ${e.criticalPath.milestonePath.join(" → ")}`),e.criticalPath.slicePath.length>0&&t.push(`Slice: ${e.criticalPath.slicePath.join(" → ")}`),t.push("")),e.changelog.entries.length>0)for(let s of(t.push("## Changelog"),t.push(""),e.changelog.entries)){if(t.push(`### ${s.milestoneId}/${s.sliceId}: ${s.title}`),s.oneLiner&&t.push(`> ${s.oneLiner}`),s.filesModified.length>0)for(let e of(t.push("Files:"),s.filesModified))t.push(`- \`${e.path}\` — ${e.description}`);s.completedAt&&t.push(`Completed: ${s.completedAt}`),t.push("")}return t.join("\n")},[e]);return(0,r.jsx)("div",{className:"space-y-6",children:(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,r.jsx)(aE,{children:"Export Project Data"}),(0,r.jsx)("p",{className:"mt-3 text-sm leading-relaxed text-muted-foreground",children:"Download the current visualizer data as a structured report. Markdown includes milestones, metrics, critical path, and changelog in a readable format. JSON contains the full raw data payload."}),(0,r.jsxs)("div",{className:"mt-7 grid gap-4 sm:grid-cols-2",children:[(0,r.jsxs)("button",{onClick:()=>t(s(),"gsd-report.md","text/markdown"),className:"group flex items-center gap-5 rounded-xl border border-border bg-muted/50 p-5 text-left transition-all hover:border-info/40 hover:bg-info/5",children:[(0,r.jsx)("div",{className:"rounded-xl border border-info/20 bg-info/10 p-4 transition-colors group-hover:bg-info/15",children:(0,r.jsx)(T.A,{className:"h-6 w-6 text-info"})}),(0,r.jsxs)("div",{className:"flex-1",children:[(0,r.jsx)("p",{className:"text-sm font-semibold transition-colors group-hover:text-info",children:"Download Markdown"}),(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Human-readable report with tables and structure"})]}),(0,r.jsx)(aj.A,{className:"h-4 w-4 shrink-0 text-muted-foreground/0 transition-all group-hover:text-info/70"})]}),(0,r.jsxs)("button",{onClick:()=>t(JSON.stringify(e,null,2),"gsd-report.json","application/json"),className:"group flex items-center gap-5 rounded-xl border border-border bg-muted/50 p-5 text-left transition-all hover:border-success/40 hover:bg-success/5",children:[(0,r.jsx)("div",{className:"rounded-xl border border-success/20 bg-success/10 p-4 transition-colors group-hover:bg-success/15",children:(0,r.jsx)(ay.A,{className:"h-6 w-6 text-success"})}),(0,r.jsxs)("div",{className:"flex-1",children:[(0,r.jsx)("p",{className:"text-sm font-semibold transition-colors group-hover:text-success",children:"Download JSON"}),(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Full raw data payload for tooling"})]}),(0,r.jsx)(aj.A,{className:"h-4 w-4 shrink-0 text-muted-foreground/0 transition-all group-hover:text-success/70"})]})]})]})})}function az({defaultValue:e,children:t}){return(0,r.jsx)(sU.bL,{defaultValue:e,className:"flex h-full flex-col overflow-hidden",children:t})}function aB(){return(0,r.jsx)(sU.B8,{className:"flex shrink-0 justify-center border-b border-border bg-background px-6",children:aC.map(({value:e,label:t,Icon:s})=>(0,r.jsxs)(sU.l9,{value:e,className:L("group relative flex items-center gap-2 px-4 py-3.5 text-sm font-medium outline-none","text-muted-foreground transition-colors duration-150","hover:text-foreground","data-[state=active]:text-foreground","focus-visible:text-foreground","disabled:pointer-events-none disabled:opacity-40"),children:[(0,r.jsx)("span",{className:L("pointer-events-none absolute bottom-0 left-0 right-0 h-0.5 rounded-t-full","bg-foreground opacity-0 transition-opacity duration-150","group-data-[state=active]:opacity-100")}),(0,r.jsx)("span",{className:"absolute inset-x-0 inset-y-1.5 rounded-lg bg-muted/0 transition-colors duration-150 group-hover:bg-muted group-data-[state=active]:bg-transparent"}),(0,r.jsx)(s,{className:"relative h-4 w-4 shrink-0 transition-colors duration-150 text-muted-foreground group-hover:text-muted-foreground group-data-[state=active]:text-foreground"}),(0,r.jsx)("span",{className:"relative",children:t})]},e))})}function aG(){let e=tb(),t=e.boot?.project.cwd,[s,a]=(0,n.useState)(null),[i,o]=(0,n.useState)(!0),[l,d]=(0,n.useState)(null),c=(0,n.useCallback)(async()=>{try{let e=await e$(tx("/api/visualizer",t));if(!e.ok){let t=await e.json().catch(()=>({error:"Unknown error"}));throw Error(t.error||`HTTP ${e.status}`)}let s=await e.json();a(s),d(null)}catch(e){d(e instanceof Error?e.message:"Failed to fetch visualizer data")}finally{o(!1)}},[t]);return((0,n.useEffect)(()=>{c();let e=setInterval(c,1e4);return()=>clearInterval(e)},[c]),i&&!s)?(0,r.jsx)("div",{className:"flex h-full items-center justify-center",children:(0,r.jsxs)("div",{className:"flex flex-col items-center gap-4",children:[(0,r.jsx)(E.A,{className:"h-7 w-7 animate-spin text-muted-foreground"}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading visualizer data…"})]})}):l&&!s?(0,r.jsx)("div",{className:"flex h-full items-center justify-center",children:(0,r.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[(0,r.jsx)("div",{className:"rounded-full border border-warning/20 bg-warning/10 p-4",children:(0,r.jsx)(sA.A,{className:"h-6 w-6 text-warning"})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-semibold",children:"Failed to load visualizer"}),(0,r.jsx)("p",{className:"mt-1.5 max-w-sm text-xs text-muted-foreground",children:l})]}),(0,r.jsxs)("button",{onClick:c,className:"mt-1 inline-flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium transition-colors hover:bg-accent",children:[(0,r.jsx)(aN.A,{className:"h-3.5 w-3.5"}),"Retry"]})]})}):s?(0,r.jsxs)("div",{className:"flex h-full flex-col overflow-hidden",children:[(0,r.jsx)("div",{className:"flex shrink-0 items-center justify-between border-b border-border px-7 py-5",children:(0,r.jsxs)("div",{children:[(0,r.jsx)("h1",{className:"text-xl font-bold tracking-tight",children:"Workflow Visualizer"}),(0,r.jsxs)("div",{className:"mt-1.5 flex items-center gap-3 text-sm text-muted-foreground",children:[(0,r.jsxs)("span",{children:["Phase:"," ",(0,r.jsx)("span",{className:L("inline-flex items-center rounded-md px-2 py-0.5 text-xs font-semibold uppercase tracking-wider","complete"===s.phase?"bg-success/15 text-success":"active"===s.phase||"running"===s.phase?"bg-info/15 text-info":"bg-muted text-muted-foreground"),children:s.phase})]}),s.remainingSliceCount>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-border",children:"\xb7"}),(0,r.jsxs)("span",{children:[s.remainingSliceCount," slice",1!==s.remainingSliceCount?"s":""," remaining"]})]}),l&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-border",children:"\xb7"}),(0,r.jsxs)("span",{className:"flex items-center gap-1 text-warning",children:[(0,r.jsx)(sA.A,{className:"h-3 w-3"}),"Stale — ",l]})]})]})]})}),(0,r.jsxs)(az,{defaultValue:"progress",children:[(0,r.jsx)(aB,{}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,r.jsxs)("div",{className:"mx-auto max-w-5xl px-7 py-7",children:[(0,r.jsx)(sU.UC,{value:"progress",className:"outline-none",children:(0,r.jsx)(a$,{data:s})}),(0,r.jsx)(sU.UC,{value:"deps",className:"outline-none",children:(0,r.jsx)(aD,{data:s})}),(0,r.jsx)(sU.UC,{value:"metrics",className:"outline-none",children:(0,r.jsx)(aF,{data:s})}),(0,r.jsx)(sU.UC,{value:"timeline",className:"outline-none",children:(0,r.jsx)(aM,{data:s})}),(0,r.jsx)(sU.UC,{value:"agent",className:"outline-none",children:(0,r.jsx)(aq,{data:s})}),(0,r.jsx)(sU.UC,{value:"changes",className:"outline-none",children:(0,r.jsx)(aO,{data:s})}),(0,r.jsx)(sU.UC,{value:"export",className:"outline-none",children:(0,r.jsx)(aU,{data:s})})]})})]})]}):null}var aW=s(73035),aK=s(65576),aH=s(68822);function aV(){let e=tb(),t=ts(e),s=td(e),a=tc(e),i=e0(s)??"project scope",o=e5(e.boot?.bridge),l=a?.currentUnit?.id??eZ(s),d=tt(e),c=e.titleOverride?.trim()||null,u=e.statusTexts,m=e.live.recoverySummary,x=td(e)?.validationIssues.length??0,h=Object.entries(u),p=h.length>0?h[h.length-1][1]:null,g="idle"===e.bootStatus||"loading"===e.bootStatus,f=e.boot?.project.cwd,[b,v]=(0,n.useState)(null),j=(0,n.useCallback)(async()=>{try{let e=await e$(tx("/api/visualizer",f));if(!e.ok)return;let t=await e.json();t.totals&&v(t.totals)}catch{}},[f]);return(0,n.useEffect)(()=>{let e=window.setTimeout(()=>{j()},0),t=window.setInterval(()=>{j()},3e4);return()=>{window.clearTimeout(e),window.clearInterval(t)}},[j]),(0,r.jsxs)("div",{className:"flex h-7 items-center justify-between border-t border-border bg-card px-2 md:px-3 text-[10px] md:text-xs",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2 md:gap-4",children:[(0,r.jsxs)("div",{className:`flex items-center gap-1.5 ${function(e){switch(e){case"success":return"text-success";case"warning":return"text-warning";case"danger":return"text-destructive";default:return"text-muted-foreground"}}(t.tone)}`,children:[(0,r.jsx)(aW.A,{className:"h-3 w-3"}),(0,r.jsx)("span",{children:t.label})]}),(0,r.jsxs)("div",{className:"hidden sm:flex items-center gap-1.5 text-muted-foreground",children:[(0,r.jsx)(N.A,{className:"h-3 w-3"}),g?(0,r.jsx)(tL,{className:"h-3 w-20"}):(0,r.jsx)("span",{className:"font-mono",children:i})]}),(0,r.jsxs)("div",{className:"hidden lg:flex items-center gap-1.5 text-muted-foreground",children:[(0,r.jsx)(aK.A,{className:"h-3 w-3"}),g?(0,r.jsx)(tL,{className:"h-3 w-24"}):(0,r.jsx)("span",{className:"font-mono",children:o})]}),!g&&(0,r.jsxs)("div",{className:"hidden max-w-xs items-center gap-1.5 truncate text-muted-foreground xl:flex","data-testid":"status-bar-retry-compaction",children:[(0,r.jsx)(R.A,{className:"h-3 w-3 shrink-0"}),(0,r.jsx)("span",{className:"truncate",children:m.retryInProgress?`Retry ${Math.max(1,m.retryAttempt)}`:m.isCompacting?"Compacting":m.freshness})]}),!g&&(0,r.jsxs)("div",{className:L("hidden items-center gap-1.5 xl:flex",x>0?"text-warning":"text-muted-foreground"),"data-testid":"status-bar-validation-count",children:[(0,r.jsx)(sA.A,{className:"h-3 w-3 shrink-0"}),(0,r.jsxs)("span",{children:[x," issue",1===x?"":"s"]})]}),!g&&d&&(0,r.jsxs)("div",{className:"hidden max-w-sm items-center gap-1.5 truncate text-destructive lg:flex","data-testid":"status-bar-error",children:[(0,r.jsx)(sA.A,{className:"h-3 w-3 shrink-0"}),(0,r.jsx)("span",{className:"truncate",children:d})]}),!g&&c&&(0,r.jsxs)("div",{className:"hidden max-w-xs items-center gap-1.5 truncate text-foreground/80 xl:flex","data-testid":"status-bar-title-override",children:[(0,r.jsx)(aH.A,{className:"h-3 w-3 shrink-0"}),(0,r.jsx)("span",{className:"truncate",title:c,children:c})]}),!g&&p&&!d&&(0,r.jsxs)("div",{className:"hidden max-w-xs items-center gap-1.5 truncate text-muted-foreground lg:flex","data-testid":"status-bar-extension-status",children:[(0,r.jsx)(aH.A,{className:"h-3 w-3 shrink-0"}),(0,r.jsx)("span",{className:"truncate",children:p})]})]}),(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2 md:gap-4",children:[(0,r.jsxs)("div",{className:"hidden sm:flex items-center gap-1.5 text-muted-foreground",children:[(0,r.jsx)(ss.A,{className:"h-3 w-3"}),g?(0,r.jsx)(tL,{className:"h-3 w-8"}):(0,r.jsx)("span",{children:aS(b?.duration??a?.elapsed??0)})]}),(0,r.jsxs)("div",{className:"hidden sm:flex items-center gap-1.5 text-muted-foreground",children:[(0,r.jsx)(sa.A,{className:"h-3 w-3"}),g?(0,r.jsx)(tL,{className:"h-3 w-6"}):(0,r.jsx)("span",{children:ak(b?.tokens.total??a?.totalTokens??0)})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,r.jsx)(sr.A,{className:"h-3 w-3"}),g?(0,r.jsx)(tL,{className:"h-3 w-10"}):(0,r.jsx)("span",{children:aw(b?.cost??a?.totalCost??0)})]}),(0,r.jsx)("span",{className:"hidden sm:inline max-w-[20rem] truncate text-muted-foreground","data-testid":"status-bar-unit",children:g?(0,r.jsx)(tL,{className:"inline-block h-3 w-28 align-middle"}):(0,r.jsx)(sp,{label:l})})]})]})}var aJ=s(59883);let aY={background:"#0a0a0a",foreground:"#e4e4e7",cursor:"#e4e4e7",cursorAccent:"#0a0a0a",selectionBackground:"#27272a",selectionForeground:"#e4e4e7",black:"#18181b",red:"#ef4444",green:"#22c55e",yellow:"#eab308",blue:"#3b82f6",magenta:"#a855f7",cyan:"#06b6d4",white:"#e4e4e7",brightBlack:"#52525b",brightRed:"#f87171",brightGreen:"#4ade80",brightYellow:"#facc15",brightBlue:"#60a5fa",brightMagenta:"#c084fc",brightCyan:"#22d3ee",brightWhite:"#fafafa"},aQ={background:"#f5f5f5",foreground:"#1a1a1a",cursor:"#1a1a1a",cursorAccent:"#f5f5f5",selectionBackground:"#d4d4d8",selectionForeground:"#1a1a1a",black:"#1a1a1a",red:"#dc2626",green:"#16a34a",yellow:"#ca8a04",blue:"#2563eb",magenta:"#9333ea",cyan:"#0891b2",white:"#e4e4e7",brightBlack:"#71717a",brightRed:"#ef4444",brightGreen:"#22c55e",brightYellow:"#eab308",brightBlue:"#3b82f6",brightMagenta:"#a855f7",brightCyan:"#06b6d4",brightWhite:"#fafafa"};function aX(e,t){if(!e||!t)return null;let s=e.getBoundingClientRect();return s.width<180||s.height<120||t.cols<20||t.rows<8?null:{cols:t.cols,rows:t.rows}}async function aZ(e,t,s,r){if("u">typeof document&&"fonts"in document)try{await Promise.race([document.fonts.ready,new Promise(e=>setTimeout(e,1e3))])}catch{}for(let a=0;a<12;a++){if(r()||(await new Promise(e=>{requestAnimationFrame(()=>e())}),r()))return null;try{s?.fit()}catch{}let a=aX(e,t);if(a)return a;await new Promise(e=>setTimeout(e,50))}return aX(e,t)}function a0({className:e,fontSize:t,projectCwd:a}){let{resolvedTheme:i}=(0,Y.D)(),o="light"!==i,l=(0,n.useRef)(null),d=(0,n.useRef)(null),c=(0,n.useRef)(null),u=(0,n.useRef)(null),m=(0,n.useRef)(null),x=(0,n.useRef)(null),h=(0,n.useRef)([]),p=(0,n.useRef)(!1),[g,f]=(0,n.useState)("connecting"),[b,v]=(0,n.useState)(!1),[j,y]=(0,n.useState)(!1),N=(0,n.useCallback)(async()=>{if(!p.current){for(p.current=!0;h.current.length>0;){let e=h.current.shift();try{await e$(t5("/api/bridge-terminal/input",a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:e})})}catch{h.current.unshift(e);break}}p.current=!1}},[a]),w=(0,n.useCallback)(e=>{h.current.push(e),N()},[N]),k=(0,n.useCallback)((e,t)=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{e$(t5("/api/bridge-terminal/resize",a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:e,rows:t})})},75)},[a]);(0,n.useEffect)(()=>{c.current&&(c.current.options.theme=o?aY:aQ)},[o]),(0,n.useEffect)(()=>{if(c.current){c.current.options.fontSize=t??13;try{u.current?.fit(),k(c.current.cols,c.current.rows)}catch{}}},[t,k]),(0,n.useEffect)(()=>{if(!d.current)return;let e=!1,r=null,n=null,i=null;return(async()=>{let l,x,[{Terminal:h},{FitAddon:p}]=await Promise.all([s.e(3888).then(s.bind(s,8422)),s.e(3606).then(s.bind(s,63606))]);if(e)return;n=new h({cursorBlink:!0,cursorStyle:"bar",fontSize:t??13,fontFamily:"'SF Mono', 'Cascadia Code', 'Fira Code', Menlo, Monaco, 'Courier New', monospace",lineHeight:1.35,letterSpacing:0,theme:o?aY:aQ,allowProposedApi:!0,scrollback:1e4,convertEol:!1}),i=new p,n.loadAddon(i),n.open(d.current),c.current=n,u.current=i;let g=await aZ(d.current,n,i,()=>e);e||(n.onData(e=>{w(e)}),n.onBinary(e=>{w(e)}),l=t2("/api/bridge-terminal/stream",window.location.origin,a),g&&(l.searchParams.set("cols",String(g.cols)),l.searchParams.set("rows",String(g.rows))),m.current=x=new EventSource(eD(l.toString())),f(e=>"connected"===e?e:"connecting"),x.onmessage=t=>{try{let s=JSON.parse(t.data);if("connected"===s.type){f("connected"),aZ(d.current,c.current,u.current,()=>e).then(e=>{e&&k(e.cols,e.rows)});return}"output"===s.type&&"string"==typeof s.data&&(c.current?.write(s.data),v(!0))}catch{f("error")}},x.onerror=()=>{f("error")},(r=new ResizeObserver(()=>{if(!e)try{i?.fit(),n&&k(n.cols,n.rows)}catch{}})).observe(d.current))})(),()=>{e=!0,x.current&&clearTimeout(x.current),m.current?.close(),m.current=null,r?.disconnect(),n?.dispose(),c.current=null,u.current=null}},[t,o,a,w,k]);let S=(0,n.useCallback)(()=>{c.current?.focus()},[]);return(0,n.useEffect)(()=>{let e=l.current;if(!e)return;let t=e=>{"Enter"!==e.key||!e.shiftKey||e.ctrlKey||e.altKey||e.metaKey||(e.preventDefault(),e.stopPropagation(),w("\n"))};return e.addEventListener("keydown",t,!0),()=>e.removeEventListener("keydown",t,!0)},[w]),(0,n.useEffect)(()=>{let e=l.current;if(!e)return;let t=0,s=e=>{e.preventDefault(),e.stopPropagation(),1===(t+=1)&&y(!0)},r=e=>{e.preventDefault(),e.stopPropagation()},n=e=>{e.preventDefault(),e.stopPropagation(),(t-=1)<=0&&(t=0,y(!1))},i=e=>{e.preventDefault(),e.stopPropagation(),t=0,y(!1);let s=Array.from(e.dataTransfer?.files??[]).find(e=>e.type.startsWith("image/"));if(!s)return;let r=tJ(s);if(!r.valid)return void console.warn("[main-terminal-upload] validation failed:",r.error);let n=new FormData;n.append("file",s),(async()=>{try{let e=await e$(t5("/api/terminal/upload",a),{method:"POST",body:n}),t=await e.json();if(!e.ok||!t.path)return void console.error("[main-terminal-upload] upload failed:",t.error??`HTTP ${e.status}`);console.log("[main-terminal-upload] injecting path:",t.path),w(`@${t.path} `)}catch(e){console.error("[main-terminal-upload] upload request failed:",e)}})()};return e.addEventListener("dragenter",s,!0),e.addEventListener("dragover",r,!0),e.addEventListener("dragleave",n,!0),e.addEventListener("drop",i,!0),()=>{e.removeEventListener("dragenter",s,!0),e.removeEventListener("dragover",r,!0),e.removeEventListener("dragleave",n,!0),e.removeEventListener("drop",i,!0)}},[a,w]),(0,n.useEffect)(()=>{let e=setTimeout(()=>c.current?.focus(),80);return()=>clearTimeout(e)},[]),(0,r.jsxs)("div",{ref:l,className:L("relative h-full w-full bg-terminal",e),onClick:S,"data-testid":"main-session-native-terminal",children:[!b&&(0,r.jsxs)("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-terminal",children:[(0,r.jsx)(E.A,{className:"h-5 w-5 animate-spin text-muted-foreground"}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"error"===g?"Reconnecting main session terminal…":"Connecting to main session…"})]}),j&&(0,r.jsxs)("div",{className:"absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 bg-background backdrop-blur-sm border-2 border-dashed border-primary rounded-md pointer-events-none",children:[(0,r.jsx)(tW.A,{className:"h-8 w-8 text-primary"}),(0,r.jsx)("span",{className:"text-sm font-medium text-primary",children:"Drop image here"})]}),(0,r.jsx)("div",{ref:d,className:"h-full w-full",style:{padding:"8px 4px 4px 8px"}})]})}function a1(){let[e,t]=(0,n.useState)(50),s=(0,n.useRef)(null),a=(0,n.useRef)(null),i=(0,n.useRef)(!1),[o]=rB(),l=tb(),d=l.boot?.project.cwd,c=function({commandInFlight:e,terminalLines:t}){if(!e)return null;for(let e=t.length-1;e>=0;e-=1){let s=t[e];if("input"!==s.type)continue;let r=s.content.trim();if(r)return r}return"prompt"===e?"Sending command":`/${e}`}({commandInFlight:l.commandInFlight,terminalLines:l.terminalLines}),u=e=>{if(!i.current||!s.current)return;let r=s.current.getBoundingClientRect();t(Math.max(20,Math.min(80,(e.clientX-r.left)/r.width*100)))},m=()=>{i.current=!1};return(0,n.useEffect)(()=>(document.addEventListener("mousemove",u),document.addEventListener("mouseup",m),()=>{document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",m)}),[]),(0,n.useEffect)(()=>{let e=a.current;if(!e)return;let t=e=>{e.preventDefault()};return e.addEventListener("dragover",t,!0),e.addEventListener("drop",t,!0),()=>{e.removeEventListener("dragover",t,!0),e.removeEventListener("drop",t,!0)}},[]),(0,r.jsxs)("div",{ref:a,className:"flex h-full flex-col",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-card px-4 py-2",children:[(0,r.jsx)("span",{className:"font-medium",children:"Power User Mode"}),(0,r.jsxs)("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[c&&(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-primary/20 bg-primary/10 px-2.5 py-1 text-primary","data-testid":"power-mode-pending-command",title:c,children:[(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}),"Sending ",c]}),(0,r.jsx)("span",{children:"Left: Main Session TUI"}),(0,r.jsx)("span",{className:"text-border",children:"|"}),(0,r.jsx)("span",{children:"Right: Interactive GSD"})]})]}),(0,r.jsxs)("div",{ref:s,className:"flex flex-1 overflow-hidden",children:[(0,r.jsx)("div",{style:{width:`${e}%`},className:"flex h-full min-w-0 flex-col overflow-hidden bg-terminal",children:(0,r.jsx)(a0,{className:"min-h-0 flex-1",fontSize:o,projectCwd:d})}),(0,r.jsx)("div",{className:"flex w-1 cursor-col-resize items-center justify-center bg-border hover:bg-muted-foreground/30 transition-colors",onMouseDown:()=>{i.current=!0},children:(0,r.jsx)(aJ.A,{className:"h-4 w-4 text-muted-foreground"})}),(0,r.jsx)("div",{style:{width:`${100-e}%`},className:"h-full min-w-0 overflow-hidden bg-terminal",children:(0,r.jsx)(st,{className:"h-full",command:"gsd",sessionPrefix:"gsd-interactive",fontSize:o,hideInitialGsdHeader:!0,projectCwd:d})})]})]})}var a5=s(58515),a2=s(96035),a3=s(36351),a4=s(24338),a8=s(56204),a6=s(47279);function a7({className:e,...t}){return(0,r.jsx)(a6.bL,{"data-slot":"checkbox",className:L("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:(0,r.jsx)(a6.C1,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:(0,r.jsx)(rk.A,{className:"size-3.5"})})})}var a9=s(91760);function ne({className:e,...t}){return(0,r.jsx)(a9.b,{"data-slot":"label",className:L("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}var nt=s(86033);function ns({className:e,...t}){return(0,r.jsx)(nt.bL,{"data-slot":"radio-group",className:L("grid gap-3",e),...t})}function nr({className:e,...t}){return(0,r.jsx)(nt.q7,{"data-slot":"radio-group-item",className:L("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:(0,r.jsx)(nt.C1,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:(0,r.jsx)(c.A,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function na({...e}){return(0,r.jsx)($.bL,{"data-slot":"sheet",...e})}function nn({...e}){return(0,r.jsx)($.ZL,{"data-slot":"sheet-portal",...e})}function ni({className:e,...t}){return(0,r.jsx)($.hJ,{"data-slot":"sheet-overlay",className:L("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function no({className:e,children:t,side:s="right",...a}){return(0,r.jsxs)(nn,{children:[(0,r.jsx)(ni,{}),(0,r.jsx)($.UC,{"data-slot":"sheet-content",className:L("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500","right"===s&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm","left"===s&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm","top"===s&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b","bottom"===s&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",e),...a,children:t})]})}function nl({className:e,...t}){return(0,r.jsx)("div",{"data-slot":"sheet-header",className:L("flex flex-col gap-1.5 p-4",e),...t})}function nd({className:e,...t}){return(0,r.jsx)("div",{"data-slot":"sheet-footer",className:L("mt-auto flex flex-col gap-2 p-4",e),...t})}function nc({className:e,...t}){return(0,r.jsx)($.hE,{"data-slot":"sheet-title",className:L("text-foreground font-semibold",e),...t})}function nu({className:e,...t}){return(0,r.jsx)($.VY,{"data-slot":"sheet-description",className:L("text-muted-foreground text-sm",e),...t})}function nm({className:e,...t}){return(0,r.jsx)("textarea",{"data-slot":"textarea",className:L("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}function nx(e){switch(e){case"select":return"Selection";case"confirm":return"Confirmation";case"input":return"Input";case"editor":return"Editor"}}function nh({request:e,onSubmit:t,disabled:s}){let a=!!e.allowMultiple,[i,o]=(0,n.useState)(""),[l,d]=(0,n.useState)(new Set),c=()=>{a?t({value:Array.from(l)}):t({value:i})},u=a?l.size>0:""!==i;return a?(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsx)("div",{className:"space-y-2",children:e.options.map(e=>(0,r.jsxs)("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 transition-colors hover:bg-accent/40",children:[(0,r.jsx)(a7,{checked:l.has(e),onCheckedChange:t=>{let s=new Set(l);t?s.add(e):s.delete(e),d(s)},disabled:s}),(0,r.jsx)("span",{className:"text-sm",children:e})]},e))}),(0,r.jsxs)(J,{onClick:c,disabled:s||!u,className:"w-full",children:[(0,r.jsx)(a8.A,{className:"h-4 w-4"}),"Submit selection (",l.size,")"]})]}):(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsx)(ns,{value:i,onValueChange:o,disabled:s,children:e.options.map(e=>(0,r.jsxs)("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 transition-colors hover:bg-accent/40",children:[(0,r.jsx)(nr,{value:e,id:`select-${e}`}),(0,r.jsx)(ne,{htmlFor:`select-${e}`,className:"cursor-pointer text-sm font-normal",children:e})]},e))}),(0,r.jsxs)(J,{onClick:c,disabled:s||!u,className:"w-full",children:[(0,r.jsx)(a8.A,{className:"h-4 w-4"}),"Submit"]})]})}function np({request:e,onSubmit:t,onCancel:s,disabled:a}){return(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsx)("div",{className:"rounded-lg border border-border bg-background px-4 py-3 text-sm leading-relaxed",children:e.message}),(0,r.jsxs)("div",{className:"flex gap-3",children:[(0,r.jsx)(J,{onClick:()=>t({value:!0}),disabled:a,className:"flex-1",children:"Confirm"}),(0,r.jsx)(J,{onClick:s,disabled:a,variant:"outline",className:"flex-1",children:"Cancel"})]})]})}function ng({request:e,onSubmit:t,disabled:s}){let[a,i]=(0,n.useState)("");return(0,r.jsxs)("form",{className:"space-y-4",onSubmit:e=>{e.preventDefault(),a.trim()&&t({value:a})},children:[(0,r.jsx)(rP,{value:a,onChange:e=>i(e.target.value),placeholder:e.placeholder||"Enter a value",disabled:s,autoFocus:!0}),(0,r.jsxs)(J,{type:"submit",disabled:s||!a.trim(),className:"w-full",children:[(0,r.jsx)(a8.A,{className:"h-4 w-4"}),"Submit"]})]})}function nf({request:e,onSubmit:t,disabled:s}){let[a,i]=(0,n.useState)(e.prefill||"");return(0,r.jsxs)("form",{className:"space-y-4",onSubmit:e=>{e.preventDefault(),t({value:a})},children:[(0,r.jsx)(nm,{value:a,onChange:e=>i(e.target.value),disabled:s,className:"min-h-[200px] font-mono text-sm",autoFocus:!0}),(0,r.jsxs)(J,{type:"submit",disabled:s,className:"w-full",children:[(0,r.jsx)(a8.A,{className:"h-4 w-4"}),"Submit"]})]})}function nb({request:e,onSubmit:t,onCancel:s,disabled:a}){switch(e.method){case"select":return(0,r.jsx)(nh,{request:e,onSubmit:t,disabled:a});case"confirm":return(0,r.jsx)(np,{request:e,onSubmit:t,onCancel:s,disabled:a});case"input":return(0,r.jsx)(ng,{request:e,onSubmit:t,disabled:a});case"editor":return(0,r.jsx)(nf,{request:e,onSubmit:t,disabled:a})}}function nv(){let e=tb(),{respondToUiRequest:t,dismissUiRequest:s}=tv(),a=e.pendingUiRequests,n=a.length>0,i=a[0]??null,o="extension_ui_response"===e.commandInFlight,l=()=>{i&&s(i.id)};return(0,r.jsx)(na,{open:n,onOpenChange:e=>{e||o||!i||l()},children:(0,r.jsx)(no,{side:"right",className:"flex flex-col sm:max-w-md","data-testid":"focused-panel",children:i&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(nl,{children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[function(e){switch(e){case"select":return(0,r.jsx)(a5.A,{className:"h-4 w-4"});case"confirm":return(0,r.jsx)(a2.A,{className:"h-4 w-4"});case"input":return(0,r.jsx)(a3.A,{className:"h-4 w-4"});case"editor":return(0,r.jsx)(a4.A,{className:"h-4 w-4"})}}(i.method),(0,r.jsx)(nc,{children:i.title||nx(i.method)})]}),(0,r.jsx)(nu,{children:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsxs)("span",{children:[nx(i.method)," requested by the agent"]}),a.length>1&&(0,r.jsxs)("span",{className:L("inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-foreground px-1.5 text-[11px] font-semibold text-background"),"data-testid":"focused-panel-queue-badge",children:["+",a.length-1]})]})})]}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto px-4 py-2",children:(0,r.jsx)(nb,{request:i,onSubmit:e=>{i&&t(i.id,e)},onCancel:l,disabled:o})}),(0,r.jsx)(nd,{children:(0,r.jsx)(J,{variant:"ghost",size:"sm",onClick:l,disabled:o,className:"text-muted-foreground",children:"Dismiss"})})]})})})}var nj=s(80642),ny=s(85787);let nN="1"===s(41463).env.NEXT_PUBLIC_GSD_DEV,nw=[{key:"forceOnboarding",label:"Onboarding wizard",description:"Force the onboarding gate to render even when credentials are valid",shortcutLabel:"Ctrl+Shift+1"}],nk={forceOnboarding:!1},nS=(0,n.createContext)(null);function nC({children:e}){let[t,s]=(0,n.useState)(!1),[a,i]=(0,n.useState)(nk),[o,l]=(0,n.useState)(nN);(0,n.useEffect)(()=>{e$("/api/dev-mode",{cache:"no-store"}).then(e=>e.json()).then(e=>{e.isDevMode&&l(!0)}).catch(()=>{})},[]);let d=(0,n.useCallback)(e=>{i(t=>({...t,[e]:!t[e]}))},[]),c=(0,n.useCallback)(e=>t&&a[e],[t,a]);(0,n.useEffect)(()=>{if(o)return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e);function e(e){t&&e.ctrlKey&&e.shiftKey&&"1"===e.key&&(e.preventDefault(),i(e=>({...e,forceOnboarding:!e.forceOnboarding})))}},[t,o]);let u=(0,n.useMemo)(()=>o?{isDevMode:o,enabled:t,setEnabled:s,overrides:a,toggle:d,isActive:c}:{isDevMode:!1,enabled:!1,setEnabled:()=>{},overrides:nk,toggle:()=>{},isActive:()=>!1},[o,t,s,a,d,c]);return(0,r.jsx)(nS.Provider,{value:u,children:e})}function nA(){let e=(0,n.useContext)(nS);if(!e)throw Error("useDevOverrides must be used within <DevOverridesProvider>");return e}function nT({onNext:e}){return(0,r.jsxs)("div",{className:"flex flex-col items-center text-center",children:[(0,r.jsxs)(ny.P.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{type:"spring",duration:.6,bounce:0},className:"relative",children:[(0,r.jsx)("div",{className:"absolute inset-0 rounded-2xl bg-foreground/5 blur-2xl"}),(0,r.jsxs)("div",{className:"relative mb-4 flex h-18 items-center justify-center",children:[(0,r.jsx)(a.default,{src:"/logo-white.svg",alt:"GSD",height:70,width:200,className:"hidden dark:block"}),(0,r.jsx)(a.default,{src:"/logo-black.svg",alt:"GSD",height:70,width:200,className:"dark:hidden"})]})]}),(0,r.jsx)(ny.P.p,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.16,duration:.4},className:"max-w-sm text-[15px] leading-relaxed text-muted-foreground",children:"Let's get your workspace ready. This takes about a minute."}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.24,duration:.4},className:"mt-10 flex items-center gap-3 text-xs text-muted-foreground",children:["Mode","Provider","Auth","Workspace"].map((e,t)=>(0,r.jsxs)("span",{className:"flex items-center gap-3",children:[t>0&&(0,r.jsx)("span",{className:"h-px w-5 bg-border"}),(0,r.jsx)("span",{className:"font-medium",children:e})]},e))}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.35,duration:.4},className:"mt-10",children:(0,r.jsxs)(J,{size:"lg",className:"group gap-2.5 px-8 text-[15px] transition-transform active:scale-[0.96]",onClick:e,"data-testid":"onboarding-start",children:["Get started",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})})]})}let nR=[{id:"expert",label:"Expert",icon:s(33591).A,tagline:"Full control",description:"Dashboard metrics, dual-pane power mode, and direct /gsd command access. Built for people who want visibility into every milestone and task."},{id:"vibe-coder",label:"Vibe Coder",icon:rd.A,tagline:"Just chat",description:"Conversational interface with the AI agent. Describe what you want and let GSD handle the structure. Same engine, friendlier surface."}];function nE({selected:e,onSelect:t,onNext:s,onBack:a}){return(0,r.jsxs)("div",{className:"flex flex-col items-center text-center",children:[(0,r.jsx)(ny.P.h2,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.4},className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",style:{textWrap:"balance"},children:"How do you want to work?"}),(0,r.jsx)(ny.P.p,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.06,duration:.4},className:"mt-2 max-w-sm text-sm leading-relaxed text-muted-foreground",children:"You can switch anytime from settings."}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.12,duration:.45},className:"mt-8 grid w-full max-w-lg gap-3 sm:grid-cols-2",children:nR.map(s=>{let a=e===s.id,n=s.icon;return(0,r.jsxs)("button",{type:"button",onClick:()=>t(s.id),className:L("group relative flex flex-col rounded-xl border px-5 py-5 text-left transition-all duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-[0.98]",a?"border-foreground/30 bg-foreground/[0.06] shadow-[0_0_0_1px_rgba(255,255,255,0.06)]":"border-border/50 bg-card/50 hover:border-foreground/15 hover:bg-card/50"),"data-testid":`onboarding-mode-${s.id}`,children:[(0,r.jsx)("div",{className:"absolute right-3.5 top-3.5",children:(0,r.jsx)("div",{className:L("flex h-5 w-5 items-center justify-center rounded-full border-[1.5px] transition-all duration-200",a?"border-foreground bg-foreground":"border-foreground/20"),children:a&&(0,r.jsx)(ny.P.svg,{initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},transition:{type:"spring",duration:.3,bounce:0},viewBox:"0 0 12 12",className:"h-2.5 w-2.5 text-background",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2.5 6 5 8.5 9.5 3.5"})})})}),(0,r.jsx)("div",{className:L("mb-4 flex h-10 w-10 items-center justify-center rounded-lg transition-colors duration-200",a?"bg-foreground/10":"bg-foreground/[0.04]"),children:(0,r.jsx)(n,{className:L("h-5 w-5 transition-colors duration-200",a?"text-foreground":"text-muted-foreground"),strokeWidth:1.5})}),(0,r.jsxs)("div",{className:"pr-7",children:[(0,r.jsx)("span",{className:"text-[15px] font-semibold text-foreground",children:s.label}),(0,r.jsx)("span",{className:L("ml-2 text-xs font-medium transition-colors duration-200","text-muted-foreground"),children:s.tagline})]}),(0,r.jsx)("p",{className:"mt-2 text-[13px] leading-relaxed text-muted-foreground",children:s.description})]},s.id)})}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2,duration:.3},className:"mt-8 flex w-full max-w-lg items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:a,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)(J,{onClick:s,disabled:!e,className:"group gap-2 transition-transform active:scale-[0.96]","data-testid":"onboarding-mode-continue",children:["Continue",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})]})}var nP=s(44478);let n_=(0,H.F)("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function nI({className:e,variant:t,asChild:s=!1,...a}){let n=s?K.DX:"span";return(0,r.jsx)(n,{"data-slot":"badge",className:L(n_({variant:t}),e),...a})}function n$({providers:e,selectedId:t,onSelect:s,onNext:a,onBack:i}){let o=(0,n.useMemo)(()=>{let t,s,r,a;return t=e.filter(e=>e.configured),s=e.filter(e=>!e.configured&&e.recommended),r=e.filter(e=>!e.configured&&!e.recommended),a=[],t.length>0&&a.push({label:"Configured",items:t}),s.length>0&&a.push({label:"Recommended",items:s}),r.length>0&&a.push({label:"Other Providers",items:r}),a},[e]),l=e.some(e=>e.configured);return(0,r.jsxs)("div",{className:"flex flex-col items-center",children:[(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.4},className:"text-center",children:[(0,r.jsx)("h2",{className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",children:"Choose a provider"}),(0,r.jsx)("p",{className:"mt-2 text-sm leading-relaxed text-muted-foreground",children:"Click a provider to configure it. Set up as many as you want, then continue."})]}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.08,duration:.45},className:"mt-8 w-full space-y-5",children:o.map(e=>(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"mb-2 px-0.5 text-[11px] font-medium uppercase tracking-widest text-muted-foreground",children:e.label}),(0,r.jsx)("div",{className:"grid gap-2 sm:grid-cols-2",children:e.items.map(e=>{let a,n=e.id===t;return(0,r.jsxs)("button",{type:"button",onClick:()=>s(e.id),className:L("group relative rounded-xl border px-4 py-3.5 text-left transition-all duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-[0.98]",n?"border-foreground/30 bg-foreground/[0.06]":"border-border/50 bg-card/50 hover:border-foreground/15 hover:bg-card/50"),"data-testid":`onboarding-provider-${e.id}`,children:[(0,r.jsx)("div",{className:"absolute right-3 top-3",children:(0,r.jsx)("div",{className:L("flex h-5 w-5 items-center justify-center rounded-full border-[1.5px] transition-all duration-200",n?"border-foreground bg-foreground":"border-foreground/15"),children:n&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-background",strokeWidth:3})})}),(0,r.jsxs)("div",{className:"pr-8",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e.label}),e.recommended&&(0,r.jsx)(nI,{variant:"outline",className:"border-foreground/10 bg-foreground/[0.03] text-[9px] text-muted-foreground",children:"Recommended"})]}),(0,r.jsx)("div",{className:"mt-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:e.configured?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nP.A,{className:"h-3 w-3 text-success/80"}),(0,r.jsx)("span",{children:function(e){switch(e){case"auth_file":return"Saved auth";case"environment":return"Environment variable";case"runtime":return"Runtime";default:return"Not configured"}}(e.configuredVia)})]}):(0,r.jsx)("span",{className:"text-muted-foreground",children:"Not configured"})})]}),(0,r.jsx)("div",{className:"mt-2.5 flex flex-wrap gap-1",children:(a=[],e.supports.apiKey&&a.push("API key"),e.supports.oauth&&a.push(e.supports.oauthAvailable?"Browser sign-in":"OAuth unavailable"),a).map(e=>(0,r.jsxs)(r$,{children:[(0,r.jsx)(rD,{asChild:!0,children:(0,r.jsx)(nI,{variant:"outline",className:"border-border/50 text-[10px] text-muted-foreground",children:e})}),(0,r.jsx)(rF,{side:"bottom",children:"API key"===e?"Enter an API key to authenticate":"Browser sign-in"===e?"Authenticate through your browser":"This auth method is not available"})]},e))})]},e.id)})})]},e.label))}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.15,duration:.3},className:"mt-8 flex w-full items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:i,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)(J,{onClick:a,disabled:!l,className:"group gap-2 transition-transform active:scale-[0.96]","data-testid":"onboarding-provider-continue",children:["Continue",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})]})}var nD=s(62032),nF=s(35756),nL=s(42268),nM=s(22164),nq=s(62791),nO=s(14897);function nU({className:e,value:t,...s}){return(0,r.jsx)(nO.bL,{"data-slot":"progress",className:L("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",e),...s,children:(0,r.jsx)(nO.C1,{"data-slot":"progress-indicator",className:"bg-primary h-full w-full flex-1 transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})})}function nz({provider:e,activeFlow:t,lastValidation:s,requestState:a,requestProviderId:i,onSaveApiKey:o,onStartFlow:d,onSubmitFlowInput:c,onCancelFlow:u,onBack:m,onNext:x,bridgeRefreshPhase:h,bridgeRefreshError:p}){let[g,f]=(0,n.useState)(""),[b,v]=(0,n.useState)(""),[j,y]=(0,n.useState)(!1),N="idle"!==a,w=i===e.id&&N,k=s?.status==="succeeded"&&s.providerId===e.id&&("succeeded"===h||"idle"===h),S=s?.status==="failed"&&s.providerId===e.id,C=S?function(e){if(!e)return{title:"Validation failed",detail:null};let t=e.match(/^\d{3}\s+[^:]+:\s*(.+)$/s),s=t?.[1]??e;try{let e=JSON.parse(s);if("object"==typeof e&&null!==e){let t=e.error_details?.message??e.error?.message??e.message??e.error??null;if("string"==typeof t&&t.length>0){if(/subscription.*(ended|expired|cancelled)/i.test(t))return{title:"Subscription expired",detail:t.replace(/\.$/,"")+". Check your plan status with this provider."};if(/rate.limit/i.test(t))return{title:"Rate limited",detail:"Too many requests. Wait a moment and try again."};if(/invalid.*key|invalid.*token|incorrect.*key/i.test(t))return{title:"Invalid credentials",detail:"The API key was rejected. Double-check and try again."};if(/quota|billing|payment/i.test(t))return{title:"Billing issue",detail:t};return{title:"Provider error",detail:t}}}}catch{}return/^401\b/i.test(e)?{title:"Unauthorized",detail:"The credentials were rejected. Double-check your API key."}:/^403\b/i.test(e)?{title:"Access denied",detail:"Your account doesn't have access. Check your subscription or permissions."}:/^429\b/i.test(e)?{title:"Rate limited",detail:"Too many requests. Wait a moment and try again."}:/^5\d{2}\b/i.test(e)?{title:"Server error",detail:"The provider returned an error. Try again in a minute."}:{title:"Validation failed",detail:e.length>200?e.slice(0,200)+"…":e}}(s.message):null;e.supports.apiKey||e.supports.oauth;let A=e.supports.oauth&&e.supports.oauthAvailable,T=e.supports.apiKey,R=t&&t.providerId===e.id&&!k,P=R&&"failed"===t.status,_=R&&("running"===t.status||"awaiting_browser_auth"===t.status),I=R&&"awaiting_input"===t.status,$=R?function(e){for(let t of[e.prompt?.message,e.auth?.instructions].filter(Boolean)){let e=t?.match(/(?:code|Code)[:\s]+([A-Z0-9]{4}[-–][A-Z0-9]{4})/i);if(e)return e[1]}return null}(t):null;return(0,n.useEffect)(()=>{if(s?.status!=="succeeded")return;let e=window.setTimeout(()=>f(""),0);return()=>window.clearTimeout(e)},[s?.checkedAt,s?.status]),(0,n.useEffect)(()=>{let e=window.setTimeout(()=>v(""),0);return()=>window.clearTimeout(e)},[t?.flowId]),(0,n.useEffect)(()=>{if(!j)return;let e=window.setTimeout(()=>y(!1),2e3);return()=>window.clearTimeout(e)},[j]),(0,r.jsxs)("div",{className:"flex flex-col items-center",children:[(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.4},className:"text-center",children:[(0,r.jsxs)("h2",{className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",children:["Connect ",e.label]}),(0,r.jsx)("p",{className:"mt-2 max-w-sm text-sm leading-relaxed text-muted-foreground",children:k?"Authenticated and ready to go.":T&&A?"Paste an API key or sign in through your browser.":T?"Paste your API key to authenticate.":"Sign in through your browser to authenticate."})]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.08,duration:.45},className:"mt-8 w-full max-w-md space-y-4",children:[(0,r.jsx)(nj.N,{children:k&&(0,r.jsxs)(ny.P.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{type:"spring",duration:.4,bounce:0},className:"flex flex-col items-center gap-3 rounded-xl border border-success/15 bg-success/[0.04] px-6 py-6 text-center",children:[(0,r.jsx)("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-success/15",children:(0,r.jsx)(nP.A,{className:"h-5 w-5 text-success"})}),(0,r.jsxs)("div",{className:"text-sm font-medium text-foreground",children:[e.label," authenticated"]})]})}),S&&C&&(0,r.jsxs)("div",{className:"flex items-start gap-3 rounded-xl border border-destructive/20 bg-destructive/[0.06] px-4 py-3 text-sm",children:[(0,r.jsx)(nD.A,{className:"mt-0.5 h-4 w-4 shrink-0 text-destructive"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"font-medium text-destructive",children:C.title}),C.detail&&(0,r.jsx)("div",{className:"mt-0.5 text-muted-foreground",children:C.detail})]})]}),"pending"===h&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3 rounded-xl border border-foreground/10 bg-foreground/[0.03] px-4 py-3 text-sm text-foreground/80",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 shrink-0 animate-spin"}),"Connecting to provider…"]}),(0,r.jsx)(nU,{value:66,className:"h-1"})]}),"failed"===h&&p&&(0,r.jsxs)("div",{className:"flex items-start gap-3 rounded-xl border border-destructive/20 bg-destructive/[0.06] px-4 py-3 text-sm",children:[(0,r.jsx)(nD.A,{className:"mt-0.5 h-4 w-4 shrink-0 text-destructive"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"font-medium text-destructive",children:"Connection failed"}),(0,r.jsx)("div",{className:"mt-0.5 text-muted-foreground",children:p})]})]}),T&&!k&&(0,r.jsxs)("div",{className:"space-y-3 rounded-xl border border-border/50 bg-card/50 p-4",children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"API key"}),(0,r.jsxs)("form",{className:"space-y-3",onSubmit:async t=>{if(t.preventDefault(),!g.trim())return;let s=await o(e.id,g);s&&!s.locked&&("succeeded"===s.bridgeAuthRefresh.phase||"idle"===s.bridgeAuthRefresh.phase)&&x()},children:[(0,r.jsx)(rP,{"data-testid":"onboarding-api-key-input",type:"password",autoComplete:"off",value:g,onChange:e=>f(e.target.value),placeholder:`Paste your ${e.label} API key`,disabled:N,className:"font-mono text-sm"}),(0,r.jsx)("div",{className:"flex items-center gap-2",children:(0,r.jsxs)(J,{type:"submit",disabled:!g.trim()||N,className:"gap-2 transition-transform active:scale-[0.96]","data-testid":"onboarding-save-api-key",children:[w&&"saving_api_key"===a?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}):(0,r.jsx)(nF.A,{className:"h-4 w-4"}),"Validate & save"]})})]})]}),A&&!k&&(0,r.jsxs)("div",{className:"space-y-3",children:[T&&(0,r.jsxs)("div",{className:"flex items-center gap-3 py-1",children:[(0,r.jsx)("div",{className:"h-px flex-1 bg-border/50"}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"or"}),(0,r.jsx)("div",{className:"h-px flex-1 bg-border/50"})]}),!R&&(0,r.jsx)("div",{className:"rounded-xl border border-border/50 bg-card/50 p-4",children:(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Browser sign-in"}),(0,r.jsxs)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["Opens a new tab to authenticate with ",e.label]})]}),(0,r.jsxs)(J,{variant:"outline",disabled:N,onClick:()=>d(e.id),className:"shrink-0 gap-2 transition-transform active:scale-[0.96]","data-testid":"onboarding-start-provider-flow",children:[w&&"starting_provider_flow"===a?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}):(0,r.jsx)(nL.A,{className:"h-4 w-4"}),"Sign in"]})]})}),R&&(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.3},className:"rounded-xl border border-border/50 bg-card/50 p-4 space-y-4","data-testid":"onboarding-active-flow",children:[$&&(0,r.jsxs)("div",{className:"flex flex-col items-center gap-3 py-2",children:[(0,r.jsx)("div",{className:"text-xs text-muted-foreground",children:"Enter this code on the sign-in page"}),(0,r.jsxs)("button",{type:"button",onClick:()=>{navigator.clipboard.writeText($).then(()=>y(!0)).catch(()=>{})},className:"group flex items-center gap-3 rounded-lg border border-border bg-background/50 px-5 py-3 transition-colors hover:border-foreground/20 active:scale-[0.98]",children:[(0,r.jsx)("span",{className:"font-mono text-2xl font-bold tracking-[0.15em] text-foreground",children:$}),(0,r.jsx)("span",{className:"text-muted-foreground transition-colors group-hover:text-muted-foreground",children:j?(0,r.jsx)(l.A,{className:"h-4 w-4 text-success"}):(0,r.jsx)(sF.A,{className:"h-4 w-4"})})]}),(0,r.jsx)("div",{className:"text-[11px] text-muted-foreground",children:j?"Copied!":"Click to copy"})]}),!$&&t.auth?.instructions&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:t.auth.instructions}),t.auth?.url&&(0,r.jsx)(J,{asChild:!0,className:"w-full gap-2 transition-transform active:scale-[0.96]",children:(0,r.jsxs)("a",{href:t.auth.url,target:"_blank",rel:"noreferrer",children:[(0,r.jsx)(nM.A,{className:"h-4 w-4"}),"Open sign-in page"]})}),(0,r.jsxs)("div",{className:"flex items-center justify-between text-xs",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[_&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}),(0,r.jsx)("span",{children:"Waiting for authentication…"})]}),P&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nq.A,{className:"h-3 w-3 text-destructive"}),(0,r.jsx)("span",{className:"text-destructive",children:"Sign-in failed or timed out"})]}),I&&!$&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}),(0,r.jsx)("span",{children:"Waiting for input…"})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[P&&(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(e.id),disabled:N,className:"h-7 gap-1.5 text-xs text-muted-foreground",children:[(0,r.jsx)(aN.A,{className:"h-3 w-3"}),"Retry"]}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(t.flowId),disabled:N,className:"h-7 text-xs text-muted-foreground",children:"Cancel"})]})]}),t.prompt&&!$&&(0,r.jsxs)("form",{className:"space-y-2 border-t border-border/50 pt-3",onSubmit:e=>{e.preventDefault(),(t.prompt?.allowEmpty||b.trim())&&c(t.flowId,b)},children:[(0,r.jsx)("div",{className:"text-xs text-muted-foreground",children:t.prompt.message}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{"data-testid":"onboarding-flow-input",value:b,onChange:e=>v(e.target.value),placeholder:t.prompt.placeholder||"Enter value",disabled:N,className:"text-sm"}),(0,r.jsx)(J,{type:"submit",disabled:N||!t.prompt.allowEmpty&&!b.trim(),className:"shrink-0 transition-transform active:scale-[0.96]",children:"submitting_provider_flow_input"===a?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}):"Submit"})]})]}),t.progress.length>0&&(0,r.jsx)("div",{className:"space-y-1 border-t border-border/50 pt-3",children:t.progress.map((e,s)=>(0,r.jsx)("div",{className:"text-xs text-muted-foreground",children:e},`${t.flowId}-${s}`))})]})]}),e.supports.oauth&&!e.supports.oauthAvailable&&!T&&(0,r.jsx)("div",{className:"rounded-xl border border-border/50 bg-card/50 px-4 py-3.5 text-sm text-muted-foreground",children:"Browser sign-in is not available in this runtime. Go back and choose a provider with API-key support."})]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.15,duration:.3},className:"mt-8 flex w-full max-w-md items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:m,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)(J,{onClick:x,disabled:!k,className:"group gap-2 transition-transform active:scale-[0.96]","data-testid":"onboarding-auth-continue",children:["Configure another provider",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})]})}var nB=s(21167),nG=s(16561),nW=s(68990);function nK({className:e,children:t,viewportRef:s,...a}){return(0,r.jsxs)(nW.bL,{"data-slot":"scroll-area",className:L("relative",e),...a,children:[(0,r.jsx)(nW.LM,{ref:s,"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1",children:t}),(0,r.jsx)(nH,{}),(0,r.jsx)(nW.OK,{})]})}function nH({className:e,orientation:t="vertical",...s}){return(0,r.jsx)(nW.VM,{"data-slot":"scroll-area-scrollbar",orientation:t,className:L("flex touch-none p-px transition-colors select-none","vertical"===t&&"h-full w-2.5 border-l border-l-transparent","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent",e),...s,children:(0,r.jsx)(nW.lr,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}let nV=["~/Projects","~/Developer","~/Code","~/dev"];function nJ({onSelect:e,onCancel:t}){let[s,a]=(0,n.useState)(""),[i,o]=(0,n.useState)(null),[l,d]=(0,n.useState)([]),[c,u]=(0,n.useState)(!1),[m,x]=(0,n.useState)(null),h=(0,n.useCallback)(async e=>{u(!0),x(null);try{let t=e?`?path=${encodeURIComponent(e)}`:"",s=await e$(`/api/browse-directories${t}`);if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`${s.status}`)}let r=await s.json();a(r.current),o(r.parent),d(r.entries)}catch(e){x(e instanceof Error?e.message:"Failed to browse")}finally{u(!1)}},[]);return(0,n.useEffect)(()=>{h()},[h]),(0,r.jsxs)("div",{className:"rounded-xl border border-border/50 bg-card/50 overflow-hidden",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2 border-b border-border/50 px-4 py-2.5",children:[(0,r.jsx)("p",{className:"min-w-0 truncate font-mono text-xs text-muted-foreground",title:s,children:s}),(0,r.jsx)(J,{type:"button",size:"sm",onClick:()=>e(s),className:"shrink-0 h-7 gap-1.5 text-xs transition-transform active:scale-[0.96]",children:"Select this folder"})]}),(0,r.jsx)(nK,{className:"h-[240px]",children:(0,r.jsxs)("div",{className:"px-1.5 py-1",children:[c&&(0,r.jsx)("div",{className:"flex items-center justify-center py-10",children:(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),m&&(0,r.jsx)("div",{className:"px-3 py-4 text-center text-xs text-destructive",children:m}),!c&&!m&&(0,r.jsxs)(r.Fragment,{children:[i&&(0,r.jsxs)("button",{type:"button",onClick:()=>void h(i),className:"flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-accent/50",children:[(0,r.jsx)(nB.A,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,r.jsx)("span",{className:"text-muted-foreground",children:".."})]}),l.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>void h(e.path),className:"group flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-accent/50",children:[(0,r.jsx)(b.A,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-foreground",children:e.name}),(0,r.jsx)(A.A,{className:"h-3 w-3 shrink-0 text-muted-foreground/50 opacity-0 transition-opacity group-hover:opacity-100"})]},e.path)),0===l.length&&!i&&(0,r.jsx)("div",{className:"px-3 py-8 text-center text-xs text-muted-foreground",children:"No subdirectories"})]})]})}),(0,r.jsx)("div",{className:"border-t border-border/50 px-4 py-2",children:(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",onClick:t,className:"h-7 text-xs text-muted-foreground",children:"Cancel"})})]})}function nY({onNext:e,onBack:t}){let[s,a]=(0,n.useState)(""),[i,o]=(0,n.useState)(!1),[l,d]=(0,n.useState)(null),[c,u]=(0,n.useState)(!1),m=(0,n.useCallback)(e=>{a(e),d(null)},[]),x=(0,n.useCallback)(async()=>{let t=s.trim();if(!t)return void d("Enter a path or skip this step");o(!0),d(null);try{let s=await e$("/api/preferences",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({devRoot:t})});if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`Request failed (${s.status})`)}e()}catch(e){d(e instanceof Error?e.message:"Failed to save preference")}finally{o(!1)}},[s,e]);return(0,r.jsxs)("div",{className:"flex flex-col items-center text-center",children:[(0,r.jsx)(ny.P.div,{initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},transition:{type:"spring",duration:.5,bounce:0},className:"mb-8",children:(0,r.jsx)("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl border border-border/50 bg-card/50",children:(0,r.jsx)(nG.A,{className:"h-7 w-7 text-foreground/80",strokeWidth:1.5})})}),(0,r.jsx)(ny.P.h2,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.06,duration:.4},className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",children:"Dev root"}),(0,r.jsx)(ny.P.p,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.12,duration:.4},className:"mt-2 max-w-sm text-sm leading-relaxed text-muted-foreground",children:"The folder that contains your projects. GSD discovers and manages workspaces inside it."}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.18,duration:.45},className:"mt-8 w-full max-w-md space-y-4",children:(0,r.jsx)(nj.N,{mode:"wait",children:c?(0,r.jsx)(ny.P.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.2},children:(0,r.jsx)(nJ,{onSelect:e=>{a(e),u(!1),d(null)},onCancel:()=>u(!1)})},"browser"):(0,r.jsxs)(ny.P.div,{className:"space-y-4",children:[(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{value:s,onChange:e=>{a(e.target.value),l&&d(null)},placeholder:"/Users/you/Projects",className:L("h-11 flex-1 font-mono text-sm",l&&"border-destructive/50 focus-visible:ring-destructive/30"),"data-testid":"onboarding-devroot-input",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&s.trim()&&x()}}),(0,r.jsxs)(J,{type:"button",variant:"outline",onClick:()=>u(!0),className:"h-11 gap-2 shrink-0 transition-transform active:scale-[0.96]",children:[(0,r.jsx)(sg.A,{className:"h-4 w-4"}),"Browse"]})]}),l&&(0,r.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:l}),(0,r.jsx)("div",{className:"flex flex-wrap items-center justify-center gap-2",children:nV.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>m(e),className:L("rounded-full border px-3 py-1 font-mono text-xs transition-all duration-150","active:scale-[0.96]",s===e?"border-foreground/25 bg-foreground/10 text-foreground":"border-border/50 text-muted-foreground hover:border-foreground/15 hover:text-foreground"),children:e},e))})]},"input")})}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.25,duration:.3},className:"mt-8 flex w-full max-w-md items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:t,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)(J,{variant:"ghost",onClick:e,className:"gap-1.5 text-muted-foreground transition-transform active:scale-[0.96]","data-testid":"onboarding-devroot-skip",children:["Skip",(0,r.jsx)(_.A,{className:"h-3.5 w-3.5"})]}),(0,r.jsx)(J,{onClick:()=>void x(),className:"group gap-2 transition-transform active:scale-[0.96]",disabled:i||c,"data-testid":"onboarding-devroot-continue",children:i?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}),"Saving…"]}):(0,r.jsxs)(r.Fragment,{children:["Continue",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})})]})]})]})}var nQ=s(3636);function nX({sections:e,onBack:t,onNext:s}){let a=e.filter(e=>"remote_questions"!==e.id),n=a.filter(e=>e.configured).length;return(0,r.jsxs)("div",{className:"flex flex-col items-center",children:[(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.4},className:"text-center",children:[(0,r.jsx)("h2",{className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",children:"Integrations"}),(0,r.jsx)("p",{className:"mt-2 text-sm leading-relaxed text-muted-foreground",children:"Optional tools. Nothing here blocks the workspace — configure later from settings."})]}),n>0&&(0,r.jsx)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.08,duration:.3},className:"mt-4",children:(0,r.jsxs)("span",{className:"text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"font-medium text-success",children:n})," of ",a.length," configured"]})}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.1,duration:.45},className:"mt-8 w-full space-y-2",children:a.map(e=>(0,r.jsxs)("div",{className:L("flex items-start gap-3.5 rounded-xl border px-4 py-3.5 transition-colors",e.configured?"border-success/15 bg-success/[0.03]":"border-border/50 bg-card/50"),"data-testid":`onboarding-optional-${e.id}`,children:[(0,r.jsx)("div",{className:L("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full",e.configured?"bg-success/15 text-success":"bg-foreground/[0.05] text-muted-foreground"),children:e.configured?(0,r.jsx)(rk.A,{className:"h-3 w-3",strokeWidth:3}):(0,r.jsx)(nQ.A,{className:"h-3 w-3"})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-foreground",children:e.label}),(0,r.jsxs)(r$,{children:[(0,r.jsx)(rD,{asChild:!0,children:(0,r.jsx)(nI,{variant:"outline",className:L("text-[10px]",e.configured?"border-success/15 text-success/70":"border-border/50 text-muted-foreground"),children:e.configured?"Ready":"Skipped"})}),(0,r.jsx)(rF,{children:e.configured?"This integration is configured and active":"You can set this up later from workspace settings"})]})]}),e.configuredItems.length>0&&(0,r.jsx)("div",{className:"mt-1.5 flex flex-wrap gap-1",children:e.configuredItems.map(e=>(0,r.jsx)(nI,{variant:"outline",className:"border-border/50 text-[10px] text-muted-foreground",children:e},e))}),0===e.configuredItems.length&&(0,r.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Not configured — add later from settings."})]})]},e.id))}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.18,duration:.3},className:"mt-8 flex w-full items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:t,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)(J,{onClick:s,className:"group gap-2 transition-transform active:scale-[0.96]","data-testid":"onboarding-optional-continue",children:["Continue",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})]})}let nZ=[{value:"slack",label:"Slack",description:"Get notified in a Slack channel"},{value:"discord",label:"Discord",description:"Get notified in a Discord channel"},{value:"telegram",label:"Telegram",description:"Get notified via Telegram bot"}],n0={slack:"Channel ID (e.g. C01ABCD2EFG)",discord:"Channel ID (17–20 digit number)",telegram:"Chat ID (numeric, may start with -)"},n1={slack:/^[A-Z0-9]{9,12}$/,discord:/^\d{17,20}$/,telegram:/^-?\d{5,20}$/},n5={slack:"SLACK_BOT_TOKEN",discord:"DISCORD_BOT_TOKEN",telegram:"TELEGRAM_BOT_TOKEN"};function n2({onBack:e,onNext:t}){let[s,a]=(0,n.useState)(null),[i,o]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1),[u,m]=(0,n.useState)(null),[x,h]=(0,n.useState)(!1),[p,g]=(0,n.useState)(!1),[f,b]=(0,n.useState)(!0),[v,j]=(0,n.useState)(""),[y,N]=(0,n.useState)(!1),[w,k]=(0,n.useState)(!1),[S,C]=(0,n.useState)(!1),[A,T]=(0,n.useState)(null);(0,n.useEffect)(()=>{e$("/api/remote-questions",{cache:"no-store"}).then(e=>e.json()).then(e=>{e.tokenSet&&C(!0),"configured"===e.status&&e.config&&(g(!0),a(e.config.channel),o(e.config.channelId),h(!0))}).catch(()=>{}).finally(()=>b(!1))},[]);let R=null!==s&&i.trim().length>0&&n1[s].test(i.trim()),P=(0,n.useCallback)(async()=>{if(s&&R){c(!0),m(null);try{let e=await e$("/api/remote-questions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s,channelId:i.trim(),timeoutMinutes:5,pollIntervalSeconds:5})}),t=await e.json();if(!e.ok)return void m(t.error??`Save failed (${e.status})`);h(!0),g(!0)}catch(e){m(e instanceof Error?e.message:"Failed to save")}finally{c(!1)}}},[s,i,R]),I=(0,n.useCallback)(async()=>{if(s&&v.trim()){k(!0),m(null),T(null);try{let e=await e$("/api/remote-questions",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:s,token:v.trim()})}),t=await e.json();if(!e.ok)return void m(t.error??`Token save failed (${e.status})`);T(`Token saved (${t.masked})`),C(!0),j(""),N(!1)}catch(e){m(e instanceof Error?e.message:"Failed to save token")}finally{k(!1)}}},[s,v]);return(0,r.jsxs)("div",{className:"flex flex-col items-center",children:[(0,r.jsx)(ny.P.div,{initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},transition:{type:"spring",duration:.5,bounce:0},className:"mb-8",children:(0,r.jsx)("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl border border-border/50 bg-card/50",children:(0,r.jsx)(a2.A,{className:"h-7 w-7 text-foreground/80",strokeWidth:1.5})})}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.06,duration:.4},className:"text-center",children:[(0,r.jsx)("h2",{className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",children:"Remote notifications"}),(0,r.jsx)("p",{className:"mt-2 max-w-sm text-sm leading-relaxed text-muted-foreground",children:"Get notified when GSD needs your input. Connect a chat channel and the agent pings you instead of waiting silently."})]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.12,duration:.45},className:"mt-8 w-full max-w-md space-y-5",children:[x&&(0,r.jsxs)("div",{className:"flex items-center gap-3 rounded-xl border border-success/15 bg-success/[0.04] px-4 py-3 text-sm",children:[(0,r.jsx)(l.A,{className:"h-4 w-4 shrink-0 text-success"}),(0,r.jsx)("span",{className:"text-muted-foreground",children:p&&!d?`Connected to ${s??"channel"}`:"Configuration saved"})]}),!f&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Channel"}),(0,r.jsx)("div",{className:"grid grid-cols-3 gap-2",children:nZ.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{a(e.value),m(null),x&&!p&&h(!1)},disabled:d,className:L("rounded-xl border px-3 py-3 text-left transition-all duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-[0.97]",s===e.value?"border-foreground/30 bg-foreground/[0.06]":"border-border/50 bg-card/50 hover:border-foreground/15 hover:bg-card/50"),children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:e.label}),(0,r.jsx)("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:e.description})]},e.value))})]}),s&&!f&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Channel ID"}),(0,r.jsx)(rP,{value:i,onChange:e=>{o(e.target.value),u&&m(null)},placeholder:n0[s],disabled:d,className:"font-mono text-sm",onKeyDown:e=>{"Enter"===e.key&&R&&P()}}),i.trim().length>0&&!n1[s].test(i.trim())&&(0,r.jsxs)("p",{className:"text-xs text-destructive/70",children:["Doesn't match the expected format for ",s]})]}),s&&!f&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"text-xs font-medium text-muted-foreground",children:["Bot token",S&&(0,r.jsx)("span",{className:"ml-2 text-success",children:"✓ configured"})]}),A&&(0,r.jsxs)("div",{className:"flex items-center gap-2 rounded-xl border border-success/15 bg-success/[0.04] px-3 py-2 text-xs text-muted-foreground",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 shrink-0 text-success"}),A]}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsxs)("div",{className:"relative flex-1",children:[(0,r.jsx)(rP,{type:y?"text":"password",value:v,onChange:e=>j(e.target.value),placeholder:`Paste your ${n5[s]}`,disabled:w,className:"pr-9 font-mono text-sm",onKeyDown:e=>{"Enter"===e.key&&v.trim()&&I()}}),(0,r.jsx)("button",{type:"button",onClick:()=>N(e=>!e),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-muted-foreground transition-colors",children:y?(0,r.jsx)(rS.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(rC.A,{className:"h-3.5 w-3.5"})})]}),(0,r.jsxs)(J,{type:"button",variant:"outline",onClick:()=>void I(),disabled:!v.trim()||w,className:"gap-1.5 transition-transform active:scale-[0.96]",children:[w?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(nF.A,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),u&&(0,r.jsx)("div",{className:"rounded-xl border border-destructive/20 bg-destructive/[0.06] px-4 py-3 text-sm text-destructive",children:u}),s&&i.trim().length>0&&!x&&(0,r.jsxs)(J,{onClick:()=>void P(),disabled:!R||d,className:"gap-2 transition-transform active:scale-[0.96]",children:[d?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}):(0,r.jsx)(l.A,{className:"h-4 w-4"}),"Save & connect"]}),f&&(0,r.jsxs)("div",{className:"flex items-center gap-2 py-4 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),"Checking existing configuration…"]})]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2,duration:.3},className:"mt-8 flex w-full max-w-md items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:e,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[!x&&(0,r.jsxs)(J,{variant:"ghost",onClick:t,className:"gap-1.5 text-muted-foreground transition-transform active:scale-[0.96]",children:["Skip",(0,r.jsx)(_.A,{className:"h-3.5 w-3.5"})]}),(0,r.jsxs)(J,{onClick:t,className:"group gap-2 transition-transform active:scale-[0.96]",children:["Continue",(0,r.jsx)(sy.A,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})]})]})}function n3({providerLabel:e,onFinish:t}){return(0,r.jsxs)("div",{className:"flex flex-col items-center text-center",children:[(0,r.jsxs)(ny.P.div,{initial:{opacity:0,scale:.7},animate:{opacity:1,scale:1},transition:{type:"spring",duration:.6,bounce:.15},className:"relative mb-8",children:[(0,r.jsx)("div",{className:"absolute inset-0 rounded-full bg-success/10 blur-2xl"}),(0,r.jsx)("div",{className:"relative flex h-16 w-16 items-center justify-center rounded-2xl border border-success/20 bg-success/10",children:(0,r.jsx)(l.A,{className:"h-8 w-8 text-success",strokeWidth:1.5})})]}),(0,r.jsx)(ny.P.h2,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.1,duration:.4},className:"text-3xl font-bold tracking-tight text-foreground sm:text-4xl",children:"You're all set"}),(0,r.jsxs)(ny.P.p,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.18,duration:.4},className:"mt-3 max-w-sm text-[15px] leading-relaxed text-muted-foreground",children:[(0,r.jsx)("span",{className:"font-medium text-foreground",children:e})," is validated. The workspace is live."]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.26,duration:.4},className:"mt-8 flex items-center gap-4 rounded-xl border border-border/50 bg-card/50 px-5 py-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,r.jsx)(a.default,{src:"/logo-icon-white.svg",alt:"",width:14,height:14,className:"hidden opacity-40 dark:block"}),(0,r.jsx)(a.default,{src:"/logo-icon-black.svg",alt:"",width:14,height:14,className:"opacity-40 dark:hidden"}),(0,r.jsx)("span",{children:"Shell unlocked"})]}),(0,r.jsx)("div",{className:"h-3 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-success"}),(0,r.jsx)("span",{children:e})]})]}),(0,r.jsx)(ny.P.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.35,duration:.4},className:"mt-8",children:(0,r.jsxs)(J,{size:"lg",className:"group gap-2.5 px-8 text-[15px] transition-transform active:scale-[0.96]",onClick:t,"data-testid":"onboarding-finish",children:["Launch workspace",(0,r.jsx)(sa.A,{className:"h-4 w-4 transition-transform group-hover:scale-110"})]})})]})}let n4={"active-gsd":{label:"Active",color:"text-success",icon:av.A},"empty-gsd":{label:"Initialized",color:"text-info",icon:sg.A},brownfield:{label:"Existing",color:"text-warning",icon:N.A},"v1-legacy":{label:"Legacy",color:"text-warning",icon:N.A},blank:{label:"New",color:"text-muted-foreground",icon:sb.A}};function n8({onFinish:e,onBack:t,onBeforeSwitch:s}){let a=tF(),[i,o]=(0,n.useState)(null),[l,d]=(0,n.useState)([]),[c,u]=(0,n.useState)(!0),[m,x]=(0,n.useState)(null),[h,p]=(0,n.useState)(!1),[g,f]=(0,n.useState)(""),[b,v]=(0,n.useState)(!1),[j,y]=(0,n.useState)(null),N=(0,n.useRef)(null),[w,k]=(0,n.useState)(null),S=(0,n.useRef)(null);(0,n.useEffect)(()=>{let e=!1;return async function(){u(!0),x(null);try{let t=await e$("/api/preferences");if(!t.ok)throw Error("Failed to load preferences");let s=await t.json();if(!s.devRoot){o(null),d([]),u(!1);return}o(s.devRoot);let r=await e$(`/api/projects?root=${encodeURIComponent(s.devRoot)}&detail=true`);if(!r.ok)throw Error("Failed to discover projects");let a=await r.json();e||d(a)}catch(t){e||x(t instanceof Error?t.message:"Unknown error")}finally{e||u(!1)}}(),()=>{e=!0}},[]),(0,n.useEffect)(()=>()=>{S.current&&clearInterval(S.current)},[]),(0,n.useEffect)(()=>{if(h){let e=setTimeout(()=>N.current?.focus(),50);return()=>clearTimeout(e)}},[h]);let C=l.map(e=>e.name),A=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(g),T=C.includes(g),R=g.length>0&&A&&!T&&!b,P=(0,n.useCallback)(t=>{s?.(),k(t.path);let r=a.switchProject(t.path);S.current&&clearInterval(S.current);let n=Date.now();S.current=setInterval(()=>{let s=r.getSnapshot(),a=Date.now()-n;("ready"===s.bootStatus||"error"===s.bootStatus||a>3e4)&&(S.current&&clearInterval(S.current),S.current=null,k(null),e(t.path))},150)},[a,e,s]),_=(0,n.useCallback)(async()=>{if(R&&i){v(!0),y(null);try{let e=await e$("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({devRoot:i,name:g})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Failed (${e.status})`)}let t=await e.json();d(e=>[...e,t].sort((e,t)=>e.name.localeCompare(t.name))),f(""),p(!1),P(t)}catch(e){y(e instanceof Error?e.message:"Failed to create project"),v(!1)}}},[R,i,g,P]),I=!c&&!i,$=[...l].sort((e,t)=>{let s={"active-gsd":0,"empty-gsd":1,brownfield:2,"v1-legacy":3,blank:4},r=s[e.kind]??5,a=s[t.kind]??5;return r!==a?r-a:e.name.localeCompare(t.name)});return(0,r.jsxs)("div",{className:"flex flex-col items-center",children:[(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.4},className:"text-center",children:[(0,r.jsx)("h2",{className:"text-2xl font-bold tracking-tight text-foreground sm:text-3xl",children:"Open a project"}),(0,r.jsx)("p",{className:"mt-2 max-w-sm text-sm leading-relaxed text-muted-foreground",children:I?"Set a dev root first to discover your projects.":"Pick a project to start working in, or create a new one."})]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:.08,duration:.45},className:"mt-8 w-full max-w-lg space-y-2",children:[c&&(0,r.jsxs)("div",{className:"flex items-center justify-center gap-2 py-10 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}),"Discovering projects…"]}),m&&(0,r.jsx)("div",{className:"rounded-xl border border-destructive/20 bg-destructive/[0.06] px-4 py-3 text-sm text-destructive",children:m}),I&&(0,r.jsx)("div",{className:"rounded-xl border border-border/50 bg-card/50 px-4 py-6 text-center text-sm text-muted-foreground",children:"No dev root configured. Go back and set one, or finish setup to configure later."}),!c&&$.length>0&&(0,r.jsx)("div",{className:"space-y-2",children:$.map(e=>{var t;let s,a=w===e.path,n=n4[e.kind],i=n.icon,o=(t=e.signals,s=[],t.isMonorepo&&s.push("Monorepo"),t.hasGitRepo&&s.push("Git"),t.hasPackageJson&&s.push("Node.js"),t.hasCargo&&s.push("Rust"),t.hasGoMod&&s.push("Go"),t.hasPyproject&&s.push("Python"),s),l=e.progress?function(e){if(0===e.milestonesTotal)return null;let t=[];return e.activeMilestone&&t.push(e.activeMilestone),e.activeSlice&&t.push(e.activeSlice),e.phase&&t.push(e.phase),t.join(" \xb7 ")||null}(e.progress):null,d=e.progress?`${e.progress.milestonesCompleted}/${e.progress.milestonesTotal}`:null;return(0,r.jsxs)("button",{type:"button",onClick:()=>P(e),disabled:!!w,className:L("group flex w-full items-start gap-3.5 rounded-xl border px-4 py-3.5 text-left transition-all duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-[0.98]",a?"border-foreground/30 bg-foreground/[0.06]":"border-border/50 bg-card/50 hover:border-foreground/15 hover:bg-card/50",w&&!a&&"opacity-40 pointer-events-none"),children:[(0,r.jsx)("div",{className:L("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg mt-0.5","active-gsd"===e.kind?"bg-success/10":"bg-foreground/[0.04]"),children:a?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin text-muted-foreground"}):(0,r.jsx)(i,{className:L("h-4 w-4",n.color)})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground truncate",children:e.name}),(0,r.jsx)("span",{className:L("text-[10px] font-medium shrink-0",n.color),children:n.label})]}),o.length>0&&(0,r.jsx)("div",{className:"mt-1 flex items-center gap-1.5",children:o.map(e=>(0,r.jsx)("span",{className:"rounded bg-foreground/[0.04] px-1.5 py-0.5 text-[10px] text-muted-foreground",children:e},e))}),l&&(0,r.jsx)("div",{className:"mt-1.5 text-[11px] text-muted-foreground",children:l}),e.progress&&e.progress.milestonesTotal>0&&(0,r.jsxs)("div",{className:"mt-2 flex items-center gap-2",children:[(0,r.jsx)("div",{className:"h-1 flex-1 overflow-hidden rounded-full bg-foreground/[0.06]",children:(0,r.jsx)("div",{className:"h-full rounded-full bg-success/60 transition-all",style:{width:`${Math.round(e.progress.milestonesCompleted/e.progress.milestonesTotal*100)}%`}})}),(0,r.jsx)("span",{className:"text-[10px] tabular-nums text-muted-foreground",children:d})]})]}),(0,r.jsx)(sy.A,{className:"mt-1 h-4 w-4 shrink-0 text-muted-foreground/50 transition-all group-hover:text-muted-foreground group-hover:translate-x-0.5"})]},e.path)})}),!c&&i&&0===l.length&&!m&&(0,r.jsxs)("div",{className:"rounded-xl border border-border/50 bg-card/50 px-4 py-6 text-center text-sm text-muted-foreground",children:["No projects found in ",i]}),!c&&i&&(0,r.jsx)(r.Fragment,{children:h?(0,r.jsxs)(ny.P.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},transition:{duration:.2},className:"rounded-xl border border-border/50 bg-card/50 p-4 space-y-3",children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"New project"}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),_()},className:"space-y-2",children:[(0,r.jsx)(rP,{ref:N,value:g,onChange:e=>{f(e.target.value),y(null)},placeholder:"my-project",autoComplete:"off",className:"text-sm",disabled:b}),g&&!A&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:"Letters, numbers, hyphens, underscores, dots. Must start with a letter or number."}),T&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:"A project with this name already exists"}),j&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:j}),g&&A&&!T&&(0,r.jsxs)("p",{className:"font-mono text-xs text-muted-foreground",children:[i,"/",g]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 pt-1",children:[(0,r.jsxs)(J,{type:"submit",size:"sm",disabled:!R,className:"gap-1.5 transition-transform active:scale-[0.96]",children:[b?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(tK.A,{className:"h-3.5 w-3.5"}),"Create & open"]}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>{p(!1),f(""),y(null)},disabled:b,className:"text-muted-foreground",children:"Cancel"})]})]})]}):(0,r.jsxs)("button",{type:"button",onClick:()=>p(!0),disabled:!!w,className:L("flex w-full items-center gap-3.5 rounded-xl border border-dashed px-4 py-3.5 text-left transition-all duration-200","border-border/50 text-muted-foreground hover:border-foreground/15 hover:text-foreground","active:scale-[0.98]",w&&"opacity-40 pointer-events-none"),children:[(0,r.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-foreground/[0.04]",children:(0,r.jsx)(tK.A,{className:"h-4 w-4"})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("span",{className:"text-sm font-medium",children:"Create new project"}),(0,r.jsx)("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Initialize a new directory with Git"})]})]})})]}),(0,r.jsxs)(ny.P.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.15,duration:.3},className:"mt-8 flex w-full max-w-lg items-center justify-between",children:[(0,r.jsx)(J,{variant:"ghost",onClick:t,className:"text-muted-foreground transition-transform active:scale-[0.96]",children:"Back"}),(0,r.jsxs)(J,{onClick:()=>{s?.(),e("")},className:"group gap-2 transition-transform active:scale-[0.96]",children:["Finish setup",(0,r.jsx)(sa.A,{className:"h-4 w-4 transition-transform group-hover:scale-110"})]})]})]})}let n6=[{id:"welcome",label:"Welcome"},{id:"mode",label:"Mode"},{id:"provider",label:"Provider"},{id:"authenticate",label:"Auth"},{id:"devRoot",label:"Root"},{id:"optional",label:"Extras"},{id:"remote",label:"Remote"},{id:"ready",label:"Ready"},{id:"project",label:"Project"}],n7=n6.length,n9=[],ie={enter:e=>({x:e>0?50:-50,opacity:0}),center:{x:0,opacity:1},exit:e=>({x:e<0?50:-50,opacity:0})};function it({current:e,total:t}){return(0,r.jsx)("div",{className:"flex items-center gap-1",children:Array.from({length:t},(t,s)=>(0,r.jsx)("div",{className:L("rounded-full transition-all duration-300",s===e?"h-1.5 w-5 bg-foreground":s<e?"h-1.5 w-1.5 bg-foreground/40":"h-1.5 w-1.5 bg-foreground/10")},s))})}function is(){let e=tb(),{refreshOnboarding:t,saveApiKey:s,startProviderFlow:i,submitProviderFlowInput:o,cancelProviderFlow:l,refreshBoot:d}=tv(),c=nA(),u=e.boot?.onboarding,m=c.isActive("forceOnboarding"),x="idle"!==e.onboardingRequestState,[h,p]=(0,n.useState)(0),[g,f]=(0,n.useState)(0),[b,v]=(0,n.useState)(null),[j,y]=(0,n.useState)(!1),[N,w]=[(0,n.useSyncExternalStore)(tT,tR,tE),(0,n.useCallback)(e=>{localStorage.setItem(tS,e),tA.forEach(e=>e())},[])],[k,S]=(0,n.useState)(N),C=u?.required.providers??n9,A=(0,n.useMemo)(()=>{if(u?.activeFlow?.providerId)return u.activeFlow.providerId;if(b&&C.some(e=>e.id===b))return b;let e=C.find(e=>!e.configured&&e.recommended);if(e)return e.id;let t=C.find(e=>!e.configured);return t?t.id:C[0]?.id??null},[u?.activeFlow?.providerId,C,b]),T=j&&!u?.locked&&!x,[R,E]=(0,n.useState)(!1),P=(0,n.useCallback)(e=>{3===e&&u?.locked?E(!0):3!==e||u?.locked||E(!1),f(e>h?1:-1),p(e)},[h,u?.locked]);(0,n.useEffect)(()=>{if(!u||3!==h||!R)return;let e=!u.locked,t="succeeded"===u.bridgeAuthRefresh.phase||"idle"===u.bridgeAuthRefresh.phase;if(!e||!t)return;let s=window.setTimeout(()=>P(4),0);return()=>window.clearTimeout(s)},[u,P,h,R]);let _=(0,n.useMemo)(()=>C.find(e=>e.id===A)??null,[A,C]);if(!u)return null;let I=!u.locked||u.lastValidation?.status==="succeeded"&&("succeeded"===u.bridgeAuthRefresh.phase||"idle"===u.bridgeAuthRefresh.phase);if(!m&&(I||T))return null;let $=n6[h]?.label??"";return(0,r.jsxs)("div",{className:"pointer-events-auto absolute inset-0 z-30 flex flex-col bg-background","data-testid":"onboarding-gate",children:[(0,r.jsxs)("header",{className:"relative z-10 flex h-12 shrink-0 items-center justify-between px-5 md:px-8",children:[(0,r.jsxs)("div",{className:"flex w-24 items-center gap-2",children:[(0,r.jsx)(a.default,{src:"/logo-white.svg",alt:"GSD",width:57,height:16,className:"hidden h-4 w-auto dark:block"}),(0,r.jsx)(a.default,{src:"/logo-black.svg",alt:"GSD",width:57,height:16,className:"h-4 w-auto dark:hidden"})]}),(0,r.jsx)("div",{className:"absolute inset-x-0 flex justify-center pointer-events-none",children:(0,r.jsx)("div",{className:"pointer-events-auto",children:(0,r.jsx)(it,{current:h,total:n7})})}),(0,r.jsx)("div",{className:"flex w-24 justify-end",children:(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:$})})]}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,r.jsx)("div",{className:"mx-auto flex min-h-full w-full max-w-2xl flex-col justify-center px-5 py-10 md:px-8 md:py-16",children:(0,r.jsx)(nj.N,{mode:"wait",custom:g,children:(0,r.jsxs)(ny.P.div,{custom:g,variants:ie,initial:"enter",animate:"center",exit:"exit",transition:{type:"spring",stiffness:400,damping:35,opacity:{duration:.15}},children:[0===h&&(0,r.jsx)(nT,{onNext:()=>P(1)}),1===h&&(0,r.jsx)(nE,{selected:k,onSelect:e=>{S(e),w(e)},onNext:()=>P(2),onBack:()=>P(0)}),2===h&&(0,r.jsx)(n$,{providers:u.required.providers,selectedId:A,onSelect:e=>{v(e),P(3)},onNext:()=>P(4),onBack:()=>P(1)}),3===h&&_&&(0,r.jsx)(nz,{provider:_,activeFlow:u.activeFlow,lastValidation:u.lastValidation,requestState:e.onboardingRequestState,requestProviderId:e.onboardingRequestProviderId,onSaveApiKey:async(e,t)=>{let r=await s(e,t);return r&&!r.locked&&("succeeded"===r.bridgeAuthRefresh.phase||"idle"===r.bridgeAuthRefresh.phase)&&(y(!0),d()),r},onStartFlow:e=>void i(e),onSubmitFlowInput:(e,t)=>void o(e,t),onCancelFlow:e=>void l(e),onBack:()=>P(2),onNext:()=>P(2),bridgeRefreshPhase:u.bridgeAuthRefresh.phase,bridgeRefreshError:u.bridgeAuthRefresh.error}),4===h&&(0,r.jsx)(nY,{onBack:()=>P(2),onNext:()=>P(5)}),5===h&&(0,r.jsx)(nX,{sections:u.optional.sections,onBack:()=>P(4),onNext:()=>P(6)}),6===h&&(0,r.jsx)(n2,{onBack:()=>P(5),onNext:()=>P(7)}),7===h&&(0,r.jsx)(n3,{providerLabel:u.lastValidation?.providerId?u.required.providers.find(e=>e.id===u.lastValidation?.providerId)?.label??"Provider":"Provider",onFinish:()=>P(8)}),8===h&&(0,r.jsx)(n8,{onBack:()=>P(7),onBeforeSwitch:()=>{c.isActive("forceOnboarding")&&c.toggle("forceOnboarding"),y(!0)},onFinish:()=>{tP("dashboard"),d()}})]},h)})})})]})}var ir=s(90718),ia=s(48334),ii=s(24332),io=s(91958),il=s(43728),id=s(46029),ic=s(25221),iu=s(61878),im=s(54452),ix=s(66609),ih=s(8678);function ip({className:e,...t}){return(0,r.jsx)(ih.bL,{"data-slot":"switch",className:L("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:(0,r.jsx)(ih.zi,{"data-slot":"switch-thumb",className:"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"})})}var ig=s(32967);function ib({severity:e,className:t}){let s=L("h-3.5 w-3.5 shrink-0",t);switch(e){case"error":case"critical":return(0,r.jsx)(nq.A,{className:L(s,"text-destructive")});case"warning":return(0,r.jsx)(sA.A,{className:L(s,"text-warning")});default:return(0,r.jsx)(aH.A,{className:L(s,"text-info")})}}function iv(e){return"error"===e||"critical"===e?"destructive":"warning"===e?"secondary":"outline"}function ij({title:e,subtitle:t,status:s,onRefresh:a,refreshing:n}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 pb-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)("h3",{className:"text-[13px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:e}),s,t&&(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:t})]}),(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:a,disabled:n,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3",n&&"animate-spin")}),"Refresh"]})]})}function iy({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 text-xs text-destructive",children:e})}function iN({label:e}){return(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),e]})}function iw({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-4 py-5 text-center text-xs text-muted-foreground",children:e})}function ik({label:e,value:t,variant:s}){return(0,r.jsxs)("div",{className:L("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs","error"===s&&"border-destructive/20 bg-destructive/5 text-destructive","warning"===s&&"border-warning/20 bg-warning/5 text-warning","info"===s&&"border-info/20 bg-info/5 text-info",(!s||"default"===s)&&"border-border/50 bg-card/50 text-foreground/80"),children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:e}),(0,r.jsx)("span",{className:"font-medium tabular-nums",children:t})]})}function iS({anomaly:e}){return(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(ib,{severity:e.severity}),(0,r.jsx)(nI,{variant:iv(e.severity),className:"text-[10px] px-1.5 py-0",children:e.severity}),(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 font-mono",children:e.type}),e.unitId&&(0,r.jsxs)("span",{className:"text-[10px] text-muted-foreground font-mono truncate",children:[e.unitType,"/",e.unitId]})]}),(0,r.jsx)("p",{className:"text-xs text-foreground",children:e.summary}),e.details&&e.details!==e.summary&&(0,r.jsx)("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:e.details})]})}function iC(){let e=tb(),{loadForensicsDiagnostics:t}=tv(),s=e.commandSurface.diagnostics.forensics,a=s.data,n="loading"===s.phase;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"diagnostics-forensics",children:[(0,r.jsx)(ij,{title:"Forensic Analysis",subtitle:a?new Date(a.timestamp).toLocaleString():null,status:a?(0,r.jsx)("span",{className:L("inline-block h-1.5 w-1.5 rounded-full",a.anomalies.length>0?"bg-warning":"bg-success")}):null,onRefresh:()=>void t(),refreshing:n}),s.error&&(0,r.jsx)(iy,{message:s.error}),n&&!a&&(0,r.jsx)(iN,{label:"Running forensic analysis…"}),a&&(0,r.jsxs)(r.Fragment,{children:[a.metrics&&(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(ik,{label:"Units",value:a.metrics.totalUnits}),(0,r.jsx)(ik,{label:"Cost",value:eX(a.metrics.totalCost)}),(0,r.jsx)(ik,{label:"Duration",value:`${Math.round(a.metrics.totalDuration/1e3)}s`}),(0,r.jsx)(ik,{label:"Traces",value:a.unitTraceCount})]}),a.crashLock?(0,r.jsxs)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(nD.A,{className:"h-3.5 w-3.5 text-destructive"}),(0,r.jsx)("span",{className:"text-xs font-medium text-destructive",children:"Crash Lock Active"})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 text-[11px]",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:"PID"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80",children:a.crashLock.pid}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"Started"}),(0,r.jsx)("span",{className:"text-foreground/80",children:new Date(a.crashLock.startedAt).toLocaleString()}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"Unit"}),(0,r.jsxs)("span",{className:"font-mono text-foreground/80",children:[a.crashLock.unitType,"/",a.crashLock.unitId]})]})]}):(0,r.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-border/50 bg-card/50 px-3 py-2 text-xs text-muted-foreground",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 text-success"}),"No crash lock"]}),a.anomalies.length>0?(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Anomalies (",a.anomalies.length,")"]}),a.anomalies.map((e,t)=>(0,r.jsx)(iS,{anomaly:e},t))]}):(0,r.jsx)(iw,{message:"No anomalies detected"}),a.recentUnits.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Recent Units (",a.recentUnits.length,")"]}),(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"ID"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Model"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cost"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Duration"})]})}),(0,r.jsx)("tbody",{children:a.recentUnits.map((e,t)=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:e.type}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80 truncate max-w-[120px]",children:e.id}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:e.model}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:eX(e.cost)}),(0,r.jsxs)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:[Math.round(e.duration/1e3),"s"]})]},t))})]})})]})]})]})}function iA({issue:e}){return(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,r.jsx)(ib,{severity:e.severity}),(0,r.jsx)(nI,{variant:iv(e.severity),className:"text-[10px] px-1.5 py-0",children:e.severity}),(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 font-mono",children:e.code.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}),e.scope&&(0,r.jsx)("span",{className:"text-[10px] text-muted-foreground font-mono",children:e.scope}),e.fixable&&(0,r.jsxs)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-success/30 text-success",children:[(0,r.jsx)(ig.A,{className:"h-2.5 w-2.5 mr-0.5"}),"fixable"]})]}),(0,r.jsx)("p",{className:"text-xs text-foreground",children:e.message}),e.file&&(0,r.jsx)("p",{className:"text-[10px] font-mono text-muted-foreground truncate",children:e.file})]})}function iT(){let e=tb(),{loadDoctorDiagnostics:t,applyDoctorFixes:s}=tv(),a=e.commandSurface.diagnostics.doctor,n=a.data,i="loading"===a.phase,o=n?.summary.fixable??0;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"diagnostics-doctor",children:[(0,r.jsx)(ij,{title:"Doctor Health Check",status:n?(0,r.jsx)("span",{className:L("inline-block h-1.5 w-1.5 rounded-full",n.ok?"bg-success":"bg-destructive")}):null,onRefresh:()=>void t(),refreshing:i}),a.error&&(0,r.jsx)(iy,{message:a.error}),i&&!n&&(0,r.jsx)(iN,{label:"Running health check…"}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(ik,{label:"Total",value:n.summary.total}),n.summary.errors>0&&(0,r.jsx)(ik,{label:"Errors",value:n.summary.errors,variant:"error"}),n.summary.warnings>0&&(0,r.jsx)(ik,{label:"Warnings",value:n.summary.warnings,variant:"warning"}),n.summary.infos>0&&(0,r.jsx)(ik,{label:"Info",value:n.summary.infos,variant:"info"}),o>0&&(0,r.jsx)(ik,{label:"Fixable",value:o,variant:"info"})]}),o>0&&(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsxs)(J,{type:"button",variant:"default",size:"sm",onClick:()=>void s(),disabled:a.fixPending,className:"h-7 gap-1.5 text-xs","data-testid":"doctor-apply-fixes",children:[a.fixPending?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(ig.A,{className:"h-3 w-3"}),"Apply Fixes (",o,")"]}),a.lastFixError&&(0,r.jsx)("span",{className:"text-[11px] text-destructive",children:a.lastFixError})]}),a.lastFixResult&&a.lastFixResult.fixesApplied.length>0&&(0,r.jsxs)("div",{className:"rounded-lg border border-success/20 bg-success/5 px-3 py-2.5 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 text-success"}),(0,r.jsx)("span",{className:"text-xs font-medium text-success",children:"Fixes Applied"})]}),(0,r.jsx)("ul",{className:"space-y-0.5 pl-5",children:a.lastFixResult.fixesApplied.map((e,t)=>(0,r.jsx)("li",{className:"text-[11px] text-foreground/80 list-disc",children:e},t))})]}),n.issues.length>0?(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Issues (",n.issues.length,")"]}),n.issues.map((e,t)=>(0,r.jsx)(iA,{issue:e},t))]}):(0,r.jsx)(iw,{message:"No issues found — workspace is healthy"})]})]})}function iR({suggestion:e}){return(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,r.jsx)(ib,{severity:e.severity}),(0,r.jsx)(nI,{variant:iv(e.severity),className:"text-[10px] px-1.5 py-0",children:e.severity}),(0,r.jsx)("span",{className:"text-[11px] font-medium text-foreground/80",children:e.skillName}),(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 font-mono",children:e.trigger.replace(/_/g," ")})]}),(0,r.jsx)("p",{className:"text-xs text-foreground",children:e.message})]})}function iE(){let e=tb(),{loadSkillHealthDiagnostics:t}=tv(),s=e.commandSurface.diagnostics.skillHealth,a=s.data,n="loading"===s.phase;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"diagnostics-skill-health",children:[(0,r.jsx)(ij,{title:"Skill Health",subtitle:a?new Date(a.generatedAt).toLocaleString():null,status:a?(0,r.jsx)("span",{className:L("inline-block h-1.5 w-1.5 rounded-full",a.decliningSkills.length>0?"bg-warning":"bg-success")}):null,onRefresh:()=>void t(),refreshing:n}),s.error&&(0,r.jsx)(iy,{message:s.error}),n&&!a&&(0,r.jsx)(iN,{label:"Analyzing skill health…"}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(ik,{label:"Skills",value:a.skills.length}),a.staleSkills.length>0&&(0,r.jsx)(ik,{label:"Stale",value:a.staleSkills.length,variant:"warning"}),a.decliningSkills.length>0&&(0,r.jsx)(ik,{label:"Declining",value:a.decliningSkills.length,variant:"error"}),(0,r.jsx)(ik,{label:"Total units",value:a.totalUnitsWithSkills})]}),a.skills.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Skills (",a.skills.length,")"]}),(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Skill"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Uses"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Success"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Tokens"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-center font-medium text-muted-foreground",children:"Trend"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Stale"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cost"})]})}),(0,r.jsx)("tbody",{children:a.skills.map(e=>{var t,s;return(0,r.jsxs)("tr",{className:L("border-b border-border/50 last:border-0",e.flagged&&"bg-destructive/3"),children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[e.name,e.flagged&&(0,r.jsx)(sA.A,{className:"h-3 w-3 text-warning shrink-0"})]})}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:e.totalUses}),(0,r.jsxs)("td",{className:L("px-2.5 py-1.5 text-right tabular-nums",e.successRate>=.9?"text-success":e.successRate>=.7?"text-warning":"text-destructive"),children:[(100*e.successRate).toFixed(0),"%"]}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:Math.round(e.avgTokens)}),(0,r.jsx)("td",{className:L("px-2.5 py-1.5 text-center","rising"===(t=e.tokenTrend)?"text-warning":"declining"===t?"text-destructive":"text-muted-foreground"),children:"rising"===(s=e.tokenTrend)?"↑":"declining"===s?"↓":"→"}),(0,r.jsx)("td",{className:L("px-2.5 py-1.5 text-right tabular-nums",e.staleDays>30?"text-warning":"text-foreground/80"),children:e.staleDays>0?`${e.staleDays}d`:"—"}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:eX(e.avgCost)})]},e.name)})})]})})]}),a.staleSkills.length>0&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-xs font-medium text-muted-foreground",children:"Stale Skills"}),(0,r.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.staleSkills.map(e=>(0,r.jsx)(nI,{variant:"secondary",className:"text-[10px] font-mono",children:e},e))})]}),a.decliningSkills.length>0&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-xs font-medium text-muted-foreground",children:"Declining Skills"}),(0,r.jsx)("div",{className:"flex flex-wrap gap-1.5",children:a.decliningSkills.map(e=>(0,r.jsx)(nI,{variant:"destructive",className:"text-[10px] font-mono",children:e},e))})]}),a.suggestions.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Suggestions (",a.suggestions.length,")"]}),a.suggestions.map((e,t)=>(0,r.jsx)(iR,{suggestion:e},t))]}),0===a.skills.length&&0===a.suggestions.length&&(0,r.jsx)(iw,{message:"No skill usage data available"})]})]})}var iP=s(52530),i_=s(29262),iI=s(31885),i$=s(28063),iD=s(15161),iF=s(88444);function iL({title:e,subtitle:t,status:s,onRefresh:a,refreshing:n}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 pb-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)("h3",{className:"text-[13px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:e}),s,t&&(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:t})]}),(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:a,disabled:n,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3",n&&"animate-spin")}),"Refresh"]})]})}function iM({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 text-xs text-destructive",children:e})}function iq({label:e}){return(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),e]})}function iO({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-4 py-5 text-center text-xs text-muted-foreground",children:e})}function iU({label:e,value:t,variant:s}){return(0,r.jsxs)("div",{className:L("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs","error"===s&&"border-destructive/20 bg-destructive/5 text-destructive","warning"===s&&"border-warning/20 bg-warning/5 text-warning","info"===s&&"border-info/20 bg-info/5 text-info",(!s||"default"===s)&&"border-border/50 bg-card/50 text-foreground/80"),children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:e}),(0,r.jsx)("span",{className:"font-medium tabular-nums",children:t})]})}function iz({type:e,className:t}){let s=L("h-3.5 w-3.5 shrink-0",t);switch(e){case"rule":return(0,r.jsx)(iP.A,{className:L(s,"text-violet-400")});case"pattern":return(0,r.jsx)(i_.A,{className:L(s,"text-info")});case"lesson":return(0,r.jsx)(iI.A,{className:L(s,"text-warning")});case"freeform":return(0,r.jsx)(T.A,{className:L(s,"text-success")})}}function iB(e){switch(e){case"quick-task":return"Quick Task";case"inject":return"Inject";case"defer":return"Defer";case"replan":return"Replan";case"note":return"Note"}}function iG({classification:e,className:t}){let s=L("h-3 w-3 shrink-0",t);switch(e){case"quick-task":return(0,r.jsx)(sa.A,{className:s});case"inject":return(0,r.jsx)(ia.A,{className:s});case"defer":return(0,r.jsx)(i$.A,{className:s});case"replan":return(0,r.jsx)(iD.A,{className:s});case"note":return(0,r.jsx)(iF.A,{className:s})}}let iW=["quick-task","inject","defer","replan","note"];function iK({entry:e}){let t=function(e){switch(e){case"rule":return{label:"Rule",className:"border-violet-500/30 bg-violet-500/10 text-violet-400"};case"pattern":return{label:"Pattern",className:"border-info/30 bg-info/10 text-info"};case"lesson":return{label:"Lesson",className:"border-warning/30 bg-warning/10 text-warning"};case"freeform":return{label:"Freeform",className:"border-success/30 bg-success/10 text-success"}}}(e.type);return(0,r.jsx)("div",{className:"group rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 transition-colors hover:bg-card/50",children:(0,r.jsxs)("div",{className:"flex items-start gap-2.5",children:[(0,r.jsx)(iz,{type:e.type,className:"mt-0.5"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-xs font-medium text-foreground truncate",children:e.title}),(0,r.jsx)(nI,{variant:"outline",className:L("text-[10px] px-1.5 py-0 h-4 shrink-0",t.className),children:t.label})]}),e.content&&(0,r.jsx)("p",{className:"mt-1 text-[11px] text-muted-foreground line-clamp-2 leading-relaxed",children:e.content})]})]})})}function iH({data:e,phase:t,error:s,onRefresh:a}){return"loading"===t?(0,r.jsx)(iq,{label:"Loading knowledge base…"}):"error"===t&&s?(0,r.jsx)(iM,{message:s}):e&&0!==e.entries.length?(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsx)(iL,{title:"Knowledge Base",subtitle:`${e.entries.length} entries`,onRefresh:a,refreshing:"loading"===t}),(0,r.jsx)("div",{className:"space-y-1.5",children:e.entries.map(e=>(0,r.jsx)(iK,{entry:e},e.id))}),e.lastModified&&(0,r.jsxs)("p",{className:"pt-2 text-[10px] text-muted-foreground",children:["Last modified: ",new Date(e.lastModified).toLocaleString()]})]}):(0,r.jsx)(iO,{message:"No knowledge entries found"})}function iV({entry:e,onResolve:t,resolvePending:s}){let a=function(e){switch(e){case"pending":return{label:"Pending",className:"border-warning/30 bg-warning/10 text-warning"};case"triaged":return{label:"Triaged",className:"border-info/30 bg-info/10 text-info"};case"resolved":return{label:"Resolved",className:"border-success/30 bg-success/10 text-success"}}}(e.status);return(0,r.jsx)("div",{className:"group rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 transition-colors hover:bg-card/50",children:(0,r.jsxs)("div",{className:"flex items-start gap-2.5",children:[(0,r.jsx)("div",{className:L("mt-1 h-2 w-2 shrink-0 rounded-full","pending"===e.status&&"bg-warning","triaged"===e.status&&"bg-info","resolved"===e.status&&"bg-success")}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,r.jsx)("span",{className:"text-xs text-foreground",children:e.text}),(0,r.jsx)(nI,{variant:"outline",className:L("text-[10px] px-1.5 py-0 h-4 shrink-0",a.className),children:a.label}),e.classification&&(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 shrink-0 border-border/50 text-muted-foreground",children:iB(e.classification)})]}),e.timestamp&&(0,r.jsxs)("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-muted-foreground",children:[(0,r.jsx)(ss.A,{className:"h-2.5 w-2.5"}),e.timestamp]}),e.resolution&&(0,r.jsx)("p",{className:"mt-1 text-[10px] text-muted-foreground italic",children:e.resolution}),"pending"===e.status&&(0,r.jsx)("div",{className:"mt-2 flex flex-wrap gap-1",children:iW.map(a=>(0,r.jsxs)(J,{type:"button",variant:"outline",size:"sm",disabled:s,onClick:()=>t(e.id,a),className:"h-6 gap-1 px-2 text-[10px] font-normal border-border/50 hover:bg-foreground/5",children:[(0,r.jsx)(iG,{classification:a}),iB(a)]},a))})]})]})})}function iJ({data:e,phase:t,error:s,resolvePending:a,resolveError:n,onRefresh:i,onResolve:o}){return"loading"===t?(0,r.jsx)(iq,{label:"Loading captures…"}):"error"===t&&s?(0,r.jsx)(iM,{message:s}):e&&0!==e.entries.length?(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsx)(iL,{title:"Captures",subtitle:`${e.entries.length} total`,status:(0,r.jsxs)("div",{className:"flex gap-1.5",children:[(0,r.jsx)(iU,{label:"Pending",value:e.pendingCount,variant:e.pendingCount>0?"warning":"default"}),(0,r.jsx)(iU,{label:"Actionable",value:e.actionableCount,variant:e.actionableCount>0?"info":"default"})]}),onRefresh:i,refreshing:"loading"===t}),n&&(0,r.jsxs)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-[11px] text-destructive",children:["Resolve error: ",n]}),(0,r.jsx)("div",{className:"space-y-1.5",children:e.entries.map(e=>(0,r.jsx)(iV,{entry:e,onResolve:o,resolvePending:a},e.id))})]}):(0,r.jsx)(iO,{message:"No captures found"})}function iY({initialTab:e}){let[t,s]=(0,n.useState)(e),a=tb(),{loadKnowledgeData:i,loadCapturesData:o,resolveCaptureAction:l}=tv(),d=a.commandSurface.knowledgeCaptures,c=d.knowledge,u=d.captures,m=d.resolveRequest,x=u.data,h=x?.pendingCount??0;return(0,r.jsxs)("div",{className:"space-y-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-0.5 border-b border-border/50 px-1",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>s("knowledge"),className:L("flex items-center gap-1.5 px-3 py-2 text-xs font-medium transition-all border-b-2 -mb-px","knowledge"===t?"border-foreground/60 text-foreground":"border-transparent text-muted-foreground hover:text-muted-foreground"),children:[(0,r.jsx)(rv.A,{className:"h-3.5 w-3.5"}),"Knowledge"]}),(0,r.jsxs)("button",{type:"button",onClick:()=>s("captures"),className:L("flex items-center gap-1.5 px-3 py-2 text-xs font-medium transition-all border-b-2 -mb-px","captures"===t?"border-foreground/60 text-foreground":"border-transparent text-muted-foreground hover:text-muted-foreground"),children:[(0,r.jsx)(rf.A,{className:"h-3.5 w-3.5"}),"Captures",h>0&&(0,r.jsxs)(nI,{variant:"outline",className:"ml-1 h-4 px-1.5 py-0 text-[10px] border-warning/30 bg-warning/10 text-warning",children:[h," pending"]})]})]}),(0,r.jsx)("div",{className:"p-4",children:"knowledge"===t?(0,r.jsx)(iH,{data:c.data,phase:c.phase,error:c.error,onRefresh:()=>void i()}):(0,r.jsx)(iJ,{data:x,phase:u.phase,error:u.error,resolvePending:m.pending,resolveError:m.lastError,onRefresh:()=>void o(),onResolve:(e,t)=>{l({captureId:e,classification:t,resolution:"Manual browser triage",rationale:"Triaged via web UI"})}})})]})}function iQ({title:e,icon:t,subtitle:s,onRefresh:a,refreshing:n}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 pb-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:t}),(0,r.jsx)("h3",{className:"text-[13px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:e}),s&&(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:s})]}),(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:a,disabled:n,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3",n&&"animate-spin")}),"Refresh"]})]})}function iX({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 text-xs text-destructive",children:e})}function iZ({label:e}){return(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),e]})}function i0({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-4 py-5 text-center text-xs text-muted-foreground",children:e})}function i1({label:e,value:t,variant:s}){return(0,r.jsxs)("div",{className:L("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs","info"===s&&"border-info/20 bg-info/5 text-info","warning"===s&&"border-warning/20 bg-warning/5 text-warning","success"===s&&"border-success/20 bg-success/5 text-success",(!s||"default"===s)&&"border-border/50 bg-card/50 text-foreground/80"),children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:e}),(0,r.jsx)("span",{className:"font-medium tabular-nums",children:t})]})}function i5({label:e,enabled:t}){return(0,r.jsxs)(nI,{variant:t?"secondary":"outline",className:L("text-[10px] px-1.5 py-0 font-mono",t?"border-success/30 text-success":"text-muted-foreground"),children:[e,": ",t?"on":"off"]})}function i2({label:e,skills:t}){return t?.length?(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:e}),(0,r.jsx)("div",{className:"flex flex-wrap gap-1",children:t.map(e=>(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 font-mono",children:e},e))})]}):null}function i3({label:e,children:t}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-4 text-xs",children:[(0,r.jsx)("span",{className:"text-muted-foreground shrink-0",children:e}),(0,r.jsx)("span",{className:"text-foreground/80 text-right truncate",children:t})]})}function i4(){let e=tb(),{loadSettingsData:t}=tv(),s=e.commandSurface.settingsData;return{state:s,data:s.data,busy:"loading"===s.phase,refresh:()=>void t()}}function i8(e){return"budget"===e?"warning":"quality"===e?"success":"info"}function i6(){let{state:e,data:t,busy:s,refresh:a}=i4(),n=t?.preferences??null;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"settings-prefs",children:[(0,r.jsx)(iQ,{title:"Effective Preferences",icon:(0,r.jsx)(w.A,{className:"h-3.5 w-3.5"}),subtitle:n?`${n.scope} scope`:null,onRefresh:a,refreshing:s}),e.error&&(0,r.jsx)(iX,{message:e.error}),s&&!t&&(0,r.jsx)(iZ,{label:"Loading preferences…"}),t&&!n&&(0,r.jsx)(i0,{message:"No preferences file found"}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(i1,{label:"Mode",value:n.mode??"solo",variant:"info"}),(0,r.jsx)(i1,{label:"Token Profile",value:n.tokenProfile??"balanced",variant:i8(n.tokenProfile)}),n.customInstructions?.length?(0,r.jsx)(i1,{label:"Custom Instructions",value:n.customInstructions.length}):null]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)(i2,{label:"Always use",skills:n.alwaysUseSkills}),(0,r.jsx)(i2,{label:"Prefer",skills:n.preferSkills}),(0,r.jsx)(i2,{label:"Avoid",skills:n.avoidSkills}),!n.alwaysUseSkills?.length&&!n.preferSkills?.length&&!n.avoidSkills?.length&&(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:"No skill preferences configured"})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-x-6 gap-y-1.5 rounded-lg border border-border/50 bg-card/50 px-3 py-2.5",children:[(0,r.jsx)(i3,{label:"Auto-Supervisor",children:n.autoSupervisor?.enabled?(0,r.jsxs)("span",{className:"text-success",children:["on",null!=n.autoSupervisor.softTimeoutMinutes&&` (${n.autoSupervisor.softTimeoutMinutes}m)`]}):(0,r.jsx)("span",{className:"text-muted-foreground",children:"off"})}),(0,r.jsx)(i3,{label:"UAT Dispatch",children:(0,r.jsx)("span",{className:n.uatDispatch?"text-success":"text-muted-foreground",children:n.uatDispatch?"on":"off"})}),(0,r.jsx)(i3,{label:"Auto-Visualize",children:(0,r.jsx)("span",{className:n.autoVisualize?"text-success":"text-muted-foreground",children:n.autoVisualize?"on":"off"})}),(0,r.jsx)(i3,{label:"Preference Scope",children:(0,r.jsx)("span",{className:"font-mono text-[10px]",children:n.scope})})]}),(0,r.jsxs)("div",{className:"text-[11px] text-muted-foreground truncate font-mono",children:["Source: ",n.path]}),n.warnings&&n.warnings.length>0&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-xs text-warning",children:[(0,r.jsx)(sA.A,{className:"h-3 w-3"}),(0,r.jsxs)("span",{className:"font-medium",children:["Warnings (",n.warnings.length,")"]})]}),n.warnings.map((e,t)=>(0,r.jsx)("div",{className:"rounded border border-warning/20 bg-warning/5 px-2.5 py-1.5 text-[11px] text-warning",children:e},t))]})]})]})}function i7({tier:e,modelId:t}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-4 text-xs",children:[(0,r.jsx)("span",{className:"text-muted-foreground capitalize",children:e}),(0,r.jsx)("span",{className:"font-mono text-[11px] text-foreground/80 truncate max-w-[200px]",children:t??(0,r.jsx)("span",{className:"text-muted-foreground italic",children:"default"})})]})}function i9({tier:e,success:t,fail:s}){return 0===t+s?null:(0,r.jsxs)(nI,{variant:"outline",className:L("text-[10px] px-1.5 py-0 font-mono",s>0?"border-destructive/20 text-destructive":"text-muted-foreground"),children:[e,": ",t,"✓",s>0&&(0,r.jsxs)("span",{children:[" ",s,"✗"]})]})}function oe(){let{state:e,data:t,busy:s,refresh:a}=i4(),n=t?.routingConfig??null,i=t?.routingHistory??null;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"settings-model-routing",children:[(0,r.jsx)(iQ,{title:"Model Routing",icon:(0,r.jsx)(aK.A,{className:"h-3.5 w-3.5"}),onRefresh:a,refreshing:s}),e.error&&(0,r.jsx)(iX,{message:e.error}),s&&!t&&(0,r.jsx)(iZ,{label:"Loading routing config…"}),t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"flex items-center gap-2",children:(0,r.jsxs)(nI,{variant:n?.enabled?"secondary":"outline",className:L("text-[10px] px-2 py-0.5",n?.enabled?"border-success/30 text-success":"text-muted-foreground"),children:["Dynamic Routing: ",n?.enabled?"enabled":"disabled"]})}),n?.tier_models&&(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Tier Assignments"}),(0,r.jsx)(i7,{tier:"light",modelId:n.tier_models.light}),(0,r.jsx)(i7,{tier:"standard",modelId:n.tier_models.standard}),(0,r.jsx)(i7,{tier:"heavy",modelId:n.tier_models.heavy})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,r.jsx)(i5,{label:"escalate_on_failure",enabled:n?.escalate_on_failure}),(0,r.jsx)(i5,{label:"budget_pressure",enabled:n?.budget_pressure}),(0,r.jsx)(i5,{label:"cross_provider",enabled:n?.cross_provider}),(0,r.jsx)(i5,{label:"hooks",enabled:n?.hooks})]}),i?(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(i1,{label:"Patterns",value:Object.keys(i.patterns).length}),(0,r.jsx)(i1,{label:"Feedback",value:i.feedback.length})]}),Object.keys(i.patterns).length>0&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground",children:"Top Patterns"}),(0,r.jsx)("div",{className:"space-y-2",children:(function(e,t=5){return Object.entries(e.patterns).map(([e,t])=>({name:e,total:t.light.success+t.light.fail+t.standard.success+t.standard.fail+t.heavy.success+t.heavy.fail,pattern:t})).sort((e,t)=>t.total-e.total).slice(0,t)})(i).map(({name:e,total:t,pattern:s})=>(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-xs font-mono text-foreground/80 truncate",children:e}),(0,r.jsxs)("span",{className:"text-[10px] text-muted-foreground tabular-nums shrink-0",children:[t," attempts"]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,r.jsx)(i9,{tier:"L",success:s.light.success,fail:s.light.fail}),(0,r.jsx)(i9,{tier:"S",success:s.standard.success,fail:s.standard.fail}),(0,r.jsx)(i9,{tier:"H",success:s.heavy.success,fail:s.heavy.fail})]})]},e))})]})]}):(0,r.jsx)(i0,{message:"No routing history yet"})]})]})}function ot(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function os(){var e;let{state:t,data:s,busy:a,refresh:n}=i4(),i=s?.preferences??null,o=s?.budgetAllocation??null,l=s?.projectTotals??null;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"settings-budget",children:[(0,r.jsx)(iQ,{title:"Budget & Costs",icon:(0,r.jsx)(sr.A,{className:"h-3.5 w-3.5"}),onRefresh:n,refreshing:a}),t.error&&(0,r.jsx)(iX,{message:t.error}),a&&!s&&(0,r.jsx)(iZ,{label:"Loading budget data…"}),s&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(i1,{label:"Ceiling",value:i?.budgetCeiling!=null?eX(i.budgetCeiling):"Not set",variant:i?.budgetCeiling!=null?"warning":"default"}),(0,r.jsx)(i1,{label:"Enforcement",value:i?.budgetEnforcement??"Not set",variant:i?.budgetEnforcement?"halt"===(e=i.budgetEnforcement)?"warning":"pause"===e?"info":"success":"default"}),(0,r.jsx)(i1,{label:"Token Profile",value:i?.tokenProfile??"balanced",variant:i8(i?.tokenProfile)})]}),o&&(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Context Budget Allocations"}),(0,r.jsxs)(i3,{label:"Summary Budget",children:[ot(o.summaryBudgetChars)," chars"]}),(0,r.jsxs)(i3,{label:"Inline Context",children:[ot(o.inlineContextBudgetChars)," chars"]}),(0,r.jsxs)(i3,{label:"Verification",children:[ot(o.verificationBudgetChars)," chars"]}),(0,r.jsxs)(i3,{label:"Task Count Range",children:[o.taskCountRange.min,"–",o.taskCountRange.max]}),(0,r.jsxs)(i3,{label:"Continue Threshold",children:[o.continueThresholdPercent,"%"]})]}),l?(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Project Cost Totals"}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(i1,{label:"Units",value:l.units}),(0,r.jsx)(i1,{label:"Total Cost",value:eX(l.cost),variant:"warning"}),(0,r.jsx)(i1,{label:"Duration",value:`${Math.round(l.duration/1e3)}s`})]}),(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Token Breakdown"}),(0,r.jsx)(i3,{label:"Input",children:eQ(l.tokens.input)}),(0,r.jsx)(i3,{label:"Output",children:eQ(l.tokens.output)}),(0,r.jsx)(i3,{label:"Cache Read",children:eQ(l.tokens.cacheRead)}),(0,r.jsx)(i3,{label:"Cache Write",children:eQ(l.tokens.cacheWrite)}),(0,r.jsx)(i3,{label:"Total",children:eQ(l.tokens.total)})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(i1,{label:"Tool Calls",value:l.toolCalls}),(0,r.jsx)(i1,{label:"Assistant Msgs",value:l.assistantMessages}),(0,r.jsx)(i1,{label:"User Msgs",value:l.userMessages})]})]}):(0,r.jsx)(i0,{message:"No execution metrics yet"})]})]})}let or=[{value:"slack",label:"Slack",description:"Get pinged in a Slack channel",idPlaceholder:"Channel ID (e.g. C01ABCD2EFG)"},{value:"discord",label:"Discord",description:"Get pinged in a Discord channel",idPlaceholder:"Channel ID (17–20 digit number)"},{value:"telegram",label:"Telegram",description:"Get pinged via Telegram bot",idPlaceholder:"Chat ID (numeric, may start with -)"}],oa={slack:/^[A-Z0-9]{9,12}$/,discord:/^\d{17,20}$/,telegram:/^-?\d{5,20}$/};function on(){let{data:e,busy:t,refresh:s}=i4(),a=e?.preferences?.remoteQuestions??null,[i,o]=(0,n.useState)(!1),[d,c]=(0,n.useState)(null),[u,m]=(0,n.useState)(!0),[x,h]=(0,n.useState)(!1),[p,g]=(0,n.useState)("slack"),[f,b]=(0,n.useState)(""),[v,j]=(0,n.useState)(5),[y,N]=(0,n.useState)(5),[w,k]=(0,n.useState)(""),[S,C]=(0,n.useState)(!1),[A,T]=(0,n.useState)(!1),[R,P]=(0,n.useState)(null),[_,I]=(0,n.useState)(!1),[$,D]=(0,n.useState)(!1),[F,M]=(0,n.useState)(null),[q,O]=(0,n.useState)(null),[U,z]=(0,n.useState)(!1),[B,G]=(0,n.useState)(!1),W=(0,n.useCallback)(async()=>{try{m(!0);let e=await e$("/api/remote-questions",{cache:"no-store"});if(!e.ok){let t=await e.json().catch(()=>({error:"Unknown error"}));M(t.error??`API error ${e.status}`);return}let t=await e.json();o(t.envVarSet),c(t.envVarName),h(t.tokenSet),z("configured"===t.status&&null!==t.config),t.config&&(g(t.config.channel),b(t.config.channelId),j(t.config.timeoutMinutes),N(t.config.pollIntervalSeconds))}catch(e){M(e instanceof Error?e.message:"Failed to fetch remote questions status")}finally{m(!1)}},[]);(0,n.useEffect)(()=>{W()},[W]),(0,n.useEffect)(()=>{a?.channel&&(g(a.channel),b(a.channelId??""),j(a.timeoutMinutes??5),N(a.pollIntervalSeconds??5))},[a]);let K=f.trim().length>0&&oa[p].test(f.trim())&&!_&&!$;(0,n.useEffect)(()=>{if(!q)return;let e=setTimeout(()=>O(null),3e3);return()=>clearTimeout(e)},[q]);let H=async()=>{I(!0),M(null),O(null);try{let e=await e$("/api/remote-questions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:p,channelId:f.trim(),timeoutMinutes:v,pollIntervalSeconds:y})}),t=await e.json();if(!e.ok)return void M(t.error??`Save failed (${e.status})`);O("Configuration saved"),z(!0),s(),W()}catch(e){M(e instanceof Error?e.message:"Failed to save configuration")}finally{I(!1)}},V=async()=>{D(!0),M(null),O(null);try{let e=await e$("/api/remote-questions",{method:"DELETE"}),t=await e.json();if(!e.ok)return void M(t.error??`Disconnect failed (${e.status})`);O("Channel disconnected"),z(!1),b(""),j(5),N(5),g("slack"),h(!1),s(),W()}catch(e){M(e instanceof Error?e.message:"Failed to disconnect channel")}finally{D(!1)}},Y=async()=>{if(w.trim()){T(!0),M(null),P(null);try{let e=await e$("/api/remote-questions",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:p,token:w.trim()})}),t=await e.json();if(!e.ok)return void M(t.error??`Token save failed (${e.status})`);P(`Token saved (${t.masked})`),h(!0),k(""),C(!1),W()}catch(e){M(e instanceof Error?e.message:"Failed to save token")}finally{T(!1)}}};(0,n.useEffect)(()=>{if(!R)return;let e=setTimeout(()=>P(null),3e3);return()=>clearTimeout(e)},[R]);let Q=d??`${p.toUpperCase()}_BOT_TOKEN`,X=or.find(e=>e.value===p);return(t||u)&&!e&&!U?(0,r.jsxs)("div",{className:"space-y-5","data-testid":"settings-remote-questions",children:[(0,r.jsx)(iQ,{title:"Integrations",icon:(0,r.jsx)(id.A,{className:"h-3.5 w-3.5"}),subtitle:"Remote notifications",onRefresh:()=>{s(),W()},refreshing:!0}),(0,r.jsx)(iZ,{label:"Loading integration status…"})]}):(0,r.jsxs)("div",{className:"space-y-5","data-testid":"settings-remote-questions",children:[(0,r.jsx)(iQ,{title:"Integrations",icon:(0,r.jsx)(id.A,{className:"h-3.5 w-3.5"}),subtitle:"Remote notifications",onRefresh:()=>{s(),W()},refreshing:t||u}),(0,r.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Connect a chat channel so the agent pings you when it needs input instead of waiting silently."}),F&&(0,r.jsx)(iX,{message:F}),q&&(0,r.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-success/15 bg-success/[0.04] px-4 py-3 text-sm text-muted-foreground",children:[(0,r.jsx)(l.A,{className:"h-4 w-4 shrink-0 text-success"}),q]}),U&&(0,r.jsxs)("div",{className:"rounded-xl border border-success/15 bg-success/[0.04] px-4 py-4",children:[(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg border border-success/20 bg-success/10",children:(0,r.jsx)(l.A,{className:"h-4.5 w-4.5 text-success"})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"text-sm font-medium text-foreground",children:["Connected to ",X.label]}),(0,r.jsx)("div",{className:"mt-0.5 font-mono text-[11px] text-muted-foreground",children:f})]})]}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>void V(),disabled:$,className:"h-7 text-xs text-destructive/70 hover:text-destructive",children:$?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):"Disconnect"})]}),(0,r.jsxs)("div",{className:"mt-3 flex gap-4 border-t border-success/10 pt-3 text-[11px] text-muted-foreground",children:[(0,r.jsxs)("span",{children:["Timeout: ",v,"m"]}),(0,r.jsxs)("span",{children:["Poll: ",y,"s"]})]})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:U?"Switch channel":"Choose a channel"}),(0,r.jsx)("div",{className:"grid grid-cols-3 gap-2",children:or.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{g(e.value),M(null)},disabled:_,className:L("rounded-xl border px-3 py-3 text-left transition-all duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-[0.97]",p===e.value?"border-foreground/30 bg-foreground/[0.06]":"border-border/50 bg-card/50 hover:border-foreground/15 hover:bg-card/50"),children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:e.label}),(0,r.jsx)("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:e.description})]},e.value))})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Channel ID"}),(0,r.jsx)("input",{type:"text",value:f,onChange:e=>{b(e.target.value),F&&M(null)},placeholder:X.idPlaceholder,disabled:_,className:L("w-full rounded-xl border bg-card/50 px-4 py-2.5 font-mono text-sm text-foreground","placeholder:text-muted-foreground","focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent","transition-colors",f.trim().length>0&&!oa[p].test(f.trim())?"border-destructive/40":"border-border/50"),onKeyDown:e=>{"Enter"===e.key&&K&&H()}}),f.trim().length>0&&!oa[p].test(f.trim())&&(0,r.jsxs)("p",{className:"text-[11px] text-destructive/70",children:["Doesn't match the expected format for ",X.label]})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>G(e=>!e),className:"flex items-center gap-1.5 text-[11px] text-muted-foreground hover:text-muted-foreground transition-colors",children:[(0,r.jsx)("svg",{className:L("h-3 w-3 transition-transform",B&&"rotate-90"),viewBox:"0 0 16 16",fill:"currentColor",children:(0,r.jsx)("path",{d:"M6 4l4 4-4 4"})}),"Advanced settings"]}),B&&(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-3 pl-4",children:[(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsx)("label",{className:"text-[11px] text-muted-foreground",htmlFor:"rq-timeout",children:"Timeout (min)"}),(0,r.jsx)("input",{id:"rq-timeout",type:"number",min:1,max:30,value:v,onChange:e=>j(Math.max(1,Math.min(30,Number(e.target.value)||1))),className:"w-full rounded-lg border border-border/50 bg-card/50 px-3 py-2 text-xs text-foreground tabular-nums focus:outline-none focus:ring-2 focus:ring-ring"})]}),(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsx)("label",{className:"text-[11px] text-muted-foreground",htmlFor:"rq-poll",children:"Poll interval (sec)"}),(0,r.jsx)("input",{id:"rq-poll",type:"number",min:2,max:30,value:y,onChange:e=>N(Math.max(2,Math.min(30,Number(e.target.value)||2))),className:"w-full rounded-lg border border-border/50 bg-card/50 px-3 py-2 text-xs text-foreground tabular-nums focus:outline-none focus:ring-2 focus:ring-ring"})]})]}),f.trim().length>0&&(0,r.jsxs)(J,{type:"button",onClick:()=>void H(),disabled:!K,className:"gap-2 transition-transform active:scale-[0.96]",children:[_?(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}):(0,r.jsx)(l.A,{className:"h-4 w-4"}),U?"Update connection":"Save & connect"]}),(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Bot token"}),R&&(0,r.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-success/15 bg-success/[0.04] px-4 py-2.5 text-xs text-muted-foreground",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 shrink-0 text-success"}),R]}),x&&!R&&(0,r.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-success/15 bg-success/[0.04] px-4 py-2.5 text-xs text-muted-foreground",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 shrink-0 text-success"}),(0,r.jsx)("span",{className:"font-mono text-[11px]",children:Q})," is configured"]}),!x&&(0,r.jsxs)("div",{className:"flex items-center gap-2.5 rounded-xl border border-warning/15 bg-warning/[0.04] px-4 py-2.5 text-xs text-muted-foreground",children:[(0,r.jsx)(sA.A,{className:"h-3.5 w-3.5 shrink-0 text-warning"}),(0,r.jsxs)("span",{children:[(0,r.jsx)("span",{className:"font-mono text-[11px]",children:Q})," not configured"]})]}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsxs)("div",{className:"relative flex-1",children:[(0,r.jsx)("input",{type:S?"text":"password",value:w,onChange:e=>k(e.target.value),placeholder:`Paste your ${X.label} bot token`,disabled:A,className:L("w-full rounded-xl border border-border/50 bg-card/50 pl-4 pr-10 py-2.5 font-mono text-sm text-foreground","placeholder:text-muted-foreground","focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent","transition-colors"),onKeyDown:e=>{"Enter"===e.key&&w.trim()&&Y()}}),(0,r.jsx)("button",{type:"button",onClick:()=>C(e=>!e),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-muted-foreground transition-colors",children:S?(0,r.jsx)(rS.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(rC.A,{className:"h-3.5 w-3.5"})})]}),(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>void Y(),disabled:!w.trim()||A,className:"h-[42px] gap-1.5 px-4",children:[A?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(nF.A,{className:"h-3.5 w-3.5"}),"Save"]})]})]})]})}let oi=[11,12,13,14,15,16],oo=[11,12,13,14,15,16];function ol({label:e,description:t,presets:s,defaultSize:a,currentSize:n,onChange:i,previewFont:o}){return(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-3 space-y-3",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-xs font-medium text-foreground",children:e}),(0,r.jsx)("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:t})]}),(0,r.jsx)("div",{className:"flex flex-wrap gap-1.5",children:s.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>i(e),className:L("rounded-md border px-3 py-1.5 text-xs font-medium tabular-nums transition-colors",n===e?"border-foreground/30 bg-foreground/10 text-foreground shadow-sm":"border-border/50 bg-card/50 text-muted-foreground hover:border-foreground/20 hover:text-foreground"),children:[e,"px",e===a&&(0,r.jsx)("span",{className:"ml-1 text-[10px] text-muted-foreground",children:"(default)"})]},e))}),(0,r.jsx)("div",{className:L("mt-2 rounded-md border border-border/50 bg-terminal px-3 py-2 text-foreground/80","mono"===o?"font-mono":"font-sans"),style:{fontSize:`${n}px`,lineHeight:1.35},children:"The quick brown fox jumps over the lazy dog"})]})}function od(){let[e,t]=rB(),[s,a]=s8();return(0,r.jsxs)("div",{className:"space-y-5","data-testid":"settings-general",children:[(0,r.jsx)(iQ,{title:"General",icon:(0,r.jsx)(rj.A,{className:"h-3.5 w-3.5"}),subtitle:"Appearance & behavior",onRefresh:()=>{},refreshing:!1}),(0,r.jsx)(ol,{label:"Terminal font size",description:"Applies to all terminals and the chat mode interface",presets:oi,defaultSize:13,currentSize:e,onChange:t,previewFont:"mono"}),(0,r.jsx)(ol,{label:"Code font size",description:"Applies to the file viewer and code editor",presets:oo,defaultSize:14,currentSize:s,onChange:a,previewFont:"mono"})]})}let oc=[{key:"rtk",label:"RTK Shell Compression",description:"Wraps shell commands through the RTK binary to reduce token usage during command execution. RTK is downloaded automatically on first use.",warning:"Experimental — may change or be removed without notice."}];function ou(){let{state:e,data:t,busy:s,refresh:a}=i4(),i=t?.preferences??null,[o,l]=(0,n.useState)({}),[d,c]=(0,n.useState)({}),[u,m]=(0,n.useState)(null);async function x(e,t){c(t=>({...t,[e]:!0})),m(null);try{let s=await e$("/api/experimental",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({flag:e,enabled:t})});if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`HTTP ${s.status}`)}l(s=>({...s,[e]:t})),a()}catch(e){m(e instanceof Error?e.message:String(e))}finally{c(t=>({...t,[e]:!1}))}}return(0,n.useEffect)(()=>{t||s||"idle"!==e.phase||a()},[]),(0,n.useEffect)(()=>{i&&l({rtk:i.experimental?.rtk===!0})},[i]),(0,r.jsxs)("div",{className:"space-y-4","data-testid":"settings-experimental",children:[(0,r.jsx)(iQ,{title:"Experimental",icon:(0,r.jsx)(ic.A,{className:"h-3.5 w-3.5"}),subtitle:"Opt-in features — may change without notice",onRefresh:a,refreshing:s}),e.error&&(0,r.jsx)(iX,{message:e.error}),u&&(0,r.jsx)(iX,{message:u}),s&&!t&&(0,r.jsx)(iZ,{label:"Loading preferences…"}),(0,r.jsx)("div",{className:"space-y-3",children:oc.map(e=>{let a=o[e.key]??!1,n=d[e.key]??!1;return(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-3 space-y-2",children:(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-xs font-medium text-foreground",children:e.label}),(0,r.jsx)("span",{className:L("rounded-full px-1.5 py-0.5 text-[10px] font-medium",a?"bg-success/10 text-success":"bg-muted text-muted-foreground"),children:a?"on":"off"})]}),(0,r.jsx)("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:e.description}),e.warning&&(0,r.jsxs)("div",{className:"flex items-center gap-1 text-[10px] text-warning",children:[(0,r.jsx)(sA.A,{className:"h-3 w-3 shrink-0"}),(0,r.jsx)("span",{children:e.warning})]})]}),(0,r.jsxs)("button",{onClick:()=>x(e.key,!a),disabled:n||s||!t,className:L("shrink-0 relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 disabled:cursor-not-allowed",a?"bg-success":"bg-muted-foreground/30"),role:"switch","aria-checked":a,"aria-label":`Toggle ${e.label}`,children:[(0,r.jsx)("span",{className:L("inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-transform",a?"translate-x-4":"translate-x-0.5")}),n&&(0,r.jsx)("span",{className:"absolute inset-0 flex items-center justify-center",children:(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin text-white"})})]})]})},e.key)})}),t&&(0,r.jsxs)("p",{className:"text-[11px] text-muted-foreground",children:["Changes are written to"," ",(0,r.jsx)("span",{className:"font-mono",children:i?.path??"~/.gsd/PREFERENCES.md"})," ","and take effect on the next session."]})]})}let om={"active-gsd":{label:"Active",color:"text-success",bgClass:"bg-success/10",icon:av.A},"empty-gsd":{label:"Initialized",color:"text-info",bgClass:"bg-info/10",icon:sg.A},brownfield:{label:"Existing",color:"text-warning",bgClass:"bg-warning/10",icon:N.A},"v1-legacy":{label:"Legacy",color:"text-warning",bgClass:"bg-warning/10",icon:sf.A},blank:{label:"New",color:"text-muted-foreground",bgClass:"bg-foreground/[0.04]",icon:sb.A}};function ox(e){let t=[];return e.isMonorepo&&t.push("Monorepo"),e.hasGitRepo&&t.push("Git"),e.hasPackageJson&&t.push("Node.js"),e.hasCargo&&t.push("Rust"),e.hasGoMod&&t.push("Go"),e.hasPyproject&&t.push("Python"),t}function oh(e){if(0===e.milestonesTotal)return null;let t=[];return e.activeMilestone&&t.push(e.activeMilestone),e.activeSlice&&t.push(e.activeSlice),e.phase&&t.push(e.phase),t.join(" \xb7 ")||null}function op({project:e,isActive:t=!1,onClick:s,disabled:a=!1}){let n=om[e.kind],i=n.icon,o=ox(e.signals),d=e.progress?oh(e.progress):null,c=e.progress?`${e.progress.milestonesCompleted}/${e.progress.milestonesTotal}`:null;return(0,r.jsxs)("button",{type:"button",onClick:s,disabled:a,className:L("group flex w-full items-start gap-3.5 rounded-xl border px-4 py-3.5 text-left transition-all duration-200","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-[0.98]",t?"border-primary/30 bg-primary/[0.08]":"border-border/50 bg-card/50 hover:border-foreground/15 hover:bg-card/50",a&&"opacity-40 pointer-events-none"),children:[(0,r.jsx)("div",{className:L("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg mt-0.5",t?"bg-primary/15":n.bgClass),children:t?(0,r.jsx)(l.A,{className:"h-4 w-4 text-primary"}):(0,r.jsx)(i,{className:L("h-4 w-4",n.color)})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground truncate",children:e.name}),(0,r.jsx)("span",{className:L("text-[10px] font-medium shrink-0",t?"text-primary":n.color),children:t?"Current":n.label})]}),o.length>0&&(0,r.jsx)("div",{className:"mt-1 flex items-center gap-1.5",children:o.map(e=>(0,r.jsx)("span",{className:"rounded bg-foreground/[0.06] px-1.5 py-0.5 text-[10px] text-muted-foreground",children:e},e))}),d&&(0,r.jsx)("div",{className:"mt-1.5 text-[11px] text-muted-foreground",children:d}),e.progress&&e.progress.milestonesTotal>0&&(0,r.jsxs)("div",{className:"mt-2 flex items-center gap-2",children:[(0,r.jsx)("div",{className:"h-1 flex-1 overflow-hidden rounded-full bg-foreground/[0.08]",children:(0,r.jsx)("div",{className:"h-full rounded-full bg-success/70 transition-all",style:{width:`${Math.round(e.progress.milestonesCompleted/e.progress.milestonesTotal*100)}%`}})}),(0,r.jsx)("span",{className:"text-[10px] tabular-nums text-muted-foreground",children:c})]})]}),(0,r.jsx)(sy.A,{className:"mt-1 h-4 w-4 shrink-0 text-muted-foreground/50 transition-all group-hover:text-muted-foreground group-hover:translate-x-0.5"})]})}function og({open:e,onOpenChange:t}){let s,a=tF(),o=(0,n.useSyncExternalStore)(a.subscribe,a.getSnapshot,a.getSnapshot),[l,d]=(0,n.useState)([]),[c,u]=(0,n.useState)(null),[m,x]=(0,n.useState)(!0),[h,p]=(0,n.useState)(null),g=(0,n.useCallback)(async e=>{let t=await e$(`/api/projects?root=${encodeURIComponent(e)}&detail=true`);if(!t.ok)throw Error(`Failed to discover projects: ${t.status}`);return await t.json()},[]);(0,n.useEffect)(()=>{if(!e)return;let t=!1;return async function(){x(!0),p(null);try{let e=await e$("/api/preferences");if(!e.ok)throw Error(`Failed to load preferences: ${e.status}`);let s=await e.json();if(!s.devRoot){u(null),d([]),x(!1);return}u(s.devRoot);let r=await g(s.devRoot);t||d(r)}catch(e){t||p(e instanceof Error?e.message:"Unknown error")}finally{t||x(!1)}}(),()=>{t=!0}},[e,g]);let f=(0,n.useCallback)(async e=>{x(!0),p(null);try{let t=await e$("/api/switch-root",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({devRoot:e})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Request failed (${t.status})`)}let s=await t.json();u(s.devRoot),d(s.projects)}catch(e){p(e instanceof Error?e.message:"Failed to switch project root")}finally{x(!1)}},[]),[b,v]=(0,n.useState)(!1),[j,y]=(0,n.useState)(!1);tb();let N=(0,n.useCallback)(e=>{d(t=>[...t,e].sort((e,t)=>e.name.localeCompare(t.name))),v(!1),w(e)},[]);function w(e){o===e.path?t(!1):(t(!1),a.switchProject(e.path),window.dispatchEvent(new CustomEvent("gsd:navigate-view",{detail:{view:"dashboard"}})))}let k=[...l].sort((e,t)=>{let s={"active-gsd":0,"empty-gsd":1,brownfield:2,"v1-legacy":3,blank:4},r=s[e.kind]??5,a=s[t.kind]??5;return r!==a?r-a:e.name.localeCompare(t.name)});return s=m?(0,r.jsxs)("div",{className:"flex items-center justify-center gap-2 py-16 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}),"Discovering projects…"]}):h?(0,r.jsxs)("div",{className:"flex flex-col items-center gap-3 px-5 py-16 text-center",children:[(0,r.jsx)(sq.A,{className:"h-8 w-8 text-destructive"}),(0,r.jsx)("p",{className:"text-sm text-destructive",children:h})]}):c?0===k.length?(0,r.jsxs)("div",{className:"flex flex-col items-center gap-4 px-5 py-16 text-center",children:[(0,r.jsx)("div",{className:"flex h-14 w-14 items-center justify-center rounded-2xl bg-muted",children:(0,r.jsx)(sg.A,{className:"h-7 w-7 text-muted-foreground"})}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h3",{className:"text-base font-semibold text-foreground",children:"No projects found"}),(0,r.jsxs)("p",{className:"text-sm text-muted-foreground leading-relaxed",children:["No project directories discovered in"," ",(0,r.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-xs font-mono text-foreground",children:c})]})]})]}):(0,r.jsxs)("div",{className:"space-y-2",children:[k.map(e=>(0,r.jsx)(op,{project:e,isActive:o===e.path,onClick:()=>w(e)},e.path)),(0,r.jsxs)("button",{type:"button",onClick:()=>v(!0),className:L("flex w-full items-center gap-3.5 rounded-xl border border-dashed px-4 py-3.5 text-left transition-all duration-200","border-border/50 text-muted-foreground hover:border-foreground/15 hover:text-foreground","active:scale-[0.98]"),children:[(0,r.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-foreground/[0.04]",children:(0,r.jsx)(tK.A,{className:"h-4 w-4"})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("span",{className:"text-sm font-medium",children:"Create new project"}),(0,r.jsx)("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Initialize a new directory with Git"})]})]}),(0,r.jsx)(of,{open:b,onOpenChange:v,devRoot:c,existingNames:l.map(e=>e.name),onCreated:N})]}):(0,r.jsx)(ov,{onSaved:f}),(0,r.jsx)(na,{open:e,onOpenChange:t,children:(0,r.jsxs)(no,{side:"left",className:"flex h-full w-full flex-col p-0 sm:max-w-[420px]","data-testid":"projects-panel",children:[(0,r.jsxs)(nl,{className:"sr-only",children:[(0,r.jsx)(nc,{children:"Projects"}),(0,r.jsx)(nu,{children:"Switch between projects or create a new one"})]}),(0,r.jsxs)("div",{className:"flex items-center justify-between border-b border-border/50 px-5 py-4",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-base font-semibold text-foreground",children:"Projects"}),c&&!m&&(0,r.jsxs)("div",{className:"mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,r.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[10px] truncate max-w-[200px]",children:c}),(0,r.jsx)("button",{type:"button",onClick:()=>y(!0),className:"shrink-0 text-[10px] text-primary hover:text-primary/80 transition-colors font-medium","data-testid":"projects-panel-change-root",children:"Change"}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"\xb7"}),(0,r.jsxs)("span",{children:[l.length," project",1!==l.length?"s":""]})]})]}),(0,r.jsx)(J,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>t(!1),children:(0,r.jsx)(i.A,{className:"h-4 w-4"})})]}),(0,r.jsx)(nK,{className:"min-h-0 flex-1",children:(0,r.jsx)("div",{className:"px-5 py-4",children:s})}),(0,r.jsx)(ob,{open:j,onOpenChange:y,onSelect:e=>void f(e),initialPath:c})]})})}function of({open:e,onOpenChange:t,devRoot:s,existingNames:a,onCreated:i}){let[o,l]=(0,n.useState)(""),[d,c]=(0,n.useState)(!1),[u,m]=(0,n.useState)(null),x=(0,n.useRef)(null);(0,n.useEffect)(()=>{if(e){l(""),m(null),c(!1);let e=setTimeout(()=>x.current?.focus(),100);return()=>clearTimeout(e)}},[e]);let h=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o),p=a.includes(o),g=o.length>0&&h&&!p&&!d,f=o?p?"A project with this name already exists":h?null:"Use letters, numbers, hyphens, underscores, dots. Must start with a letter or number.":null;async function b(){if(g){c(!0),m(null);try{let e=await e$("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({devRoot:s,name:o})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Failed (${e.status})`)}let t=await e.json();i(t)}catch(e){m(e instanceof Error?e.message:"Failed to create project"),c(!1)}}}return(0,r.jsx)(M,{open:e,onOpenChange:t,children:(0,r.jsxs)(U,{className:"sm:max-w-md",children:[(0,r.jsxs)(z,{children:[(0,r.jsx)(G,{children:"New Project"}),(0,r.jsxs)(W,{children:["Create a new project directory in"," ",(0,r.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs font-mono",children:s})]})]}),(0,r.jsx)("form",{onSubmit:e=>{e.preventDefault(),b()},className:"space-y-4 py-2",children:(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)(ne,{htmlFor:"project-name",children:"Project name"}),(0,r.jsx)(rP,{ref:x,id:"project-name",placeholder:"my-project",value:o,onChange:e=>{l(e.target.value),m(null)},autoComplete:"off","aria-invalid":!!f}),f&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:f}),u&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:u}),o&&h&&!p&&(0,r.jsxs)("p",{className:"text-xs text-muted-foreground font-mono",children:[s,"/",o]})]})}),(0,r.jsxs)(B,{children:[(0,r.jsx)(J,{variant:"ghost",size:"sm",onClick:()=>t(!1),disabled:d,children:"Cancel"}),(0,r.jsxs)(J,{size:"sm",onClick:()=>void b(),disabled:!g,className:"gap-1.5",children:[d?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(tK.A,{className:"h-3.5 w-3.5"}),"Create"]})]})]})})}function ob({open:e,onOpenChange:t,onSelect:s,initialPath:a}){let[i,o]=(0,n.useState)(""),[l,d]=(0,n.useState)(null),[c,u]=(0,n.useState)([]),[m,x]=(0,n.useState)(!1),[h,p]=(0,n.useState)(null),g=(0,n.useCallback)(async e=>{x(!0),p(null);try{let t=e?`?path=${encodeURIComponent(e)}`:"",s=await e$(`/api/browse-directories${t}`);if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`${s.status}`)}let r=await s.json();o(r.current),d(r.parent),u(r.entries)}catch(e){p(e instanceof Error?e.message:"Failed to browse")}finally{x(!1)}},[]);return(0,n.useEffect)(()=>{e&&g(a??void 0)},[e,a,g]),(0,r.jsx)(M,{open:e,onOpenChange:t,children:(0,r.jsxs)(U,{className:"sm:max-w-lg gap-0 p-0 overflow-hidden",children:[(0,r.jsxs)(z,{className:"px-5 pt-5 pb-3",children:[(0,r.jsx)(G,{className:"text-base",children:"Choose Folder"}),(0,r.jsx)(W,{className:"text-xs",children:"Navigate to the folder that contains your project directories."})]}),(0,r.jsx)("div",{className:"border-y border-border/50 bg-muted/50 px-5 py-2",children:(0,r.jsx)("p",{className:"font-mono text-xs text-muted-foreground truncate",title:i,children:i})}),(0,r.jsx)(nK,{className:"h-[320px]",children:(0,r.jsxs)("div",{className:"px-2 py-1",children:[m&&(0,r.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,r.jsx)(E.A,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),h&&(0,r.jsx)("div",{className:"px-3 py-4 text-center text-xs text-destructive",children:h}),!m&&!h&&(0,r.jsxs)(r.Fragment,{children:[l&&(0,r.jsxs)("button",{onClick:()=>void g(l),className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-accent/50",children:[(0,r.jsx)(nB.A,{className:"h-4 w-4 text-muted-foreground shrink-0"}),(0,r.jsx)("span",{className:"text-muted-foreground",children:".."})]}),c.map(e=>(0,r.jsxs)("button",{onClick:()=>void g(e.path),className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-accent/50 group",children:[(0,r.jsx)(b.A,{className:"h-4 w-4 text-muted-foreground shrink-0"}),(0,r.jsx)("span",{className:"text-foreground truncate flex-1",children:e.name}),(0,r.jsx)(A.A,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0"})]},e.path)),!l&&0===c.length&&(0,r.jsx)("div",{className:"px-3 py-8 text-center text-xs text-muted-foreground",children:"No subdirectories"})]})]})}),(0,r.jsxs)(B,{className:"border-t border-border/50 px-5 py-3",children:[(0,r.jsx)(J,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),(0,r.jsxs)(J,{size:"sm",onClick:()=>{s(i),t(!1)},disabled:!i,className:"gap-1.5",children:[(0,r.jsx)(sg.A,{className:"h-3.5 w-3.5"}),"Select This Folder"]})]})]})})}function ov({onSaved:e,currentRoot:t}){let[s,a]=(0,n.useState)(!1),[i,o]=(0,n.useState)(null),[d,c]=(0,n.useState)(!1),[u,m]=(0,n.useState)(!1),x=(0,n.useCallback)(async t=>{a(!0),o(null),c(!1);try{let s=await e$("/api/preferences",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({devRoot:t})});if(!s.ok){let e=await s.json().catch(()=>({}));throw Error(e.error??`Request failed (${s.status})`)}c(!0),e(t)}catch(e){o(e instanceof Error?e.message:"Failed to save preference")}finally{a(!1)}},[e]);return t?(0,r.jsxs)("div",{className:"space-y-3","data-testid":"devroot-settings",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("code",{className:"flex-1 truncate rounded border border-border/50 bg-muted/50 px-3 py-2 font-mono text-xs text-foreground",children:t}),(0,r.jsx)(J,{size:"sm",variant:"outline",onClick:()=>m(!0),disabled:s,className:"h-9 gap-1.5 shrink-0",children:s?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):d?(0,r.jsx)(l.A,{className:"h-3.5 w-3.5 text-success"}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sg.A,{className:"h-3.5 w-3.5"}),"Change"]})})]}),i&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:i}),d&&(0,r.jsx)("p",{className:"text-xs text-success",children:"Dev root updated"}),(0,r.jsx)(ob,{open:u,onOpenChange:m,onSelect:e=>void x(e),initialPath:t})]}):(0,r.jsxs)("div",{className:"rounded-md border border-border bg-card p-6",children:[(0,r.jsxs)("div",{className:"flex items-start gap-4",children:[(0,r.jsx)("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md border border-border bg-accent",children:(0,r.jsx)(nG.A,{className:"h-5 w-5 text-muted-foreground"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:"Set your development root"}),(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground leading-relaxed",children:"Point GSD at the folder that contains your project directories. It scans one level deep."}),(0,r.jsx)(J,{onClick:()=>m(!0),disabled:s,size:"sm",className:"mt-3 gap-2","data-testid":"projects-devroot-browse",children:s?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sg.A,{className:"h-3.5 w-3.5"}),"Browse"]})}),i&&(0,r.jsx)("p",{className:"mt-2 text-xs text-destructive",children:i})]})]}),(0,r.jsx)(ob,{open:u,onOpenChange:m,onSelect:e=>void x(e)})]})}function oj(){let[e,t]=(0,n.useState)(null),[s,a]=(0,n.useState)(!0);return((0,n.useEffect)(()=>{e$("/api/preferences").then(e=>e.json()).then(e=>t(e.devRoot??null)).catch(()=>t(null)).finally(()=>a(!1))},[]),s)?(0,r.jsxs)("div",{className:"flex items-center gap-2 py-4 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),"Loading preferences…"]}):(0,r.jsxs)("div",{className:"space-y-3","data-testid":"settings-devroot",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)(nG.A,{className:"h-3.5 w-3.5 text-muted-foreground"}),(0,r.jsx)("h3",{className:"text-[13px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:"Development Root"})]}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"The parent folder containing your project directories. GSD scans one level deep for projects."}),(0,r.jsx)(ov,{currentRoot:e??"",onSaved:e=>t(e)})]})}function oy(){let e=tF(),[t,s]=(0,n.useState)([]),[i,o]=(0,n.useState)(null),[l,d]=(0,n.useState)(!0),[c,u]=(0,n.useState)(null),[m,x]=(0,n.useState)(!1),[h,p]=(0,n.useState)(!1),[g,f]=(0,n.useState)(""),b=(0,n.useCallback)(async e=>{let t=await e$(`/api/projects?root=${encodeURIComponent(e)}&detail=true`);if(!t.ok)throw Error(`Failed to discover projects: ${t.status}`);return await t.json()},[]);(0,n.useEffect)(()=>{let e=!1;return async function(){d(!0),u(null);try{let t=await e$("/api/preferences");if(!t.ok)throw Error(`Failed to load preferences: ${t.status}`);let r=await t.json();if(!r.devRoot){o(null),s([]),d(!1);return}o(r.devRoot);let a=await b(r.devRoot);e||s(a)}catch(t){e||u(t instanceof Error?t.message:"Unknown error")}finally{e||d(!1)}}(),()=>{e=!0}},[b]);let v=(0,n.useCallback)(async e=>{d(!0),u(null);try{let t=await e$("/api/switch-root",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({devRoot:e})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Request failed (${t.status})`)}let r=await t.json();o(r.devRoot),s(r.projects)}catch(e){u(e instanceof Error?e.message:"Failed to switch project root")}finally{d(!1)}},[]),j=(0,n.useCallback)(t=>{s(e=>[...e,t].sort((e,t)=>e.name.localeCompare(t.name))),x(!1),e.switchProject(t.path)},[e]),y=[...t].sort((e,t)=>{let s={"active-gsd":0,"empty-gsd":1,brownfield:2,"v1-legacy":3,blank:4},r=s[e.kind]??5,a=s[t.kind]??5;return r!==a?r-a:e.name.localeCompare(t.name)}),N=g.trim()?y.filter(e=>e.name.toLowerCase().includes(g.toLowerCase())):y,w=!l&&y.length>0,k=y.length>5;return(0,r.jsxs)("div",{className:"flex h-screen flex-col bg-background text-foreground","data-testid":"project-selection-gate",children:[(0,r.jsx)("div",{className:"flex-1 overflow-y-auto",children:(0,r.jsxs)("div",{className:"mx-auto max-w-2xl px-6 pt-16 pb-10 md:px-10 lg:pt-24",children:[(0,r.jsxs)("div",{className:"flex flex-col items-center text-center mb-10",children:[(0,r.jsx)(a.default,{src:"/logo-black.svg",alt:"GSD",width:100,height:28,className:"h-7 w-auto dark:hidden"}),(0,r.jsx)(a.default,{src:"/logo-white.svg",alt:"GSD",width:100,height:28,className:"h-7 w-auto hidden dark:block"}),(0,r.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:"Select a project to get started"})]}),l&&(0,r.jsxs)("div",{className:"flex items-center gap-3 py-20 justify-center text-sm text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-4 w-4 animate-spin"}),"Scanning for projects…"]}),c&&!l&&(0,r.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/[0.06] px-4 py-3 text-sm text-destructive",children:c}),!i&&!l&&!c&&(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:"Welcome to GSD"}),(0,r.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Set a development root to get started. GSD will discover projects inside it."})]}),(0,r.jsx)(ov,{onSaved:v})]}),i&&!l&&0===y.length&&!c&&(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:"No projects found"}),(0,r.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"No project directories were discovered. Create one to get started."})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>x(!0),className:"flex items-center gap-3 rounded-md border border-dashed border-border px-4 py-3 text-sm text-muted-foreground transition-colors hover:border-foreground/20 hover:text-foreground",children:[(0,r.jsx)(tK.A,{className:"h-4 w-4"}),"Create a new project"]})]}),w&&(0,r.jsxs)("div",{className:"space-y-5",children:[i&&(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,r.jsx)(nG.A,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,r.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground truncate",children:i}),(0,r.jsx)("button",{type:"button",onClick:()=>p(!0),className:"shrink-0 text-[11px] text-primary hover:text-primary/80 transition-colors font-medium","data-testid":"gate-change-root",children:"Change"})]}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,r.jsxs)("p",{className:"text-xs text-muted-foreground tabular-nums",children:[y.length," project",1!==y.length?"s":""]}),k&&(0,r.jsxs)("div",{className:"relative w-48",children:[(0,r.jsx)(iu.A,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),(0,r.jsx)("input",{type:"text",placeholder:"Filter…",value:g,onChange:e=>f(e.target.value),className:"h-8 w-full rounded-md border border-border bg-background pl-8 pr-3 text-xs text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"})]})]}),(0,r.jsxs)("div",{className:"rounded-md border border-border bg-card overflow-hidden divide-y divide-border",children:[N.map(t=>{let s=om[t.kind],a=s.icon,n=ox(t.signals),i=t.progress?oh(t.progress):null,o=t.progress&&t.progress.milestonesTotal>0,l=o?Math.round(t.progress.milestonesCompleted/t.progress.milestonesTotal*100):0;return(0,r.jsxs)("button",{type:"button",onClick:()=>{e.switchProject(t.path)},className:"group flex w-full items-center gap-4 px-4 py-3 text-left transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:bg-accent/50",children:[(0,r.jsx)("div",{className:L("flex h-8 w-8 shrink-0 items-center justify-center rounded-md",s.bgClass),children:(0,r.jsx)(a,{className:L("h-3.5 w-3.5",s.color)})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-foreground truncate",children:t.name}),(0,r.jsx)("span",{className:L("text-[10px] font-medium shrink-0",s.color),children:s.label})]}),(0,r.jsxs)("div",{className:"mt-0.5 flex items-center gap-2 text-[11px] text-muted-foreground",children:[n.length>0&&(0,r.jsx)("span",{children:n.join(" \xb7 ")}),n.length>0&&i&&(0,r.jsx)("span",{className:"text-muted-foreground/50",children:"—"}),i&&(0,r.jsx)("span",{className:"truncate",children:i})]})]}),o&&(0,r.jsxs)("div",{className:"hidden sm:flex items-center gap-2 shrink-0 w-24",children:[(0,r.jsx)("div",{className:"h-1 flex-1 overflow-hidden rounded-full bg-foreground/[0.08]",children:(0,r.jsx)("div",{className:"h-full rounded-full bg-success/70 transition-all",style:{width:`${l}%`}})}),(0,r.jsxs)("span",{className:"text-[10px] tabular-nums text-muted-foreground w-6 text-right",children:[t.progress.milestonesCompleted,"/",t.progress.milestonesTotal]})]}),t.lastModified>0&&(0,r.jsx)("span",{className:"hidden lg:inline text-[10px] text-muted-foreground shrink-0 w-16 text-right tabular-nums",children:function(e){let t=Date.now()-e;if(t<6e4)return"just now";let s=Math.floor(t/6e4);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);if(r<24)return`${r}h ago`;let a=Math.floor(r/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}(t.lastModified)}),(0,r.jsx)(A.A,{className:"h-4 w-4 shrink-0 text-muted-foreground/50 transition-colors group-hover:text-muted-foreground"})]},t.path)}),0===N.length&&g.trim()&&(0,r.jsxs)("div",{className:"px-4 py-8 text-center text-xs text-muted-foreground",children:['No projects matching "',g,'"']})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>x(!0),className:"flex items-center gap-3 rounded-md border border-dashed border-border px-4 py-2.5 text-sm text-muted-foreground transition-colors hover:border-foreground/20 hover:text-foreground w-full",children:[(0,r.jsx)(tK.A,{className:"h-3.5 w-3.5"}),"New project"]}),i&&(0,r.jsx)(of,{open:m,onOpenChange:x,devRoot:i,existingNames:t.map(e=>e.name),onCreated:j})]}),i&&!l&&0===y.length&&!c&&(0,r.jsx)("div",{className:"mt-4",children:(0,r.jsxs)("button",{type:"button",onClick:()=>p(!0),className:"flex items-center gap-2 text-xs text-primary hover:text-primary/80 transition-colors font-medium","data-testid":"gate-change-root-empty",children:[(0,r.jsx)(sg.A,{className:"h-3.5 w-3.5"}),"Change project root"]})})]})}),(0,r.jsx)(ob,{open:h,onOpenChange:p,onSelect:e=>void v(e),initialPath:i})]})}var oN=s(48144),ow=s(8195),ok=s(1709),oS=s(484);function oC({title:e,icon:t,subtitle:s,status:a,onRefresh:n,refreshing:i}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 pb-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:t}),(0,r.jsx)("h3",{className:"text-[13px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:e}),a,s&&(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:s})]}),n&&(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:n,disabled:i,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3",i&&"animate-spin")}),"Refresh"]})]})}function oA({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 text-xs text-destructive",children:e})}function oT({label:e}){return(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),e]})}function oR({message:e}){return(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-4 py-5 text-center text-xs text-muted-foreground",children:e})}function oE({label:e,value:t,variant:s}){return(0,r.jsxs)("div",{className:L("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs","info"===s&&"border-info/20 bg-info/5 text-info","warning"===s&&"border-warning/20 bg-warning/5 text-warning","success"===s&&"border-success/20 bg-success/5 text-success","error"===s&&"border-destructive/20 bg-destructive/5 text-destructive",(!s||"default"===s)&&"border-border/50 bg-card/50 text-foreground/80"),children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:e}),(0,r.jsx)("span",{className:"font-medium tabular-nums",children:t})]})}function oP(e){if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60),r=t%60;if(s<60)return r>0?`${s}m ${r}s`:`${s}m`;let a=Math.floor(s/60),n=s%60;return n>0?`${a}h ${n}m`:`${a}h`}function o_(){return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-quick",children:[(0,r.jsx)(oC,{title:"Quick Task",icon:(0,r.jsx)(sa.A,{className:"h-3.5 w-3.5"})}),(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-4 py-4 space-y-3",children:[(0,r.jsx)("p",{className:"text-xs text-foreground",children:"Create a quick one-off task outside the current plan. Useful for small fixes, experiments, or ad-hoc work that doesn't fit into the milestone structure."}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Usage"}),(0,r.jsx)("div",{className:"rounded-md border border-border/50 bg-background/50 px-3 py-2 font-mono text-[11px] text-foreground/80",children:"/gsd quick <description>"})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Examples"}),(0,r.jsx)("div",{className:"space-y-1.5",children:["Fix the typo in README.md header","Add .env.example with required keys","Update the LICENSE year to 2026","Run prettier on the whole project"].map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-2 text-[11px]",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:"$"}),(0,r.jsxs)("code",{className:"font-mono text-muted-foreground",children:["/gsd quick ",e]})]},e))})]}),(0,r.jsx)("div",{className:"rounded-md border border-info/15 bg-info/5 px-3 py-2 text-[11px] text-info/90",children:"Quick tasks run as standalone units — they don't affect milestone progress, slices, or the plan. Use them for work that should happen now without ceremony."})]})]})}function oI(){let e=tb(),{loadHistoryData:t}=tv(),s=e.commandSurface.remainingCommands.history,a=s.data,i="loading"===s.phase,[o,l]=(0,n.useState)("phase");return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-history",children:[(0,r.jsx)(oC,{title:"History & Metrics",icon:(0,r.jsx)(ss.A,{className:"h-3.5 w-3.5"}),onRefresh:()=>void t(),refreshing:i}),s.error&&(0,r.jsx)(oA,{message:s.error}),i&&!a&&(0,r.jsx)(oT,{label:"Loading history data…"}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(oE,{label:"Units",value:a.totals.units}),(0,r.jsx)(oE,{label:"Cost",value:eX(a.totals.cost),variant:"warning"}),(0,r.jsx)(oE,{label:"Duration",value:oP(a.totals.duration)}),(0,r.jsx)(oE,{label:"Tool Calls",value:a.totals.toolCalls})]}),(0,r.jsx)("div",{className:"flex gap-1 rounded-lg border border-border/50 bg-card/50 p-0.5",children:["phase","slice","model","units"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>l(e),className:L("flex-1 rounded-md px-2.5 py-1 text-[11px] font-medium capitalize transition-colors",o===e?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-muted-foreground"),children:"units"===e?"Recent":`By ${e}`},e))}),"phase"===o&&a.byPhase.length>0&&(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Phase"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Units"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cost"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Duration"})]})}),(0,r.jsx)("tbody",{children:a.byPhase.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80 capitalize",children:e.phase}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:e.units}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:eX(e.cost)}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:oP(e.duration)})]},e.phase))})]})}),"slice"===o&&a.bySlice.length>0&&(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Slice"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Units"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cost"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Duration"})]})}),(0,r.jsx)("tbody",{children:a.bySlice.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:e.sliceId}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:e.units}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:eX(e.cost)}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:oP(e.duration)})]},e.sliceId))})]})}),"model"===o&&a.byModel.length>0&&(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Model"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Units"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cost"})]})}),(0,r.jsx)("tbody",{children:a.byModel.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80 truncate max-w-[180px]",children:e.model}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:e.units}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:eX(e.cost)})]},e.model))})]})}),"units"===o&&(0,r.jsx)(r.Fragment,{children:a.units.length>0?(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"ID"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Model"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cost"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Duration"})]})}),(0,r.jsx)("tbody",{children:a.units.slice(0,20).map((e,t)=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:e.type}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80 truncate max-w-[120px]",children:e.id}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-muted-foreground truncate max-w-[120px]",children:e.model}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:eX(e.cost)}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:oP(e.finishedAt-e.startedAt)})]},t))})]})}):(0,r.jsx)(oR,{message:"No unit history recorded yet"})}),"phase"===o&&0===a.byPhase.length&&(0,r.jsx)(oR,{message:"No phase breakdown available"}),"slice"===o&&0===a.bySlice.length&&(0,r.jsx)(oR,{message:"No slice breakdown available"}),"model"===o&&0===a.byModel.length&&(0,r.jsx)(oR,{message:"No model breakdown available"})]})]})}function o$(){let e=tb(),{loadUndoInfo:t,executeUndoAction:s}=tv(),a=e.commandSurface.remainingCommands.undo,i=a.data,o="loading"===a.phase,[d,c]=(0,n.useState)(!1),[u,m]=(0,n.useState)(!1),[x,h]=(0,n.useState)(null),p=async()=>{m(!0),h(null);try{let e=await s();h(e),c(!1)}finally{m(!1)}};return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-undo",children:[(0,r.jsx)(oC,{title:"Undo Last Unit",icon:(0,r.jsx)(rb.A,{className:"h-3.5 w-3.5"}),onRefresh:()=>{h(null),c(!1),t()},refreshing:o}),a.error&&(0,r.jsx)(oA,{message:a.error}),o&&!i&&(0,r.jsx)(oT,{label:"Loading undo info…"}),x&&(0,r.jsxs)("div",{className:L("rounded-lg border px-3 py-2.5 text-xs",x.success?"border-success/20 bg-success/5 text-success":"border-destructive/20 bg-destructive/5 text-destructive"),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[x.success?(0,r.jsx)(l.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(nq.A,{className:"h-3.5 w-3.5"}),(0,r.jsx)("span",{className:"font-medium",children:x.success?"Undo Successful":"Undo Failed"})]}),(0,r.jsx)("p",{className:"mt-1 text-[11px] text-muted-foreground",children:x.message})]}),i&&(0,r.jsx)(r.Fragment,{children:i.lastUnitType?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Last Completed Unit"}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-x-4 gap-y-0.5 text-[11px]",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:"Type"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80",children:i.lastUnitType}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"ID"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80 truncate",children:i.lastUnitId??"—"}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"Key"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80 truncate",children:i.lastUnitKey??"—"})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(oE,{label:"Completed Units",value:i.completedCount}),i.commits.length>0&&(0,r.jsx)(oE,{label:"Commits",value:i.commits.length,variant:"info"})]}),i.commits.length>0&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground",children:"Associated Commits"}),(0,r.jsx)("div",{className:"flex flex-wrap gap-1",children:i.commits.map(e=>(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0 font-mono",children:e.slice(0,8)},e))})]}),d?(0,r.jsxs)("div",{className:"rounded-lg border border-warning/20 bg-warning/5 px-3 py-2.5 space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs text-warning",children:[(0,r.jsx)(sA.A,{className:"h-3.5 w-3.5"}),(0,r.jsx)("span",{className:"font-medium",children:"This will revert the last unit and its git commits."})]}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsxs)(J,{type:"button",variant:"destructive",size:"sm",onClick:()=>void p(),disabled:u,className:"h-7 gap-1.5 text-xs",children:[u?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(aN.A,{className:"h-3 w-3"}),"Confirm Undo"]}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(!1),disabled:u,className:"h-7 text-xs",children:"Cancel"})]})]}):(0,r.jsxs)(J,{type:"button",variant:"destructive",size:"sm",onClick:()=>c(!0),disabled:u||!!x?.success,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(aN.A,{className:"h-3 w-3"}),"Undo Last Unit"]})]}):(0,r.jsx)(oR,{message:"No completed units to undo"})})]})}function oD(){let e=tb(),{loadSteerData:t,sendSteer:s}=tv(),a=e.commandSurface.remainingCommands.steer,i=a.data,o="loading"===a.phase,[d,c]=(0,n.useState)(""),[u,m]=(0,n.useState)(!1),[x,h]=(0,n.useState)(!1),p=async()=>{if(d.trim()){m(!0),h(!1);try{await s(d.trim()),h(!0),c(""),t()}finally{m(!1)}}};return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-steer",children:[(0,r.jsx)(oC,{title:"Steer",icon:(0,r.jsx)(oN.A,{className:"h-3.5 w-3.5"}),onRefresh:()=>{h(!1),t()},refreshing:o}),a.error&&(0,r.jsx)(oA,{message:a.error}),o&&!i&&(0,r.jsx)(oT,{label:"Loading steer data…"}),x&&(0,r.jsxs)("div",{className:"rounded-lg border border-success/20 bg-success/5 px-3 py-2.5 text-xs text-success flex items-center gap-2",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5"}),"Steering message sent successfully."]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Current Overrides"}),i?.overridesContent?(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-background/50 px-3 py-2.5 text-[11px] font-mono text-foreground/80 whitespace-pre-wrap max-h-[200px] overflow-y-auto leading-relaxed",children:i.overridesContent}):(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 text-[11px] text-muted-foreground italic",children:"No active overrides"})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Send Steering Message"}),(0,r.jsx)(nm,{value:d,onChange:e=>c(e.target.value),placeholder:"Enter steering instructions for the agent…",className:"min-h-[80px] text-xs resize-none"}),(0,r.jsxs)(J,{type:"button",variant:"default",size:"sm",onClick:()=>void p(),disabled:u||!d.trim(),className:"h-7 gap-1.5 text-xs",children:[u?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(oN.A,{className:"h-3 w-3"}),"Send"]})]})]})}function oF(){let e=tb(),{loadHooksData:t}=tv(),s=e.commandSurface.remainingCommands.hooks,a=s.data,n="loading"===s.phase;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-hooks",children:[(0,r.jsx)(oC,{title:"Hooks",icon:(0,r.jsx)(av.A,{className:"h-3.5 w-3.5"}),status:a?(0,r.jsxs)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[a.entries.length," ",1===a.entries.length?"hook":"hooks"]}):null,onRefresh:()=>void t(),refreshing:n}),s.error&&(0,r.jsx)(oA,{message:s.error}),n&&!a&&(0,r.jsx)(oT,{label:"Loading hooks…"}),a&&(0,r.jsxs)(r.Fragment,{children:[a.entries.length>0?(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Name"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Type"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-center font-medium text-muted-foreground",children:"Status"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Targets"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Cycles"})]})}),(0,r.jsx)("tbody",{children:a.entries.map(e=>{let t=Object.values(e.activeCycles).reduce((e,t)=>e+t,0);return(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:e.name}),(0,r.jsx)("td",{className:"px-2.5 py-1.5",children:(0,r.jsx)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:e.type})}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-center",children:(0,r.jsx)(nI,{variant:e.enabled?"secondary":"outline",className:L("text-[10px] px-1.5 py-0",e.enabled?"border-success/30 text-success":"text-muted-foreground"),children:e.enabled?"enabled":"disabled"})}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-muted-foreground",children:e.targets.length>0?e.targets.join(", "):"all"}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right tabular-nums text-foreground/80",children:t})]},e.name)})})]})}):(0,r.jsx)(oR,{message:"No hooks configured"}),a.formattedStatus&&(0,r.jsx)("div",{className:"rounded-lg border border-border/50 bg-background/50 px-3 py-2.5 text-[11px] font-mono text-muted-foreground whitespace-pre-wrap leading-relaxed",children:a.formattedStatus})]})]})}function oL(){let e=tb(),{loadInspectData:t}=tv(),s=e.commandSurface.remainingCommands.inspect,a=s.data,n="loading"===s.phase;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-inspect",children:[(0,r.jsx)(oC,{title:"Inspect Database",icon:(0,r.jsx)(ow.A,{className:"h-3.5 w-3.5"}),subtitle:a?.schemaVersion!=null?`v${a.schemaVersion}`:null,onRefresh:()=>void t(),refreshing:n}),s.error&&(0,r.jsx)(oA,{message:s.error}),n&&!a&&(0,r.jsx)(oT,{label:"Loading database…"}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(oE,{label:"Decisions",value:a.counts.decisions,variant:"info"}),(0,r.jsx)(oE,{label:"Requirements",value:a.counts.requirements,variant:"info"}),(0,r.jsx)(oE,{label:"Artifacts",value:a.counts.artifacts})]}),a.recentDecisions.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Recent Decisions (",a.recentDecisions.length,")"]}),(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"ID"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Decision"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Choice"})]})}),(0,r.jsx)("tbody",{children:a.recentDecisions.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:e.id}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-foreground/80 max-w-[200px] truncate",children:e.decision}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-muted-foreground max-w-[150px] truncate",children:e.choice})]},e.id))})]})})]}),a.recentRequirements.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Recent Requirements (",a.recentRequirements.length,")"]}),(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"ID"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Status"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Description"})]})}),(0,r.jsx)("tbody",{children:a.recentRequirements.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80",children:e.id}),(0,r.jsx)("td",{className:"px-2.5 py-1.5",children:(0,r.jsx)(nI,{variant:"active"===e.status?"secondary":"outline",className:L("text-[10px] px-1.5 py-0","active"===e.status&&"border-success/30 text-success","validated"===e.status&&"border-info/30 text-info","deferred"===e.status&&"text-muted-foreground"),children:e.status})}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-foreground/80 max-w-[220px] truncate",children:e.description})]},e.id))})]})})]}),0===a.recentDecisions.length&&0===a.recentRequirements.length&&(0,r.jsx)(oR,{message:"Database is empty — no decisions or requirements recorded"})]})]})}function oM(){let e=tb(),{loadExportData:t}=tv(),s=e.commandSurface.remainingCommands.exportData,a=s.data,i="loading"===s.phase,[o,d]=(0,n.useState)("markdown"),c=e=>{let t="json"===e.format?"application/json":"text/markdown",s=new Blob([e.content],{type:t}),r=URL.createObjectURL(s),a=document.createElement("a");a.href=r,a.download=e.filename,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)},u=async()=>{let e=await t(o);e&&c(e)};return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-export",children:[(0,r.jsx)(oC,{title:"Export",icon:(0,r.jsx)(aj.A,{className:"h-3.5 w-3.5"})}),s.error&&(0,r.jsx)(oA,{message:s.error}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Format"}),(0,r.jsx)("div",{className:"flex gap-1 rounded-lg border border-border/50 bg-card/50 p-0.5",children:["markdown","json"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e),className:L("flex-1 rounded-md px-3 py-1.5 text-[11px] font-medium capitalize transition-colors",o===e?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-muted-foreground"),children:"markdown"===e?"Markdown":"JSON"},e))})]}),(0,r.jsxs)(J,{type:"button",variant:"default",size:"sm",onClick:()=>void u(),disabled:i,className:"h-7 gap-1.5 text-xs",children:[i?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(aj.A,{className:"h-3 w-3"}),"Generate Export"]}),a&&(0,r.jsxs)("div",{className:"rounded-lg border border-success/20 bg-success/5 px-3 py-2.5 space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs text-success",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5"}),(0,r.jsx)("span",{className:"font-medium",children:"Export Ready"})]}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[11px] font-mono text-muted-foreground",children:a.filename}),(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(a),className:"h-6 gap-1 text-[10px]",children:[(0,r.jsx)(aj.A,{className:"h-2.5 w-2.5"}),"Download Again"]})]})]})]})}function oq(){let e=tb(),{loadCleanupData:t,executeCleanupAction:s}=tv(),a=e.commandSurface.remainingCommands.cleanup,i=a.data,o="loading"===a.phase,[d,c]=(0,n.useState)(!1),[u,m]=(0,n.useState)(null),x=i?.branches.filter(e=>e.merged)??[],h=i?.snapshots??[],p=async e=>{c(!0),m(null);try{let r="branches"===e?x.map(e=>e.name):[],a="snapshots"===e?h.map(e=>e.ref):[],n=await s(r,a);m(n),t()}finally{c(!1)}};return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-cleanup",children:[(0,r.jsx)(oC,{title:"Cleanup",icon:(0,r.jsx)(sL.A,{className:"h-3.5 w-3.5"}),onRefresh:()=>{m(null),t()},refreshing:o}),a.error&&(0,r.jsx)(oA,{message:a.error}),o&&!i&&(0,r.jsx)(oT,{label:"Scanning for cleanup targets…"}),u&&(0,r.jsxs)("div",{className:"rounded-lg border border-success/20 bg-success/5 px-3 py-2.5 text-xs text-success",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(l.A,{className:"h-3.5 w-3.5"}),(0,r.jsx)("span",{className:"font-medium",children:"Cleanup Complete"})]}),(0,r.jsx)("p",{className:"mt-1 text-[11px] text-muted-foreground",children:u.message})]}),i&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Branches (",i.branches.length,")"]}),x.length>0&&(0,r.jsxs)(J,{type:"button",variant:"destructive",size:"sm",onClick:()=>void p("branches"),disabled:d,className:"h-6 gap-1 text-[10px]",children:[d?(0,r.jsx)(E.A,{className:"h-2.5 w-2.5 animate-spin"}):(0,r.jsx)(ok.A,{className:"h-2.5 w-2.5"}),"Delete Merged (",x.length,")"]})]}),i.branches.length>0?(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Branch"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-center font-medium text-muted-foreground",children:"Status"})]})}),(0,r.jsx)("tbody",{children:i.branches.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80 truncate max-w-[250px]",children:(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(N.A,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.name]})}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-center",children:(0,r.jsx)(nI,{variant:e.merged?"secondary":"outline",className:L("text-[10px] px-1.5 py-0",e.merged?"border-success/30 text-success":"text-muted-foreground"),children:e.merged?"merged":"active"})})]},e.name))})]})}):(0,r.jsx)(oR,{message:"No branches to clean up"})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("h4",{className:"text-xs font-medium text-muted-foreground",children:["Snapshots (",i.snapshots.length,")"]}),h.length>0&&(0,r.jsxs)(J,{type:"button",variant:"destructive",size:"sm",onClick:()=>void p("snapshots"),disabled:d,className:"h-6 gap-1 text-[10px]",children:[d?(0,r.jsx)(E.A,{className:"h-2.5 w-2.5 animate-spin"}):(0,r.jsx)(ii.A,{className:"h-2.5 w-2.5"}),"Prune Snapshots (",h.length,")"]})]}),i.snapshots.length>0?(0,r.jsx)("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:(0,r.jsxs)("table",{className:"w-full text-[11px]",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border/50 bg-card/50",children:[(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-left font-medium text-muted-foreground",children:"Ref"}),(0,r.jsx)("th",{className:"px-2.5 py-1.5 text-right font-medium text-muted-foreground",children:"Date"})]})}),(0,r.jsx)("tbody",{children:i.snapshots.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 last:border-0",children:[(0,r.jsx)("td",{className:"px-2.5 py-1.5 font-mono text-foreground/80 truncate max-w-[200px]",children:e.ref}),(0,r.jsx)("td",{className:"px-2.5 py-1.5 text-right text-muted-foreground",children:e.date})]},e.ref))})]})}):(0,r.jsx)(oR,{message:"No snapshots to prune"})]})]})]})}function oO(){let e=td(tb()),t=e?.milestones??[],s=e?.active;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-queue",children:[(0,r.jsx)(oC,{title:"Queue",icon:(0,r.jsx)(oS.A,{className:"h-3.5 w-3.5"}),status:(0,r.jsxs)(nI,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[t.length," ",1===t.length?"milestone":"milestones"]})}),t.length>0?(0,r.jsx)("div",{className:"space-y-2",children:t.map(e=>{var t;let a=s?.milestoneId===e.id,n={done:(t=e.slices).filter(e=>e.done).length,total:t.length};return(0,r.jsxs)("div",{className:L("rounded-lg border px-3 py-2.5 space-y-1.5",a?"border-info/25 bg-info/5":"border-border/50 bg-card/50"),children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-xs font-mono font-medium text-foreground/80",children:e.id}),(0,r.jsx)("span",{className:"text-xs text-foreground truncate",children:e.title}),a&&(0,r.jsx)(nI,{variant:"secondary",className:"text-[10px] px-1.5 py-0 border-info/30 text-info",children:"active"})]}),(0,r.jsxs)("span",{className:"text-[10px] text-muted-foreground tabular-nums shrink-0",children:[n.done,"/",n.total," slices"]})]}),n.total>0&&(0,r.jsx)("div",{className:"h-1 rounded-full bg-border/50 overflow-hidden",children:(0,r.jsx)("div",{className:L("h-full rounded-full transition-all",n.done===n.total?"bg-success":"bg-info"),style:{width:`${n.done/n.total*100}%`}})}),a&&e.slices.length>0&&(0,r.jsx)("div",{className:"space-y-0.5 pt-1",children:e.slices.map(e=>(0,r.jsxs)("div",{className:"flex items-center gap-2 text-[11px]",children:[e.done?(0,r.jsx)(l.A,{className:"h-3 w-3 text-success shrink-0"}):(0,r.jsx)("span",{className:L("inline-block h-1.5 w-1.5 rounded-full shrink-0",s?.sliceId===e.id?"bg-info":"bg-border/50")}),(0,r.jsx)("span",{className:"font-mono text-muted-foreground",children:e.id}),(0,r.jsx)("span",{className:L("truncate",e.done?"text-muted-foreground line-through":"text-foreground/80"),children:e.title}),s?.sliceId===e.id&&!e.done&&(0,r.jsx)(nI,{variant:"outline",className:"text-[9px] px-1 py-0 text-info",children:"current"})]},e.id))})]},e.id)})}):(0,r.jsx)(oR,{message:"No milestones in the plan"})]})}function oU(){let e=td(tb()),t=e?.active,s=e?.milestones??[],a=s.find(e=>e.id===t?.milestoneId),n=a?.slices.find(e=>e.id===t?.sliceId),i=s.reduce((e,t)=>e+t.slices.length,0),o=s.reduce((e,t)=>e+t.slices.filter(e=>e.done).length,0);return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"gsd-surface-gsd-status",children:[(0,r.jsx)(oC,{title:"Status",icon:(0,r.jsx)(rE.A,{className:"h-3.5 w-3.5"})}),(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-3 space-y-2",children:[(0,r.jsx)("h4",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide",children:"Active Context"}),(0,r.jsxs)("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px]",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:"Phase"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80",children:t?.phase?(0,r.jsx)(nI,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:t.phase}):(0,r.jsx)("span",{className:"text-muted-foreground italic",children:"idle"})}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"Milestone"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80",children:a?(0,r.jsxs)("span",{children:[a.id," — ",a.title]}):(0,r.jsx)("span",{className:"text-muted-foreground italic",children:"none"})}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"Slice"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80",children:n?(0,r.jsxs)("span",{children:[n.id," — ",n.title]}):(0,r.jsx)("span",{className:"text-muted-foreground italic",children:"none"})}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"Task"}),(0,r.jsx)("span",{className:"font-mono text-foreground/80",children:t?.taskId??(0,r.jsx)("span",{className:"text-muted-foreground italic",children:"none"})})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,r.jsx)(oE,{label:"Milestones",value:s.length}),(0,r.jsx)(oE,{label:"Slices",value:`${o}/${i}`,variant:o===i&&i>0?"success":"info"})]}),i>0&&(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[(0,r.jsx)("span",{children:"Overall Progress"}),(0,r.jsxs)("span",{className:"tabular-nums",children:[Math.round(o/i*100),"%"]})]}),(0,r.jsx)("div",{className:"h-1.5 rounded-full bg-border/50 overflow-hidden",children:(0,r.jsx)("div",{className:L("h-full rounded-full transition-all",o===i?"bg-success":"bg-info"),style:{width:`${o/i*100}%`}})})]}),0===s.length&&(0,r.jsx)(oR,{message:"No plan loaded — run /gsd to initialize"})]})}let oz=["general","model","session-behavior","recovery","auth","integrations","workspace","experimental"],oB=["git"],oG=["resume","name","fork","session","compact"];function oW(e){return({model:"Model",thinking:"Thinking",git:"Git",login:"Login",logout:"Logout",settings:"Settings",resume:"Resume",name:"Name",fork:"Fork",session:"Session",export:"Export",compact:"Compact"})[e??""]??"Settings"}function oK(e){let t=Date.now()-new Date(e).getTime();if(t<6e4)return"just now";let s=Math.floor(t/6e4);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);if(r<24)return`${r}h ago`;let a=Math.floor(r/24);return`${a}d ago`}function oH({status:e}){return(0,r.jsx)("span",{className:L("inline-block h-1.5 w-1.5 rounded-full","ok"===e&&"bg-success","warning"===e&&"bg-warning","error"===e&&"bg-destructive","idle"===e&&"bg-foreground/20")})}function oV({title:e,action:t,status:s}){return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 pb-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsx)("h3",{className:"text-[13px] font-semibold uppercase tracking-[0.08em] text-muted-foreground",children:e}),s]}),t]})}function oJ({label:e,children:t,mono:s}){return(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-4 py-1.5 text-sm",children:[(0,r.jsx)("span",{className:"shrink-0 text-muted-foreground",children:e}),(0,r.jsx)("span",{className:L("text-right text-foreground",s&&"font-mono text-xs"),children:t})]})}function oY({label:e,description:t,checked:s,onCheckedChange:a,disabled:n,busy:i,testId:o}){return(0,r.jsxs)("div",{className:"flex items-start justify-between gap-4 rounded-lg border border-border/50 bg-card/50 px-4 py-3",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium text-foreground",children:[e,i&&(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),t&&(0,r.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:t})]}),(0,r.jsx)(ip,{checked:s,onCheckedChange:a,disabled:n||i,"data-testid":o})]})}function oQ({options:e,value:t,onChange:s,disabled:a}){return(0,r.jsx)("div",{className:"inline-flex rounded-lg border border-border bg-card/50 p-0.5",children:e.map(e=>(0,r.jsx)("button",{type:"button",className:L("rounded-md px-3 py-1.5 text-xs font-medium transition-all",t===e.value?"bg-foreground/10 text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),onClick:()=>s(e.value),disabled:a||t===e.value,children:e.label},e.value))})}function oX(){var e,t;let s,a,o,l,d=tb(),{closeCommandSurface:c,openCommandSurface:u,refreshBoot:m,setCommandSurfaceSection:x,selectCommandSurfaceTarget:h,loadGitSummary:p,loadRecoveryDiagnostics:g,loadForensicsDiagnostics:f,loadDoctorDiagnostics:b,loadSkillHealthDiagnostics:v,loadKnowledgeData:j,loadCapturesData:y,loadSettingsData:w,updateSessionBrowserState:S,loadSessionBrowser:C,renameSessionFromSurface:P,loadAvailableModels:_,applyModelSelection:I,applyThinkingLevel:$,setSteeringModeFromSurface:D,setFollowUpModeFromSurface:F,setAutoCompactionFromSurface:M,setAutoRetryFromSurface:q,abortRetryFromSurface:O,switchSessionFromSurface:U,loadSessionStats:z,exportSessionFromSurface:B,loadForkMessages:G,forkSessionFromSurface:W,compactSessionFromSurface:K,saveApiKeyFromSurface:H,startProviderFlowFromSurface:V,submitProviderFlowInputFromSurface:Y,cancelProviderFlowFromSurface:Q,logoutProviderFromSurface:X,loadHistoryData:Z,loadInspectData:ee,loadHooksData:et,loadUndoInfo:es,loadCleanupData:er,loadSteerData:ea}=tv(),{commandSurface:en}=d,eo=d.boot?.onboarding??null,el=eo?.activeFlow??null,ed=en.gitSummary,ec=en.recovery,eu=en.sessionBrowser,em=d.boot?.bridge.sessionState??null,ex=en.settingsRequests,eh=e5(d.boot?.bridge),ep=e1(d.boot?.bridge),[eg,ef]=(0,n.useState)({}),[eb,ev]=(0,n.useState)(""),ej=(0,n.useRef)(null);(0,n.useEffect)(()=>{!en.open||"model"!==en.section||en.availableModels.length>0||"loading_models"!==en.pendingAction&&_()},[en.open,en.section,en.availableModels.length,en.pendingAction,_]),(0,n.useEffect)(()=>{!en.open||"git"!==en.section||"load_git_summary"===en.pendingAction||en.gitSummary.loaded||en.gitSummary.error||p()},[en.open,en.section,en.pendingAction,en.gitSummary.loaded,en.gitSummary.error,p]),(0,n.useEffect)(()=>{!en.open||"recovery"!==en.section||"load_recovery_diagnostics"===en.pendingAction||en.recovery.pending||(!en.recovery.loaded||en.recovery.stale||en.recovery.error)&&g()},[en.open,en.section,en.pendingAction,en.recovery.pending,en.recovery.loaded,en.recovery.stale,en.recovery.error,g]);let ey=en.diagnostics,eN=en.knowledgeCaptures,ew=en.settingsData,ek=en.remainingCommands;(0,n.useEffect)(()=>{en.open&&("gsd-forensics"===en.section&&"idle"===ey.forensics.phase?f():"gsd-doctor"===en.section&&"idle"===ey.doctor.phase?b():"gsd-skill-health"===en.section&&"idle"===ey.skillHealth.phase?v():"gsd-knowledge"===en.section&&"idle"===eN.knowledge.phase?(j(),y()):("gsd-capture"===en.section||"gsd-triage"===en.section)&&"idle"===eN.captures.phase?(y(),j()):("gsd-prefs"===en.section||"gsd-mode"===en.section||"gsd-config"===en.section||"experimental"===en.section)&&"idle"===ew.phase?w():"gsd-history"===en.section&&"idle"===ek.history.phase?Z():"gsd-inspect"===en.section&&"idle"===ek.inspect.phase?ee():"gsd-hooks"===en.section&&"idle"===ek.hooks.phase?et():"gsd-undo"===en.section&&"idle"===ek.undo.phase?es():"gsd-cleanup"===en.section&&"idle"===ek.cleanup.phase?er():"gsd-steer"===en.section&&"idle"===ek.steer.phase&&ea())},[en.open,en.section,ey.forensics.phase,ey.doctor.phase,ey.skillHealth.phase,eN.knowledge.phase,eN.captures.phase,ew.phase,ek.history.phase,ek.inspect.phase,ek.hooks.phase,ek.undo.phase,ek.cleanup.phase,ek.steer.phase,f,b,v,j,y,w,Z,ee,et,es,er,ea]),(0,n.useEffect)(()=>{!en.open||"resume"!==en.section&&"name"!==en.section||"load_session_browser"===en.pendingAction||en.sessionBrowser.loaded||C()},[en.open,en.section,en.pendingAction,en.sessionBrowser.loaded,C]),(0,n.useEffect)(()=>{if(!en.open)return;let e=ej.current;e&&(e.scrollTop=0)},[en.open,en.activeSurface,en.section]),(0,n.useEffect)(()=>{!en.open||"session"!==en.section||en.sessionStats||"load_session_stats"!==en.pendingAction&&z()},[en.open,en.section,en.sessionStats,en.pendingAction,z]),(0,n.useEffect)(()=>{!en.open||"fork"!==en.section||en.forkMessages.length>0||"load_fork_messages"!==en.pendingAction&&G()},[en.open,en.section,en.forkMessages.length,en.pendingAction,G]),(0,n.useEffect)(()=>{if(!en.open||"resume"!==en.section)return;let e=en.selectedTarget?.kind==="resume"?en.selectedTarget:null;if(e?.sessionPath)return;let t=eu.sessions.find(e=>!e.isActive)??eu.sessions[0];t&&h({kind:"resume",sessionPath:t.path})},[en.open,en.section,en.selectedTarget,eu.sessions,h]),(0,n.useEffect)(()=>{if(!en.open||"name"!==en.section)return;let e=en.selectedTarget?.kind==="name"?en.selectedTarget:null;if(e?.sessionPath)return;let t=eu.sessions.find(e=>e.isActive)??eu.sessions[0];t&&h({kind:"name",sessionPath:t.path,name:t.name??""})},[en.open,en.section,en.selectedTarget,eu.sessions,h]),(0,n.useEffect)(()=>{let e=window.setTimeout(()=>{ev("")},0);return()=>window.clearTimeout(e)},[el?.flowId]),(0,n.useEffect)(()=>{en.lastError&&ix.oR.error(en.lastError)},[en.lastError]),(0,n.useEffect)(()=>{en.lastResult&&ix.oR.success(en.lastResult)},[en.lastResult]);let eS=en.selectedTarget?.kind==="model"?en.selectedTarget:null,eC=en.selectedTarget?.kind==="thinking"?en.selectedTarget:null,eA=en.selectedTarget?.kind==="auth"?en.selectedTarget:null,eT=en.selectedTarget?.kind==="resume"?en.selectedTarget:null,eR=en.selectedTarget?.kind==="name"?en.selectedTarget:null,eE=en.selectedTarget?.kind==="fork"?en.selectedTarget:null,eP=en.selectedTarget?.kind==="session"?en.selectedTarget:null,e_=en.selectedTarget?.kind==="compact"?en.selectedTarget:null,eI=(e=en.activeSurface,t=en.selectedTarget,t?.kind==="auth"?t.intent:"login"===e?"login":"logout"===e?"logout":"manage"),e$=eo?.required.providers.find(e=>e.id===eA?.providerId)??null,eD=(eS?.query??en.args).trim().toLowerCase(),eF=(0,n.useMemo)(()=>eD?en.availableModels.filter(e=>`${e.provider} ${e.modelId} ${e.name??""}`.toLowerCase().includes(eD)):en.availableModels,[en.availableModels,eD]),eL=(0,n.useMemo)(()=>{let e=new Map;for(let t of eF){let s=t.provider,r=e.get(s);r?r.push(t):e.set(s,[t])}return e},[eF]),eM="idle"!==d.onboardingRequestState,eq="loading_models"===en.pendingAction||"get_available_models"===d.commandInFlight,eO="load_git_summary"===en.pendingAction,eU="load_recovery_diagnostics"===en.pendingAction||ec.pending,ez=ec.diagnostics,eB="load_session_browser"===en.pendingAction,eG="load_fork_messages"===en.pendingAction||"fork_session"===en.pendingAction,eW="load_session_stats"===en.pendingAction||"export_html"===en.pendingAction,eK="switch_session"===en.pendingAction,eH="rename_session"===en.pendingAction,eV="compact_session"===en.pendingAction||em?.isCompacting===!0,eJ=ex.steeringMode.pending||ex.followUpMode.pending,eZ=ex.autoCompaction.pending,e0=ex.autoRetry.pending,e2=ex.abortRetry.pending,e3=e$?eg[e$.id]??"":"",e4=nA(),e8=function(e,t=!1){switch(e){case"git":return[...oB];case"resume":case"name":case"fork":case"session":case"export":case"compact":return[...oG];default:return t?[...oz,"admin"]:[...oz]}}(en.activeSurface,e4.isDevMode),e6=`/${en.activeSurface??"settings"}`,e7=e=>{let t="name"===e,s=t?eR?.sessionPath:eT?.sessionPath;return(0,r.jsxs)("div",{className:"space-y-4","data-testid":t?"command-surface-name":"command-surface-resume",children:[(0,r.jsx)(oV,{title:t?"Rename":"Resume",status:t?null:(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:ep??"pending"})}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsxs)("div",{className:"relative flex-1",children:[(0,r.jsx)(iu.A,{className:"absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),(0,r.jsx)(rP,{value:eu.query,onChange:e=>S({query:e.target.value}),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),C())},placeholder:"Search sessions…",className:"h-8 pl-9 text-xs",disabled:eB,"data-testid":"command-surface-session-browser-query"})]}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>void C(),disabled:eB,className:"h-8 w-8 p-0",children:(0,r.jsx)(io.A,{className:L("h-3.5 w-3.5",eB&&"animate-spin")})})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(oQ,{options:[{value:"threaded",label:"Threaded"},{value:"recent",label:"Recent"},{value:"relevance",label:"Relevance"}],value:eu.sortMode,onChange:e=>{S({sortMode:e}),C({sortMode:e})},disabled:eB}),(0,r.jsx)("button",{type:"button",className:L("rounded-md border border-border px-2.5 py-1.5 text-[11px] font-medium transition-colors","named"===eu.nameFilter?"bg-foreground/10 text-foreground":"text-muted-foreground hover:text-foreground"),onClick:()=>{let e="named"===eu.nameFilter?"all":"named";S({nameFilter:e}),C({nameFilter:e})},disabled:eB,children:"Named"})]}),eu.error&&(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 text-xs text-destructive",children:eu.error}),eB&&0===eu.sessions.length?(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),"Loading sessions…"]}):eu.sessions.length>0?(0,r.jsx)("div",{className:"space-y-1","data-testid":"command-surface-session-browser-results",children:eu.sessions.map(e=>{let a=e.path===s;return(0,r.jsxs)("button",{type:"button",className:L("flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",a?"bg-foreground/[0.07]":"hover:bg-foreground/[0.03]"),style:{paddingLeft:`${.75+.6*e.depth}rem`},onClick:()=>t?h({kind:"name",sessionPath:e.path,name:eR?.sessionPath===e.path?eR?.name??e.name??"":e.name??""}):h({kind:"resume",sessionPath:e.path}),"data-testid":`command-surface-session-browser-item-${e.id}`,children:[(0,r.jsx)("div",{className:L("mt-1 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",a?"border-foreground bg-foreground":"border-foreground/25"),children:a&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-background"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"truncate text-sm font-medium text-foreground",children:e.name||e.firstMessage||e.id}),e.isActive&&(0,r.jsx)(oH,{status:"ok"})]}),e.name&&e.firstMessage&&(0,r.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:e.firstMessage}),(0,r.jsxs)("div",{className:"mt-0.5 flex gap-3 text-[11px] text-muted-foreground",children:[(0,r.jsxs)("span",{children:[e.messageCount," msgs"]}),(0,r.jsx)("span",{children:oK(e.modifiedAt)})]})]})]},e.path)})}):(0,r.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:"No sessions matched."}),eu.loaded&&(0,r.jsxs)("p",{className:"text-[11px] text-muted-foreground","data-testid":"command-surface-session-browser-meta",children:["Current-project sessions \xb7 ",eu.returnedSessions," of ",eu.totalSessions," \xb7 ",eu.sortMode," \xb7 ",eu.nameFilter]}),t&&(0,r.jsxs)("div",{className:"space-y-3 border-t border-border/50 pt-3",children:[(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{value:eR?.name??"",onChange:e=>h({kind:"name",sessionPath:eR?.sessionPath,name:e.target.value}),placeholder:"Session name",className:"h-8 flex-1 text-xs",disabled:!eR?.sessionPath||eH,"data-testid":"command-surface-rename-input"}),(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>eR?.sessionPath&&void P(eR.sessionPath,eR.name),disabled:!eR?.sessionPath||!eR.name.trim()||eH,"data-testid":"command-surface-apply-rename",className:"h-8 gap-1.5",children:[eH?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(il.A,{className:"h-3.5 w-3.5"}),"Rename"]})]}),en.renameRequest.error&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:en.renameRequest.error}),en.renameRequest.result&&(0,r.jsx)("p",{className:"text-xs text-success",children:en.renameRequest.result})]}),!t&&(0,r.jsxs)("div",{className:"flex items-center justify-between border-t border-border/50 pt-3",children:[(0,r.jsx)("span",{className:"text-xs text-muted-foreground","data-testid":"command-surface-resume-state",children:eK?"Switching…":en.resumeRequest.error??en.resumeRequest.result??"Select a session"}),(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>eT?.sessionPath&&void U(eT.sessionPath),disabled:!eT?.sessionPath||eK,"data-testid":"command-surface-apply-resume",className:"h-8 gap-1.5",children:[eK?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(ia.A,{className:"h-3.5 w-3.5"}),"Switch"]})]})]})},e9=e8.length<=1,te="git"===en.activeSurface,tt=ed.result;return(0,r.jsx)(na,{open:en.open,onOpenChange:e=>!e&&c(),children:(0,r.jsxs)(no,{side:"right",className:"flex h-full w-full flex-col p-0 sm:max-w-[540px]","data-testid":"command-surface",children:[(0,r.jsxs)(nl,{className:"sr-only",children:[(0,r.jsx)(nc,{children:oW(en.activeSurface)}),(0,r.jsx)(nu,{children:"Settings and controls"})]}),(0,r.jsxs)("div",{className:"flex h-full min-h-0",children:[!e9&&(0,r.jsx)("nav",{className:"flex w-12 shrink-0 flex-col items-center gap-0.5 border-r border-border/50 bg-card/50 py-3","data-testid":"command-surface-sections",children:e8.map(e=>{let t=en.section===e;return(0,r.jsxs)(r$,{children:[(0,r.jsx)(rD,{asChild:!0,children:(0,r.jsx)("button",{type:"button",className:L("flex h-9 w-9 items-center justify-center rounded-lg transition-colors",t?"bg-foreground/10 text-foreground":"text-muted-foreground hover:bg-foreground/[0.04] hover:text-foreground"),onClick:()=>x(e),"data-testid":`command-surface-section-${e}`,children:{general:(0,r.jsx)(rj.A,{className:"h-4 w-4"}),model:(0,r.jsx)(aK.A,{className:"h-4 w-4"}),thinking:(0,r.jsx)(ir.A,{className:"h-4 w-4"}),queue:(0,r.jsx)(ia.A,{className:"h-4 w-4"}),compaction:(0,r.jsx)(ii.A,{className:"h-4 w-4"}),retry:(0,r.jsx)(io.A,{className:"h-4 w-4"}),"session-behavior":(0,r.jsx)(ia.A,{className:"h-4 w-4"}),recovery:(0,r.jsx)(R.A,{className:"h-4 w-4"}),auth:(0,r.jsx)(nP.A,{className:"h-4 w-4"}),admin:(0,r.jsx)(tH.A,{className:"h-4 w-4"}),git:(0,r.jsx)(N.A,{className:"h-4 w-4"}),resume:(0,r.jsx)(ia.A,{className:"h-4 w-4"}),name:(0,r.jsx)(il.A,{className:"h-4 w-4"}),fork:(0,r.jsx)(N.A,{className:"h-4 w-4"}),session:(0,r.jsx)(T.A,{className:"h-4 w-4"}),compact:(0,r.jsx)(ii.A,{className:"h-4 w-4"}),workspace:(0,r.jsx)(nG.A,{className:"h-4 w-4"}),integrations:(0,r.jsx)(id.A,{className:"h-4 w-4"}),experimental:(0,r.jsx)(ic.A,{className:"h-4 w-4"})}[e]??null})}),(0,r.jsx)(rF,{side:"right",sideOffset:6,children:{general:"General",model:"Model",thinking:"Thinking",queue:"Queue",compaction:"Compaction",retry:"Retry","session-behavior":"Session",recovery:"Recovery",auth:"Auth",admin:"Admin",git:"Git",resume:"Resume",name:"Name",fork:"Fork",session:"Session",compact:"Compact",workspace:"Workspace",integrations:"Integrations",experimental:"Experimental"}[e]??e})]},e)})}),(0,r.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[te?(s=tt?.kind==="repo"?tt.branch??"detached":null,a=tt?.kind==="repo"?tt.mainBranch:null,o=tt?.kind==="repo"&&tt.hasChanges,l=tt?.kind==="repo"&&!o,(0,r.jsx)("div",{className:"border-b border-border/50 px-5 py-4",children:(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("div",{className:L("flex h-8 w-8 items-center justify-center rounded-lg",l?"bg-success/10":o?"bg-warning/10":"bg-card/50"),children:(0,r.jsx)(N.A,{className:L("h-4 w-4",l?"text-success":o?"text-warning":"text-muted-foreground")})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("h2",{className:"text-sm font-semibold text-foreground","data-testid":"command-surface-title",children:s??"Git"}),s&&a&&s!==a&&(0,r.jsxs)("span",{className:"text-[11px] text-muted-foreground",children:["from ",a]})]}),tt?.kind==="repo"&&(0,r.jsxs)("div",{className:"mt-0.5 flex items-center gap-1.5",children:[(0,r.jsx)(oH,{status:l?"ok":o?"warning":"idle"}),(0,r.jsx)("span",{className:"text-[11px] text-muted-foreground",children:l?"Clean":o?"Changes detected":"Loading…"})]})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)(J,{type:"button",variant:"ghost",size:"icon",onClick:()=>void p(),disabled:eO,"aria-label":"Refresh",className:"h-7 w-7",children:(0,r.jsx)(io.A,{className:L("h-3.5 w-3.5",eO&&"animate-spin")})}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"icon",onClick:c,"aria-label":"Close",className:"h-7 w-7",children:(0,r.jsx)(i.A,{className:"h-3.5 w-3.5"})})]})]})})):(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 border-b border-border/50 px-5 py-4",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Command surface"}),(0,r.jsx)("div",{className:"text-lg font-semibold text-foreground","data-testid":"command-surface-title",children:oW(en.activeSurface)})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("div",{className:"rounded-full border border-border bg-card px-2.5 py-1 text-xs font-medium text-muted-foreground","data-testid":"command-surface-kind",children:e6}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"icon",onClick:c,"aria-label":"Close",className:"h-8 w-8",children:(0,r.jsx)(i.A,{className:"h-4 w-4"})})]})]}),(en.lastResult||en.lastError)&&(0,r.jsx)("div",{className:L("border-b border-border/50 px-5 py-3 text-xs",en.lastError?"bg-destructive/5 text-destructive":"bg-success/5 text-success"),"data-testid":"command-surface-result",children:en.lastError??en.lastResult}),(0,r.jsx)(nK,{className:"min-h-0 flex-1",viewportRef:ej,children:(0,r.jsx)("div",{className:"px-5 py-5",children:(()=>{switch(en.section){case"general":return(0,r.jsx)(od,{});case"experimental":return(0,r.jsx)(ou,{});case"model":case"thinking":return(0,r.jsxs)("div",{className:"space-y-8",children:[(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-models",children:[(0,r.jsx)(oV,{title:"Model",status:(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:eh}),action:(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>void _(),disabled:eq,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3",eq&&"animate-spin")}),"Refresh"]})}),(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(iu.A,{className:"absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),(0,r.jsx)(rP,{value:eS?.query??en.args,onChange:e=>h({kind:"model",provider:eS?.provider,modelId:eS?.modelId,query:e.target.value}),placeholder:"Filter models…",className:"h-8 pl-9 text-xs"})]}),eq&&0===en.availableModels.length?(0,r.jsxs)("div",{className:"flex items-center gap-2 py-8 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),"Loading models…"]}):eF.length>0?(0,r.jsx)("div",{className:"space-y-4",children:Array.from(eL.entries()).map(([e,t])=>(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"mb-1.5 px-1 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground",children:e}),(0,r.jsx)("div",{className:"space-y-0.5",children:t.map(e=>{let t=eS?.provider===e.provider&&eS?.modelId===e.modelId;return(0,r.jsxs)("button",{type:"button",className:L("group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left transition-colors",t?"bg-foreground/[0.07]":"hover:bg-foreground/[0.03]"),onClick:()=>h({kind:"model",provider:e.provider,modelId:e.modelId,query:eS?.query}),children:[(0,r.jsx)("div",{className:L("flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",t?"border-foreground bg-foreground":"border-foreground/25"),children:t&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-background"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-foreground",children:e.name||e.modelId}),e.isCurrent&&(0,r.jsx)(oH,{status:"ok"})]}),(0,r.jsx)("div",{className:"mt-0.5 font-mono text-[11px] text-muted-foreground",children:e.modelId})]}),(0,r.jsxs)("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.isCurrent&&(0,r.jsx)("span",{className:"rounded bg-foreground/10 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:"Active"}),e.reasoning&&(0,r.jsx)("span",{className:"rounded bg-foreground/10 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:"Thinking"})]})]},`${e.provider}/${e.modelId}`)})})]},e))}):(0,r.jsx)("p",{className:"py-6 text-center text-xs text-muted-foreground",children:"No models matched."}),(0,r.jsx)("div",{className:"flex justify-end border-t border-border/50 pt-3",children:(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>eS?.provider&&eS?.modelId&&void I(eS.provider,eS.modelId),disabled:!eS?.provider||!eS.modelId||"set_model"===en.pendingAction,"data-testid":"command-surface-apply-model",className:"h-8 gap-1.5",children:["set_model"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5"}),"Apply model"]})})]}),(0,r.jsx)("div",{className:"border-t border-border/50 pt-6",children:(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-thinking",children:[(0,r.jsx)(oV,{title:"Thinking level",status:(0,r.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:d.boot?.bridge.sessionState?.thinkingLevel??"off"})}),(0,r.jsx)("div",{className:"space-y-1",children:ei.map(e=>{let t=eC?.level===e,s=d.boot?.bridge.sessionState?.thinkingLevel===e,a="off"===e?"No reasoning overhead":"minimal"===e?"Light reasoning":"low"===e?"Basic analysis":"medium"===e?"Balanced reasoning":"high"===e?"Deep analysis":"Maximum deliberation";return(0,r.jsxs)("button",{type:"button",className:L("flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",t?"bg-foreground/[0.07]":"hover:bg-foreground/[0.03]"),onClick:()=>h({kind:"thinking",level:e}),children:[(0,r.jsx)("div",{className:L("flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",t?"border-foreground bg-foreground":"border-foreground/25"),children:t&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-background"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-medium capitalize text-foreground",children:e}),s&&(0,r.jsx)(oH,{status:"ok"})]}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:a})]})]},e)})}),(0,r.jsx)("div",{className:"flex justify-end border-t border-border/50 pt-3",children:(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>eC&&void $(eC.level),disabled:!eC||"set_thinking_level"===en.pendingAction,"data-testid":"command-surface-apply-thinking",className:"h-8 gap-1.5",children:["set_thinking_level"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(rk.A,{className:"h-3.5 w-3.5"}),"Apply"]})})]})})]});case"session-behavior":case"queue":case"compaction":case"retry":return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("div",{className:"space-y-5","data-testid":"command-surface-queue-settings",children:[(0,r.jsx)(oV,{title:"Queue modes"}),(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Steering mode"}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:"How steering messages queue during streaming"})]}),ex.steeringMode.pending&&(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"})]}),(0,r.jsx)(oQ,{options:[{value:"all",label:"Queue all"},{value:"one-at-a-time",label:"One at a time"}],value:em?.steeringMode??null,onChange:e=>void D(e),disabled:!em||eJ}),ex.steeringMode.error&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:ex.steeringMode.error})]}),(0,r.jsx)("div",{className:"border-t border-border/50"}),(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Follow-up mode"}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:"How follow-up prompts sequence during a live turn"})]}),ex.followUpMode.pending&&(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"})]}),(0,r.jsx)(oQ,{options:[{value:"all",label:"Queue all"},{value:"one-at-a-time",label:"One at a time"}],value:em?.followUpMode??null,onChange:e=>void F(e),disabled:!em||eJ}),ex.followUpMode.error&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:ex.followUpMode.error})]})]}),(0,r.jsx)("div",{className:"border-t border-border/50 pt-4",children:(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-auto-compaction-settings",children:[(0,r.jsx)(oV,{title:"Auto-compaction",status:em?.isCompacting?(0,r.jsxs)("span",{className:"flex items-center gap-1.5 text-xs text-warning",children:[(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"})," Compacting"]}):null}),(0,r.jsx)(oY,{label:"Auto-compact",description:"Automatically compact when context thresholds are crossed",checked:em?.autoCompactionEnabled??!1,onCheckedChange:e=>void M(e),disabled:!em||eZ,busy:eZ,testId:"command-surface-toggle-auto-compaction"}),ex.autoCompaction.error&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:ex.autoCompaction.error}),ex.autoCompaction.result&&(0,r.jsx)("p",{className:"text-xs text-success",children:ex.autoCompaction.result})]})}),(0,r.jsx)("div",{className:"border-t border-border/50 pt-4",children:(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-retry-settings",children:[(0,r.jsx)(oV,{title:"Retry",status:em?.retryInProgress?(0,r.jsxs)("span",{className:"flex items-center gap-1.5 text-xs text-warning",children:[(0,r.jsx)(id.A,{className:"h-3 w-3"})," Attempt ",Math.max(1,em.retryAttempt)]}):null}),(0,r.jsx)(oY,{label:"Auto-retry",description:"Automatically retry on transient failures",checked:em?.autoRetryEnabled??!1,onCheckedChange:e=>void q(e),disabled:!em||e0,busy:e0,testId:"command-surface-toggle-auto-retry"}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"command-surface-auto-retry-state",children:e0?"Updating auto-retry…":ex.autoRetry.error?ex.autoRetry.error:ex.autoRetry.result?ex.autoRetry.result:em?.autoRetryEnabled?"Auto-retry enabled":"Auto-retry disabled"}),em?.retryInProgress&&(0,r.jsxs)("div",{className:"flex items-center justify-between rounded-lg border border-warning/20 bg-warning/5 px-4 py-3",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Retry in progress"}),(0,r.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Attempt ",Math.max(1,em.retryAttempt)," is active"]})]}),(0,r.jsxs)(J,{type:"button",variant:"destructive",size:"sm",onClick:()=>void O(),disabled:e2,"data-testid":"command-surface-abort-retry",className:"h-7 gap-1.5 text-xs",children:[e2?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(i.A,{className:"h-3 w-3"}),"Abort"]})]}),ex.autoRetry.error&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:ex.autoRetry.error}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"command-surface-abort-retry-state",children:e2?"Aborting retry…":ex.abortRetry.error?ex.abortRetry.error:ex.abortRetry.result?ex.abortRetry.result:em?.retryInProgress?"Retry can be aborted":"No retry in progress"}),ex.abortRetry.error&&(0,r.jsx)("p",{className:"text-xs text-destructive",children:ex.abortRetry.error})]})})]});case"recovery":return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-recovery",children:[(0,r.jsx)("div",{className:"text-xs text-muted-foreground","data-testid":"command-surface-recovery-state",children:eU?"Loading recovery diagnostics…":ec.error?"Recovery diagnostics failed":ec.stale?"Recovery diagnostics stale":ec.loaded?"Recovery diagnostics loaded":"Recovery diagnostics idle"}),(0,r.jsx)(oV,{title:"Recovery",status:ez?(0,r.jsx)(oH,{status:"healthy"===ez.summary.tone?"ok":"warning"===ez.summary.tone?"warning":"error"}):null,action:(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>void g(),disabled:eU,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3",eU&&"animate-spin")}),"Refresh"]})}),ec.error&&(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5 text-xs text-destructive","data-testid":"command-surface-recovery-error",children:ec.error}),eU&&!ez&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),"Loading diagnostics…"]}),(0,r.jsx)("div",{className:"flex flex-wrap gap-2 border-t border-border/50 pt-3","data-testid":"command-surface-recovery-actions",children:(0,r.jsx)(J,{type:"button",variant:"default",size:"sm",onClick:()=>void g(),"data-testid":"command-surface-recovery-action-refresh_diagnostics",className:"h-7 text-xs",children:"Refresh diagnostics"})})]}),ez?.status==="unavailable"&&!ec.error&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"space-y-1 rounded-lg border border-border/50 bg-card/50 px-4 py-3","data-testid":"command-surface-recovery-summary",children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:ez.summary.label}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:ez.summary.detail})]}),(0,r.jsx)("div",{className:"flex flex-wrap gap-2 border-t border-border/50 pt-3","data-testid":"command-surface-recovery-actions",children:(0,r.jsx)(J,{type:"button",variant:"default",size:"sm",onClick:()=>void g(),"data-testid":"command-surface-recovery-action-refresh_diagnostics",className:"h-7 text-xs",children:"Refresh diagnostics"})})]}),ez&&"unavailable"!==ez.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"space-y-1","data-testid":"command-surface-recovery-summary",children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:ez.summary.label}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:ez.summary.detail})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5",children:[(0,r.jsx)("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Validation"}),(0,r.jsx)("div",{className:"mt-1 text-lg font-semibold tabular-nums text-foreground",children:ez.summary.validationCount})]}),(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5",children:[(0,r.jsx)("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Doctor"}),(0,r.jsx)("div",{className:"mt-1 text-lg font-semibold tabular-nums text-foreground",children:ez.summary.doctorIssueCount})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[ez.summary.retryInProgress&&(0,r.jsxs)(nI,{variant:"default",className:"text-[10px]",children:["Retry ",Math.max(1,ez.summary.retryAttempt)]}),ez.summary.compactionActive&&(0,r.jsx)(nI,{variant:"default",className:"text-[10px]",children:"Compacting"}),ez.summary.lastFailurePhase&&(0,r.jsxs)(nI,{variant:"destructive",className:"text-[10px]",children:["Phase ",ez.summary.lastFailurePhase]}),ec.stale&&(0,r.jsx)(nI,{variant:"outline",className:"text-[10px]",children:"Stale"})]}),ez.bridge.lastFailure&&(0,r.jsxs)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2.5","data-testid":"command-surface-recovery-last-failure",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-destructive",children:"Last failure"}),(0,r.jsx)("p",{className:"mt-1 text-xs text-destructive/80",children:ez.bridge.lastFailure.message}),(0,r.jsxs)("div",{className:"mt-1.5 flex gap-3 text-[10px] text-destructive/60",children:[(0,r.jsxs)("span",{children:["Phase: ",ez.bridge.lastFailure.phase]}),(0,r.jsx)("span",{children:oK(ez.bridge.lastFailure.at)})]})]}),ez.validation.topIssues.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Validation issues"}),ez.validation.topIssues.map(e=>(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2",children:[(0,r.jsx)("div",{className:"flex items-center gap-2",children:(0,r.jsx)(nI,{variant:"error"===e.severity?"destructive":"outline",className:"text-[10px]",children:e.code})}),(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:e.message}),e.suggestion&&(0,r.jsxs)("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:["→ ",e.suggestion]})]},`${e.code}:${e.file??e.message}`))]}),ez.doctor.topIssues.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Doctor issues"}),ez.doctor.topIssues.map(e=>(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2",children:[(0,r.jsx)(nI,{variant:"outline",className:"text-[10px]",children:e.code}),(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:e.message})]},`${e.code}:${e.unitId??e.message}`))]}),ez.interruptedRun.detected&&(0,r.jsxs)("div",{className:"rounded-lg border border-warning/20 bg-warning/5 px-3 py-2.5","data-testid":"command-surface-recovery-interrupted-run",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-warning",children:"Interrupted run detected"}),(0,r.jsxs)("div",{className:"mt-1 space-y-1 text-xs text-warning/80",children:[(0,r.jsx)("p",{children:"Available: yes"}),(0,r.jsx)("p",{children:"Detected: yes"}),(0,r.jsx)("p",{children:ez.interruptedRun.detail})]}),(0,r.jsxs)("div",{className:"mt-1.5 grid gap-1 text-[10px] text-warning/60",children:[(0,r.jsxs)("span",{children:["Tool calls: ",ez.interruptedRun.counts.toolCalls]}),(0,r.jsxs)("span",{children:["Files written: ",ez.interruptedRun.counts.filesWritten]}),(0,r.jsxs)("span",{children:["Commands: ",ez.interruptedRun.counts.commandsRun]}),(0,r.jsxs)("span",{children:["Errors: ",ez.interruptedRun.counts.errors]}),(0,r.jsxs)("span",{children:["Last forensic error: ",ez.interruptedRun.lastError??"[redacted]"]})]})]}),(0,r.jsx)("div",{className:"flex flex-wrap gap-2 border-t border-border/50 pt-3","data-testid":"command-surface-recovery-actions",children:ez.actions.browser.length>0?ez.actions.browser.map(e=>(0,r.jsx)(J,{type:"button",variant:"danger"===e.emphasis?"destructive":"primary"===e.emphasis?"default":"outline",size:"sm",onClick:()=>(e=>{switch(e){case"refresh_diagnostics":g();return;case"refresh_workspace":m({soft:!0});return;case"open_retry_controls":x("retry");return;case"open_resume_controls":u("resume",{source:"surface"});return;case"open_auth_controls":x("auth");return;default:return}})(e.id),"data-testid":`command-surface-recovery-action-${e.id}`,className:"h-7 text-xs",children:e.label},e.id)):(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:eU?"Loading recovery actions…":"No browser recovery actions available."})}),ez.actions.commands.length>0&&(0,r.jsxs)("div",{className:"space-y-2 border-t border-border/50 pt-3","data-testid":"command-surface-recovery-commands",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Suggested commands"}),ez.actions.commands.map(e=>(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2 text-xs",children:[(0,r.jsx)("div",{className:"font-mono text-foreground",children:e.command}),(0,r.jsx)("p",{className:"mt-1 text-muted-foreground",children:e.label})]},e.command))]})]})]});case"auth":return eo?(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-auth",children:[(0,r.jsx)(oV,{title:"Auth",status:(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"login"===eI?"Login":"logout"===eI?"Logout":"Manage"})}),(0,r.jsx)("div",{className:"space-y-1",children:eo.required.providers.map(e=>{let t=e.id===e$?.id;return(0,r.jsxs)("button",{type:"button",className:L("flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",t?"bg-foreground/[0.07]":"hover:bg-foreground/[0.03]"),onClick:()=>h({kind:"auth",providerId:e.id,intent:eI}),children:[(0,r.jsx)("div",{className:L("flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",t?"border-foreground bg-foreground":"border-foreground/25"),children:t&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-background"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-foreground",children:e.label}),e.configured&&(0,r.jsx)(oH,{status:"ok"})]}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:e.configured?`via ${e.configuredVia}`:"Not configured"})]}),e.recommended&&(0,r.jsx)("span",{className:"rounded bg-foreground/10 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:"Recommended"})]},e.id)})}),e$&&(0,r.jsxs)("div",{className:"space-y-4 border-t border-border/50 pt-3",children:[(0,r.jsx)("div",{className:"flex items-center justify-between",children:(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:e$.label}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:e$.configuredVia??"Not configured"})]})}),e$.supports.apiKey&&(0,r.jsx)("form",{className:"space-y-3",onSubmit:e=>{e.preventDefault(),e3.trim()&&H(e$.id,e3)},children:(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{type:"password",autoComplete:"off",value:e3,onChange:e=>ef(t=>({...t,[e$.id]:e.target.value})),placeholder:"Paste API key",className:"h-8 flex-1 text-xs",disabled:eM,"data-testid":"command-surface-api-key-input"}),(0,r.jsxs)(J,{type:"submit",size:"sm",disabled:!e3.trim()||eM,"data-testid":"command-surface-save-api-key",className:"h-8 gap-1.5",children:["save_api_key"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(nF.A,{className:"h-3.5 w-3.5"}),"Save"]})]})}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-2",children:[e$.supports.oauth&&e$.supports.oauthAvailable&&(0,r.jsxs)(J,{type:"button",variant:"outline",size:"sm",disabled:eM,onClick:()=>void V(e$.id),"data-testid":"command-surface-start-provider-flow",className:"h-8 gap-1.5 text-xs",children:["start_provider_flow"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(im.A,{className:"h-3.5 w-3.5"}),"Browser sign-in"]}),(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",disabled:eM,onClick:()=>void X(e$.id),"data-testid":"command-surface-logout-provider",className:"h-8 gap-1.5 text-xs text-destructive hover:text-destructive",children:["logout_provider"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(k.A,{className:"h-3.5 w-3.5"}),"Logout"]})]}),el&&el.providerId===e$.id&&(0,r.jsxs)("div",{className:"space-y-3 rounded-lg border border-foreground/10 bg-foreground/[0.03] px-4 py-3","data-testid":"command-surface-active-flow",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs",children:[(0,r.jsx)(nI,{variant:"outline",className:"text-[10px]",children:el.status.replaceAll("_"," ")}),(0,r.jsx)("span",{className:"text-muted-foreground",children:new Date(el.updatedAt).toLocaleTimeString()})]}),el.auth?.instructions&&(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:el.auth.instructions}),el.auth?.url&&(0,r.jsx)(J,{asChild:!0,variant:"outline",size:"sm",className:"h-7 gap-1.5 text-xs","data-testid":"command-surface-open-auth-url",children:(0,r.jsxs)("a",{href:el.auth.url,target:"_blank",rel:"noreferrer",children:[(0,r.jsx)(nM.A,{className:"h-3 w-3"}),"Open sign-in page"]})}),el.progress.length>0&&(0,r.jsx)("div",{className:"space-y-1",children:el.progress.map((e,t)=>(0,r.jsx)("div",{className:"rounded-md border border-border/50 bg-card/50 px-2.5 py-1.5 text-xs text-muted-foreground",children:e},`${el.flowId}-${t}`))}),el.prompt&&(0,r.jsxs)("form",{className:"space-y-2",onSubmit:e=>{e.preventDefault(),(el.prompt?.allowEmpty||eb.trim())&&Y(el.flowId,eb)},children:[(0,r.jsx)(rP,{value:eb,onChange:e=>ev(e.target.value),placeholder:el.prompt.placeholder||"Enter value",className:"h-8 text-xs",disabled:eM,"data-testid":"command-surface-flow-input"}),(0,r.jsx)("p",{className:"text-[11px] text-muted-foreground",children:el.prompt.message}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsxs)(J,{type:"submit",size:"sm",disabled:eM||!el.prompt.allowEmpty&&!eb.trim(),className:"h-7 gap-1.5 text-xs",children:["submit_provider_flow_input"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(nP.A,{className:"h-3 w-3"}),"Continue"]}),(0,r.jsx)(J,{type:"button",variant:"ghost",size:"sm",disabled:eM,onClick:()=>void Q(el.flowId),className:"h-7 text-xs",children:"Cancel"})]})]})]}),"idle"!==eo.bridgeAuthRefresh.phase&&(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 text-xs",children:[(0,r.jsx)("span",{className:"font-medium text-foreground",children:"Auth refresh"}),(0,r.jsx)("span",{className:"ml-2 text-muted-foreground",children:"pending"===eo.bridgeAuthRefresh.phase?"Refreshing…":"failed"===eo.bridgeAuthRefresh.phase?eo.bridgeAuthRefresh.error||"Failed.":"Complete."})]})]})]}):null;case"admin":return(0,r.jsxs)("div",{className:"space-y-5","data-testid":"command-surface-admin",children:[(0,r.jsx)(oV,{title:"Admin",status:(0,r.jsx)(nI,{variant:"outline",className:"border-warning/20 bg-warning/[0.06] text-[10px] text-warning",children:"Dev only"})}),(0,r.jsx)(oY,{label:"UI overrides",description:"Enable keyboard shortcuts and forced UI states for development",checked:e4.enabled,onCheckedChange:e4.setEnabled,testId:"admin-ui-overrides-master"}),e4.enabled&&(0,r.jsxs)("div",{className:"space-y-2 rounded-lg border border-border/50 bg-card/50 p-3",children:[(0,r.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Override shortcuts"}),nw.map(e=>(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3 rounded-md px-3 py-2.5 transition-colors hover:bg-foreground/[0.03]",children:[(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-foreground",children:e.label}),(0,r.jsx)(nI,{variant:"outline",className:"border-border font-mono text-[10px] text-muted-foreground",children:e.shortcutLabel})]}),(0,r.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:e.description})]}),(0,r.jsx)(ip,{checked:e4.overrides[e.key],onCheckedChange:()=>e4.toggle(e.key),"data-testid":`admin-override-${e.key}`})]},e.key))]}),(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 p-3 space-y-3",children:[(0,r.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Onboarding"}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3 px-3 py-2.5",children:[(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Run setup wizard"}),(0,r.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Opens the full onboarding flow as a new user would see it."})]}),(0,r.jsx)(J,{type:"button",size:"sm",className:"h-8 shrink-0 gap-1.5 text-xs",onClick:()=>{c(),window.setTimeout(()=>{e4.enabled||e4.setEnabled(!0),e4.overrides.forceOnboarding||e4.toggle("forceOnboarding")},150)},"data-testid":"admin-trigger-onboarding",children:"Launch"})]})]}),(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 text-xs text-muted-foreground",children:["This tab is only visible when running via"," ",(0,r.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"npm run gsd:web"}),". Overrides reset on page refresh."]})]});case"git":let e;return e=ed.result,(0,r.jsxs)("div",{className:"space-y-5","data-testid":"command-surface-git-summary",children:[(0,r.jsx)("div",{className:"text-xs text-muted-foreground","data-testid":"command-surface-git-state",children:eO?"Loading git summary…":ed.error?"Git summary failed":e?.kind==="not_repo"?"No git repository":e?.kind==="repo"?`Repo ready${e.hasChanges?" — changes detected":" — clean"}`:"Git summary idle"}),eO&&!e&&(0,r.jsxs)("div",{className:"flex flex-col items-center justify-center gap-3 py-16",children:[(0,r.jsx)(E.A,{className:"h-5 w-5 animate-spin text-muted-foreground"}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"Loading repo state…"})]}),ed.error&&(0,r.jsx)("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 px-4 py-3 text-xs text-destructive","data-testid":"command-surface-git-error",children:ed.error}),!ed.error&&e?.kind==="not_repo"&&(0,r.jsxs)("div",{className:"flex flex-col items-center gap-3 py-16 text-center","data-testid":"command-surface-git-not-repo",children:[(0,r.jsx)("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-border/50 bg-card/50",children:(0,r.jsx)(N.A,{className:"h-4.5 w-4.5 text-muted-foreground"})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-sm font-medium text-foreground",children:"No Git repository"}),(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:e.message})]})]}),!ed.error&&e?.kind==="repo"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,r.jsx)("span",{className:"font-mono",children:eY(e.project.repoRoot,3)}),e.project.repoRelativePath&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(A.A,{className:"h-3 w-3 text-muted-foreground"}),(0,r.jsx)("span",{className:"font-mono",children:e.project.repoRelativePath})]})]}),(0,r.jsx)("div",{className:"grid grid-cols-4 gap-1.5","data-testid":"command-surface-git-counts",children:[{label:"Staged",count:e.counts.staged,active:e.counts.staged>0,color:"text-success"},{label:"Modified",count:e.counts.dirty,active:e.counts.dirty>0,color:"text-warning"},{label:"Untracked",count:e.counts.untracked,active:e.counts.untracked>0,color:"text-muted-foreground"},{label:"Conflicts",count:e.counts.conflicts,active:e.counts.conflicts>0,color:"text-destructive"}].map(({label:e,count:t,active:s,color:a})=>(0,r.jsxs)("div",{className:L("rounded-md border px-2 py-2 text-center transition-colors",s?"border-border bg-card":"border-border/50 bg-card/50"),children:[(0,r.jsx)("div",{className:L("text-base font-semibold tabular-nums leading-none",s?a:"text-muted-foreground"),children:t}),(0,r.jsx)("div",{className:L("mt-1.5 text-[10px] leading-none","text-muted-foreground"),children:e})]},e))}),e.changedFiles.length>0&&(0,r.jsxs)("div",{"data-testid":"command-surface-git-files",children:[(0,r.jsxs)("div",{className:"mb-2 flex items-center justify-between",children:[(0,r.jsx)("span",{className:"text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:"Changes"}),(0,r.jsxs)("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[e.changedFiles.length,e.truncatedFileCount>0?`+${e.truncatedFileCount}`:""," files"]})]}),(0,r.jsx)("div",{className:"space-y-px rounded-lg border border-border/50 bg-card/50 overflow-hidden",children:e.changedFiles.map(e=>(0,r.jsxs)("div",{className:"group flex items-center gap-2.5 px-3 py-2 transition-colors hover:bg-foreground/[0.03]",children:[(0,r.jsx)("span",{className:L("flex h-5 w-5 shrink-0 items-center justify-center rounded text-[10px] font-semibold",(e=>{switch(e){case"M":return"text-warning bg-warning/10";case"A":return"text-success bg-success/10";case"D":case"U":return"text-destructive bg-destructive/10";case"R":case"C":return"text-info bg-info/10";default:return"text-muted-foreground bg-foreground/5"}})(e.status)),children:e.status}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-foreground/80",children:e.path}),e.conflict&&(0,r.jsx)("span",{className:"shrink-0 rounded bg-destructive/15 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-destructive",children:"conflict"})]},`${e.status}:${e.repoPath}`))}),e.truncatedFileCount>0&&(0,r.jsxs)("p",{className:"mt-1.5 text-center text-[11px] text-muted-foreground",children:["+",e.truncatedFileCount," more files not shown"]})]}),0===e.changedFiles.length&&(0,r.jsxs)("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[(0,r.jsx)(rk.A,{className:"h-4 w-4 text-success/60"}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"Working tree clean"})]})]})]});case"resume":return e7("resume");case"name":return e7("name");case"fork":return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-fork",children:[(0,r.jsx)(oV,{title:"Fork",action:(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>void G(),disabled:eG,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3","load_fork_messages"===en.pendingAction&&"animate-spin")}),"Refresh"]})}),eG&&0===en.forkMessages.length?(0,r.jsxs)("div",{className:"flex items-center gap-2 py-6 text-xs text-muted-foreground",children:[(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}),"Loading fork points…"]}):en.forkMessages.length>0?(0,r.jsx)("div",{className:"space-y-1",children:en.forkMessages.map(e=>{let t=eE?.entryId===e.entryId;return(0,r.jsxs)("button",{type:"button",className:L("flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",t?"bg-foreground/[0.07]":"hover:bg-foreground/[0.03]"),onClick:()=>h({kind:"fork",entryId:e.entryId}),children:[(0,r.jsx)("div",{className:L("mt-1 flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition-colors",t?"border-foreground bg-foreground":"border-foreground/25"),children:t&&(0,r.jsx)(rk.A,{className:"h-2.5 w-2.5 text-background"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] text-muted-foreground",children:e.entryId}),(0,r.jsx)("p",{className:"mt-0.5 text-sm text-foreground",children:e.text})]})]},e.entryId)})}):(0,r.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:"No fork points available yet."}),(0,r.jsx)("div",{className:"flex justify-end border-t border-border/50 pt-3",children:(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>eE?.entryId&&void W(eE.entryId),disabled:!eE?.entryId||"fork_session"===en.pendingAction,"data-testid":"command-surface-apply-fork",className:"h-8 gap-1.5",children:["fork_session"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(N.A,{className:"h-3.5 w-3.5"}),"Create fork"]})})]});case"session":return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-session",children:[(0,r.jsx)(oV,{title:"Session",status:(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:ep??"pending"}),action:(0,r.jsxs)(J,{type:"button",variant:"ghost",size:"sm",onClick:()=>void z(),disabled:eW,className:"h-7 gap-1.5 text-xs",children:[(0,r.jsx)(io.A,{className:L("h-3 w-3","load_session_stats"===en.pendingAction&&"animate-spin")}),"Refresh"]})}),en.sessionStats?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"grid grid-cols-3 gap-2",children:[{label:"Input",value:eQ(en.sessionStats.tokens.input)},{label:"Output",value:eQ(en.sessionStats.tokens.output)},{label:"Total",value:eQ(en.sessionStats.tokens.total)}].map(({label:e,value:t})=>(0,r.jsxs)("div",{className:"rounded-lg border border-border/50 bg-card/50 px-3 py-2.5 text-center",children:[(0,r.jsx)("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:e}),(0,r.jsx)("div",{className:"mt-1 text-sm font-semibold tabular-nums text-foreground",children:t})]},e))}),(0,r.jsxs)("div",{className:"divide-y divide-border/30 rounded-lg border border-border/50 bg-card/50",children:[(0,r.jsxs)("div",{className:"px-4 py-2",children:[(0,r.jsx)(oJ,{label:"User messages",children:en.sessionStats.userMessages}),(0,r.jsx)(oJ,{label:"Assistant messages",children:en.sessionStats.assistantMessages}),(0,r.jsx)(oJ,{label:"Tool calls",children:en.sessionStats.toolCalls}),(0,r.jsx)(oJ,{label:"Tool results",children:en.sessionStats.toolResults})]}),(0,r.jsxs)("div",{className:"px-4 py-2",children:[(0,r.jsx)(oJ,{label:"Total messages",children:en.sessionStats.totalMessages}),(0,r.jsx)(oJ,{label:"Cost",children:eX(en.sessionStats.cost)}),en.sessionStats.tokens.cacheRead>0&&(0,r.jsx)(oJ,{label:"Cache read",children:eQ(en.sessionStats.tokens.cacheRead)})]})]})]}):(0,r.jsx)("p",{className:"py-4 text-center text-xs text-muted-foreground",children:"Refresh to load session stats."}),(0,r.jsxs)("div",{className:"space-y-3 border-t border-border/50 pt-3",children:[(0,r.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Export"}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(rP,{value:eP?.outputPath??"",onChange:e=>h({kind:"session",outputPath:e.target.value}),placeholder:"Output path (optional)",className:"h-8 flex-1 text-xs",disabled:"export_html"===en.pendingAction,"data-testid":"command-surface-export-path"}),(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>void B(eP?.outputPath),disabled:"export_html"===en.pendingAction,"data-testid":"command-surface-export-session",className:"h-8 gap-1.5",children:["export_html"===en.pendingAction?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(aj.A,{className:"h-3.5 w-3.5"}),"Export HTML"]})]})]})]});case"compact":return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"command-surface-compact",children:[(0,r.jsx)(oV,{title:"Manual compact",status:eV?(0,r.jsxs)("span",{className:"flex items-center gap-1.5 text-xs text-warning",children:[(0,r.jsx)(E.A,{className:"h-3 w-3 animate-spin"})," Working"]}):null}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("label",{className:"text-xs font-medium text-muted-foreground",htmlFor:"command-surface-compact-instructions",children:"Custom instructions"}),(0,r.jsx)(nm,{id:"command-surface-compact-instructions","data-testid":"command-surface-compact-instructions",value:e_?.customInstructions??"",onChange:e=>h({kind:"compact",customInstructions:e.target.value}),placeholder:"Tell compaction what to preserve or emphasize…",rows:4,disabled:eV,className:"text-xs"})]}),(0,r.jsx)("div",{className:"flex justify-end",children:(0,r.jsxs)(J,{type:"button",size:"sm",onClick:()=>void K(e_?.customInstructions),disabled:eV,"data-testid":"command-surface-apply-compact",className:"h-8 gap-1.5",children:[eV?(0,r.jsx)(E.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(ii.A,{className:"h-3.5 w-3.5"}),"Compact now"]})}),en.lastCompaction&&(0,r.jsxs)("div",{className:"space-y-2 rounded-lg border border-border/50 bg-card/50 px-4 py-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Last compaction"}),(0,r.jsxs)("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[eQ(en.lastCompaction.tokensBefore)," before"]})]}),(0,r.jsx)("p",{className:"whitespace-pre-wrap text-xs text-foreground",children:en.lastCompaction.summary}),(0,r.jsxs)("p",{className:"text-[11px] text-muted-foreground",children:["First kept: ",en.lastCompaction.firstKeptEntryId]})]})]});case"workspace":return(0,r.jsx)(oj,{});case"integrations":return(0,r.jsx)(on,{});case"gsd-forensics":return(0,r.jsx)(iC,{});case"gsd-doctor":return(0,r.jsx)(iT,{});case"gsd-skill-health":return(0,r.jsx)(iE,{});case"gsd-knowledge":return(0,r.jsx)(iY,{initialTab:"knowledge"});case"gsd-capture":case"gsd-triage":return(0,r.jsx)(iY,{initialTab:"captures"});case"gsd-prefs":return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsx)(oj,{}),(0,r.jsx)(i6,{}),(0,r.jsx)(oe,{}),(0,r.jsx)(os,{}),(0,r.jsx)(on,{}),(0,r.jsx)(od,{}),(0,r.jsx)(ou,{})]});case"gsd-mode":return(0,r.jsx)(oe,{});case"gsd-config":return(0,r.jsx)(os,{});case"gsd-quick":return(0,r.jsx)(o_,{});case"gsd-history":return(0,r.jsx)(oI,{});case"gsd-undo":return(0,r.jsx)(o$,{});case"gsd-steer":return(0,r.jsx)(oD,{});case"gsd-hooks":return(0,r.jsx)(oF,{});case"gsd-inspect":return(0,r.jsx)(oL,{});case"gsd-export":return(0,r.jsx)(oM,{});case"gsd-cleanup":return(0,r.jsx)(oq,{});case"gsd-queue":return(0,r.jsx)(oO,{});case"gsd-status":return(0,r.jsx)(oU,{});default:if(en.section?.startsWith("gsd-"))return(0,r.jsxs)("div",{className:"p-4 text-sm text-muted-foreground","data-testid":`gsd-surface-${en.section}`,children:[(0,r.jsxs)("p",{className:"font-medium text-foreground",children:["/gsd ",en.section.slice(4)]}),(0,r.jsx)("p",{className:"mt-1",children:"Unknown GSD surface."})]});return null}})()})})]})]})]})})}function oZ(){let[e,t]=(0,n.useState)(null),[s,a]=(0,n.useState)(!1),[i,o]=(0,n.useState)(!1),l=(0,n.useRef)(null),d=(0,n.useCallback)(async()=>{try{let e=await e$("/api/update");if(!e.ok)return;let s=await e.json();t(s)}catch{}},[]);(0,n.useEffect)(()=>{d()},[d]),(0,n.useEffect)(()=>(e?.updateStatus==="running"&&(l.current=setInterval(()=>void d(),3e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}),[e?.updateStatus,d]);let c=async()=>{a(!0);try{let e=await e$("/api/update",{method:"POST"});e.ok||202===e.status?await d():409===e.status&&await d()}catch{}finally{a(!1)}};if(!e||!e.updateAvailable&&"idle"===e.updateStatus||i)return null;let u="running"===e.updateStatus,m="success"===e.updateStatus,x="error"===e.updateStatus,h=e.targetVersion??e.latestVersion;return(0,r.jsxs)("div",{"data-testid":"update-banner",className:L("flex items-center gap-3 border-b px-4 py-2 text-xs",m&&"border-success/20 bg-success/10 text-success",x&&"border-destructive/20 bg-destructive/10 text-destructive",!m&&!x&&"border-warning/20 bg-warning/10 text-warning"),children:[m?(0,r.jsxs)("span",{className:"flex-1","data-testid":"update-banner-message",children:["Update complete — restart GSD to use v",h]}):x?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"flex-1","data-testid":"update-banner-message",children:["Update failed",e.error?`: ${e.error}`:""]}),(0,r.jsx)("button",{onClick:()=>void c(),disabled:s,className:L("flex-shrink-0 rounded border border-destructive/30 bg-background px-2 py-0.5 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10",s&&"cursor-not-allowed opacity-50"),"data-testid":"update-banner-retry",children:"Retry"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"flex-1","data-testid":"update-banner-message",children:u?(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(o0,{}),"Updating to v",h,"…"]}):(0,r.jsxs)(r.Fragment,{children:["Update available: v",e.currentVersion," → v",e.latestVersion]})}),!u&&(0,r.jsx)("button",{onClick:()=>void c(),disabled:s,className:L("flex-shrink-0 rounded border border-warning/30 bg-background px-2 py-0.5 text-xs font-medium text-warning transition-colors hover:bg-warning/10",s&&"cursor-not-allowed opacity-50"),"data-testid":"update-banner-action",children:"Update"})]}),(0,r.jsx)("button",{onClick:()=>o(!0),"aria-label":"Dismiss update banner",className:"flex-shrink-0 rounded p-0.5 opacity-50 transition-opacity hover:opacity-100","data-testid":"update-banner-dismiss",children:(0,r.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function o0(){return(0,r.jsxs)("svg",{className:"h-3 w-3 animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[(0,r.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,r.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})}let o1=new Set(["dashboard","power","chat","roadmap","files","activity","visualize"]);function o5(e){return`gsd-active-view:${e}`}function o2(){let[e,t]=(0,n.useState)("dashboard"),[s,l]=(0,n.useState)(!1),[d,c]=(0,n.useState)(300),[u,m]=(0,n.useState)(!1),x=(0,n.useRef)(!1),h=(0,n.useRef)(!1),p=(0,n.useRef)(0),g=(0,n.useRef)(0),[f,b]=(0,n.useState)(256),v=(0,n.useRef)(!1),j=(0,n.useRef)(0),y=(0,n.useRef)(0),[N,w]=(0,n.useState)(!1),[k,S]=(0,n.useState)(!1),[C,A]=(0,n.useState)(!1),[T,R]=(0,n.useState)(!1),[E,P]=(0,n.useState)(!1),_=tb(),{refreshBoot:I}=tv(),$=ts(_),D=_.boot?.project.cwd,F=D?D.split(/[\\/]/).filter(Boolean).at(-1)||D:"Current project",M=_.titleOverride?.trim()||null,q=eZ(_.boot?.workspace),O=tt(_);(0,n.useEffect)(()=>{if(k||!D)return;let e=window.setTimeout(()=>{try{let e=sessionStorage.getItem(o5(D));e&&o1.has(e)&&t(e)}catch{}S(!0)},0);return()=>window.clearTimeout(e)},[D,k]),(0,n.useEffect)(()=>{if(D)try{sessionStorage.setItem(o5(D),e)}catch{}},[e,D]),(0,n.useEffect)(()=>{let e=window.setTimeout(()=>{try{let e=localStorage.getItem("gsd-sidebar-collapsed");"true"===e&&w(!0)}catch{}},0);return()=>window.clearTimeout(e)},[]),(0,n.useEffect)(()=>{try{localStorage.setItem("gsd-sidebar-collapsed",String(N))}catch{}},[N]),(0,n.useEffect)(()=>{if("u"<typeof document)return;let e=F?`GSD - ${F}`:"GSD";document.title=M?`${M} \xb7 ${e}`:e},[M,F]);let U=(0,n.useCallback)(e=>{t(e),R(!1)},[]);(0,n.useEffect)(()=>{let e=()=>{t("files")};return window.addEventListener("gsd:open-file",e),()=>window.removeEventListener("gsd:open-file",e)},[]),(0,n.useEffect)(()=>{let e=e=>{o1.has(e.detail.view)&&U(e.detail.view)};return window.addEventListener("gsd:navigate-view",e),()=>window.removeEventListener("gsd:navigate-view",e)},[U]),(0,n.useEffect)(()=>{let e=()=>A(!0);return window.addEventListener("gsd:open-projects",e),()=>window.removeEventListener("gsd:open-projects",e)},[]),(0,n.useEffect)(()=>{let e=e=>{if(x.current){h.current=!0;let t=p.current-e.clientY;c(Math.max(150,Math.min(600,g.current+t)))}if(v.current){let t=j.current-e.clientX;b(Math.max(180,Math.min(480,y.current+t)))}},t=()=>{x.current=!1,v.current=!1,m(!1),document.body.style.cursor="",document.body.style.userSelect=""};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[]);let z=(0,n.useCallback)(e=>{x.current=!0,m(!0),p.current=e.clientY,g.current=d,document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[d]),B=(0,n.useCallback)(e=>{v.current=!0,j.current=e.clientX,y.current=f,document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[f]),G=!!_.commandInFlight||"idle"!==_.onboardingRequestState,W="idle"===_.bootStatus||"loading"===_.bootStatus;(0,n.useEffect)(()=>{if(!W)return;let e=ix.oR.loading("Connecting to workspace…",{description:"Establishing the live bridge session",duration:1/0});return()=>{ix.oR.dismiss(e)}},[W]);let K=_.boot?.projectDetection,H=!W&&"dashboard"===e&&null!=K&&"active-gsd"!==K.kind&&"empty-gsd"!==K.kind;return"unauthenticated"===_.bootStatus?(0,r.jsxs)("div",{className:"flex h-dvh flex-col items-center justify-center gap-6 bg-background p-8 text-center",children:[(0,r.jsx)(a.default,{src:"/logo-black.svg",alt:"GSD",width:57,height:16,className:"shrink-0 h-4 w-auto dark:hidden"}),(0,r.jsx)(a.default,{src:"/logo-white.svg",alt:"GSD",width:57,height:16,className:"shrink-0 h-4 w-auto hidden dark:block"}),(0,r.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,r.jsx)("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication Required"}),(0,r.jsxs)("p",{className:"max-w-sm text-sm text-muted-foreground",children:["This workspace requires an auth token. Copy the full URL from your terminal (including the"," ",(0,r.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"#token=…"})," ","part) or restart with"," ",(0,r.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"gsd --web"}),"."]})]})]}):(0,r.jsxs)("div",{className:"relative flex h-screen flex-col overflow-hidden bg-background text-foreground",children:[(0,r.jsxs)("header",{className:"flex h-12 flex-shrink-0 items-center justify-between border-b border-border bg-card px-2 md:px-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 md:gap-3 min-w-0",children:[(0,r.jsx)("button",{className:"flex md:hidden h-10 w-10 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/50 hover:text-foreground transition-colors",onClick:()=>R(!T),"aria-label":T?"Close navigation":"Open navigation","data-testid":"mobile-nav-toggle",children:T?(0,r.jsx)(i.A,{className:"h-5 w-5"}):(0,r.jsx)(o.A,{className:"h-5 w-5"})}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(a.default,{src:"/logo-black.svg",alt:"GSD",width:57,height:16,className:"shrink-0 h-4 w-auto dark:hidden"}),(0,r.jsx)(a.default,{src:"/logo-white.svg",alt:"GSD",width:57,height:16,className:"shrink-0 h-4 w-auto hidden dark:block"}),(0,r.jsx)(nI,{variant:"outline",className:"hidden sm:inline-flex text-[10px] rounded-full border-foreground/15 bg-accent/40 text-muted-foreground font-normal",children:"beta"})]}),(0,r.jsx)("span",{className:"hidden sm:inline text-2xl font-thin text-muted-foreground leading-none select-none",children:"/"}),(0,r.jsx)("span",{className:"hidden sm:inline text-sm text-muted-foreground truncate","data-testid":"workspace-project-cwd",title:D??void 0,children:W?(0,r.jsx)(tL,{className:"inline-block h-4 w-28 align-middle"}):(0,r.jsxs)(r.Fragment,{children:[F,M&&(0,r.jsx)("span",{className:"ml-2 inline-flex items-center rounded-full border border-foreground/15 bg-accent/60 px-2 py-0.5 text-[10px] font-medium text-foreground","data-testid":"workspace-title-override",title:M,children:M})]})})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 md:gap-3",children:[(0,r.jsx)("span",{className:"sr-only","data-testid":"workspace-connection-status",children:$.label}),(0,r.jsx)("span",{className:"hidden sm:inline text-xs text-muted-foreground","data-testid":"workspace-scope-label",children:W?(0,r.jsx)(tL,{className:"inline-block h-3.5 w-40 align-middle"}):(0,r.jsx)(sx,{label:q,size:"sm"})})]})]}),(0,r.jsx)(oZ,{}),!W&&O&&(0,r.jsxs)("div",{className:"flex items-center gap-3 border-b border-destructive/20 bg-destructive/10 px-4 py-2 text-xs text-destructive","data-testid":"workspace-error-banner",children:[(0,r.jsx)("span",{className:"flex-1",children:O}),(0,r.jsx)("button",{onClick:()=>void I(),disabled:G,className:L("flex-shrink-0 rounded border border-destructive/30 bg-background px-2 py-0.5 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10",G&&"cursor-not-allowed opacity-50"),children:"Retry"})]}),T&&(0,r.jsx)("div",{className:"fixed inset-0 z-40 bg-black/50 md:hidden",onClick:()=>R(!1),"data-testid":"mobile-nav-overlay"}),(0,r.jsx)("div",{className:L("fixed inset-y-0 left-0 z-50 w-64 transform bg-sidebar border-r border-border transition-transform duration-200 ease-out md:hidden",T?"translate-x-0":"-translate-x-full"),"data-testid":"mobile-nav-drawer",children:(0,r.jsx)(tB,{activeView:e,onViewChange:W?()=>{}:U,isConnecting:W,mobile:!0})}),E&&(0,r.jsx)("div",{className:"fixed inset-0 z-40 bg-black/50 md:hidden",onClick:()=>P(!1),"data-testid":"mobile-milestone-overlay"}),!H&&(0,r.jsx)("div",{className:L("fixed inset-y-0 right-0 z-50 w-72 transform bg-sidebar border-l border-border transition-transform duration-200 ease-out md:hidden",E?"translate-x-0":"translate-x-full"),"data-testid":"mobile-milestone-drawer",children:(0,r.jsx)(tU,{isConnecting:W,width:288,onCollapse:()=>P(!1)})}),(0,r.jsxs)("div",{className:"flex flex-1 overflow-hidden",children:[(0,r.jsx)("div",{className:"hidden md:flex",children:(0,r.jsx)(tB,{activeView:e,onViewChange:W?()=>{}:U,isConnecting:W})}),(0,r.jsxs)("div",{className:"flex flex-1 flex-col overflow-hidden",children:[(0,r.jsx)("div",{className:L("flex-1 overflow-hidden transition-all",s&&"h-1/3"),children:W?(0,r.jsx)(sC,{}):(0,r.jsxs)(r.Fragment,{children:["dashboard"===e&&(0,r.jsx)(sC,{onSwitchView:U,onExpandTerminal:()=>l(!0)}),"power"===e&&(0,r.jsx)(a1,{}),"roadmap"===e&&(0,r.jsx)(sE,{}),"files"===e&&(0,r.jsx)(ag,{}),"activity"===e&&(0,r.jsx)(ab,{}),"visualize"===e&&(0,r.jsx)(aG,{}),"chat"===e&&(0,r.jsx)(rJ,{})]})}),"power"!==e&&"chat"!==e&&(0,r.jsxs)("div",{className:"border-t border-border flex flex-col",style:{flexShrink:0},children:[(0,r.jsx)("div",{role:"button",tabIndex:0,onClick:()=>{if(h.current){h.current=!1;return}W||l(!s)},onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),W||l(!s))},className:L("flex h-8 w-full items-center justify-between bg-card px-3 text-xs select-none transition-colors",s&&"cursor-row-resize",!s&&!W&&"cursor-pointer hover:bg-muted/50",W&&"cursor-default"),onMouseDown:e=>{s&&z(e)},children:(0,r.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,r.jsx)("span",{className:"font-medium text-foreground",children:"Terminal"}),(0,r.jsx)("span",{className:"text-[10px] text-muted-foreground",children:s?"▼":"▲"})]})}),(0,r.jsx)("div",{className:"overflow-hidden",style:{height:s?d:0,transition:u?"none":"height 200ms"},children:(0,r.jsx)(st,{className:"h-full",projectCwd:_.boot?.project.cwd})})]})]}),!H&&!N&&(0,r.jsxs)("div",{className:"relative hidden md:flex h-full items-stretch",style:{flexShrink:0},children:[(0,r.jsx)("div",{className:"w-px bg-border"}),(0,r.jsx)("div",{className:"absolute left-[-3px] top-0 bottom-0 w-[7px] cursor-col-resize z-10 hover:bg-muted-foreground/20 transition-colors",onMouseDown:B})]}),(0,r.jsx)("div",{className:"hidden md:flex",children:!H&&(N?(0,r.jsx)(tz,{onExpand:()=>w(!1)}):(0,r.jsx)(tU,{isConnecting:W,width:f,onCollapse:()=>w(!0)}))})]}),(0,r.jsx)("div",{className:"hidden md:block",children:(0,r.jsx)(aV,{})}),!H&&(0,r.jsxs)("div",{className:"flex md:hidden h-12 items-center justify-between border-t border-border bg-card px-3","data-testid":"mobile-bottom-bar",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-xs text-muted-foreground truncate",children:[(0,r.jsx)("span",{className:"sr-only","data-testid":"workspace-connection-status-mobile",children:$.label}),(0,r.jsx)("span",{className:L("h-2 w-2 rounded-full shrink-0","success"===$.tone?"bg-success":"warning"===$.tone?"bg-warning":"danger"===$.tone?"bg-destructive":"bg-muted-foreground")}),(0,r.jsx)("span",{className:"truncate",children:q})]}),(0,r.jsx)("button",{onClick:()=>P(!E),className:"flex h-10 items-center gap-2 rounded-md px-3 text-xs font-medium text-muted-foreground hover:bg-accent/50 hover:text-foreground transition-colors","data-testid":"mobile-milestone-toggle",children:"Milestones"})]}),(0,r.jsx)(og,{open:C,onOpenChange:A}),(0,r.jsx)(oX,{}),(0,r.jsx)(nv,{}),(0,r.jsx)(is,{})]})}function o3(){return eI(),(0,r.jsx)(tD,{children:(0,r.jsx)(o4,{})})}function o4(){let e=tF(),t=(0,n.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot),s=t?e.getActiveStore():null;return((0,n.useEffect)(()=>{let e=()=>{let e=eI(),t=e?`/api/shutdown?_token=${e}`:"/api/shutdown";navigator.sendBeacon(t,"")};return window.addEventListener("pagehide",e),()=>{window.removeEventListener("pagehide",e)}},[]),t&&s)?(0,r.jsx)(tg,{store:s,children:(0,r.jsx)(nC,{children:(0,r.jsx)(o2,{})})}):(0,r.jsx)(oy,{})}}}]);