@shawnstack/quickforge 1.7.9 → 1.7.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentProfilesPage-BSM5w3bn.js → AgentProfilesPage-Cvb1KTz5.js} +1 -1
- package/dist/assets/ChatPanelHost-C7zV-xE_.js +48 -0
- package/dist/assets/{CloudAccountSettingsPage-BJMrfgy9.js → CloudAccountSettingsPage-mAs_nbvw.js} +1 -1
- package/dist/assets/{PluginsPage-mJkTmVVV.js → PluginsPage-mLvwvTmL.js} +1 -1
- package/dist/assets/{ScheduledTasksPage-DJj_NLm9.js → ScheduledTasksPage-CuUW_9lq.js} +1 -1
- package/dist/assets/{SettingsWorkspacePage-7lQ0Wl63.js → SettingsWorkspacePage-0OINfEqK.js} +390 -390
- package/dist/assets/{ShareLinksSettingsPage-DjFq_Lnb.js → ShareLinksSettingsPage-DqeyJYoD.js} +1 -1
- package/dist/assets/{SharedConversationPage-BbuNpcpP.js → SharedConversationPage-C7CDEoX9.js} +1 -1
- package/dist/assets/TerminalDock-CZXcuMpq.js +2 -0
- package/dist/assets/{WorkspaceInspector-0i6x-diB.js → WorkspaceInspector-CNSBOEvP.js} +3 -3
- package/dist/assets/index-BgMvQW1b.js +66 -0
- package/dist/assets/index-CB1g2D0f.css +3 -0
- package/dist/assets/local-tools-Dopjg9xq.js +270 -0
- package/dist/assets/{mcp-servers-dialog-BG4b67ea.js → mcp-servers-dialog-B2lALtTE.js} +1 -1
- package/dist/assets/{skills-dialog-DIzZvQqW.js → skills-dialog-DYp35JM3.js} +1 -1
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/server/acp/server.mjs +3 -6
- package/server/agent-manager.mjs +125 -43
- package/server/auto-archive.mjs +55 -8
- package/server/auto-compaction.mjs +0 -2
- package/server/context-usage.mjs +9 -7
- package/server/index.mjs +172 -51
- package/server/lan-access-cutover.mjs +21 -4
- package/server/maintenance/downgrade-session-state-v1.mjs +50 -87
- package/server/maintenance/export-session-state-v1.mjs +5 -13
- package/server/routes/backup.mjs +8 -1
- package/server/routes/storage.mjs +85 -48
- package/server/scheduled-runs-cutover.mjs +15 -1
- package/server/session-index-service.mjs +57 -391
- package/server/session-persistence-lock.mjs +17 -6
- package/server/session-state-backup.mjs +60 -7
- package/server/session-state-import.mjs +157 -0
- package/server/session-state-maintenance.mjs +126 -0
- package/server/session-state-service.mjs +133 -194
- package/server/share-cutover.mjs +21 -4
- package/server/sqlite/database.mjs +142 -7
- package/server/sqlite/lan-access-repository.mjs +6 -4
- package/server/sqlite/migrations.mjs +109 -0
- package/server/sqlite/scheduled-task-runs-repository.mjs +6 -3
- package/server/sqlite/session-index-repository.mjs +59 -208
- package/server/sqlite/session-state-repository.mjs +359 -289
- package/server/sqlite/share-repository.mjs +56 -45
- package/server/startup-state.mjs +107 -0
- package/server/storage.mjs +240 -448
- package/server/utils/logger.mjs +15 -4
- package/server/utils/process-tree.mjs +14 -2
- package/dist/assets/ChatPanelHost-cd80S4EX.js +0 -48
- package/dist/assets/TerminalDock-CczcCJJE.js +0 -2
- package/dist/assets/index-D-J_8Smf.css +0 -3
- package/dist/assets/index-DFASc15l.js +0 -66
- package/dist/assets/local-tools-Dn1Y9aPe.js +0 -270
- package/server/session-state-cutover.mjs +0 -370
package/server/utils/logger.mjs
CHANGED
|
@@ -13,14 +13,25 @@ function enabled(level) {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
// --- Timestamp ---
|
|
16
|
+
// Local-time "YYYY-MM-DD HH:mm:ss.SSS" keeps logs intuitive to read against
|
|
17
|
+
// the local clock (the previous ISO-UTC form was off by the UTC offset and
|
|
18
|
+
// swapped AM/PM readers to a different day around midnight).
|
|
16
19
|
function timestamp() {
|
|
17
|
-
|
|
20
|
+
const now = new Date()
|
|
21
|
+
const pad = (value, width = 2) => String(value).padStart(width, '0')
|
|
22
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} `
|
|
23
|
+
+ `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function localDateKey() {
|
|
27
|
+
const now = new Date()
|
|
28
|
+
const pad = (value) => String(value).padStart(2, '0')
|
|
29
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
|
|
18
30
|
}
|
|
19
31
|
|
|
20
32
|
// --- Log file (daily rotation) ---
|
|
21
33
|
function logFile() {
|
|
22
|
-
|
|
23
|
-
return path.join(logsDir, `server-${date}.log`)
|
|
34
|
+
return path.join(logsDir, `server-${localDateKey()}.log`)
|
|
24
35
|
}
|
|
25
36
|
|
|
26
37
|
// --- File write stream (async, buffered) ---
|
|
@@ -31,7 +42,7 @@ const FLUSH_INTERVAL_MS = 5000
|
|
|
31
42
|
const pendingLines = []
|
|
32
43
|
|
|
33
44
|
function getStream() {
|
|
34
|
-
const date =
|
|
45
|
+
const date = localDateKey()
|
|
35
46
|
if (stream && streamDate === date) return stream
|
|
36
47
|
|
|
37
48
|
// Rotate: close old stream
|
|
@@ -3,6 +3,7 @@ import { once } from 'node:events'
|
|
|
3
3
|
|
|
4
4
|
const DEFAULT_GRACE_MS = 1000
|
|
5
5
|
const DEFAULT_FORCE_WAIT_MS = 1000
|
|
6
|
+
const TASKKILL_TIMEOUT_MS = 10_000
|
|
6
7
|
|
|
7
8
|
function isRunning(child) {
|
|
8
9
|
return Boolean(child?.pid) && child.exitCode == null && child.signalCode == null
|
|
@@ -36,8 +37,19 @@ function runTaskkill(pid, force, spawnImpl = spawn) {
|
|
|
36
37
|
resolve(false)
|
|
37
38
|
return
|
|
38
39
|
}
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
let settled = false
|
|
41
|
+
const finish = (ok) => {
|
|
42
|
+
if (settled) return
|
|
43
|
+
settled = true
|
|
44
|
+
clearTimeout(timer)
|
|
45
|
+
resolve(ok)
|
|
46
|
+
}
|
|
47
|
+
// taskkill normally exits immediately, but a wedged taskkill.exe must not
|
|
48
|
+
// hang dispose()/destroyAgent forever on a dangling child process.
|
|
49
|
+
const timer = setTimeout(() => finish(false), TASKKILL_TIMEOUT_MS)
|
|
50
|
+
timer.unref?.()
|
|
51
|
+
command.once?.('error', () => finish(false))
|
|
52
|
+
command.once?.('exit', (code) => finish(code === 0))
|
|
41
53
|
})
|
|
42
54
|
}
|
|
43
55
|
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import{i as e}from"./rolldown-runtime-DWdDZTNf.js";import{Jt as t}from"./icons-DM_qJ7VJ.js";import{n}from"./react-vendor-BpWW_Nvp.js";import{g as r,h as i}from"./pi-web-ui-DV5jKjSg.js";import{t as a}from"./logger-8REuLPGK.js";import{i as o}from"./model-display-label-CURwH0xM.js";import{At as s,Kt as c,Pn as l,Ut as u,V as d,Wt as f,k as p,n as m,o as h,t as g}from"./index-DFASc15l.js";import{c as _,d as v,f as y,g as b,h as x,i as ee,l as S,m as C,n as te,p as ne,r as re,t as ie,u as ae}from"./local-tools-Dn1Y9aPe.js";import{t as w}from"./plugin-api-BrdQeM4B.js";var T=e(t(),1);function oe({panel:e,onReachTop:t,onAutoScrollEnabled:n}){let r=!0,i,a=0,o,s=-1/0,c=-1/0,l,u=0,d=()=>e.querySelector(`agent-interface .overflow-y-auto`),f=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=80,p=t=>{e.querySelector(`agent-interface`)?.setAutoScroll?.(t)},m=()=>{let e=Math.max(s,c);return window.performance.now()-e<=500},h=()=>{i!==void 0&&(window.cancelAnimationFrame(i),i=void 0),r=!1,p(!1)},g=()=>{s=window.performance.now(),h()},_=()=>{c=window.performance.now()},v=()=>{let e=d();if(!e||!r)return;let t=e.scrollHeight-e.clientHeight;if(Math.abs(e.scrollTop-t)<=1){a=e.scrollTop;return}e.scrollTop=e.scrollHeight,a=e.scrollTop},y=()=>{i===void 0&&(i=window.requestAnimationFrame(()=>{i=void 0,v(),window.requestAnimationFrame(v)}))},b=()=>{r=!0,p(!0),n?.(),y()},x=()=>{let e=d();if(!e)return;let n=e.scrollTop,i=n<a-1;if(u>0){a=n;return}n<=0&&a>0&&t?.();let o=i&&m();if(i&&r&&!o&&!f(e)){a=n,y();return}o?h():f(e)&&(r=!0,p(!0)),a=n},ee=e=>{e.deltaY<0&&g()},S=e=>{e.target===e.currentTarget&&_()},C=e=>{(e.key===`ArrowUp`||e.key===`PageUp`||e.key===`Home`)&&g()},te=e=>{o=e.touches[0]?.clientY},ne=e=>{let t=e.touches[0]?.clientY;t===void 0||o===void 0||(t>o+1&&g(),o=t)};return{get isEnabled(){return r},beginProgrammaticScroll:()=>(u+=1,h(),()=>{u=Math.max(0,u-1);let e=d();e&&(a=e.scrollTop)}),enable:b,disable:h,scheduleScrollToBottom:y,setup:()=>{let t=d();if(!t||l)return;a=t.scrollTop,t.addEventListener(`scroll`,x,{passive:!0}),t.addEventListener(`wheel`,ee,{passive:!0}),t.addEventListener(`pointerdown`,S,{passive:!0}),t.addEventListener(`keydown`,C),t.addEventListener(`touchstart`,te,{passive:!0}),t.addEventListener(`touchmove`,ne,{passive:!0}),l=new ResizeObserver(()=>{r&&y()}),l.observe(t);let n=t.querySelector(`.max-w-3xl`);n&&l.observe(n);let i=e.querySelector(`.quickforge-composer-dock`);i&&l.observe(i),b()},cleanup:()=>{let e=d();e?.removeEventListener(`scroll`,x),e?.removeEventListener(`wheel`,ee),e?.removeEventListener(`pointerdown`,S),e?.removeEventListener(`keydown`,C),e?.removeEventListener(`touchstart`,te),e?.removeEventListener(`touchmove`,ne),l?.disconnect(),l=void 0,i!==void 0&&(window.cancelAnimationFrame(i),i=void 0)}}}function E(e){return e.role===`user`||e.role===`user-with-attachments`}function D(e){let t=[];for(let n=0;n<e.length;n++)E(e[n])&&t.push(n);return t}function se(e,t){if(typeof e==`string`)return Math.min(e.length,t);if(!Array.isArray(e))return 0;let n=0;for(let r of e){if(n>=t)break;if(typeof r==`string`){n+=Math.min(r.length,t-n);continue}if(!r||typeof r!=`object`)continue;let e=r;for(let r of[`text`,`content`,`arguments`]){let i=e[r];if(typeof i==`string`&&(n+=Math.min(i.length,t-n),n>=t))break}}return n}function ce(e,t){let n=0;for(let r of e)if(n+=se(r.content,t-n),n>=t)return!0;return!1}function le(e,t){if(e.role!==`assistant`)return;let n=Array.isArray(e.content)?e.content:[];for(let e of n){if(!e||typeof e!=`object`)continue;let n=e;n.type!==`toolCall`||!n.id||t.add(n.id)}}function O(e,t,n){let r=e.slice(t,n),i=new Set;for(let r=t;r<n;r++)le(e[r],i);if(i.size===0)return r;let a=[];for(let r=0;r<e.length;r++){if(r>=t&&r<n)continue;let o=e[r];o.role===`toolResult`&&typeof o.toolCallId==`string`&&i.has(o.toolCallId)&&a.push(o)}return a.length>0?[...r,...a]:r}function ue(e={}){let t=e.enabled??!0,n=e.enableTurns??6,r=e.enableMessages??48,i=e.enableContentChars??8e4,a=e.windowTurns??3,o=e.pageTurns??3,s=[],c=[],l=a,u=0,d=0,f=[],p=!1,m=!1,h=e=>Math.max(0,e-l),g=()=>{let e=u===0?0:c[u],t=Math.min(c.length,u+l),n=t<c.length?c[t]:s.length;d=e,f=O(s,e,n)};return{setFullMessages(e){s=e,c=D(e);let o=c.length;return l=Math.min(a,Math.max(1,o-1)),m=t&&o>1&&(o>n||e.length>r||ce(e,i)),m?(u=p?Math.max(0,Math.min(u,h(o))):h(o),g(),f):(u=0,d=0,f=e,p=!1,e)},getWindowStart(){return d},getWindowMessages(){return f},isEnabled(){return m},hasMore(){return m&&u>0},loadMore(){return!m||u<=0?null:(p=!0,u=Math.max(0,u-o),g(),f)},showMessageIndex(e){if(!m||c.length===0)return null;let t=Math.max(0,Math.min(e,s.length-1)),n=0;for(let e=0;e<c.length&&!(c[e]>t);e++)n=e;let r=Math.min(c.length,u+l);return n>=u&&n<r?f:(p=!0,u=Math.min(n,h(c.length)),g(),f)},resetToTail(){p=!1},isAssignedWindow(e){return e===f}}}var de=!1,k=null;function fe(){return customElements.get(`message-list`)||null}function pe(e){if(k=e(),de)return;let t=()=>{let e=fe();if(!e)return!1;let t=Object.getOwnPropertyDescriptor(e,`messages`);if(!t||typeof t.set!=`function`)return!1;de=!0;let n=t.set;return Object.defineProperty(e,`messages`,{...t,set(e){let t=k,r=this.hasAttribute(`data-quickforge-subagent-process`);if(t&&!r){if(t.isAssignedWindow(e)){n.call(this,e);return}n.call(this,t.setFullMessages(e));return}n.call(this,e)}}),!0};t()||customElements.whenDefined(`message-list`).then(()=>{t()})}function me(e){k===e&&(k=null)}function he({panel:e,getCustomCommands:t,restoreDraftIntoComposer:n}){let r=e=>`/${e.name}${e.argumentHint?` ${e.argumentHint}`:``}`,i=()=>[{name:`init`,description:l(`initCommandDescription`),argumentHint:``},{name:`plan`,description:l(`planCommandDescription`),argumentHint:`[task]`},{name:`review`,description:l(`reviewCommandDescription`),argumentHint:`[scope]`},{name:`summary`,description:l(`summaryCommandDescription`),argumentHint:``},{name:`compact`,description:l(`compactCommandDescription`),argumentHint:``},{name:`clear`,description:l(`clearCommandDescription`),argumentHint:``},{name:`help`,description:l(`helpCommandDescription`),argumentHint:``}],a=()=>{let n=(e.querySelector(`.quickforge-command-suggestions`)?.querySelector(`.quickforge-command-suggestion-item`))?.dataset.quickforgeCommandName;if(n)return[...i(),...t()].find(e=>e.name===n)},o=()=>{let t=e.querySelector(`.quickforge-command-suggestions`);t?.__quickforgeDismissHandler&&(document.removeEventListener(`pointerdown`,t.__quickforgeDismissHandler,!0),t.__quickforgeDismissHandler=void 0),t?.remove()},s=t=>{let r=e.querySelector(`message-editor`),i=`/${t.name}${t.argumentHint?` `:``}`;n({text:i,attachments:[]});let a=r?.querySelector(`textarea`);a?.focus(),a&&(a.selectionStart=i.length,a.selectionEnd=i.length),o()};return{update:n=>{let a=e.querySelector(`message-editor`),c=n??a?.value??a?.querySelector(`textarea`)?.value??``,u=a?.querySelector(`textarea`),d=e.querySelector(`.quickforge-command-suggestions`);if(!a||!u||!c.startsWith(`/`)){d?.remove();return}let f=c.slice(1).trim().toLowerCase(),p=t(),m=[...i(),...p].filter(e=>e.name.includes(f)||e.description?.toLowerCase().includes(f));if(m.length===0){d?.remove();return}let h=d??document.createElement(`div`);h.className=`quickforge-command-suggestions`,h.setAttribute(`role`,`listbox`),h.innerHTML=``;let g=document.createElement(`div`);g.className=`quickforge-command-suggestions-header`,g.textContent=l(p.length?`customCommandsHint`:`customCommandsEmptyHint`),h.append(g);for(let e of m){let t=document.createElement(`button`);t.type=`button`,t.className=`quickforge-command-suggestion-item`,t.dataset.quickforgeCommandName=e.name,t.setAttribute(`role`,`option`),t.innerHTML=`
|
|
2
|
-
<span class="quickforge-command-suggestion-name"></span>
|
|
3
|
-
<span class="quickforge-command-suggestion-description"></span>
|
|
4
|
-
`,t.querySelector(`.quickforge-command-suggestion-name`).textContent=r(e),t.querySelector(`.quickforge-command-suggestion-description`).textContent=e.description??``,t.onpointerdown=t=>{t.preventDefault(),t.stopPropagation(),s(e)},h.append(t)}d||a.parentElement?.insertBefore(h,a),h.__quickforgeDismissHandler||(h.__quickforgeDismissHandler=e=>{h.contains(e.target)||a.contains(e.target)||o()},document.addEventListener(`pointerdown`,h.__quickforgeDismissHandler,!0))},remove:o,setupTextareaHandler:e=>{let t=e?.querySelector(`textarea`);if(!t)return;let n=t;n.__quickforgeCommandCompleteHandler&&n.removeEventListener(`keydown`,n.__quickforgeCommandCompleteHandler,!0),n.__quickforgeCommandCompleteHandler=t=>{if(t.isComposing||t.key===`Process`)return;if(t.key===`Enter`&&t.shiftKey){t.stopImmediatePropagation();return}if(t.key!==`Tab`||!(e?.value??n.value??``).startsWith(`/`)||t.shiftKey)return;let r=a();r&&(t.preventDefault(),t.stopPropagation(),s(r))},n.addEventListener(`keydown`,n.__quickforgeCommandCompleteHandler,!0)},cleanupTextareaHandler:()=>{let t=e.querySelector(`message-editor textarea`);t?.__quickforgeCommandCompleteHandler&&t.removeEventListener(`keydown`,t.__quickforgeCommandCompleteHandler,!0)}}}var ge={plugin:`
|
|
5
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
|
6
|
-
<path d="M7.4 3.2h5.2a1.2 1.2 0 0 1 1.2 1.2v2.1h.9a2.1 2.1 0 1 1 0 4.2h-.9v2.1a1.2 1.2 0 0 1-1.2 1.2h-2.1v.7a2.1 2.1 0 1 1-4.2 0V14H4.4a1.2 1.2 0 0 1-1.2-1.2V9.9h.8a1.8 1.8 0 1 0 0-3.6h-.8V4.4a1.2 1.2 0 0 1 1.2-1.2h2.1v-.8a1.8 1.8 0 1 1 3.6 0v.8Z" />
|
|
7
|
-
</svg>`,document:`
|
|
8
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">
|
|
9
|
-
<path d="M5.4 2.8h6.1L15.8 7v10.2H5.4z" />
|
|
10
|
-
<path d="M11.4 2.9V7h4.1" />
|
|
11
|
-
<path d="M7.6 10.2h5" />
|
|
12
|
-
<path d="M7.6 13h4.3" />
|
|
13
|
-
</svg>`,spreadsheet:`
|
|
14
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">
|
|
15
|
-
<rect x="3.4" y="4" width="13.2" height="12.2" rx="1.5" />
|
|
16
|
-
<path d="M3.4 8h13.2" />
|
|
17
|
-
<path d="M7.8 4v12.2" />
|
|
18
|
-
<path d="M12.2 4v12.2" />
|
|
19
|
-
<path d="M3.4 12h13.2" />
|
|
20
|
-
</svg>`,presentation:`
|
|
21
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">
|
|
22
|
-
<path d="M3 4.2h14" />
|
|
23
|
-
<rect x="4.2" y="4.2" width="11.6" height="8.4" rx="1.2" />
|
|
24
|
-
<path d="M10 12.6v3.2" />
|
|
25
|
-
<path d="m7.2 17 2.8-1.2 2.8 1.2" />
|
|
26
|
-
<path d="M7.1 9.5 9 7.7l1.5 1.3 2.4-2.5" />
|
|
27
|
-
</svg>`,skill:`
|
|
28
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
|
29
|
-
<path d="M4.2 3.2h4.4A2.4 2.4 0 0 1 11 5.6v11a2.4 2.4 0 0 0-2.4-2.4H4.2V3.2Z" />
|
|
30
|
-
<path d="M11 5.6a2.4 2.4 0 0 1 2.4-2.4h2.4v11.1h-2.4A2.4 2.4 0 0 0 11 16.7" />
|
|
31
|
-
</svg>`,tool:`
|
|
32
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
33
|
-
<path d="M12.8 3.5a4.2 4.2 0 0 0 4 5.5l-7.6 7.6a2.2 2.2 0 0 1-3.1-3.1l7.6-7.6a4.2 4.2 0 0 0-5.5-4" />
|
|
34
|
-
</svg>`,command:`
|
|
35
|
-
<svg viewBox="0 0 20 20" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
36
|
-
<path d="m5 6 4 4-4 4" />
|
|
37
|
-
<path d="M10.5 14h4.5" />
|
|
38
|
-
</svg>`};function A(e){return e.split(/[-_/\\]+/).filter(Boolean).map(e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`).join(` `)}function _e(e){switch(e.name){case`documents`:return{label:l(`pluginDocumentsName`),description:l(`pluginDocumentsDescription`),mention:`Documents`,iconKind:`document`};case`spreadsheets`:return{label:l(`pluginSpreadsheetsName`),description:l(`pluginSpreadsheetsDescription`),mention:`Spreadsheets`,iconKind:`spreadsheet`};case`presentations`:return{label:l(`pluginPresentationsName`),description:l(`pluginPresentationsDescription`),mention:`Presentations`,iconKind:`presentation`};default:return null}}function j(e){let t=_e(e);return t?t.label:(e.displayName||A(e.name.replace(/^openai-/,``))).replace(/^OpenAI\s+/i,``)}function M(e){let t=_e(e),n=t?.label??j(e),r=t?.mention??n.replace(/\s+/g,``);return[{type:`plugin`,iconKind:t?.iconKind??`plugin`,pluginName:e.name,name:e.name,label:n,mention:r,insertText:r,description:t?.description??e.description}]}function N(e,t){let n=e.slice(0,t),r=/(^|\s)@([^\s@]*)$/.exec(n);if(!r)return null;let i=r[1]?.length??0;return{start:n.length-r[0].length+i,end:t,query:r[2]??``}}function ve(e){let t=new Set,n=/(^|\s)@([\p{L}\p{N}_-]+)/gu,r;for(;r=n.exec(e);)t.add((r[2]||``).toLowerCase());return t}function ye({panel:e,restoreDraftIntoComposer:t,onSelectionChange:n,enabled:r=!0}){let i=[],a=null,o=`idle`,s=!1,c=!1,u=new Map,d=()=>n?.([...u.values()]),f=()=>a||(o===`loaded`?Promise.resolve():(o=`loading`,a=w().then(e=>{i=(e.plugins??[]).filter(e=>e.enabled&&e.status===`loaded`)}).catch(()=>{i=[]}).finally(()=>{a=null,o=`loaded`}),a));r&&f();let p=()=>i.flatMap(M),m=()=>{let t=(e.querySelector(`.quickforge-capability-suggestions`)?.querySelector(`.quickforge-capability-suggestion-item`))?.dataset.quickforgeCapabilityKey;if(t)return p().find(e=>P(e)===t)},h=()=>{let t=e.querySelector(`.quickforge-capability-suggestions`);t?.__quickforgeDismissHandler&&(document.removeEventListener(`pointerdown`,t.__quickforgeDismissHandler,!0),t.__quickforgeDismissHandler=void 0),t?.remove()},g=(n,r)=>{let i=e.querySelector(`message-editor`),a=i?.querySelector(`textarea`),o=i?.value??a?.value??``,s=a?.selectionStart??o.length,c=r??N(o,s),l=`@${n.insertText}`,f=c?`${o.slice(0,c.start)}${l} ${o.slice(c.end)}`:`${o}${o.endsWith(` `)||o.length===0?``:` `}${l} `,p=c?c.start+l.length+1:f.length;u.set(P(n),n),d(),t({text:f,attachments:i?.attachments?[...i.attachments]:[]});let m=i?.querySelector(`textarea`);m?.focus(),m&&(m.selectionStart=p,m.selectionEnd=p),h()},_=e=>{let t=()=>{let t=p().find(t=>t.insertText===e);t&&g(t)};if(i.length>0){t();return}c||(c=!0,f().then(()=>{c=!1,t()}))},v=t=>{let n=e.querySelector(`message-editor`),r=n?.querySelector(`textarea`),c=t??n?.value??r?.value??``,u=N(c,r?.selectionStart??c.length),d=e.querySelector(`.quickforge-capability-suggestions`);if(!n||!r||!u){s&&(o=`idle`),s=!1,d?.remove();return}if(s=!0,i.length===0){let t=f();a!==null&&t.then(()=>{let t=e.querySelector(`message-editor`),n=t?.querySelector(`textarea`),r=t?.value??n?.value??``;N(r,n?.selectionStart??r.length)&&v(r)})}let m=u.query.toLowerCase(),_=p().filter(e=>[e.label,e.name,e.pluginName,e.description].filter(Boolean).join(` `).toLowerCase().includes(m)).slice(0,8);if(_.length===0){d?.remove();return}let y=d??document.createElement(`div`);y.className=`quickforge-capability-suggestions`,y.setAttribute(`role`,`listbox`),y.innerHTML=``;let b=document.createElement(`div`);b.className=`quickforge-capability-suggestions-header`,b.textContent=l(`pluginMentionHeader`),y.append(b);for(let e of _){let t=document.createElement(`button`);t.type=`button`,t.className=`quickforge-capability-suggestion-item`,t.dataset.quickforgeCapabilityKey=P(e),t.dataset.quickforgePluginName=e.pluginName,t.setAttribute(`role`,`option`),t.innerHTML=`
|
|
39
|
-
<span class="quickforge-capability-suggestion-icon quickforge-capability-suggestion-icon-${e.iconKind}">${ge[e.iconKind]}</span>
|
|
40
|
-
<span class="quickforge-capability-suggestion-main">
|
|
41
|
-
<span class="quickforge-capability-suggestion-line">
|
|
42
|
-
<span class="quickforge-capability-suggestion-name"></span>
|
|
43
|
-
</span>
|
|
44
|
-
<span class="quickforge-capability-suggestion-description"></span>
|
|
45
|
-
</span>
|
|
46
|
-
`,t.querySelector(`.quickforge-capability-suggestion-name`).textContent=e.label,t.querySelector(`.quickforge-capability-suggestion-description`).textContent=e.description??e.pluginName,t.onpointerdown=t=>{t.preventDefault(),t.stopPropagation(),g(e,u)},y.append(t)}d||n.parentElement?.insertBefore(y,n),y.__quickforgeDismissHandler||(y.__quickforgeDismissHandler=e=>{y.contains(e.target)||n.contains(e.target)||h()},document.addEventListener(`pointerdown`,y.__quickforgeDismissHandler,!0))};return{update:v,remove:h,setupTextareaHandler:e=>{let t=e?.querySelector(`textarea`);if(!t)return;let n=t;n.__quickforgeCapabilityCompleteHandler&&n.removeEventListener(`keydown`,n.__quickforgeCapabilityCompleteHandler,!0),n.__quickforgeCapabilityCompleteHandler=t=>{if(t.isComposing||t.key===`Process`)return;if(t.key===`Escape`){h();return}if(t.key!==`Tab`&&t.key!==`Enter`)return;let r=e?.value??n.value??``,i=N(r,n.selectionStart??r.length);if(!i||t.shiftKey)return;let a=m();a&&(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),g(a,i))},n.addEventListener(`keydown`,n.__quickforgeCapabilityCompleteHandler,!0)},cleanupTextareaHandler:()=>{let t=e.querySelector(`message-editor textarea`);t?.__quickforgeCapabilityCompleteHandler&&t.removeEventListener(`keydown`,t.__quickforgeCapabilityCompleteHandler,!0)},consumeSelectedCapabilities:e=>{let t=ve(e),n=[...u.values()].filter(e=>t.has(e.mention.toLowerCase())),r=p().filter(e=>t.has(e.insertText.toLowerCase())||t.has(e.label.replace(/\s+/g,``).toLowerCase())),i=new Map;for(let e of[...n,...r])i.set(P(e),e);return u=new Map,d(),[...i.values()].slice(0,4)},insertBuiltinPluginMention:_,availablePluginRows:p}}function P(e){return`${e.type}:${e.pluginName}:${e.name}`}function be(e){return e>=5}function xe(e){return e.role===`user`||e.role===`user-with-attachments`}function F(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
47
|
-
|
|
48
|
-
`).trim():``}function Se(e){return xe(e)?(typeof e.content==`string`?e.content:F(e.content)).trim():``}function Ce(e){return e.role===`assistant`?F(e.content):``}function we(e,t){let n=[];for(let t=0;t<e.length;t++){let r=e[t];if(!xe(r))continue;let i=``;for(let n=t+1;n<e.length;n++){let t=e[n];if(xe(t))break;t.role===`assistant`&&(i=Ce(t))}n.push({messageIndex:t,userText:Se(r),finalAnswerText:i,isGenerating:!1})}return t&&n.length>0&&(n[n.length-1].isGenerating=!0),n}var I=xe;function L(e,t){return e.trim().replace(/\s+/g,` `)||t}function Te({host:e,panel:t,getMessages:n,isStreaming:r,windowLayer:i,beginProgrammaticScroll:a,onWindowChanged:o}){let s=document.createElement(`nav`);s.className=`quickforge-turn-navigation`,s.setAttribute(`aria-label`,l(`turnNavigationLabel`)),s.hidden=!0;let c=document.createElement(`div`);c.className=`quickforge-turn-navigation-track`,s.append(c),e.append(s);let u=[],d=``,f=-1,p=null,m=null,h,g,_=null,v=0,y=null,b=null,x=()=>{h!==void 0&&(window.clearTimeout(h),h=void 0)},ee=()=>{g!==void 0&&(window.clearTimeout(g),g=void 0)},S=()=>{x(),ee(),p?.remove(),p=null,m?.removeAttribute(`aria-describedby`),m=null},C=()=>{if(!p||!m)return;let e=m.getBoundingClientRect(),t=p.getBoundingClientRect(),n=e.right+10;n+t.width>window.innerWidth-12&&(n=e.left-t.width-10);let r=Math.min(Math.max(12,e.top+e.height/2-t.height/2),Math.max(12,window.innerHeight-t.height-12));p.style.left=`${Math.max(12,n)}px`,p.style.top=`${r}px`},te=(e,t)=>{x(),ee(),S();let n=u[t];if(!n)return;let r=document.createElement(`div`),i=`quickforge-turn-navigation-tooltip-${t}`;r.id=i,r.className=`quickforge-turn-navigation-tooltip`,r.setAttribute(`role`,`tooltip`);let a=document.createElement(`div`);a.className=`quickforge-turn-navigation-tooltip-text quickforge-turn-navigation-tooltip-user`,a.textContent=L(n.userText,l(`turnNavigationAttachmentOnly`)),r.append(a);let o=n.isGenerating?l(`turnNavigationGenerating`):n.finalAnswerText.trim();if(o){let e=document.createElement(`div`);e.className=`quickforge-turn-navigation-tooltip-text quickforge-turn-navigation-tooltip-answer`,e.textContent=o,r.append(e)}r.addEventListener(`pointerenter`,ee),r.addEventListener(`pointerleave`,()=>{g=window.setTimeout(S,100)}),document.body.append(r),p=r,m=e,e.setAttribute(`aria-describedby`,i),C()},ne=(e,t)=>{x(),ee(),h=window.setTimeout(()=>te(e,t),150)},re=e=>{e!==f&&(f=e,c.querySelectorAll(`.quickforge-turn-navigation-node`).forEach((t,n)=>{let r=n===e,i=Math.abs(n-e);t.classList.toggle(`is-active`,r),t.classList.toggle(`is-nearby`,i===1),t.classList.toggle(`is-nearby-secondary`,i===2),r?t.setAttribute(`aria-current`,`true`):t.removeAttribute(`aria-current`)}))},ie=()=>{let e=_,r=t.querySelector(`message-list`);if(!e||!r||u.length===0)return;let a=n(),o=(i.isEnabled()?i.getWindowMessages():a).map(e=>I(e)?a.indexOf(e):-1).filter(e=>e>=0).map(e=>u.findIndex(t=>t.messageIndex===e)).filter(e=>e>=0),s=Array.from(r.querySelectorAll(`user-message`)).filter(e=>e.closest(`message-list`)===r);if(s.length===0||o.length===0)return;let c=e.getBoundingClientRect().top+Math.min(120,e.clientHeight*.2),l=0;for(let e=0;e<s.length&&s[e].getBoundingClientRect().top<=c;e++)l=e;re(o[Math.min(l,o.length-1)])},ae=()=>{let e=t.querySelector(`agent-interface .overflow-y-auto`);e!==_&&(_?.removeEventListener(`scroll`,ie),_=e,_?.addEventListener(`scroll`,ie,{passive:!0}))},w=e=>{let r=u[e],s=t.querySelector(`message-list`),c=t.querySelector(`agent-interface .overflow-y-auto`);if(!r||!s||!c)return;S();let l=++v;b?.(),b=null,y?.(),y=a();let d=()=>{if(l!==v)return;b?.(),b=null;let e=y;y=null,window.requestAnimationFrame(()=>e?.())},f=()=>{let e=!1,t=()=>{e||(e=!0,c.removeEventListener(`scrollend`,t),window.clearTimeout(n),d())};c.addEventListener(`scrollend`,t,{once:!0});let n=window.setTimeout(t,900);b=()=>{e=!0,c.removeEventListener(`scrollend`,t),window.clearTimeout(n)}},p=i.showMessageIndex(r.messageIndex);p&&s.messages!==p&&(s.messages=p);let m=()=>{window.requestAnimationFrame(()=>{if(l!==v)return;let t=n(),a=i.isEnabled()?i.getWindowMessages():t,u=a.findIndex(e=>e===t[r.messageIndex]);if(u<0){d();return}let p=a.slice(0,u+1).filter(I).length-1,m=Array.from(s.querySelectorAll(`user-message`)).filter(e=>e.closest(`message-list`)===s)[p];if(!m){d();return}let h=c.scrollTop+m.getBoundingClientRect().top-c.getBoundingClientRect().top-24,g=Math.max(0,h);Math.abs(c.scrollTop-g)<=1?(c.scrollTop=g,d()):(f(),c.scrollTo({top:g,behavior:`smooth`})),re(e),o()})};(s.updateComplete??Promise.resolve()).then(m,m)},T=()=>{if(c.replaceChildren(),!be(u.length)){s.hidden=!0;return}s.hidden=!1,u.forEach((e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`quickforge-turn-navigation-node`,n.setAttribute(`aria-label`,l(`turnNavigationJumpLabel`,{index:t+1,preview:L(e.userText,l(`turnNavigationAttachmentOnly`))})),n.addEventListener(`pointerenter`,()=>ne(n,t)),n.addEventListener(`pointerleave`,()=>{x(),g=window.setTimeout(S,100)}),n.addEventListener(`focus`,()=>ne(n,t)),n.addEventListener(`blur`,()=>{g=window.setTimeout(S,100)}),n.addEventListener(`click`,()=>w(t)),c.append(n)}),f=-1},oe=()=>{u=we(n(),r());let e=u.map(e=>`${e.messageIndex}:${e.userText}`).join(`|`);e!==d&&(d=e,T()),ae(),ie()},E=e=>{e.key===`Escape`&&S()},D=()=>S();return document.addEventListener(`keydown`,E),window.addEventListener(`resize`,D),{update:oe,cleanup(){v+=1,b?.(),b=null,y?.(),y=null,S(),_?.removeEventListener(`scroll`,ie),document.removeEventListener(`keydown`,E),window.removeEventListener(`resize`,D),s.remove()}}}function R(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function z(e,t){let n=e[t];return typeof n==`string`&&n.trim()?n:void 0}function Ee(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function De(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Oe(e){let t=e&&R(e.diff)?e.diff:void 0;return{addedLines:t?De(t,`addedLines`):void 0,removedLines:t?De(t,`removedLines`):void 0}}function ke(e=``){let t=e.toLowerCase(),n=t.replace(/\\/g,`/`).split(`/`).pop()||t;return t.endsWith(`.html`)||t.endsWith(`.htm`)?`html`:/\.(svg|png|jpe?g|webp|gif|ico)$/i.test(t)?`image`:/\.(md|mdx|markdown)$/i.test(t)?`markdown`:n===`dockerfile`||n.endsWith(`.dockerfile`)||n===`makefile`||/\.(ts|tsx|js|jsx|mjs|cjs|css|scss|less|json|jsonc|txt|csv|tsv|log|sql|xml|yml|yaml|toml|ini|py|rb|go|rs|java|swift|kt|kts|c|h|cpp|hpp|cs|php|sh|bash|zsh|ps1)$/i.test(t)?`code`:`unknown`}function B(e){return e===`html`||e===`image`||e===`markdown`||e===`code`}function V(e){return[e.source,e.path??``,e.command??``,e.outputFile??``,e.toolCallId??``,e.preview?`preview`:``].join(`\0`)}function Ae(e,t,n){let r=V(n);t.has(r)||(t.add(r),e.push({id:`${e.length}:${r}`,...n}))}function H(e){if(!(typeof e!=`string`||!e.trim()))try{return JSON.parse(e)}catch{return}}function U(e,t){if(t&&(Array.isArray(t.files)||Array.isArray(t.previewed)))return t;let n=e.data;if(Array.isArray(n))for(let e of n){if(!R(e)||e.type!==`text`)continue;let t=H(e.text);if(R(t)&&(Array.isArray(t.files)||Array.isArray(t.previewed)))return t}let r=e.content;if(Array.isArray(r))for(let e of r){if(!R(e)||e.type!==`text`)continue;let t=H(e.text);if(R(t)&&(Array.isArray(t.files)||Array.isArray(t.previewed)))return t}return t}function je(e){if(typeof e==`string`&&e.trim())return{path:e};if(R(e)){let t=z(e,`path`);return t?{path:t,title:z(e,`title`),description:z(e,`description`),kind:z(e,`kind`),preview:Ee(e,`preview`)}:void 0}}function Me(e){let t=new Set,n=[];for(let r of e){if(r.role!==`toolResult`)continue;let e=typeof r.toolName==`string`?r.toolName:``,i=R(r.details)?r.details:void 0,a=typeof r.toolCallId==`string`?r.toolCallId:void 0;if(!(!i&&e!==`present_files`)){if(e===`write_file`||e===`edit_file`){let r=i?z(i,`path`):void 0;if(r){let o=ke(r),{addedLines:s,removedLines:c}=Oe(i);Ae(n,t,{source:e,confidence:`high`,path:r,toolCallId:a,kind:o,preview:B(o),presentation:`inferred`,addedLines:s,removedLines:c})}}else if(e===`present_files`){let e=U(r,i),o=R(e)&&Array.isArray(e.files)?e.files:[],s=R(e)?z(e,`defaultPreview`):void 0,c=new Set(R(e)&&Array.isArray(e.previewed)?e.previewed.filter(e=>typeof e==`string`):[]);for(let e of o){let r=je(e);if(!r?.path)continue;let i=r.kind??ke(r.path);Ae(n,t,{source:`present_files`,confidence:`high`,path:r.path,title:r.title,description:r.description,toolCallId:a,kind:i,preview:r.preview??(c.has(r.path)||s===r.path||B(i)),defaultPreview:s===r.path,presentation:`explicit`})}}else if(e===`run_command`&&i){let e=z(i,`command`),r=z(i,`outputFile`);(e||r)&&Ae(n,t,{source:`run_command`,confidence:`low`,command:e,outputFile:r,toolCallId:a})}}}return n}function Ne(e){return e?.length?Me(e):[]}var W=`quickforge:composer-drafts:v1`,G=100,K={},q=!1;function Pe(e){return!!(e&&!e.startsWith(`pending-`))}function Fe(e){return Pe(e.sessionId)?`session:${e.sessionId}`:e.scope===`project`&&e.projectId?`new:project:${e.projectId}`:`new:global`}function Ie(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!=`object`||Array.isArray(r))continue;let e=r;typeof e.text==`string`&&(t[n]={text:e.text,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:new Date().toISOString(),scope:e.scope===`project`?`project`:e.scope===`global`?`global`:void 0,projectId:typeof e.projectId==`string`?e.projectId:void 0,sessionId:typeof e.sessionId==`string`?e.sessionId:void 0})}return t}function Le(){try{return globalThis.localStorage}catch{return}}function Re(e,t=G){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.text.length>0).sort(([,e],[,t])=>t.updatedAt.localeCompare(e.updatedAt)).slice(0,t))}function ze(){let e=Le();if(!e||q)return K;let t;try{t=e.getItem(W)}catch{return q=!0,K}try{return Ie(t?JSON.parse(t):void 0)}catch{return K}}function Be(e){let t=Re(e);K=t;let n=Le();if(!(!n||q))try{Object.keys(t).length===0?n.removeItem(W):n.setItem(W,JSON.stringify(t))}catch{let e=Re(t,Math.ceil(G/2));K=e;try{Object.keys(e).length===0?n.removeItem(W):n.setItem(W,JSON.stringify(e))}catch{q=!0}}}async function Ve(e){let t=ze()[e];if(!(!t||t.text.length===0))return{text:t.text,attachments:[]}}async function He(e,t,n){let r=t.text??``;if(r.length===0){await Ue(e);return}let i=ze();i[e]={text:r,updatedAt:new Date().toISOString(),scope:n.scope,projectId:n.scope===`project`?n.projectId:void 0,sessionId:Pe(n.sessionId)?n.sessionId:void 0},Be(i)}async function Ue(e){let t=ze();Object.prototype.hasOwnProperty.call(t,e)&&(delete t[e],Be(t))}function We(e,t,n=200){for(e.delete(t),e.add(t);e.size>n;){let t=e.values().next().value;if(t===void 0)break;e.delete(t)}}function Ge(){let e=0;return{version:()=>e,isCurrent:t=>t===e,invalidate:()=>(e+=1,e)}}var Ke=n();function qe(e){let t=e.state.contextCompaction;if(!t?.summaryMessage)return e.state.messages;let n=e.state.messages,r=Math.min(n.length,Math.max(0,Number(t.compactedUpToIndex)||0));return[t.summaryMessage,...n.slice(r)]}function Je(e){let t=String(e.length);for(let n of e)n.role===`toolResult`&&(t+=`|${n.toolCallId??``}:${n.toolName??``}`);return t}function Ye({agent:e,onModelSelect:t,revision:n,agentAccessMode:w,workspaceToolsEnabled:E,project:D,projectId:se,chatScope:ce=`global`,onAccessModeChange:le,onRollbackFromMessage:O,onRetryFromMessage:de,onCopyAnswer:k,onForkFromMessage:fe,onApproveToolCall:ge,onRejectToolCall:A,onApproveAutoCompact:_e,onRejectAutoCompact:j,onOpenWorkspaceGitChanges:M,onOpenLocalFilePath:N,onArtifactsChange:ve,onContextUsageDisplayChange:P,onInitialRenderReady:be,onInitialRenderError:xe,restoredDraft:F,onRestoredDraftConsumed:Se,disableFork:Ce=!1,readOnly:we=!1,approvalReadOnly:I=!1,approvalReadOnlyMessage:L,bypassClientApiKeyCheck:R=!1,allowModelControls:z=!0,newChatEmptyState:Ee=!1,showTurnNavigation:De=!0,rollbackConfirmTitle:Oe,rollbackConfirmDescription:ke,capabilities:B=g}){let V=(0,T.useRef)(null),Ae=(0,T.useRef)(void 0),H=(0,T.useRef)(void 0),U=(0,T.useRef)(new Map),je=(0,T.useRef)([]),Me=(0,T.useRef)(void 0),W=(0,T.useRef)(new Set),G=(0,T.useRef)(void 0),K=(0,T.useRef)(null),q=(0,T.useRef)(!1),Pe=(0,T.useRef)(new WeakSet),Ie=(0,T.useRef)(``),Le=(0,T.useRef)(``),Re=(0,T.useRef)(Ge()),[ze,Be]=(0,T.useState)(),[Ye,Xe]=(0,T.useState)(!1),J=(0,T.useMemo)(()=>m(B,{readOnly:we,disableFork:Ce}),[B,we,Ce]),Ze=(0,T.useCallback)(()=>Xe(e=>!e),[]),Qe=(0,T.useCallback)(()=>Xe(!1),[]);(0,T.useEffect)(()=>{let t=e,n=J.planMode&&Ye;t?.setPlanMode?.(n,n?Qe:void 0),!J.planMode&&Ye&&queueMicrotask(Qe)},[e,Ye,Qe,J.planMode]);let $e=(0,T.useCallback)(()=>{G.current&&=(window.clearTimeout(G.current),void 0)},[]),Y=(0,T.useCallback)(()=>{K.current?.cancel(),K.current=null,q.current=!1},[]),et=(0,T.useCallback)(e=>{We(W.current,e),Se?.(e)},[Se]),tt=(0,T.useMemo)(()=>({sessionId:e?.sessionId,scope:ce,projectId:se}),[e?.sessionId,ce,se]),nt=Fe(tt),rt=(0,T.useRef)(tt),it=(0,T.useRef)(nt);(0,T.useEffect)(()=>{rt.current=tt,it.current=nt},[tt,nt]),(0,T.useEffect)(()=>()=>{$e(),Y()},[$e,Y]);let at=(0,T.useCallback)((e,t,n)=>{if(t.text.length===0){Ue(e).catch(e=>a.error(`Failed to clear composer draft:`,e));return}He(e,t,n).catch(e=>a.error(`Failed to save composer draft:`,e))},[]),ot=(0,T.useCallback)((e,t,n)=>{G.current&&window.clearTimeout(G.current),G.current=window.setTimeout(()=>{G.current=void 0,at(e,t,n)},400)},[at]),st=(0,T.useCallback)((e,t=it.current,n=rt.current)=>{let r=C(e);c(r)?U.current.set(t,r):U.current.delete(t),at(t,r,n)},[at]),X=(0,T.useRef)({onCopyAnswer:k,onRollbackFromMessage:O,onRetryFromMessage:de,onForkFromMessage:fe,onAccessModeChange:le,onTogglePlanMode:Ze,onApproveToolCall:ge,onRejectToolCall:A,onApproveAutoCompact:_e,onRejectAutoCompact:j,onOpenWorkspaceGitChanges:M,onOpenLocalFilePath:N,onArtifactsChange:ve,onContextUsageDisplayChange:P,onInitialRenderReady:be,onInitialRenderError:xe,onModelSelect:t,agentAccessMode:w,planMode:Ye,workspaceToolsEnabled:E,disableFork:Ce,readOnly:we,approvalReadOnly:I,approvalReadOnlyMessage:L,allowModelControls:z,newChatEmptyState:Ee,bypassClientApiKeyCheck:R,rollbackConfirmTitle:Oe,rollbackConfirmDescription:ke,capabilities:J,gitBranch:ze});(0,T.useEffect)(()=>{X.current={onCopyAnswer:k,onRollbackFromMessage:O,onRetryFromMessage:de,onForkFromMessage:fe,onAccessModeChange:le,onTogglePlanMode:Ze,onApproveToolCall:ge,onRejectToolCall:A,onApproveAutoCompact:_e,onRejectAutoCompact:j,onOpenWorkspaceGitChanges:M,onOpenLocalFilePath:N,onArtifactsChange:ve,onContextUsageDisplayChange:P,onInitialRenderReady:be,onInitialRenderError:xe,onModelSelect:t,agentAccessMode:w,planMode:Ye,workspaceToolsEnabled:E,disableFork:Ce,readOnly:we,approvalReadOnly:I,approvalReadOnlyMessage:L,allowModelControls:z,newChatEmptyState:Ee,bypassClientApiKeyCheck:R,rollbackConfirmTitle:Oe,rollbackConfirmDescription:ke,capabilities:J,gitBranch:ze},H.current=F});let ct=D?.id??se;(0,T.useEffect)(()=>{let e=!1;return queueMicrotask(()=>{if(!e){if(!ct){Be(void 0);return}p(ct).then(t=>{e||Be(t.isGitRepository?t.branch:void 0)}).catch(t=>{e||(a.warn(`Failed to load git branch:`,t),Be(void 0))})}}),()=>{e=!0}},[ct,n]);let lt=(0,T.useRef)(null),ut=(0,T.useRef)(null),Z=(0,T.useRef)(null),Q=(0,T.useRef)(null),$=(0,T.useRef)(null);(0,T.useEffect)(()=>{let e=!1;return!J.commands||!D?.id?(je.current=[],()=>{e=!0}):(fetch(`/api/project/commands?projectId=${encodeURIComponent(D.id)}`,{cache:`no-store`}).then(e=>e.ok?e.json():{commands:[]}).then(t=>{e||(je.current=Array.isArray(t.commands)?t.commands:[],Z.current?.())}).catch(()=>{e||(je.current=[],Z.current?.())}),()=>{e=!0})},[D?.id,n,J.commands]);let dt=(0,T.useCallback)((e,t,n,r)=>{if(t.sessionId&&t.sessionId!==n||!c(t)||W.current.has(t.id))return;let i=e.querySelector(`message-editor`),a=i?{text:i.value??i.querySelector(`textarea`)?.value??``,attachments:i.attachments?[...i.attachments]:[]}:U.current.get(r),o=Me.current;if(!(o?.id!==t.id||!c(a??f())||a?.text===o.text))return;Re.current.invalidate(),Y();let s=e.querySelector(`agent-interface`);K.current=b(e,t,U.current,r,{shouldApply:()=>!W.current.has(t.id)&&e.isConnected&&!!V.current?.contains(e),onApplyStart:()=>{q.current=!0},onApplyEnd:()=>{q.current=!1},onApplied:()=>{Pe.current.add(e),Ae.current=t.id,Me.current={id:t.id,text:t.text},et(t.id)},updateComplete:s?.updateComplete})},[Y,et]);return(0,T.useEffect)(()=>{if(!V.current||!e)return;let t=Re.current,n=Pe.current,p=new r;Xe(!1);let m=e.sessionId,g=it.current,C=rt.current,w=!1,T,E=!1,D=!1,se=!1,ce=e.state.isStreaming,le=!1,O=0,de,k=ue({enabled:!1});pe(()=>k);let fe=!1,ge=()=>{if(w||fe||!k.hasMore())return;let e=p.querySelector(`message-list`),t=p.querySelector(`agent-interface .overflow-y-auto`);if(!e||!t)return;let n=Array.from(e.querySelectorAll(`user-message, assistant-message`)).filter(t=>t.closest(`message-list`)===e),r=t.getBoundingClientRect().top,i=-1,a=0;for(let e=0;e<n.length;e++){let t=n[e].getBoundingClientRect();if(t.bottom>r){i=e,a=t.top;break}}let o=t.scrollTop,s=k.loadMore();if(!s)return;fe=!0,e.messages=s;let c=()=>{window.requestAnimationFrame(()=>{if(fe=!1,!w){if(i>=0){let n=Array.from(e.querySelectorAll(`user-message, assistant-message`))[i];n&&(t.scrollTop=o+(n.getBoundingClientRect().top-a))}Z.current?.()}})};(e.updateComplete??Promise.resolve()).then(c,c)},A=oe({panel:p,onReachTop:()=>{ge()},onAutoScrollEnabled:()=>{k.resetToTail()}});ut.current=A;let _e=null,j=he({panel:p,getCustomCommands:()=>je.current,getComposerDrafts:()=>U.current,sessionId:g,setComposerDrafts:e=>{U.current=e},restoreDraftIntoComposer:e=>{x(p,e,U.current,g),ot(g,e,C)}}),M=ye({panel:p,enabled:J.capabilitySuggestions,restoreDraftIntoComposer:e=>{x(p,e,U.current,g),ot(g,e,C)}}),N=u({panel:p,getSystemPrompt:()=>e.state.systemPrompt,getMessages:()=>e.state.messages,getEffectiveMessages:()=>qe(e),getContextWindow:()=>e.state.model?.contextWindow??0,getTools:()=>e.state.tools,getMaxTokens:()=>e.state.model?.maxTokens,getServerContextUsage:()=>e.state.contextUsage??null,getIsCompacted:()=>!!e.state.contextCompaction?.summaryMessage,getGitBranch:()=>X.current.gitBranch,onGitBranchClick:()=>X.current.onOpenWorkspaceGitChanges?.(),renderInline:!1,renderModelRing:s().showContextUsage,onDisplayChange:t=>X.current.onContextUsageDisplayChange?.(e.sessionId,t)}),ve=S({panel:p,getAcpSession:()=>e.state.acpSession??null}),P=()=>{if(q.current)return;se=!0,t.invalidate(),Y();let e=H.current;e&&(!e.sessionId||e.sessionId===m)&&et(e.id)},be=e=>{P(),E=!1;let t=p.querySelector(`message-editor`),n={text:e,attachments:t?.attachments?[...t.attachments]:[]};c(n)?(U.current.set(g,n),ot(g,n,C)):(U.current.delete(g),$e(),Ue(g).catch(e=>a.error(`Failed to clear composer draft:`,e)))},xe=e=>{P(),E=!1;let t=p.querySelector(`message-editor`),n=t?.querySelector(`textarea`),r={text:t?.value??n?.value??``,attachments:e?[...e]:[]};c(r)?(U.current.set(g,r),ot(g,r,C)):(U.current.delete(g),$e(),Ue(g).catch(e=>a.error(`Failed to clear composer draft:`,e)));let i=p.querySelector(`agent-interface`);i?.requestUpdate?.(),window.requestAnimationFrame(()=>Z.current?.()),i?.updateComplete?.then(()=>Z.current?.())},F=()=>{e.state.isStreaming?p.dataset.quickforgeAgentStreaming=`true`:delete p.dataset.quickforgeAgentStreaming},Se=!1,Ce=()=>{if(w||Se)return;Se=!0;let t=()=>{if(Se=!1,w)return;let t=Ne(e.state.messages),n=JSON.stringify(t.map(e=>[e.source,e.path,e.command,e.outputFile,e.confidence,e.preview,e.defaultPreview,e.addedLines,e.removedLines]));n!==Ie.current&&(Ie.current=n,X.current.onArtifactsChange?.(t))};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(t,{timeout:500}):t()},we=()=>{if(w||!p.isConnected)return;F();let t=()=>k.isEnabled()?k.getWindowMessages():e.state.messages,n=k.isEnabled()?k.getWindowStart():0,r=X.current,i=Je(e.state.messages);i!==Le.current&&(Le.current=i,Ce());try{ee({panel:p,getMessages:t,messageIndexOffset:n,isStreaming:()=>e.state.isStreaming,onCopyAnswer:r.onCopyAnswer,onRollbackFromMessage:r.onRollbackFromMessage,onRetryFromMessage:r.onRetryFromMessage,onForkFromMessage:r.onForkFromMessage,onOpenLocalFilePath:r.onOpenLocalFilePath,disableFork:!r.capabilities.forkFromMessage,allowRollback:r.capabilities.rollback,allowRetry:r.capabilities.retry,readOnly:r.readOnly,enableTerminalCommandActions:!r.readOnly,rollbackConfirmTitle:r.rollbackConfirmTitle,rollbackConfirmDescription:r.rollbackConfirmDescription}),ae({panel:p,getMessages:t,getContextCompaction:()=>r.capabilities.compaction?e.state.contextCompaction??null:null,messageIndexOffset:n}),re({panel:p,getMessages:t,isStreaming:()=>e.state.isStreaming,isActive:ce})}catch(e){a.warn(`Failed to decorate chat messages:`,e)}try{te({panel:p,isStreaming:()=>e.state.isStreaming,abort:()=>e.abort(),agentAccessMode:r.agentAccessMode,harness:e.harness,getAcpSession:()=>e.state.acpSession??null,onOpenCodeConfigOptionChange:(t,n)=>{e.setConfigOption(t,n).catch(e=>{a.error(`Failed to update OpenCode config option:`,e)})},onOpenCodeModeChange:t=>{e.setMode(t).catch(e=>{a.error(`Failed to update OpenCode mode:`,e)})},planMode:r.planMode,workspaceToolsEnabled:r.workspaceToolsEnabled,readOnly:r.readOnly,allowModelControls:r.allowModelControls&&r.capabilities.modelSelection,planModeEnabled:r.capabilities.planMode,accessModeEnabled:r.capabilities.accessMode,commandSuggestionsEnabled:r.capabilities.commands,capabilitySuggestionsEnabled:r.capabilities.capabilitySuggestions,attachmentsEnabled:r.capabilities.attachments,onAccessModeChange:r.onAccessModeChange,onTogglePlanMode:r.onTogglePlanMode,onInput:be,onFilesChange:xe,removeCommandSuggestions:j.remove,updateCommandSuggestions:j.update,setupCommandTextareaHandler:j.setupTextareaHandler,removeCapabilitySuggestions:M.remove,updateCapabilitySuggestions:M.update,setupCapabilityTextareaHandler:M.setupTextareaHandler,insertBuiltinPluginMention:M.insertBuiltinPluginMention,availablePluginRows:M.availablePluginRows,onBeforeSend:t=>{h();let n=r.capabilities.capabilitySuggestions?M.consumeSelectedCapabilities(t):[];e.setNextPromptCapabilities?.(n)}})}catch{}let o=Q.current??(()=>{let t=e.state.pendingToolApproval;return t?{...t,sessionId:e.sessionId}:null})();if(o&&o.sessionId===e.sessionId&&typeof o.toolCallId==`string`&&typeof o.toolName==`string`){let t=o.toolCallId;v({panel:p,tone:`warning`,disabled:r.approvalReadOnly,disabledReason:r.approvalReadOnlyMessage,onApprove:async()=>{await X.current.onApproveToolCall(t),Q.current=null,e.state.pendingToolApproval=null,y(p)},onReject:async()=>{await X.current.onRejectToolCall(t),Q.current=null,e.state.pendingToolApproval=null,y(p)}},o.toolName,t,o.args,o.source)}else{let n=$.current??(()=>{let t=e.state.pendingAutoCompactApproval;return t?{...t,sessionId:e.sessionId}:null})();if(n&&n.sessionId===e.sessionId){let i=n.approvalId,a=!r.onApproveAutoCompact||!r.onRejectAutoCompact,o=r.approvalReadOnly||a,s=r.approvalReadOnly?r.approvalReadOnlyMessage:a?l(`autoCompactApprovalUnavailable`):void 0;v({panel:p,tone:`info`,copy:{status:l(`autoCompactApprovalStatus`),title:l(`autoCompactApprovalTitle`),risk:l(`autoCompactApprovalRisk`,{keepRecentTurns:n.keepRecentTurns??3}),approve:l(`autoCompactApprovalAccept`),reject:l(`autoCompactApprovalReject`)},disabled:o,disabledReason:s,getMessages:t,keepRecentTurns:n.keepRecentTurns??3,onApprove:async()=>{let t=X.current.onApproveAutoCompact;if(!t)throw Error(l(`autoCompactApprovalUnavailable`));await t(i),$.current=null,e.state.pendingAutoCompactApproval=null,y(p)},onReject:async()=>{let t=X.current.onRejectAutoCompact;if(!t)throw Error(l(`autoCompactApprovalUnavailable`));await t(i),$.current=null,e.state.pendingAutoCompactApproval=null,y(p)}},l(`contextManagement`),i,{percent:n.usage?.percent??0,threshold:n.thresholdPercent??0,keepRecentTurns:n.keepRecentTurns??3,summary:l(`autoCompactApprovalWaiting`,{percent:n.usage?.percent??0,threshold:n.thresholdPercent??0}),description:l(`autoCompactApprovalPreview`,{keepRecentTurns:n.keepRecentTurns??3})})}else y(p)}r.capabilities.contextUsage?N.update():N.cleanup(),e.harness===`opencode`&&ve.update(),_e?.update(),A.setup(),A.isEnabled&&(k.resetToTail(),A.scheduleScrollToBottom())},I=!1,L,R=!1,z,Ee=()=>{z===void 0&&(z=window.requestAnimationFrame(()=>{z=void 0,R=!1}))},Oe=()=>{if(!w){R=!0;try{we()}finally{Ee()}}},ke=()=>{I||(I=!0,L=window.requestAnimationFrame(()=>{L=void 0,I=!1,Oe()}))};lt.current=Oe;let B=()=>p.querySelector(`agent-interface`),Me=()=>{le||(le=!0,window.requestAnimationFrame(()=>{if(le=!1,w)return;F();let e=B();e?.requestUpdate?.(),(e?.updateComplete??Promise.resolve()).then(()=>{w||Oe()}),A.isEnabled&&A.scheduleScrollToBottom()}))};Z.current=ke;let W=()=>{let e=++O;p.dataset.quickforgeProcessHandoff=String(e);let t=B();t?.requestUpdate?.(),Z.current?.(),window.requestAnimationFrame(()=>{!w&&O===e&&Z.current?.()});let n=()=>{w||O!==e||(delete p.dataset.quickforgeProcessHandoff,Z.current?.(),window.requestAnimationFrame(()=>{!w&&O===e&&Z.current?.()}))};(t?.updateComplete??Promise.resolve()).then(n,n)};p.setAgent(e,{onApiKeyRequired:!X.current.capabilities.clientApiKeyCheck||X.current.bypassClientApiKeyCheck?async()=>!0:t=>o(e.state.model)?Promise.resolve(!0):i.prompt(t),onBeforeSend:()=>{t.invalidate(),Y();let e=H.current;e&&(!e.sessionId||e.sessionId===m)&&et(e.id),$e(),E=!0,j.remove(),U.current.delete(g),Ue(g).catch(e=>a.error(`Failed to clear composer draft:`,e)),A.enable()},onModelSelect:X.current.onModelSelect,toolsFactory:()=>ie(e.state.tools)}).then(()=>{if(w)return;let e=H.current,n=t.version(),r=r=>{if(!(w||!t.isCurrent(n)))if(e&&Ae.current!==e.id)dt(p,e,m,g);else{let e=r??U.current.get(g)??f();c(e)||(D=!0),Y();let i=p.querySelector(`agent-interface`);K.current=b(p,e,U.current,g,{shouldApply:()=>!w&&t.isCurrent(n)&&p.isConnected&&!!V.current?.contains(p),onApplyStart:()=>{q.current=!0},onApplyEnd:()=>{q.current=!1},onApplied:()=>{D=!0,Pe.current.add(p)},updateComplete:i?.updateComplete})}};if(e&&Ae.current!==e.id)r();else{let e=U.current.get(g);e?r(e):Ve(g).then(e=>r(e)).catch(e=>a.error(`Failed to load composer draft:`,e))}T=new MutationObserver(()=>{R||ke()}),T.observe(p,{childList:!0,subtree:!0}),window.requestAnimationFrame(()=>{w||Oe()});let i=B(),o=()=>{w||(de=d(()=>{w||X.current.onInitialRenderReady?.(m)}))};(i?.updateComplete??Promise.resolve()).then(o,o)},e=>{w||(a.error(`Failed to initialize chat panel:`,e),X.current.onInitialRenderError?.(m,e))}),V.current.replaceChildren(p),De&&(_e=Te({host:V.current,panel:p,getMessages:()=>e.state.messages,isStreaming:()=>e.state.isStreaming,windowLayer:k,beginProgrammaticScroll:A.beginProgrammaticScroll,onWindowChanged:()=>Z.current?.()}));let G=e.subscribe(t=>{if(t.type===`agent_start`&&(O+=1,delete p.dataset.quickforgeProcessHandoff,ce=!0,F(),Z.current?.(),A.enable(),Q.current?.sessionId===e.sessionId&&(Q.current=null),$.current?.sessionId===e.sessionId&&($.current=null)),t.type===`message_start`||t.type===`message_update`||t.type===`message_end`||t.type===`turn_end`||t.type===`agent_end`){F();let e=t.message;t.type===`message_start`&&e?.role===`assistant`&&(O+=1,delete p.dataset.quickforgeProcessHandoff),(t.type===`message_update`||e?.role===`assistant`)&&(ce=!1),Z.current?.(),t.type===`message_end`&&e?.role===`assistant`&&W(),A.isEnabled&&A.scheduleScrollToBottom()}if(t.type===`messages_replaced`){let e=H.current;e&&Ae.current===e.id&&dt(p,e,m,g)}let n=t.type;if(n===`tool_execution_start`){let n=t,r=Q.current,i=n.sessionId??e.sessionId;r&&r.sessionId===e.sessionId&&i===e.sessionId&&n.toolCallId===r.toolCallId&&(Q.current=null,e.state.pendingToolApproval?.toolCallId===n.toolCallId&&(e.state.pendingToolApproval=null),Z.current?.())}if((n===`tool_execution_start`||n===`tool_execution_update`||n===`tool_execution_end`)&&Me(),(n===`acp_session_update`||n===`acp_session_usage_update`)&&Z.current?.(),t.type===`agent_end`&&(ce=!1,F(),W(),Q.current?.sessionId===e.sessionId&&(Q.current=null,Z.current?.()),$.current?.sessionId===e.sessionId&&($.current=null,Z.current?.())),(n===`auto_compact_completed`||n===`auto_compact_failed`)&&($.current?.sessionId===e.sessionId&&($.current=null),e.state.pendingAutoCompactApproval=null,Z.current?.()),n===`auto_compact_completed`||n===`messages_replaced`){_(p);let e=B();e?.requestUpdate?.(),Z.current?.(),window.requestAnimationFrame(()=>Z.current?.()),e?.updateComplete?.then(()=>Z.current?.())}if(n===`auto_compact_failed`&&a.warn(l(`autoCompactFailed`)),t.type===`tool_approval_required`){let e=t;Q.current={toolCallId:e.toolCallId,toolName:e.toolName,args:e.args,sessionId:e.sessionId,source:e.source},Z.current?.()}if(t.type===`auto_compact_approval_required`){let e=t;$.current={approvalId:e.approvalId,usage:e.usage,thresholdPercent:e.thresholdPercent,keepRecentTurns:e.keepRecentTurns,sessionId:e.sessionId},Z.current?.()}});return()=>{w=!0,t.invalidate(),Y(),$e(),de?.(),E?(U.current.delete(g),Ue(g).catch(e=>a.error(`Failed to clear composer draft:`,e))):(D||se||n.has(p))&&(ne(p,U.current,g),st(p,g,C)),j.remove(),j.cleanupTextareaHandler(),M.remove(),M.cleanupTextareaHandler(),N.cleanup(),ve.cleanup(),_e?.cleanup(),A.cleanup(),ut.current=null,me(k),G(),T?.disconnect(),L!==void 0&&window.cancelAnimationFrame(L),z!==void 0&&window.cancelAnimationFrame(z),lt.current=null,p.remove()}},[e,De,J.capabilitySuggestions,$e,Y,et,st,dt,ot]),(0,T.useEffect)(()=>{let e=V.current;e&&(e.classList.toggle(`quickforge-chat-panel-empty-host`,Ee),e.dataset.quickforgeEmptyChat=Ee?`true`:`false`)},[Ee]),(0,T.useEffect)(()=>{lt.current?.(),(V.current?.querySelector(`agent-interface`))?.requestUpdate?.()},[w,Ye,E,ze,Ce,we,I,L,z,B,n]),(0,T.useEffect)(()=>{let t=H.current;if(!t||!V.current)return;let n=e?.sessionId??``;if(t.sessionId&&t.sessionId!==n||W.current.has(t.id))return;let r=V.current.querySelector(`pi-chat-panel`);r&&dt(r,t,n,it.current)},[F,e,dt]),(0,Ke.jsx)(`div`,{ref:V,className:`quickforge-chat-panel-host min-h-0 flex-1 overflow-hidden`})}export{Ye as ChatPanelHost};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{i as e}from"./rolldown-runtime-DWdDZTNf.js";import{D as t,J as n,Jt as r,Pt as i,W as a,n as o,u as s,z as c}from"./icons-DM_qJ7VJ.js";import{n as l}from"./react-vendor-BpWW_Nvp.js";import{An as u,Pn as d,_t as f,bt as p,ft as m,kn as h,wn as ee}from"./index-DFASc15l.js";import{n as g,t as _}from"./xterm-Bm_IbozX.js";var v=e(r(),1);async function y(e,t){let n=await fetch(e,{cache:`no-store`,...t}),r=await n.json().catch(()=>null);if(!n.ok)throw Error(r?.error||`Request failed: ${n.status}`);return r}function b(){return y(`/api/terminal/capabilities`,{cache:`default`})}function x(e){return y(`/api/terminal/sessions${e?`?projectId=${encodeURIComponent(e)}`:``}`)}function S(e){return y(`/api/terminal/sessions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})}function C(e){return y(`/api/terminal/sessions/${encodeURIComponent(e)}`,{method:`DELETE`})}function te(e,t){return y(`/api/terminal/sessions/${encodeURIComponent(e)}/input`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({data:t})})}function ne(){let[e,t]=(0,v.useState)(()=>m());return(0,v.useEffect)(()=>{if(typeof document>`u`)return;let e=document.documentElement,n=()=>t(m());n();let r=new MutationObserver(n);return r.observe(e,{attributes:!0,attributeFilter:[`class`]}),()=>r.disconnect()},[]),e}var w=1e4,T=[1e3,2e3,4e3],E=T.length;function D(e){return T[e]}function O(e){return e.code===`SESSION_NOT_FOUND`||e.retryable===!1||e.message===`Terminal session not found`}var k=l(),re={light:{background:`#ffffff`,foreground:`#1f2937`,cursor:`#1f2937`,selectionBackground:`#dbeafe`},dark:{background:`#171717`,foreground:`#e5e7eb`,cursor:`#e5e7eb`,selectionBackground:`#3f3f46`}};function ie({session:e,active:t,height:n,retryKey:r,onReady:i,onExited:a,onConnectionError:o,onConnectionState:s}){let c=re[ne()],l=(0,v.useRef)(null),u=(0,v.useRef)(null),m=(0,v.useRef)(null),h=(0,v.useRef)(null),y=(0,v.useRef)(null),b=(0,v.useRef)(()=>{}),x=(0,v.useRef)(!1);return(0,v.useEffect)(()=>{let e=l.current;if(!e)return;let t=p(),n=new g({cursorBlink:!0,convertEol:!1,fontFamily:getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace`,fontSize:t.fontSize,lineHeight:t.lineHeight,scrollback:5e3}),r=new _;n.loadAddon(r),n.open(e),u.current=n,m.current=r;let i=()=>{if(e.isConnected)try{r.fit();let e=h.current;e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:`resize`,cols:n.cols,rows:n.rows}))}catch{}};b.current=i;let a=new ResizeObserver(()=>i());a.observe(e);let o=()=>{let e=p();n.options.fontSize=e.fontSize,n.options.lineHeight=e.lineHeight,window.setTimeout(i,0)};return window.addEventListener(f,o),window.setTimeout(i,50),()=>{window.removeEventListener(f,o),a.disconnect(),b.current=()=>{},n.dispose(),u.current=null,m.current=null}},[e.id]),(0,v.useEffect)(()=>{let e=u.current;e&&(e.options.theme=c)},[c]),(0,v.useEffect)(()=>{let t=!1,n=!1,r=!1,c=0,l,f=0,p=n=>{t||s(e.id,n)},m=()=>{if(t||n||r)return;let s=++f,g=!1,_=!1,v=new WebSocket(`${ee()}/api/terminal/sessions/${encodeURIComponent(e.id)}/ws`);h.current=v,p(c===0?{status:`connecting`}:{status:`reconnecting`,reconnectAttempt:c});let S=window.setTimeout(()=>{if(!(t||n||r||_||s!==f)){C(d(`terminalConnectionTimedOut`));try{v.close()}catch{}}},w),C=i=>{if(t||n||r||g||s!==f)return;g=!0,window.clearTimeout(S),y.current?.dispose(),y.current=null;let a=D(c);if(c<E&&a!==void 0){c+=1,p({status:`reconnecting`,reconnectAttempt:c}),l=window.setTimeout(m,a);return}p({status:`disconnected`}),o(e.id,i)};v.addEventListener(`open`,()=>{if(t||n||g||s!==f){try{v.close()}catch{}return}y.current?.dispose(),y.current=u.current?.onData(e=>{v.readyState===WebSocket.OPEN&&v.send(JSON.stringify({type:`input`,data:e}))})??null,window.setTimeout(b.current,0)}),v.addEventListener(`message`,t=>{try{let s=JSON.parse(String(t.data));if(s.type===`ready`)_=!0,c=0,window.clearTimeout(S),o(e.id,void 0),p({status:`connected`}),x.current||(x.current=!0,u.current?.writeln(`\x1b[2mConnected to ${e.cwd}\x1b[0m`)),i(e.id);else if(s.type===`output`)u.current?.write(s.data);else if(s.type===`exit`)n=!0,window.clearTimeout(S),l!==void 0&&window.clearTimeout(l),u.current?.writeln(``),u.current?.writeln(`\x1b[33m[process exited with code ${s.exitCode??`unknown`}]\x1b[0m`),p({status:`exited`}),a(e.id);else if(s.type===`error`)if(O(s)){r=!0,g=!0,window.clearTimeout(S),l!==void 0&&window.clearTimeout(l),y.current?.dispose(),y.current=null,p({status:`unavailable`}),o(e.id,d(`terminalSessionUnavailable`));try{v.close()}catch{}}else C(s.message||d(`terminalConnectionFailed`))}catch{}}),v.addEventListener(`error`,()=>{C(d(_?`terminalConnectionClosedUnexpectedly`:`terminalConnectionFailed`))}),v.addEventListener(`close`,()=>{window.clearTimeout(S),y.current?.dispose(),y.current=null,!(t||n||r||g||s!==f)&&C(d(_?`terminalConnectionClosedUnexpectedly`:`terminalConnectionFailed`))})};return o(e.id,void 0),m(),()=>{t=!0,f+=1,l!==void 0&&window.clearTimeout(l),y.current?.dispose(),y.current=null;let e=h.current;h.current=null;try{e?.close()}catch{}}},[o,s,a,i,r,e.cwd,e.id]),(0,v.useEffect)(()=>{t&&window.setTimeout(()=>{try{m.current?.fit(),u.current?.focus()}catch{}},0)},[t,n]),(0,k.jsx)(`div`,{className:t?`h-full min-h-0 w-full pl-2 md:pl-3`:`hidden`,"aria-hidden":!t,children:(0,k.jsx)(`div`,{ref:l,className:`h-full min-h-0 w-full`})})}var ae=180,oe=.7,se=320;function A(e,t){let n=t?t.name:`Terminal`,r=new Set(e.map(e=>e.name));if(n!==`Terminal`&&!r.has(n))return n;let i=1;for(;r.has(`${n} ${i}`);)i+=1;return`${n} ${i}`}function j(e,t){let n=e?.terminalShellProfiles||[],r=t||e?.defaultTerminalShellProfileId||``;return n.find(e=>e.id===r)||n[0]}function M({project:e,onCollapse:r,pendingCommand:l,onPendingCommandHandled:f,variant:p=`dock`,singleSession:m=!1,panelInstanceId:ee,panelSessionId:g,onPanelSessionReady:_}){let[y,ne]=(0,v.useState)(null),[w,T]=(0,v.useState)([]),[E,D]=(0,v.useState)(),[O,re]=(0,v.useState)(se),[M,ce]=(0,v.useState)(!0),[N,le]=(0,v.useState)(!1),[ue,P]=(0,v.useState)(),[de,fe]=(0,v.useState)({}),[F,pe]=(0,v.useState)({}),[me,he]=(0,v.useState)({}),[I,L]=(0,v.useState)(!1),[R,ge]=(0,v.useState)(!1),z=(0,v.useRef)(!1),B=(0,v.useRef)(!1),V=(0,v.useRef)(new Set),_e=(0,v.useRef)(l),H=(0,v.useRef)(new Set),U=(0,v.useRef)(new Set),W=(0,v.useRef)(new Map),G=(0,v.useRef)(!0),ve=(0,v.useRef)(_),[ye,be]=(0,v.useState)(()=>new Set),xe=(0,v.useRef)(null),Se=(0,v.useRef)(null),K=e?.id,q=p===`panel`&&!!ee,J=(0,v.useMemo)(()=>w.find(e=>e.id===E)??w[0],[E,w]);(0,v.useEffect)(()=>{_e.current=l},[l]),(0,v.useEffect)(()=>{ve.current=_},[_]),(0,v.useEffect)(()=>()=>{G.current=!1},[]);let Ce=(0,v.useCallback)(async()=>{let e=await x(K);return T(e.sessions),D(t=>t&&e.sessions.some(e=>e.id===t)?t:e.sessions[0]?.id),e.sessions},[K]),we=(0,v.useCallback)(async(e,t)=>{if(z.current)return;let n=j(y,t);z.current=!0,le(!0),P(void 0);try{let t=await S({projectId:K,name:A(e,n),cols:120,rows:30,shellProfileId:n?.id,shellProfileName:n?.name});T(e=>[...e,t]),D(t.id),q&&ve.current?.(t.id)}catch(e){P(e instanceof Error?e.message:d(`terminalCreateFailed`))}finally{z.current=!1,le(!1)}},[y,q,K]);(0,v.useEffect)(()=>{let e=!1;return(async()=>{ce(!0),P(void 0);try{let[t,n]=await Promise.all([b(),x(K)]);if(e)return;if(ne(t),t.enabled&&q&&g&&n.sessions.some(e=>e.id===g)){B.current=!0,T(n.sessions),D(g);return}if(t.enabled&&q&&!B.current){B.current=!0;let r=j(t);try{let t=await S({projectId:K,name:A(n.sessions,r),cols:120,rows:30,shellProfileId:r?.id,shellProfileName:r?.name});if(e){C(t.id).catch(()=>{});return}T([...n.sessions,t]),D(t.id),ve.current?.(t.id);return}catch(t){e||P(t instanceof Error?t.message:d(`terminalCreateFailed`))}}if(T(n.sessions),D(n.sessions[0]?.id),t.enabled&&n.sessions.length===0&&!_e.current){let n=j(t);S({projectId:K,name:A([],n),cols:120,rows:30,shellProfileId:n?.id,shellProfileName:n?.name}).then(t=>{if(e){C(t.id).catch(()=>{});return}T([t]),D(t.id)}).catch(t=>{e||P(t instanceof Error?t.message:d(`terminalCreateFailed`))})}}catch(t){e||P(t instanceof Error?t.message:d(`terminalUnavailable`))}finally{e||ce(!1)}})(),()=>{e=!0}},[q,g,K]),(0,v.useEffect)(()=>{if(!I)return;let e=e=>{Se.current?.contains(e.target)||L(!1)},t=e=>{e.key===`Escape`&&L(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[I]),(0,v.useEffect)(()=>{if(!R)return;let e=e=>{e.key===`Escape`&&ge(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[R]),(0,v.useEffect)(()=>{if(!l||V.current.has(l.id)||W.current.has(l.id)||H.current.has(l.id)||M||N||!y)return;if(!y.enabled){V.current.add(l.id),window.setTimeout(()=>{P(y.reason||d(`terminalUnavailable`)),f?.(l.id)},0);return}let e=J&&!J.exited?J:w.find(e=>!e.exited);if(e){W.current.set(l.id,e.id),window.setTimeout(()=>{G.current&&D(e.id)},0);return}H.current.add(l.id),window.setTimeout(()=>{G.current&&P(void 0)},0);let t=j(y);S({projectId:K,name:A(w,t),cols:120,rows:30,shellProfileId:t?.id,shellProfileName:t?.name}).then(e=>{if(!G.current){C(e.id).catch(()=>{});return}W.current.set(l.id,e.id),T(t=>t.some(t=>t.id===e.id)?t:[...t,e]),D(e.id)}).catch(e=>{G.current&&(P(e instanceof Error?e.message:d(`terminalCommandExecuteFailed`)),V.current.add(l.id),f?.(l.id))}).finally(()=>{H.current.delete(l.id)})},[J,y,N,M,f,l,K,w]),(0,v.useEffect)(()=>{if(!l||V.current.has(l.id)||U.current.has(l.id))return;let e=W.current.get(l.id),t=e?w.find(t=>t.id===e):J&&!J.exited?J:w.find(e=>!e.exited);!t||t.exited||!ye.has(t.id)||(U.current.add(l.id),window.setTimeout(()=>{G.current&&(D(t.id),P(void 0))},0),(async()=>{try{if(l.execute){let e=l.command.split(`
|
|
2
|
-
`),n=e.flatMap((t,n)=>n<e.length-1?[t,`\r`]:[t]);n.push(`\r`),await te(t.id,n.join(``))}else await te(t.id,l.command)}catch(e){G.current&&P(e instanceof Error?e.message:d(`terminalCommandExecuteFailed`))}finally{V.current.add(l.id),U.current.delete(l.id),W.current.delete(l.id),G.current&&f?.(l.id)}})())},[J,f,l,ye,w]);let Y=async e=>{P(void 0),fe(t=>{if(!t[e])return t;let n={...t};return delete n[e],n}),pe(t=>{if(!t[e])return t;let n={...t};return delete n[e],n}),he(t=>{if(t[e]===void 0)return t;let n={...t};return delete n[e],n});let t=w.filter(t=>t.id!==e);T(t),E===e&&D(t[0]?.id);try{await C(e)}catch(e){P(e instanceof Error?e.message:d(`terminalCloseFailed`)),Ce().catch(()=>{})}},Te=(0,v.useCallback)(e=>{T(t=>t.map(t=>t.id===e?{...t,exited:!0}:t)),be(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),Ee=(0,v.useCallback)(e=>{be(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},[]),De=(0,v.useCallback)((e,t)=>{fe(n=>{if(!t){if(!n[e])return n;let t={...n};return delete t[e],t}return n[e]===t?n:{...n,[e]:t}})},[]),Oe=(0,v.useCallback)((e,t)=>{pe(n=>{let r=n[e];return r?.status===t.status&&r.reconnectAttempt===t.reconnectAttempt?n:{...n,[e]:t}})},[]),ke=(0,v.useCallback)(e=>{fe(t=>{if(!t[e])return t;let n={...t};return delete n[e],n}),he(t=>({...t,[e]:(t[e]||0)+1}))},[]),Ae=async e=>{let t=w.filter(t=>t.id!==e);await Y(e),await we(t)},je=(e,t)=>e.exited||t===`exited`||t===`unavailable`?`bg-muted-foreground/40`:t===`connected`?`bg-emerald-500/80`:t===`connecting`||t===`reconnecting`?`bg-amber-500/80`:`bg-destructive/70`,Me=e=>{xe.current={startY:e.clientY,startHeight:O},e.currentTarget.setPointerCapture(e.pointerId)},Ne=e=>{let t=xe.current;if(!t)return;let n=Math.max(ae,Math.floor(window.innerHeight*oe));re(Math.min(n,Math.max(ae,t.startHeight+t.startY-e.clientY)))},Pe=e=>{xe.current=null;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}},X=y?.terminalShellProfiles||[],Fe=y?.defaultTerminalShellProfileId||``,Ie=X.find(e=>e.id===Fe)||X[0],Le=!!(y&&w.length>=y.maxSessions),Re=N||Le,ze=J?de[J.id]:void 0,Z=J?F[J.id]:void 0,Be=Z?.status===`unavailable`,Ve=Z?.status===`connecting`?d(`terminalConnecting`):Z?.status===`reconnecting`?d(`terminalReconnecting`,{attempt:Z.reconnectAttempt||1,max:3}):void 0,He=q&&J?[J]:w,Q=ue??ze,Ue=Q?void 0:Ve,We=!!(Q||Ue),$=p===`panel`,Ge=$&&m,Ke=$?void 0:R?We?`calc(100% - 4.25rem)`:`calc(100% - 2.25rem)`:We?O-72:O-45;return(0,k.jsxs)(`div`,{className:u($?`flex min-h-0 flex-1 flex-col bg-background`:`shrink-0 border-t border-border bg-background`,R&&`quickforge-terminal-fullscreen z-40 flex flex-col border-t-0`),style:R||$?void 0:{height:O},children:[!R&&!$?(0,k.jsx)(`div`,{className:`h-1 cursor-row-resize bg-transparent hover:bg-border`,onPointerDown:Me,onPointerMove:Ne,onPointerUp:Pe,onPointerCancel:Pe}):null,(0,k.jsxs)(`div`,{className:`flex h-9 items-center gap-1 border-b border-border px-2`,children:[(0,k.jsx)(s,{className:`size-4 shrink-0 text-muted-foreground/60`}),(0,k.jsx)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-x-auto`,children:He.map(e=>{let t=u(`flex max-w-44 shrink-0 items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground/72`,J?.id===e.id&&`bg-muted/28 text-foreground/90`);return Ge?(0,k.jsxs)(`div`,{className:t,title:`${e.name} — ${e.cwd}`,children:[(0,k.jsx)(`span`,{className:u(`size-1.5 rounded-full`,je(e,F[e.id]?.status))}),(0,k.jsx)(`span`,{className:`truncate`,children:e.name})]},e.id):(0,k.jsxs)(`button`,{type:`button`,className:u(t,`hover:bg-muted/20 hover:text-foreground/85`),onClick:()=>D(e.id),title:`${e.name} — ${e.cwd}`,children:[(0,k.jsx)(`span`,{className:u(`size-1.5 rounded-full`,je(e,F[e.id]?.status))}),(0,k.jsx)(`span`,{className:`truncate`,children:e.name}),(0,k.jsx)(`span`,{role:`button`,tabIndex:0,className:`ml-1 rounded-sm p-0.5 opacity-60 hover:bg-background hover:opacity-100`,onClick:t=>{t.stopPropagation(),Y(e.id)},onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),t.stopPropagation(),Y(e.id))},"aria-label":d(`terminalCloseSession`,{name:e.name}),children:(0,k.jsx)(o,{className:`size-3`})})]},e.id)})}),Ge?null:(0,k.jsxs)(`div`,{className:`relative shrink-0`,ref:Se,children:[(0,k.jsxs)(`div`,{className:`flex items-center overflow-hidden rounded-md border border-border bg-background`,children:[(0,k.jsx)(`button`,{type:`button`,className:`inline-flex h-7 w-7 items-center justify-center text-foreground/85 transition-colors hover:bg-muted/20 disabled:pointer-events-none disabled:opacity-50`,onClick:()=>void we(w),disabled:Re,title:Ie?d(`terminalNewWithProfile`,{name:Ie.name}):d(`terminalNew`),"aria-label":d(`terminalNew`),children:N?(0,k.jsx)(n,{className:`size-3.5 animate-spin`}):(0,k.jsx)(t,{className:`size-3.5`})}),X.length>0?(0,k.jsx)(`button`,{type:`button`,className:`inline-flex h-7 w-7 items-center justify-center border-l border-border text-muted-foreground/72 transition-colors hover:bg-muted/20 hover:text-foreground/85 disabled:pointer-events-none disabled:opacity-50`,onClick:()=>L(e=>!e),disabled:Re,title:d(`terminalSelectShell`),"aria-label":d(`terminalSelectShell`),"aria-expanded":I,children:(0,k.jsx)(i,{className:`size-3.5`})}):null]}),I?(0,k.jsxs)(`div`,{className:u(`absolute right-0 z-30 w-64 overflow-hidden rounded-lg border border-border bg-background p-1.5 shadow-[0_16px_38px_-22px_rgb(15_23_42_/_0.65)]`,$?`top-9`:`bottom-9`),children:[(0,k.jsx)(`div`,{className:`px-2 pb-1.5 pt-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground/60`,children:d(`terminalNewWith`)}),X.map(e=>(0,k.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/80 hover:bg-muted/20 hover:text-foreground/90`,onClick:()=>{L(!1),we(w,e.id)},children:[(0,k.jsx)(`span`,{className:`inline-flex size-5 shrink-0 items-center justify-center rounded bg-muted/20 text-[10px] text-muted-foreground/70`,children:e.name.slice(0,1).toUpperCase()}),(0,k.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,k.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,k.jsx)(`span`,{className:`block truncate font-mono text-[11px] text-muted-foreground/55`,children:e.command})]})]},e.id))]}):null]}),Ge?null:(0,k.jsx)(h,{variant:`ghost`,size:`icon`,className:`size-7`,onClick:()=>ge(e=>!e),title:d(R?`terminalExitFullscreen`:`terminalFullscreen`),"aria-label":d(R?`terminalExitFullscreen`:`terminalFullscreen`),children:R?(0,k.jsx)(c,{className:`size-3.5`}):(0,k.jsx)(a,{className:`size-3.5`})}),(0,k.jsx)(h,{variant:`ghost`,size:`icon`,className:u(`size-7`,$&&`hidden`),onClick:r,title:d(`terminalCollapse`),"aria-label":d(`terminalCollapse`),children:(0,k.jsx)(i,{className:`size-3.5`})})]}),Q?(0,k.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-border px-3 py-1.5 text-xs text-destructive`,children:[(0,k.jsx)(`span`,{children:Q}),Be&&J?(0,k.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,k.jsx)(`button`,{type:`button`,className:`rounded px-1.5 py-0.5 font-medium text-foreground/80 hover:bg-muted/40`,onClick:()=>void Ae(J.id),disabled:N,children:d(`terminalStartNew`)}),(0,k.jsx)(`button`,{type:`button`,className:`rounded px-1.5 py-0.5 font-medium text-muted-foreground hover:bg-muted/40`,onClick:()=>void Y(J.id),children:d(`close`)})]}):ze&&J&&!J.exited?(0,k.jsx)(`button`,{type:`button`,className:`shrink-0 rounded px-1.5 py-0.5 font-medium text-destructive hover:bg-destructive/10`,onClick:()=>ke(J.id),children:d(`retry`)}):null]}):Ue?(0,k.jsx)(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-muted-foreground/70`,children:Ue}):null,(0,k.jsx)(`div`,{className:u(`min-h-0 bg-background`,$&&`flex-1`),style:Ke===void 0?void 0:{height:Ke},children:M?(0,k.jsxs)(`div`,{className:`flex h-full items-center justify-center gap-2 text-xs text-muted-foreground/60`,children:[(0,k.jsx)(n,{className:`size-4 animate-spin`}),` `,d(`terminalStarting`)]}):y&&!y.enabled?(0,k.jsx)(`div`,{className:`flex h-full items-center justify-center px-4 text-center text-xs text-muted-foreground/60`,children:y.reason||d(`terminalUnavailable`)}):w.length===0?(0,k.jsx)(`div`,{className:`flex h-full items-center justify-center text-xs text-muted-foreground/60`,children:d(`terminalNoSessions`)}):w.map(e=>(0,k.jsx)(ie,{session:e,active:e.id===J?.id,height:R?window.innerHeight-36:$?0:O,retryKey:me[e.id]||0,onReady:Ee,onExited:Te,onConnectionError:De,onConnectionState:Oe},e.id))})]})}export{M as TerminalDock,ne as t};
|