aicodeman 1.16.2 → 1.16.4

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 (158) hide show
  1. package/README.md +11 -10
  2. package/dist/claude-credentials.d.ts +50 -0
  3. package/dist/claude-credentials.d.ts.map +1 -0
  4. package/dist/claude-credentials.js +102 -0
  5. package/dist/claude-credentials.js.map +1 -0
  6. package/dist/config/voice.d.ts +43 -0
  7. package/dist/config/voice.d.ts.map +1 -0
  8. package/dist/config/voice.js +48 -0
  9. package/dist/config/voice.js.map +1 -0
  10. package/dist/search-service.d.ts +9 -1
  11. package/dist/search-service.d.ts.map +1 -1
  12. package/dist/search-service.js +13 -3
  13. package/dist/search-service.js.map +1 -1
  14. package/dist/services/unified-session-service.d.ts +9 -0
  15. package/dist/services/unified-session-service.d.ts.map +1 -1
  16. package/dist/services/unified-session-service.js +4 -1
  17. package/dist/services/unified-session-service.js.map +1 -1
  18. package/dist/types/search.d.ts +17 -3
  19. package/dist/types/search.d.ts.map +1 -1
  20. package/dist/web/ports/config-port.d.ts +2 -0
  21. package/dist/web/ports/config-port.d.ts.map +1 -1
  22. package/dist/web/public/admin-ui.js +35 -20
  23. package/dist/web/public/admin-ui.js.br +0 -0
  24. package/dist/web/public/admin-ui.js.gz +0 -0
  25. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  26. package/dist/web/public/{app.4d006245.js → app.f9c6aadd.js} +18 -18
  27. package/dist/web/public/app.f9c6aadd.js.br +0 -0
  28. package/dist/web/public/app.f9c6aadd.js.gz +0 -0
  29. package/dist/web/public/approvals-ui.js.gz +0 -0
  30. package/dist/web/public/{constants.7d0f4047.js → constants.53dc0fa1.js} +43 -0
  31. package/dist/web/public/constants.53dc0fa1.js.br +0 -0
  32. package/dist/web/public/constants.53dc0fa1.js.gz +0 -0
  33. package/dist/web/public/cron-ui.js.gz +0 -0
  34. package/dist/web/public/entrance-animations.js.gz +0 -0
  35. package/dist/web/public/home-sessions.js +132 -10
  36. package/dist/web/public/home-sessions.js.br +0 -0
  37. package/dist/web/public/home-sessions.js.gz +0 -0
  38. package/dist/web/public/i18n.89097ff5.js +1 -0
  39. package/dist/web/public/i18n.89097ff5.js.br +0 -0
  40. package/dist/web/public/i18n.89097ff5.js.gz +0 -0
  41. package/dist/web/public/image-input.ee16ad88.js.gz +0 -0
  42. package/dist/web/public/index.html +1335 -1000
  43. package/dist/web/public/index.html.br +0 -0
  44. package/dist/web/public/index.html.gz +0 -0
  45. package/dist/web/public/input-cjk.63794d0b.js.gz +0 -0
  46. package/dist/web/public/{keyboard-accessory.1f35b482.js → keyboard-accessory.0f524637.js} +207 -5
  47. package/dist/web/public/keyboard-accessory.0f524637.js.br +0 -0
  48. package/dist/web/public/keyboard-accessory.0f524637.js.gz +0 -0
  49. package/dist/web/public/mobile-handlers.32fdd57f.js.gz +0 -0
  50. package/dist/web/public/mobile-overview.js.gz +0 -0
  51. package/dist/web/public/mobile.4f875962.css +1 -0
  52. package/dist/web/public/mobile.4f875962.css.br +0 -0
  53. package/dist/web/public/mobile.4f875962.css.gz +0 -0
  54. package/dist/web/public/notification-manager.5d229063.js.gz +0 -0
  55. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  56. package/dist/web/public/{panels-ui.3df9cd95.js → panels-ui.54b0d004.js} +1 -1
  57. package/dist/web/public/panels-ui.54b0d004.js.br +0 -0
  58. package/dist/web/public/panels-ui.54b0d004.js.gz +0 -0
  59. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  60. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  61. package/dist/web/public/readmymind-ui.js +98 -18
  62. package/dist/web/public/readmymind-ui.js.br +0 -0
  63. package/dist/web/public/readmymind-ui.js.gz +0 -0
  64. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  65. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  66. package/dist/web/public/{session-ui.f4fed187.js → session-ui.46a0993c.js} +5 -5
  67. package/dist/web/public/session-ui.46a0993c.js.br +0 -0
  68. package/dist/web/public/session-ui.46a0993c.js.gz +0 -0
  69. package/dist/web/public/settings-ui.63be4178.js +67 -0
  70. package/dist/web/public/settings-ui.63be4178.js.br +0 -0
  71. package/dist/web/public/settings-ui.63be4178.js.gz +0 -0
  72. package/dist/web/public/styles.9e04378d.css +1 -0
  73. package/dist/web/public/styles.9e04378d.css.br +0 -0
  74. package/dist/web/public/styles.9e04378d.css.gz +0 -0
  75. package/dist/web/public/subagent-windows.4cc8b005.js.gz +0 -0
  76. package/dist/web/public/sw.js.gz +0 -0
  77. package/dist/web/public/terminal-ui.ae776405.js +4 -0
  78. package/dist/web/public/terminal-ui.ae776405.js.br +0 -0
  79. package/dist/web/public/terminal-ui.ae776405.js.gz +0 -0
  80. package/dist/web/public/ultracode-panel.js.gz +0 -0
  81. package/dist/web/public/ultracode-windows.js.gz +0 -0
  82. package/dist/web/public/upload.html.gz +0 -0
  83. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  84. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  85. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  86. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  87. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  88. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  89. package/dist/web/public/vendor/xterm-predictive-echo.6cec0fba.js.gz +0 -0
  90. package/dist/web/public/vendor/xterm-zerolag-input.137ad9f0.js.gz +0 -0
  91. package/dist/web/public/vendor/xterm.css.gz +0 -0
  92. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  93. package/dist/web/public/{voice-input.e5461859.js → voice-input.4ec670b0.js} +421 -13
  94. package/dist/web/public/voice-input.4ec670b0.js.br +0 -0
  95. package/dist/web/public/voice-input.4ec670b0.js.gz +0 -0
  96. package/dist/web/public/voice-pcm-worklet.js +57 -0
  97. package/dist/web/public/voice-pcm-worklet.js.br +0 -0
  98. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  99. package/dist/web/public/webview-tabs.js.gz +0 -0
  100. package/dist/web/routes/index.d.ts +1 -0
  101. package/dist/web/routes/index.d.ts.map +1 -1
  102. package/dist/web/routes/index.js +1 -0
  103. package/dist/web/routes/index.js.map +1 -1
  104. package/dist/web/routes/search-routes.d.ts +3 -1
  105. package/dist/web/routes/search-routes.d.ts.map +1 -1
  106. package/dist/web/routes/search-routes.js +34 -1
  107. package/dist/web/routes/search-routes.js.map +1 -1
  108. package/dist/web/routes/session-routes.d.ts.map +1 -1
  109. package/dist/web/routes/session-routes.js +151 -9
  110. package/dist/web/routes/session-routes.js.map +1 -1
  111. package/dist/web/routes/voice-routes.d.ts +45 -0
  112. package/dist/web/routes/voice-routes.d.ts.map +1 -0
  113. package/dist/web/routes/voice-routes.js +172 -0
  114. package/dist/web/routes/voice-routes.js.map +1 -0
  115. package/dist/web/schemas.d.ts +2 -0
  116. package/dist/web/schemas.d.ts.map +1 -1
  117. package/dist/web/schemas.js +12 -0
  118. package/dist/web/schemas.js.map +1 -1
  119. package/dist/web/server.d.ts +1 -0
  120. package/dist/web/server.d.ts.map +1 -1
  121. package/dist/web/server.js +11 -1
  122. package/dist/web/server.js.map +1 -1
  123. package/dist/web/session-history-index.d.ts +108 -0
  124. package/dist/web/session-history-index.d.ts.map +1 -0
  125. package/dist/web/session-history-index.js +118 -0
  126. package/dist/web/session-history-index.js.map +1 -0
  127. package/dist/web/voice-stream.d.ts +96 -0
  128. package/dist/web/voice-stream.d.ts.map +1 -0
  129. package/dist/web/voice-stream.js +268 -0
  130. package/dist/web/voice-stream.js.map +1 -0
  131. package/package.json +1 -1
  132. package/dist/web/public/app.4d006245.js.br +0 -0
  133. package/dist/web/public/app.4d006245.js.gz +0 -0
  134. package/dist/web/public/constants.7d0f4047.js.br +0 -0
  135. package/dist/web/public/constants.7d0f4047.js.gz +0 -0
  136. package/dist/web/public/i18n.ef50083f.js +0 -1
  137. package/dist/web/public/i18n.ef50083f.js.br +0 -0
  138. package/dist/web/public/i18n.ef50083f.js.gz +0 -0
  139. package/dist/web/public/keyboard-accessory.1f35b482.js.br +0 -0
  140. package/dist/web/public/keyboard-accessory.1f35b482.js.gz +0 -0
  141. package/dist/web/public/mobile.5d8c896c.css +0 -1
  142. package/dist/web/public/mobile.5d8c896c.css.br +0 -0
  143. package/dist/web/public/mobile.5d8c896c.css.gz +0 -0
  144. package/dist/web/public/panels-ui.3df9cd95.js.br +0 -0
  145. package/dist/web/public/panels-ui.3df9cd95.js.gz +0 -0
  146. package/dist/web/public/session-ui.f4fed187.js.br +0 -0
  147. package/dist/web/public/session-ui.f4fed187.js.gz +0 -0
  148. package/dist/web/public/settings-ui.1c15649c.js +0 -67
  149. package/dist/web/public/settings-ui.1c15649c.js.br +0 -0
  150. package/dist/web/public/settings-ui.1c15649c.js.gz +0 -0
  151. package/dist/web/public/styles.0024c22e.css +0 -1
  152. package/dist/web/public/styles.0024c22e.css.br +0 -0
  153. package/dist/web/public/styles.0024c22e.css.gz +0 -0
  154. package/dist/web/public/terminal-ui.e7c5d233.js +0 -4
  155. package/dist/web/public/terminal-ui.e7c5d233.js.br +0 -0
  156. package/dist/web/public/terminal-ui.e7c5d233.js.gz +0 -0
  157. package/dist/web/public/voice-input.e5461859.js.br +0 -0
  158. package/dist/web/public/voice-input.e5461859.js.gz +0 -0
@@ -2,12 +2,16 @@
2
2
  * @fileoverview Read My Mind UI: predict the prompt you were about to type.
3
3
  *
4
4
  * A 🧠 header button (marker-hidden until the synced opt-in `readMyMindEnabled`
5
- * setting is ON) opens a modal that asks the server for the user's most likely
5
+ * setting is ON; phones get a keyboard-accessory 🧠 key gated on the same
6
+ * setting) opens a modal that asks the server for the user's most likely
6
7
  * next prompt (`POST /api/sessions/:id/readmymind`, one-shot predictor over the
7
8
  * case's intent profile + live session signals). The top suggestion lands in an
8
- * editable single-line field with its rationale below; buttons are Send (with
9
- * Enter), Insert (drop on the CLI composer WITHOUT Enter, for editing), Rethink
10
- * (re-run with the shown suggestion recorded as rejected), Dismiss.
9
+ * editable single-line field with its rationale below; the predictor's other
10
+ * suggestions render as tappable alternate rows that swap into the field
11
+ * without losing edits. Buttons are Send (with Enter), Insert (drop on the CLI
12
+ * composer WITHOUT Enter, for editing), Rethink (re-run with the whole shown
13
+ * set, main + alternates, recorded as rejected, plus the optional free-text
14
+ * steer note, e.g. "no, I meant the mobile bug", sent as `steer`), Dismiss.
11
15
  *
12
16
  * Suggestions are NEVER auto-sent: the explicit click here is the security
13
17
  * boundary for observed/injectable predictor inputs, so suggestion text is
@@ -20,6 +24,7 @@
20
24
  *
21
25
  * @mixin Extends CodemanApp.prototype via Object.assign
22
26
  * @dependency app.js (CodemanApp class, this.sessions, this.activeSessionId, showToast)
27
+ * @dependency mobile-handlers.js (MobileDetection.isTouchDevice, focus policy)
23
28
  * @dependency settings-ui.js (loadAppSettingsFromStorage)
24
29
  * @dependency api-client.js at runtime (this._apiJson; loads later but is only called after init)
25
30
  * @loadorder 11.3, after panels-ui.js, before ultracode-panel.js
@@ -43,8 +48,11 @@ Object.assign(CodemanApp.prototype, {
43
48
  this.showToast('Read My Mind works on Claude sessions only', 'warning');
44
49
  return;
45
50
  }
46
- // Rethink memory resets on each open (a fresh open is a fresh question).
47
- this._rmm = { sessionId, shown: null, rejected: [], busy: false };
51
+ // Rethink memory resets on each open (a fresh open is a fresh question),
52
+ // and the steer note resets with it.
53
+ this._rmm = { sessionId, suggestions: [], selected: 0, rejected: [], busy: false };
54
+ const steer = document.getElementById('readMyMindSteer');
55
+ if (steer) steer.value = '';
48
56
  document.getElementById('readMyMindModal')?.classList.add('active');
49
57
  this._readMyMindPredict();
50
58
  },
@@ -54,14 +62,20 @@ Object.assign(CodemanApp.prototype, {
54
62
  this._rmm = null;
55
63
  },
56
64
 
57
- /** Run (or re-run) the prediction and render the top suggestion. */
65
+ /** Run (or re-run) the prediction and render the suggestion set. */
58
66
  async _readMyMindPredict() {
59
67
  const state = this._rmm;
60
68
  if (!state || state.busy) return;
61
69
  state.busy = true;
62
70
  this._rmmSetPhase('loading');
63
71
 
64
- const body = state.rejected.length > 0 ? { rejected: state.rejected.slice(-10) } : {};
72
+ const body = {};
73
+ if (state.rejected.length > 0) body.rejected = state.rejected.slice(-10);
74
+ // The steer note rides every re-run while it stays in the field: what the
75
+ // user sees in the box is what the predictor gets. Empty on first open
76
+ // (openReadMyMind clears it), so a plain predict sends neither key.
77
+ const steer = document.getElementById('readMyMindSteer')?.value.trim() ?? '';
78
+ if (steer) body.steer = steer.slice(0, 2000);
65
79
  const data = await this._apiJson(`/api/sessions/${state.sessionId}/readmymind`, { method: 'POST', body });
66
80
 
67
81
  // The modal may have been dismissed (or reopened for another session) while
@@ -69,26 +83,83 @@ Object.assign(CodemanApp.prototype, {
69
83
  if (this._rmm !== state) return;
70
84
  state.busy = false;
71
85
 
72
- const suggestion = data && data.suggestions && data.suggestions[0];
73
- if (!suggestion) {
86
+ const suggestions = (data && Array.isArray(data.suggestions) ? data.suggestions : []).filter(
87
+ (s) => s && typeof s.prompt === 'string' && s.prompt.trim()
88
+ );
89
+ if (suggestions.length === 0) {
74
90
  this._rmmSetPhase('error');
75
91
  return;
76
92
  }
77
- state.shown = suggestion;
93
+ state.suggestions = suggestions.slice(0, 3);
94
+ state.selected = 0;
78
95
  this._rmmSetPhase('ready');
96
+ this._rmmRender();
97
+ this._rmmFocusPrompt();
98
+ },
99
+
100
+ /** Paint the selected suggestion into the editable field, the rest as alternates. */
101
+ _rmmRender() {
102
+ const state = this._rmm;
103
+ const current = state && state.suggestions[state.selected];
104
+ if (!current) return;
79
105
 
80
106
  const input = document.getElementById('readMyMindPrompt');
81
107
  const why = document.getElementById('readMyMindWhy');
82
108
  const kind = document.getElementById('readMyMindKind');
83
109
  // Predictor output is derived from observable (injectable) content:
84
110
  // value/textContent only, never innerHTML.
85
- if (input) input.value = suggestion.prompt;
86
- if (why) why.textContent = suggestion.why || '';
111
+ if (input) input.value = current.prompt;
112
+ if (why) why.textContent = current.why || '';
87
113
  if (kind) {
88
- kind.textContent = suggestion.kind || 'continue';
89
- kind.className = `readmymind-kind readmymind-kind-${suggestion.kind || 'continue'}`;
114
+ kind.textContent = current.kind || 'continue';
115
+ kind.className = `readmymind-kind readmymind-kind-${current.kind || 'continue'}`;
90
116
  }
91
- input?.focus();
117
+
118
+ const alternates = document.getElementById('readMyMindAlternates');
119
+ if (!alternates) return;
120
+ alternates.replaceChildren();
121
+ // The container is data-i18n-skip (suggestion text must never be mistaken
122
+ // for app copy), so the one piece of app copy inside it is pre-translated.
123
+ const translate = window.codemanT || ((s) => s);
124
+ state.suggestions.forEach((suggestion, index) => {
125
+ if (index === state.selected) return;
126
+ const row = document.createElement('button');
127
+ row.type = 'button';
128
+ row.className = 'readmymind-alt';
129
+ row.title = suggestion.why || '';
130
+ row.setAttribute('aria-label', translate('Use this suggestion instead'));
131
+ const badge = document.createElement('span');
132
+ badge.className = `readmymind-kind readmymind-kind-${suggestion.kind || 'continue'}`;
133
+ badge.textContent = suggestion.kind || 'continue';
134
+ const text = document.createElement('span');
135
+ text.className = 'readmymind-alt-text';
136
+ text.textContent = suggestion.prompt;
137
+ row.append(badge, text);
138
+ row.addEventListener('click', () => this._rmmSelect(index));
139
+ alternates.appendChild(row);
140
+ });
141
+ alternates.style.display = alternates.childElementCount > 0 ? '' : 'none';
142
+ },
143
+
144
+ /** Swap an alternate into the field, folding the current edit back first. */
145
+ _rmmSelect(index) {
146
+ const state = this._rmm;
147
+ if (!state || state.busy || !state.suggestions[index]) return;
148
+ const input = document.getElementById('readMyMindPrompt');
149
+ const current = state.suggestions[state.selected];
150
+ // Keep edits: fold the field text back into the suggestion it belongs to,
151
+ // so toggling between alternates never loses typing.
152
+ if (input && current) current.prompt = input.value;
153
+ state.selected = index;
154
+ this._rmmRender();
155
+ this._rmmFocusPrompt();
156
+ },
157
+
158
+ /** Focus the editable field on desktop. On touch devices leave it blurred so
159
+ * the OS keyboard doesn't pop over the alternates that just rendered. */
160
+ _rmmFocusPrompt() {
161
+ if (typeof MobileDetection !== 'undefined' && MobileDetection.isTouchDevice()) return;
162
+ document.getElementById('readMyMindPrompt')?.focus();
92
163
  },
93
164
 
94
165
  /**
@@ -114,11 +185,15 @@ Object.assign(CodemanApp.prototype, {
114
185
  this.showToast(withEnter ? 'Prompt sent' : 'Inserted, press Enter in the terminal to send', 'success');
115
186
  },
116
187
 
117
- /** Re-run with the shown suggestion recorded as a rejection. */
188
+ /** Re-run with the whole shown set (main + alternates) recorded as rejected:
189
+ * the user saw every row and asked for something else. The steer note (if
190
+ * any) is read from the field by _readMyMindPredict itself. */
118
191
  rethinkReadMyMind() {
119
192
  const state = this._rmm;
120
193
  if (!state || state.busy) return;
121
- if (state.shown && state.shown.prompt) state.rejected.push(state.shown.prompt);
194
+ for (const suggestion of state.suggestions) {
195
+ if (suggestion.prompt && suggestion.prompt.trim()) state.rejected.push(suggestion.prompt);
196
+ }
122
197
  this._readMyMindPredict();
123
198
  },
124
199
 
@@ -129,6 +204,11 @@ Object.assign(CodemanApp.prototype, {
129
204
  modal.querySelector('.readmymind-loading').style.display = phase === 'loading' ? '' : 'none';
130
205
  modal.querySelector('.readmymind-result').style.display = phase === 'ready' ? '' : 'none';
131
206
  modal.querySelector('.readmymind-error').style.display = phase === 'error' ? '' : 'none';
207
+ // The steer note belongs to Rethink, so it shows wherever Rethink is live:
208
+ // the ready phase AND the empty-result phase (typed text survives the
209
+ // loading round-trip, only the row's visibility toggles).
210
+ const steerRow = document.getElementById('readMyMindSteerRow');
211
+ if (steerRow) steerRow.style.display = phase === 'loading' ? 'none' : '';
132
212
  const rethinkBtn = document.getElementById('readMyMindRethink');
133
213
  if (rethinkBtn) rethinkBtn.disabled = phase === 'loading';
134
214
  },
Binary file
Binary file
@@ -10,10 +10,10 @@
10
10
  <span class="case-combobox-check">${l?"\u2713":""}</span>
11
11
  <span class="case-combobox-option-label">${escapeHtml(o.label)}</span>
12
12
  </button>
13
- `}).join(""),t.classList.remove("hidden"),e.setAttribute("aria-activedescendant",`quickStartCaseOption-${this._casePickerActiveIndex}`)},selectQuickStartCase(e,{save:t=!0}={}){const s=document.getElementById("quickStartCase");s&&(s.value=e||"testcase",this.updateCasePickerInput(s.value),this.closeCasePicker(),this.updateDirDisplayForCase(s.value),this.updateMobileCaseLabel(s.value),t&&this.saveLastUsedCase(s.value))},setupQuickStartCasePicker(){const e=document.getElementById("quickStartCase"),t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList"),a=document.getElementById("quickStartCasePicker");!e||!t||!s||!a||t.dataset.listenerAdded||(t.addEventListener("focus",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("click",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("input",()=>{this.openCasePicker(t.value)}),t.addEventListener("keydown",n=>{const i=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||t.value);if(n.key==="ArrowDown")n.preventDefault(),this._casePickerActiveIndex=Math.min((this._casePickerActiveIndex||0)+1,Math.max(0,i.length-1)),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(n.key==="ArrowUp")n.preventDefault(),this._casePickerActiveIndex=Math.max((this._casePickerActiveIndex||0)-1,0),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(n.key==="Enter"){const o=i[this._casePickerActiveIndex||0];o&&(n.preventDefault(),this.selectQuickStartCase(o.name),this.run?.())}else n.key==="Escape"?(n.preventDefault(),this.updateCasePickerInput(e.value),this.closeCasePicker()):n.key==="Tab"&&(this.updateCasePickerInput(e.value),this.closeCasePicker())}),s.addEventListener("mousedown",n=>n.preventDefault()),s.addEventListener("click",n=>{const i=n.target.closest?.(".case-combobox-option");i?.dataset?.case&&this.selectQuickStartCase(i.dataset.case)}),document.addEventListener&&!this._casePickerDocumentListenerAdded&&(document.addEventListener("pointerdown",n=>{a.contains(n.target)||(this.updateCasePickerInput(e.value),this.closeCasePicker())}),this._casePickerDocumentListenerAdded=!0),t.dataset.listenerAdded="true")},async loadQuickStartCases(e=null,t=null){try{let s=null;try{const r=t?await t:await fetch("/api/settings").then(c=>c.ok?c.json():null).then(c=>c?.data??null);r&&(s=r.lastUsedCase||null)}catch{}const n=(await(await fetch("/api/cases")).json()).data;this.cases=n,console.log("[loadQuickStartCases] Loaded cases:",n.map(r=>r.name),"lastUsedCase:",s);const i=document.getElementById("quickStartCase"),o=this.getCasePickerOptions();if(this.renderQuickStartCaseSelectOptions(i,o),console.log("[loadQuickStartCases] Set options:",i.innerHTML.substring(0,200)),e)i.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&n.some(r=>r.name===s))i.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(n.length>0){const r=n.find(c=>c.name==="testcase")||n[0];i.value=r.name,this.updateDirDisplayForCase(r.name),this.updateMobileCaseLabel(r.name)}else i.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");this.updateCasePickerInput(i.value),this.renderCasePickerList(),this.closeCasePicker(),i.dataset.listenerAdded||(i.addEventListener("change",()=>{this.updateDirDisplayForCase(i.value),this.saveLastUsedCase(i.value),this.updateMobileCaseLabel(i.value),this.updateCasePickerInput(i.value)}),i.dataset.listenerAdded="true"),this.setupQuickStartCasePicker(),this._refreshMobileOverviewIfVisible?.()}catch(s){console.error("Failed to load cases:",s)}},async updateDirDisplayForCase(e){try{const s=(await(await fetch(`/api/cases/${e}`)).json()).data;s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}},async saveLastUsedCase(e){try{await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({lastUsedCase:e})})}catch(t){console.error("Failed to save last used case:",t)}},async quickStart(){return this.run()},async _ensureCreatedSessionVisible(e,t){if(!e)return;let s=t;if(!s&&!this.sessions?.has(e)){const n=await(await fetch(`/api/sessions/${encodeURIComponent(e)}`)).json();if(!n.success)throw new Error(n.error||"Failed to load the new session");s=n.data?.session||n.data}s?.id&&this._onSessionCreated(s),this._renderSessionTabsImmediate?.()},async run(){if(this._runInFlight)return;const e=Date.now(),t=Number.isFinite(this._runMinLockMs)?this._runMinLockMs:500,s=document.getElementById("runBtn");this._runInFlight=!0,s&&(s.disabled=!0,s.setAttribute("aria-busy","true"));try{const a=this._runMode||"claude";return a==="opencode"?await this.runOpenCode():a==="codex"?await this.runCodex():a==="gemini"?await this.runGemini():a==="antigravity"?await this.runAntigravity():a==="shell"?await this.runShell():await this.runClaude()}finally{const a=t-(Date.now()-e);a>0&&await new Promise(n=>setTimeout(n,a)),this._runInFlight=!1,s&&(s.disabled=!1,s.removeAttribute("aria-busy"))}},setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),this._apiPut("/api/settings",{runMode:e}).catch(()=>{}),document.getElementById("runModeMenu")?.classList.remove("active")},toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){this._loadRunModeHistory(),this._refreshRunModeAvailability(t);const s=a=>{t.contains(a.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},_refreshRunModeAvailability(e){for(const t of["claude","opencode","codex","gemini","antigravity"]){const s=e.querySelector(`.run-mode-option[data-mode="${t}"]`);s&&(s.style.display=this.isCliAvailable(t)?"flex":"none")}},async _loadRunModeHistory(){const e=document.getElementById("runModeHistory");if(e){e.innerHTML='<div class="run-mode-hist-empty">Loading...</div>';try{const t=await this._fetchHistorySessions(10);if(t.length===0){e.innerHTML='<div class="run-mode-hist-empty">No history</div>';return}e.replaceChildren();for(const s of t){const a=new Date(s.lastModified),n=a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),i=s.workingDir.replace(/^\/home\/[^/]+\//,"~/"),o=document.createElement("button");o.className="run-mode-option",o.title=s.workingDir,o.dataset.sessionId=s.sessionId,o.dataset.workingDir=s.workingDir;const r=document.createElement("span");r.className="hist-dir",r.textContent=i;const c=document.createElement("span");c.className="hist-meta",c.textContent=n,o.append(r,c),o.addEventListener("click",l=>{l.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir,s.name)}),e.appendChild(o)}}catch{e.innerHTML='<div class="run-mode-hist-empty">Failed to load</div>'}}},_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,a=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),a&&(a.textContent=e==="opencode"?"Run OC":e==="codex"?"Run CX":e==="gemini"?"Run GM":e==="antigravity"?"Run AG":e==="shell"?"Run SH":"Run")},sendEnterKey(){if(!this.activeSessionId)return;const e=this.terminal?._core?.coreService;if(e&&typeof e.triggerDataEvent=="function"){e.triggerDataEvent("\r",!0);return}this.sendInput("\r")},_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()},incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},_nextCaseSessionStartNumber(e,t="w"){const s=new RegExp(`^${t}(\\d+)-([a-zA-Z0-9_-]+)`);let a=1;for(const[,n]of this.sessions||[]){const i=n.name&&n.name.match(s);if(i&&i[2]===e){const o=parseInt(i[1]);o>=a&&(a=o+1)}}return a},_beginSessionLaunchStatus(e,t="1;32"){const s=!this.activeSessionId;return s?(this.terminal.clear(),this.terminal.writeln(`\x1B[${t}m ${e}\x1B[0m`),this.terminal.writeln("")):this.showToast?.(e,"info"),s},_appendSessionLaunchStatus(e,t,s="90"){!e||this.activeSessionId||this.terminal.writeln(`\x1B[${s}m ${t}\x1B[0m`)},_reportSessionLaunchError(e,t){e&&!this.activeSessionId?this.terminal.writeln(`\x1B[1;31m Error: ${t}\x1B[0m`):this.showToast?.(t,"error")},async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1)),s=this._beginSessionLaunchStatus(`Starting ${t} Claude session(s) in ${e}...`);this.terminal.focus();try{let n=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!n.path){const C=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!C.success)throw new Error(C.error||"Failed to create case");n=C.data.case}const i=n.path;if(!i)throw new Error("Case path not found");if(n.location==="remote"||n.location==="docker"){const f=this._nextCaseSessionStartNumber(e);let C;if(n.location==="docker"){const v=this.loadAppSettingsFromStorage(),k=this.getCaseSettings(e).opusContext1m||v.opusContext1mEnabled;C=v.claudeModel||(k?"opus[1m]":"")}const E=[];let T=!1;for(let v=0;v<t;v++){const B=JSON.stringify({caseName:e,mode:"claude",sessionName:`w${f+v}-${e}`,...C!==void 0?{modelOverride:C}:{}}),k=async()=>(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:B})).json();let S=await k();if(!S.success&&S.errorCode==="CONFLICT"&&n.location==="docker"&&!T&&(T=!0,confirm(`Container config for "${e}" changed since its container was created.
13
+ `}).join(""),t.classList.remove("hidden"),e.setAttribute("aria-activedescendant",`quickStartCaseOption-${this._casePickerActiveIndex}`)},selectQuickStartCase(e,{save:t=!0}={}){const s=document.getElementById("quickStartCase");s&&(s.value=e||"testcase",this.updateCasePickerInput(s.value),this.closeCasePicker(),this.updateDirDisplayForCase(s.value),this.updateMobileCaseLabel(s.value),t&&this.saveLastUsedCase(s.value))},setupQuickStartCasePicker(){const e=document.getElementById("quickStartCase"),t=document.getElementById("quickStartCaseSearch"),s=document.getElementById("quickStartCaseList"),a=document.getElementById("quickStartCasePicker");!e||!t||!s||!a||t.dataset.listenerAdded||(t.addEventListener("focus",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("click",()=>{t.select?.(),this.openCasePicker("")}),t.addEventListener("input",()=>{this.openCasePicker(t.value)}),t.addEventListener("keydown",n=>{const i=this.filterCasePickerOptions(this.getCasePickerOptions(),this._casePickerFilter||t.value);if(n.key==="ArrowDown")n.preventDefault(),this._casePickerActiveIndex=Math.min((this._casePickerActiveIndex||0)+1,Math.max(0,i.length-1)),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(n.key==="ArrowUp")n.preventDefault(),this._casePickerActiveIndex=Math.max((this._casePickerActiveIndex||0)-1,0),this._casePickerOpen?this.renderCasePickerList():this.openCasePicker(t.value);else if(n.key==="Enter"){const o=i[this._casePickerActiveIndex||0];o&&(n.preventDefault(),this.selectQuickStartCase(o.name),this.run?.())}else n.key==="Escape"?(n.preventDefault(),this.updateCasePickerInput(e.value),this.closeCasePicker()):n.key==="Tab"&&(this.updateCasePickerInput(e.value),this.closeCasePicker())}),s.addEventListener("mousedown",n=>n.preventDefault()),s.addEventListener("click",n=>{const i=n.target.closest?.(".case-combobox-option");i?.dataset?.case&&this.selectQuickStartCase(i.dataset.case)}),document.addEventListener&&!this._casePickerDocumentListenerAdded&&(document.addEventListener("pointerdown",n=>{a.contains(n.target)||(this.updateCasePickerInput(e.value),this.closeCasePicker())}),this._casePickerDocumentListenerAdded=!0),t.dataset.listenerAdded="true")},async loadQuickStartCases(e=null,t=null){try{let s=null;try{const r=t?await t:await fetch("/api/settings").then(c=>c.ok?c.json():null).then(c=>c?.data??null);r&&(s=r.lastUsedCase||null)}catch{}const n=(await(await fetch("/api/cases")).json()).data;this.cases=n,console.log("[loadQuickStartCases] Loaded cases:",n.map(r=>r.name),"lastUsedCase:",s);const i=document.getElementById("quickStartCase"),o=this.getCasePickerOptions();if(this.renderQuickStartCaseSelectOptions(i,o),console.log("[loadQuickStartCases] Set options:",i.innerHTML.substring(0,200)),e)i.value=e,this.updateDirDisplayForCase(e),this.updateMobileCaseLabel(e);else if(s&&n.some(r=>r.name===s))i.value=s,this.updateDirDisplayForCase(s),this.updateMobileCaseLabel(s);else if(n.length>0){const r=n.find(c=>c.name==="testcase")||n[0];i.value=r.name,this.updateDirDisplayForCase(r.name),this.updateMobileCaseLabel(r.name)}else i.value="testcase",document.getElementById("dirDisplay").textContent="~/codeman-cases/testcase",this.updateMobileCaseLabel("testcase");this.updateCasePickerInput(i.value),this.renderCasePickerList(),this.closeCasePicker(),i.dataset.listenerAdded||(i.addEventListener("change",()=>{this.updateDirDisplayForCase(i.value),this.saveLastUsedCase(i.value),this.updateMobileCaseLabel(i.value),this.updateCasePickerInput(i.value)}),i.dataset.listenerAdded="true"),this.setupQuickStartCasePicker(),this._refreshMobileOverviewIfVisible?.()}catch(s){console.error("Failed to load cases:",s)}},async updateDirDisplayForCase(e){try{const s=(await(await fetch(`/api/cases/${e}`)).json()).data;s.path&&(document.getElementById("dirDisplay").textContent=s.path,document.getElementById("dirInput").value=s.path)}catch{document.getElementById("dirDisplay").textContent=e}},async saveLastUsedCase(e){try{await fetch("/api/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({lastUsedCase:e})})}catch(t){console.error("Failed to save last used case:",t)}},async quickStart(){return this.run()},async _ensureCreatedSessionVisible(e,t){if(!e)return;let s=t;if(!s&&!this.sessions?.has(e)){const n=await(await fetch(`/api/sessions/${encodeURIComponent(e)}`)).json();if(!n.success)throw new Error(n.error||"Failed to load the new session");s=n.data?.session||n.data}s?.id&&this._onSessionCreated(s),this._renderSessionTabsImmediate?.()},async run(){if(this._runInFlight)return;const e=Date.now(),t=Number.isFinite(this._runMinLockMs)?this._runMinLockMs:500,s=document.getElementById("runBtn");this._runInFlight=!0,s&&(s.disabled=!0,s.setAttribute("aria-busy","true"));try{const a=this._runMode||"claude";return a==="opencode"?await this.runOpenCode():a==="codex"?await this.runCodex():a==="gemini"?await this.runGemini():a==="antigravity"?await this.runAntigravity():a==="shell"?await this.runShell():await this.runClaude()}finally{const a=t-(Date.now()-e);a>0&&await new Promise(n=>setTimeout(n,a)),this._runInFlight=!1,s&&(s.disabled=!1,s.removeAttribute("aria-busy"))}},setRunMode(e){this._runMode=e;try{localStorage.setItem("codeman_runMode",e)}catch{}this._applyRunMode(),this._apiPut("/api/settings",{runMode:e}).catch(()=>{}),document.getElementById("runModeMenu")?.classList.remove("active")},toggleRunModeMenu(e){e?.stopPropagation();const t=document.getElementById("runModeMenu");if(t&&(t.classList.toggle("active"),t.querySelectorAll(".run-mode-option").forEach(s=>{s.classList.toggle("selected",s.dataset.mode===this.runMode)}),t.classList.contains("active"))){this._loadRunModeHistory(),this._refreshRunModeAvailability(t);const s=a=>{t.contains(a.target)||(t.classList.remove("active"),document.removeEventListener("click",s))};setTimeout(()=>document.addEventListener("click",s),0)}},_refreshRunModeAvailability(e){for(const t of["claude","opencode","codex","gemini","antigravity"]){const s=e.querySelector(`.run-mode-option[data-mode="${t}"]`);s&&(s.style.display=this.isCliAvailable(t)?"flex":"none")}},async _loadRunModeHistory(){const e=document.getElementById("runModeHistory");if(e){e.innerHTML='<div class="run-mode-hist-empty">Loading...</div>';try{const t=await this._fetchHistorySessions(10);if(t.length===0){e.innerHTML='<div class="run-mode-hist-empty">No history</div>';return}e.replaceChildren();for(const s of t){const a=new Date(s.lastModified),n=a.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+a.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1}),i=this._shortenHomePath(s.workingDir),o=i.lastIndexOf("/"),r=o===-1?i:i.slice(o+1),c=(o===-1?"":i.slice(0,o)).replace(/\/\.claude\/worktrees$/,""),l=document.createElement("button");l.className="run-mode-option run-mode-hist-row",l.title=s.workingDir,l.dataset.sessionId=s.sessionId,l.dataset.workingDir=s.workingDir;const m=document.createElement("span");m.className="hist-name",m.textContent=r;const h=[m],u=this._worktreeLabel?this._worktreeLabel(s):"";if(u){const d=document.createElement("span");d.className="hist-wt",d.textContent=u,h.push(d)}if(c){const d=document.createElement("span");d.className="hist-dir",d.textContent=c,h.push(d)}const f=document.createElement("span");f.className="hist-meta",f.textContent=n,h.push(f),l.append(...h),l.addEventListener("click",d=>{d.stopPropagation(),this.resumeHistorySession(s.sessionId,s.workingDir,s.name)}),e.appendChild(l)}}catch{e.innerHTML='<div class="run-mode-hist-empty">Failed to load</div>'}}},_applyRunMode(){const e=this.runMode,t=document.getElementById("runBtn"),s=t?.nextElementSibling,a=document.getElementById("runBtnLabel");t&&(t.className=`btn-toolbar btn-run mode-${e}`),s&&(s.className=`btn-toolbar btn-run-gear mode-${e}`),a&&(a.textContent=e==="opencode"?"Run OC":e==="codex"?"Run CX":e==="gemini"?"Run GM":e==="antigravity"?"Run AG":e==="shell"?"Run SH":"Run")},sendEnterKey(){if(!this.activeSessionId)return;const e=this.terminal?._core?.coreService;if(e&&typeof e.triggerDataEvent=="function"){e.triggerDataEvent("\r",!0);return}this.sendInput("\r")},_initRunMode(){try{this._runMode=localStorage.getItem("codeman_runMode")||"claude"}catch{this._runMode="claude"}this._applyRunMode()},incrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementTabCount(){const e=document.getElementById("tabCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},incrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.min(20,t+1)},decrementShellCount(){const e=document.getElementById("shellCount"),t=parseInt(e.value)||1;e.value=Math.max(1,t-1)},_nextCaseSessionStartNumber(e,t="w"){const s=new RegExp(`^${t}(\\d+)-([a-zA-Z0-9_-]+)`);let a=1;for(const[,n]of this.sessions||[]){const i=n.name&&n.name.match(s);if(i&&i[2]===e){const o=parseInt(i[1]);o>=a&&(a=o+1)}}return a},_beginSessionLaunchStatus(e,t="1;32"){const s=!this.activeSessionId;return s?(this.terminal.clear(),this.terminal.writeln(`\x1B[${t}m ${e}\x1B[0m`),this.terminal.writeln("")):this.showToast?.(e,"info"),s},_appendSessionLaunchStatus(e,t,s="90"){!e||this.activeSessionId||this.terminal.writeln(`\x1B[${s}m ${t}\x1B[0m`)},_reportSessionLaunchError(e,t){e&&!this.activeSessionId?this.terminal.writeln(`\x1B[1;31m Error: ${t}\x1B[0m`):this.showToast?.(t,"error")},async runClaude(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("tabCount").value)||1)),s=this._beginSessionLaunchStatus(`Starting ${t} Claude session(s) in ${e}...`);this.terminal.focus();try{let n=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!n.path){const C=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!C.success)throw new Error(C.error||"Failed to create case");n=C.data.case}const i=n.path;if(!i)throw new Error("Case path not found");if(n.location==="remote"||n.location==="docker"){const y=this._nextCaseSessionStartNumber(e);let C;if(n.location==="docker"){const v=this.loadAppSettingsFromStorage(),b=this.getCaseSettings(e).opusContext1m||v.opusContext1mEnabled;C=v.claudeModel||(b?"opus[1m]":"")}const E=[];let T=!1;for(let v=0;v<t;v++){const B=JSON.stringify({caseName:e,mode:"claude",sessionName:`w${y+v}-${e}`,...C!==void 0?{modelOverride:C}:{}}),b=async()=>(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:B})).json();let S=await b();if(!S.success&&S.errorCode==="CONFLICT"&&n.location==="docker"&&!T&&(T=!0,confirm(`Container config for "${e}" changed since its container was created.
14
14
 
15
- Recreate the container to apply the new config? Workspace files and the conversation survive (the conversation resumes on launch).`))){const x=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/recreate`,{method:"POST"})).json();if(!x.success)throw new Error(x.error||"Failed to recreate container");S=await k()}if(!S.success)throw new Error(S.error||"Failed to start remote Claude session");await this._ensureCreatedSessionVisible(S.data.sessionId,S.data.session),E.push(S.data.sessionId)}this._appendSessionLaunchStatus(s,`All ${t} remote session(s) ready`),E[0]&&(await this.selectSession(E[0]),this.loadQuickStartCases()),this.terminal.focus();return}let o=null;const r=this._nextCaseSessionStartNumber(e),c=this.isRalphTrackerEnabledByDefault(),l=[];for(let f=0;f<t;f++)l.push(`w${r+f}-${e}`);const d=this.getCaseSettings(e),p=this.loadAppSettingsFromStorage(),u=this.buildEnvOverrides(d,p),y=Object.keys(u).length>0,m=this.getEffortSetting(p),g=d.opusContext1m||p.opusContext1mEnabled,h=p.claudeModel||(g?"opus[1m]":"");this._appendSessionLaunchStatus(s,`Creating ${t} session(s)...`);const I=l.map(f=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:f,...y?{envOverrides:u}:{},...m?{effort:m}:{},...h!==void 0?{modelOverride:h}:{},statusLineTelemetry:this.planUsageChipEnabled(p)})}).then(C=>C.json())),w=await Promise.all(I),b=[];for(const f of w){if(!f.success)throw new Error(f.error);await this._ensureCreatedSessionVisible(f.data.session.id,f.data.session),b.push(f.data.session.id)}o=b[0],await Promise.all(b.map(f=>fetch(`/api/sessions/${f}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:c,disableAutoEnable:!c})}))),this._appendSessionLaunchStatus(s,`Starting ${t} session(s) in parallel...`),await Promise.all(b.map(f=>fetch(`/api/sessions/${f}/interactive`,{method:"POST"}))),this._appendSessionLaunchStatus(s,`All ${t} sessions ready`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(a){this._reportSessionLaunchError(s,a.message)}},stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))},async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1)),s=this._beginSessionLaunchStatus(`Starting ${t} Shell session(s) in ${e}...`,"1;33");try{let n=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!n.path){const g=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!g.success)throw new Error(g.error||"Failed to create case");n=g.data.case}const i=(this.cases||[]).find(m=>m.name===e),o=n.location==="remote"||n.location==="docker"||i?.location==="remote"||i?.location==="docker",r=n.path;if(!r)throw new Error("Case path not found");if(n.location==="remote"||n.location==="docker"){const m=this._nextCaseSessionStartNumber(e,"s"),g=[];for(let h=0;h<t;h++){const w=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"shell",sessionName:`s${m+h}-${e}`})})).json();if(!w.success)throw new Error(w.error||"Failed to start remote shell session");await this._ensureCreatedSessionVisible(w.data.sessionId,w.data.session),g.push(w.data.sessionId)}g[0]&&await this.selectSession(g[0]),this.terminal.focus();return}const c=this._nextCaseSessionStartNumber(e,"s"),l=[];for(let m=0;m<t;m++)l.push(`s${c+m}-${e}`);const d=l.map(m=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o?{caseName:e}:{workingDir:r},mode:"shell",name:m})}).then(g=>g.json())),p=await Promise.all(d),u=[];for(const m of p){if(!m.success)throw new Error(m.error);await this._ensureCreatedSessionVisible(m.data.session.id,m.data.session),u.push(m.data.session.id)}await Promise.all(u.map(m=>fetch(`/api/sessions/${m}/shell`,{method:"POST"})));const y=this.getTerminalDimensions();y&&await Promise.all(u.map(m=>fetch(`/api/sessions/${m}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}))),u.length>0&&await this.selectSession(u[0]),this.terminal.focus()}catch(a){this._reportSessionLaunchError(s,a.message)}},async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting OpenCode session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/opencode/status")).json()).data.available){this._reportSessionLaunchError(a,"OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash");return}const n=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{openCodeConfig:{autoAllowTools:!0},...Object.keys(n).length>0?{envOverrides:n}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start OpenCode");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},async runCodex(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting Codex session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/codex/status")).json()).data.available){this._reportSessionLaunchError(a,"Codex CLI not found. Install with: npm install -g @openai/codex");return}const n=this.loadAppSettingsFromStorage(),i=this.buildEnvOverrides(this.getCaseSettings(e),n),r=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"codex",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{codexConfig:{dangerouslyBypassApprovals:n.codexDangerouslyBypassApprovals??!1,animations:n.codexAnimationsEnabled??!1,renderMode:"hybrid"},...Object.keys(i).length>0?{envOverrides:i}:{}}})})).json();if(!r.success)throw new Error(r.error||"Failed to start Codex");await this._ensureCreatedSessionVisible(r.data.sessionId,r.data.session),r.data.sessionId&&await this.selectSession(r.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},async runGemini(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting Gemini session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/gemini/status")).json()).data.available){this._reportSessionLaunchError(a,"Gemini CLI not found. Install with: npm install -g @google/gemini-cli");return}const n=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"gemini",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{geminiConfig:{approvalMode:"yolo"},...Object.keys(n).length>0?{envOverrides:n}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Gemini");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},async runAntigravity(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting Antigravity session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/antigravity/status")).json()).data.available){this._reportSessionLaunchError(a,"Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash");return}const n=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"antigravity",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{antigravityConfig:{dangerouslySkipPermissions:!0},...Object.keys(n).length>0?{envOverrides:n}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Antigravity");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e;const s=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini"||t.mode==="antigravity";this.switchOptionsTab(s?"summary":"respawn");const a=document.getElementById("sessionRespawnStatus"),n=document.getElementById("modalEnableRespawnBtn"),i=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(a.classList.add("active"),a.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",n.style.display="none",i.style.display=""):(a.classList.remove("active"),a.querySelector(".respawn-status-text").textContent="Not active",n.style.display="",i.style.display="none");const o=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?o.style.display="":o.style.display="none";const r=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini"||t.mode==="antigravity";document.querySelectorAll("[data-claude-only]").forEach(h=>{h.style.display=r?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalAutoResumeEnabled").checked=t.autoResumeEnabled??!1,this.updateAutoResumeStatus(e),document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1;const l=parseSessionPrefix(t.name),d=document.getElementById("modalSessionPrefix");l?(d.textContent=l.prefix+": ",d.style.display="",document.getElementById("modalSessionName").value=l.suffix,document.getElementById("modalSessionName").placeholder="Add description..."):(d.style.display="none",d.textContent="",document.getElementById("modalSessionName").value=t.name||"",document.getElementById("modalSessionName").placeholder="Auto (directory name)");const p=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(h=>{h.classList.toggle("selected",h.dataset.color===p)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const y=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="ralph"]'),m=document.querySelector('#sessionOptionsModal .modal-tab-btn[data-tab="respawn"]');if(r?(y&&(y.style.display="none"),m&&(m.style.display="none"),this.switchOptionsTab("context")):(y&&(y.style.display=""),m&&(m.style.display="")),!r){const h=this.ralphStates.get(e);this.populateRalphForm({enabled:h?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:h?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:h?.loop?.maxIterations||t.ralphLoop?.maxIterations||0,maxTodos:h?.loop?.maxTodos||t.ralphLoop?.maxTodos,todoExpirationMinutes:h?.loop?.todoExpirationMinutes||t.ralphLoop?.todoExpirationMinutes})}const g=document.getElementById("sessionOptionsModal");g.classList.add("active"),this.activeFocusTrap=new FocusTrap(g),this.activeFocusTrap.activate()},async saveSessionName(){if(!this.editingSessionId)return;const e=this.sessions.get(this.editingSessionId),t=e?parseSessionPrefix(e.name):null,s=document.getElementById("modalSessionName").value.trim();let a;t?a=t.prefix+(s?": "+s:""):a=s;try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:a})}catch(n){this.showToast("Failed to save session name: "+n.message,"error")}},async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}},async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}},async autoSaveAutoResume(){if(!this.editingSessionId)return;const e=document.getElementById("modalAutoResumeEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.autoResumeEnabled=e,e||(t.autoResumeAt=void 0)),this.updateAutoResumeStatus(this.editingSessionId),this.showToast(`Auto-resume on usage limit ${e?"enabled":"disabled"}`,"success")}catch(t){this.showToast("Failed to toggle auto-resume: "+t.message,"error")}},updateAutoResumeStatus(e){const t=document.getElementById("autoResumeStatus");if(!t||this.editingSessionId!==e)return;const s=this.sessions.get(e);if(s?.autoResumeAt&&s.autoResumeAt>Date.now()){const a=new Date(s.autoResumeAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});t.textContent=`Usage limit pause active \u2014 resumes at ${a}`,t.classList.add("active")}else t.textContent="",t.classList.remove("active")},async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}},async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}},async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}},async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.data&&s.data.config){const a=s.data.config;document.getElementById("modalRespawnPrompt").value=a.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=a.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=a.sendInit??!0,document.getElementById("modalRespawnKickstart").value=a.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=a.autoAcceptPrompts??!0,a.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${a.durationMinutes}"]`)?this.selectDurationPreset(String(a.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=a.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(n=>n.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),a=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),a.focus()):(s.classList.remove("visible"),a.value="")},getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const a=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return a?parseInt(a):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .modal-tab-btn").forEach(t=>{t.classList.toggle("active",t.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary"),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)},getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}},populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60},async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}},startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;this._inlineRenameActive=!0;const a=this.getSessionName(t),n=parseSessionPrefix(t.name),i=s.textContent;for(s.textContent="";s.firstChild;)s.removeChild(s.firstChild);if(n){const c=document.createElement("span");c.textContent=n.prefix+": ",c.style.cssText="color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;",s.appendChild(c)}const o=document.createElement("input");o.type="text",o.value=n?n.suffix:t.name||"",o.placeholder=n?"Add description...":a,o.className="tab-rename-input",o.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;",s.appendChild(o),o.focus(),o.select();const r=async({commit:c})=>{if(!this._inlineRenameActive)return;if(this._inlineRenameActive=!1,this._activeRename=null,!c){this.renderSessionTabs();return}const l=o.value.trim(),d=n?n.prefix+(l?": "+l:""):l;if(s.textContent=d||i,this.sessions.has(e)&&d!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:d})})}catch{s.textContent=i,this.showToast("Failed to rename","error")}this.renderSessionTabs()};this._activeRename={sessionId:e,cancel:()=>r({commit:!1})},o.addEventListener("blur",()=>r({commit:!0})),o.addEventListener("keydown",c=>{c.isComposing||c.keyCode===229||(c.key==="Enter"?(c.preventDefault(),o.blur()):c.key==="Escape"&&(o.value="",o.blur()))})},toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,document.getElementById("caseOpusContext1m").checked=s.opusContext1m,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1,opusContext1m:!0}},saveCaseSettings(e,t){localStorage.setItem("caseSettings_"+e,JSON.stringify(t))},onCaseSettingChanged(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeams").checked,t.opusContext1m=document.getElementById("caseOpusContext1m").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1mMobile");a&&(a.checked=t.opusContext1m)},toggleCaseSettingsMobile(){const e=document.getElementById("caseSettingsPopoverMobile");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeamsMobile").checked=s.agentTeams,document.getElementById("caseOpusContext1mMobile").checked=s.opusContext1m,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,t.opusContext1m=document.getElementById("caseOpusContext1mMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1m");a&&(a.checked=t.opusContext1m)},showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",["remoteCaseName","remoteCasePath","remoteHostId","remoteHostAddress","remoteHostUsername","remoteHostPort","remoteHostCodexCommand","remoteHostIdentityFile","remoteHostSocksProxy","remoteHostJumpHost","remoteHostExtraSshOptions"].forEach(a=>{const n=document.getElementById(a);n&&(n.value="")}),this._resetCloneForm();const t=document.getElementById("caseCloneTabBtn");t&&(t.style.display=this.isCliAvailable("git")?"":"none"),this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const s=document.getElementById("createCaseModal");s.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(a=>{a.onclick=()=>this.switchCaseModalTab(a.dataset.tab)}),s.querySelectorAll('input[type="text"]').forEach(a=>{a._mobileScrollWired||(a._mobileScrollWired=!0,a.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>a.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),s.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".modal-tabs .modal-tab-btn").forEach(a=>{a.classList.toggle("active",a.dataset.tab===e)}),t.querySelectorAll(".modal-tab-content").forEach(a=>{a.classList.toggle("hidden",a.id!==e)});const s=document.getElementById("caseModalSubmit");e==="case-manage"?(s.style.display="none",this.renderCaseManageList(),this.refreshDockerExports()):(s.style.display="",s.textContent=e==="case-create"?"Create":e==="case-clone"?"Clone":e==="case-remote"?"Link Remote":e==="case-docker"?"Link Docker":"Link"),e==="case-create"?document.getElementById("newCaseName").focus():e==="case-clone"?document.getElementById("cloneRepoUrl").focus():e==="case-link"?document.getElementById("linkCaseName").focus():e==="case-remote"?document.getElementById("remoteCaseName").focus():e==="case-docker"&&document.getElementById("dockerCaseName").focus()},closeCreateCaseModal(){document.getElementById("createCaseModal").classList.remove("active")},async submitCaseModal(){const e=document.getElementById("caseModalSubmit"),t=e.textContent;e.classList.add("loading"),e.textContent=this.caseModalTab==="case-create"?"Creating...":this.caseModalTab==="case-clone"?"Cloning...":"Linking...",e.disabled=!0;try{this.caseModalTab==="case-create"?await this.createCase():this.caseModalTab==="case-clone"?await this.cloneCase():this.caseModalTab==="case-remote"?await this.linkRemoteCase():this.caseModalTab==="case-docker"?await this.linkDockerCase():await this.linkCase()}finally{e.classList.remove("loading"),e.disabled=!1,e.textContent=t}},async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}const s=document.getElementById("newCaseDocker")?.checked,a=s?"/api/cases/docker-quickcreate":"/api/cases",n=s?{name:e,description:t,...this._collectDockerQuickSettings()}:{name:e,description:t};try{const o=await(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(o.success)if(this.closeCreateCaseModal(),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e),s){const r=o.data?.capsEnforced===!1?" (resource caps advisory on this engine)":"";this.showToast(`Docker case "${e}" created${r} \u2014 starting session\u2026`,"success"),await this.runClaude()}else this.showToast(`Case "${e}" created`,"success");else this.showToast(o.error||"Failed to create case","error")}catch(i){console.error("Failed to create case:",i),this.showToast("Failed to create case: "+i.message,"error")}},applyDockerTemplate(){const e=document.getElementById("quickDockerTemplate")?.value,s={small:{m:"2g",c:"1",g:""},medium:{m:"",c:"",g:""},large:{m:"8g",c:"4",g:""},gpu:{m:"8g",c:"4",g:"all"}}[e];if(!s)return;const a=(n,i)=>{const o=document.getElementById(n);o&&(o.value=i)};a("quickDockerMemory",s.m),a("quickDockerCpus",s.c),a("quickDockerGpus",s.g)},_collectDockerQuickSettings(){const e=c=>(document.getElementById(c)?.value||"").trim(),t={},s=e("quickDockerMemory");s&&(t.memory=s);const a=e("quickDockerCpus");a&&(t.cpus=a);const n=e("quickDockerGpus");n&&n.toLowerCase()!=="none"&&(t.gpus=n);const i=document.getElementById("quickDockerNetwork")?.value;i&&i!=="bridge"&&(t.network=i);const o=e("quickDockerImage");o&&(t.image=o);const r=document.getElementById("quickDockerMountCreds");return r&&!r.checked&&(t.mountCredentials=!1),t},async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const a=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},_resetCloneForm(){const e=(o,r)=>{const c=document.getElementById(o);c&&(c.value=r)};e("cloneRepoUrl",""),e("cloneCaseName",""),e("cloneRepoRef","");const t=document.getElementById("cloneShallow");t&&(t.checked=!1);const s=document.getElementById("cloneStartSession");s&&(s.checked=!1);const a=document.getElementById("cloneRepoRefOptions");a&&a.replaceChildren();const n=document.getElementById("cloneRefHint");n&&(n.textContent="Leave blank for the repository's default branch."),this._cloneNameEdited=!1,this._clonePreflight=null,clearTimeout(this._clonePreflightTimer),this._clonePreflightAbort?.abort(),this._clonePreflightAbort=null,this._setCloneStatus("Public repositories only: Codeman clones with no credentials.","");const i=document.getElementById("cloneCaseBrain");if(i){for(const r of i.options){const c=r.dataset.cli;r.hidden=!!c&&!this.isCliAvailable(c)}const o=this.runMode||"claude";i.value=[...i.options].some(r=>r.value===o&&!r.hidden)?o:""}},_setCloneStatus(e,t){const s=document.getElementById("cloneRepoStatus");s&&(s.textContent=e,s.className=`form-hint clone-status${t?" clone-status-"+t:""}`)},_repoNameFromUrl(e){const t=(e||"").trim().replace(/\/+$/,"");return t?(t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,"").replace(/^[^@/]*@/,"").split(/[/:]/).filter(Boolean).pop()||"").replace(/\.git$/i,"").replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,64):""},onCloneNameEdited(){this._cloneNameEdited=!!document.getElementById("cloneCaseName")?.value.trim()},onCloneUrlInput(){const e=document.getElementById("cloneRepoUrl")?.value.trim()||"",t=document.getElementById("cloneCaseName");if(t&&!this._cloneNameEdited&&(t.value=this._repoNameFromUrl(e)),clearTimeout(this._clonePreflightTimer),this._clonePreflightAbort?.abort(),this._clonePreflightAbort=null,!e){this._setCloneStatus("Public repositories only: Codeman clones with no credentials.","");return}if(this.isCliAvailable("git")===!1){this._setCloneStatus("git is not installed on the Codeman host, so cloning is unavailable.","err");return}this._setCloneStatus("Checking the repository\u2026",""),this._clonePreflightTimer=setTimeout(()=>this._runClonePreflight(e),450)},async _runClonePreflight(e){const t=new AbortController;this._clonePreflightAbort=t;try{const a=await(await fetch("/api/cases/clone-preflight",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repository:e}),signal:t.signal})).json();if(document.getElementById("cloneRepoUrl")?.value.trim()!==e)return;if(!a.success){this._setCloneStatus(a.error||"Could not check that URL.","err");return}this._applyClonePreflight(a.data,e)}catch(s){if(s.name==="AbortError")return;this._setCloneStatus("Could not reach Codeman to check that URL.","err")}},_applyClonePreflight(e,t){this._clonePreflight=e;const s=e?.parse;if(!s?.cloneable){this._setCloneStatus(s?.message||"That URL cannot be cloned.","err");return}const a=document.getElementById("cloneCaseName");a&&!this._cloneNameEdited&&s.suggestedName&&(a.value=s.suggestedName);const n=s.owner?`${s.provider} ${s.owner}/${s.repo}`:`${s.provider} ${s.repo}`;if(e.gitAvailable===!1){this._setCloneStatus(`${n}: git is not installed on the Codeman host.`,"err");return}const i=e.remote;if(i&&!i.reachable){this._setCloneStatus(`${n}: ${i.failure?.message||"the remote could not be read."}`,"err");return}const o=document.getElementById("cloneRefHint"),r=document.getElementById("cloneRepoRefOptions");if(i&&r){r.replaceChildren();for(const l of[...i.branches||[],...i.tags||[]]){const d=document.createElement("option");d.value=l,r.appendChild(d)}if(o){const l=`${i.branches?.length||0} branches, ${i.tags?.length||0} tags`;o.textContent=i.defaultBranch?`Blank clones the default branch (${i.defaultBranch}). ${l} available.`:`Blank clones the default branch. ${l} available.`}}const c=s.warnings?.[0];this._setCloneStatus(c?`${n}: ${c}`:`${n}: ready to clone.`,c?"warn":"ok")},async cloneCase(){const e=document.getElementById("cloneRepoUrl").value.trim(),t=document.getElementById("cloneCaseName").value.trim(),s=document.getElementById("cloneRepoRef").value.trim(),a=!!document.getElementById("cloneShallow")?.checked,n=document.getElementById("cloneCaseBrain")?.value||"",i=!!document.getElementById("cloneStartSession")?.checked;if(!e){this.showToast("Please enter a repository URL","error");return}if(!t){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}this._setCloneStatus(`Cloning ${e}\u2026 this can take a while for a large repository.`,"");try{const r=await(await fetch("/api/cases/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,repository:e,...s?{ref:s}:{},...a?{shallow:!0}:{}})})).json();if(!r.success){this._setCloneStatus(r.error||"Clone failed.","err"),this.showToast(r.error||"Failed to clone repository","error");return}n&&this.setRunMode(n),this.closeCreateCaseModal(),await this.loadQuickStartCases(t),await this.saveLastUsedCase(t),this.showToast(`Cloned into case "${t}"`,"success");for(const c of r.data?.warnings||[])this.showToast(c,"warning");i&&await this.run()}catch(o){console.error("Failed to clone repository:",o),this._setCloneStatus(`Lost the connection while cloning: ${o.message}. If git finishes, the case still appears in the list.`,"warn"),this.showToast("Clone request interrupted \u2014 watch the case list","error")}},openLinkCasePathPicker(){const e=document.getElementById("linkCasePath");PathPicker.open({title:"Select Existing Project Folder",initialPath:e.value.trim(),directoriesOnly:!0,onSelect:t=>{e.value=t;const s=document.getElementById("linkCaseName");if(!s.value.trim()){const a=t.split("/").filter(Boolean).pop()||"";/^[\p{L}\p{N}_-]+$/u.test(a)&&(s.value=a)}e.focus(),e.setSelectionRange(t.length,t.length)}})},async linkRemoteCase(){const e=document.getElementById("remoteCaseName").value.trim(),t=document.getElementById("remoteCasePath").value.trim(),s=document.getElementById("remoteHostId").value.trim(),a=document.getElementById("remoteHostAddress").value.trim(),n=document.getElementById("remoteHostUsername").value.trim(),i=document.getElementById("remoteHostCodexCommand").value.trim(),o=document.getElementById("remoteHostPort").value.trim(),r=document.getElementById("remoteHostIdentityFile").value.trim(),c=document.getElementById("remoteHostSocksProxy").value.trim(),l=document.getElementById("remoteHostJumpHost").value.trim(),d=document.getElementById("remoteHostExtraSshOptions").value.split(`
16
- `).map(u=>u.trim()).filter(u=>u.length>0);if(!e||!t||!s||!a||!n){this.showToast("Please complete all required remote fields","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Remote path must be absolute","error");return}let p;if(o&&(p=Number(o),!Number.isInteger(p)||p<1||p>65535)){this.showToast("SSH port must be a number between 1 and 65535","error");return}try{const u={id:s,label:s,host:a,username:n,...p?{port:p}:{},...r?{identityFile:r}:{},...c?{socksProxy:c}:{},...l?{jumpHost:l}:{},...d.length?{extraSshOptions:d}:{},...i?{commands:{codex:i}}:{}},m=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})).json();if(!m.success&&m.errorCode!=="ALREADY_EXISTS")throw new Error(m.error||"Failed to save remote host");const h=await(await fetch("/api/cases/remote-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,remotePath:t})})).json();h.success?(this.closeCreateCaseModal(),this.showToast(`Remote case "${e}" linked`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(h.error||"Failed to link remote case","error")}catch(u){console.error("Failed to link remote case:",u),this.showToast("Failed to link remote case: "+u.message,"error")}},async linkDockerCase(){const e=document.getElementById("dockerCaseName").value.trim(),t=document.getElementById("dockerWorkspacePath").value.trim(),s=document.getElementById("dockerHostId").value.trim()||"local",a=document.getElementById("dockerImage").value.trim()||"codeman/agent:base",n=document.getElementById("dockerNetwork").value,i=document.getElementById("dockerMemory").value.trim(),o=document.getElementById("dockerCpus").value.trim(),r=document.getElementById("dockerMountCredentials").checked,c=document.getElementById("dockerResumeOnStart").checked,l=document.getElementById("dockerLinkStatus");if(!e||!t){this.showToast("Please enter a case name and workspace path","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Workspace path must be absolute","error");return}try{l&&(l.textContent="Checking docker daemon + base image...");const d={};i&&(d.memory=i),o&&(d.cpus=o);const p={id:s,label:s,image:a,network:n,mountCredentials:r,resumeOnStart:c,...Object.keys(d).length?{resources:d}:{}};let u=await fetch("/api/docker-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}),y=await u.json();if(!y.success&&y.errorCode==="ALREADY_EXISTS"&&(u=await fetch(`/api/docker-hosts/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}),y=await u.json()),!y.success)throw new Error(y.error||"Failed to save docker host");const g=await(await fetch("/api/cases/docker-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,hostWorkspacePath:t})})).json();if(g.success){this.closeCreateCaseModal();const h=g.data?.capsEnforced===!1?" (resource caps are advisory on this engine)":"";this.showToast(`Docker case "${e}" linked${h}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)}else l&&(l.textContent=g.error||"Failed to link docker case"),this.showToast(g.error||"Failed to link docker case","error")}catch(d){console.error("Failed to link docker case:",d),l&&(l.textContent=d.message),this.showToast("Failed to link docker case: "+d.message,"error")}},async refreshDockerExports(){const e=document.getElementById("dockerExportsList");if(e)try{const a=(await(await fetch("/api/docker-exports")).json())?.data?.exports||[];if(a.length===0){e.innerHTML='<span class="form-hint">No exports yet. Export a docker case from its tab.</span>';return}e.innerHTML=a.map(n=>{const i=(n.sizeBytes/1e6).toFixed(1),o=escapeHtml(n.name);return`<div class="case-manage-item" style="display:flex; align-items:center; gap:8px; justify-content:space-between;">
15
+ Recreate the container to apply the new config? Workspace files and the conversation survive (the conversation resumes on launch).`))){const x=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/recreate`,{method:"POST"})).json();if(!x.success)throw new Error(x.error||"Failed to recreate container");S=await b()}if(!S.success)throw new Error(S.error||"Failed to start remote Claude session");await this._ensureCreatedSessionVisible(S.data.sessionId,S.data.session),E.push(S.data.sessionId)}this._appendSessionLaunchStatus(s,`All ${t} remote session(s) ready`),E[0]&&(await this.selectSession(E[0]),this.loadQuickStartCases()),this.terminal.focus();return}let o=null;const r=this._nextCaseSessionStartNumber(e),c=this.isRalphTrackerEnabledByDefault(),l=[];for(let y=0;y<t;y++)l.push(`w${r+y}-${e}`);const m=this.getCaseSettings(e),h=this.loadAppSettingsFromStorage(),u=this.buildEnvOverrides(m,h),f=Object.keys(u).length>0,d=this.getEffortSetting(h),g=m.opusContext1m||h.opusContext1mEnabled,p=h.claudeModel||(g?"opus[1m]":"");this._appendSessionLaunchStatus(s,`Creating ${t} session(s)...`);const I=l.map(y=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:i,name:y,...f?{envOverrides:u}:{},...d?{effort:d}:{},...p!==void 0?{modelOverride:p}:{},statusLineTelemetry:this.planUsageChipEnabled(h)})}).then(C=>C.json())),w=await Promise.all(I),k=[];for(const y of w){if(!y.success)throw new Error(y.error);await this._ensureCreatedSessionVisible(y.data.session.id,y.data.session),k.push(y.data.session.id)}o=k[0],await Promise.all(k.map(y=>fetch(`/api/sessions/${y}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:c,disableAutoEnable:!c})}))),this._appendSessionLaunchStatus(s,`Starting ${t} session(s) in parallel...`),await Promise.all(k.map(y=>fetch(`/api/sessions/${y}/interactive`,{method:"POST"}))),this._appendSessionLaunchStatus(s,`All ${t} sessions ready`),o&&(await this.selectSession(o),this.loadQuickStartCases()),this.terminal.focus()}catch(a){this._reportSessionLaunchError(s,a.message)}},stopClaude(){if(!this.activeSessionId)return;const e=document.querySelector(".btn-toolbar.btn-stop");e&&(this._stopConfirmTimer?(clearTimeout(this._stopConfirmTimer),this._stopConfirmTimer=null,e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml,e.classList.remove("confirming"),fetch(`/api/sessions/${this.activeSessionId}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:""})})):(e.dataset.origHtml=e.innerHTML,e.textContent="Tap again",e.classList.add("confirming"),this._stopConfirmTimer=setTimeout(()=>{this._stopConfirmTimer=null,e.dataset.origHtml&&(e.innerHTML=e.dataset.origHtml,delete e.dataset.origHtml),e.classList.remove("confirming")},2e3)))},async runShell(){const e=document.getElementById("quickStartCase").value||"testcase",t=Math.min(20,Math.max(1,parseInt(document.getElementById("shellCount").value)||1)),s=this._beginSessionLaunchStatus(`Starting ${t} Shell session(s) in ${e}...`,"1;33");try{let n=(await(await fetch(`/api/cases/${e}`)).json())?.data??{};if(!n.path){const g=await(await fetch("/api/cases",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,description:""})})).json();if(!g.success)throw new Error(g.error||"Failed to create case");n=g.data.case}const i=(this.cases||[]).find(d=>d.name===e),o=n.location==="remote"||n.location==="docker"||i?.location==="remote"||i?.location==="docker",r=n.path;if(!r)throw new Error("Case path not found");if(n.location==="remote"||n.location==="docker"){const d=this._nextCaseSessionStartNumber(e,"s"),g=[];for(let p=0;p<t;p++){const w=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"shell",sessionName:`s${d+p}-${e}`})})).json();if(!w.success)throw new Error(w.error||"Failed to start remote shell session");await this._ensureCreatedSessionVisible(w.data.sessionId,w.data.session),g.push(w.data.sessionId)}g[0]&&await this.selectSession(g[0]),this.terminal.focus();return}const c=this._nextCaseSessionStartNumber(e,"s"),l=[];for(let d=0;d<t;d++)l.push(`s${c+d}-${e}`);const m=l.map(d=>fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o?{caseName:e}:{workingDir:r},mode:"shell",name:d})}).then(g=>g.json())),h=await Promise.all(m),u=[];for(const d of h){if(!d.success)throw new Error(d.error);await this._ensureCreatedSessionVisible(d.data.session.id,d.data.session),u.push(d.data.session.id)}await Promise.all(u.map(d=>fetch(`/api/sessions/${d}/shell`,{method:"POST"})));const f=this.getTerminalDimensions();f&&await Promise.all(u.map(d=>fetch(`/api/sessions/${d}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}))),u.length>0&&await this.selectSession(u[0]),this.terminal.focus()}catch(a){this._reportSessionLaunchError(s,a.message)}},async runOpenCode(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting OpenCode session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/opencode/status")).json()).data.available){this._reportSessionLaunchError(a,"OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash");return}const n=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"opencode",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{openCodeConfig:{autoAllowTools:!0},...Object.keys(n).length>0?{envOverrides:n}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start OpenCode");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},async runCodex(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting Codex session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/codex/status")).json()).data.available){this._reportSessionLaunchError(a,"Codex CLI not found. Install with: npm install -g @openai/codex");return}const n=this.loadAppSettingsFromStorage(),i=this.buildEnvOverrides(this.getCaseSettings(e),n),r=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"codex",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{codexConfig:{dangerouslyBypassApprovals:n.codexDangerouslyBypassApprovals??!1,animations:n.codexAnimationsEnabled??!1,renderMode:"hybrid"},...Object.keys(i).length>0?{envOverrides:i}:{}}})})).json();if(!r.success)throw new Error(r.error||"Failed to start Codex");await this._ensureCreatedSessionVisible(r.data.sessionId,r.data.session),r.data.sessionId&&await this.selectSession(r.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},async runGemini(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting Gemini session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/gemini/status")).json()).data.available){this._reportSessionLaunchError(a,"Gemini CLI not found. Install with: npm install -g @google/gemini-cli");return}const n=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"gemini",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{geminiConfig:{approvalMode:"yolo"},...Object.keys(n).length>0?{envOverrides:n}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Gemini");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},async runAntigravity(){const e=document.getElementById("quickStartCase").value||"testcase",t=(this.cases||[]).find(n=>n.name===e)?.location,s=t==="remote"||t==="docker",a=this._beginSessionLaunchStatus(`Starting Antigravity session in ${e}...`);this.terminal.focus();try{if(!s&&!(await(await fetch("/api/antigravity/status")).json()).data.available){this._reportSessionLaunchError(a,"Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash");return}const n=this.buildEnvOverrides(this.getCaseSettings(e),this.loadAppSettingsFromStorage()),o=await(await fetch("/api/quick-start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({caseName:e,mode:"antigravity",sessionName:`w${this._nextCaseSessionStartNumber(e)}-${e}`,...s?{}:{antigravityConfig:{dangerouslySkipPermissions:!0},...Object.keys(n).length>0?{envOverrides:n}:{}}})})).json();if(!o.success)throw new Error(o.error||"Failed to start Antigravity");await this._ensureCreatedSessionVisible(o.data.sessionId,o.data.session),o.data.sessionId&&await this.selectSession(o.data.sessionId),this.terminal.focus()}catch(n){this._reportSessionLaunchError(a,n.message)}},openSessionOptions(e){const t=this.sessions.get(e);if(!t)return;this.editingSessionId=e;const s=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini"||t.mode==="antigravity";this.switchOptionsTab(s?"summary":"respawn");const a=document.getElementById("sessionRespawnStatus"),n=document.getElementById("modalEnableRespawnBtn"),i=document.getElementById("modalStopRespawnBtn");this.respawnStatus[e]?(a.classList.add("active"),a.querySelector(".respawn-status-text").textContent=this.respawnStatus[e].state||"Active",n.style.display="none",i.style.display=""):(a.classList.remove("active"),a.querySelector(".respawn-status-text").textContent="Not active",n.style.display="",i.style.display="none");const o=document.getElementById("sessionRespawnSection");t.mode==="claude"&&t.pid?o.style.display="":o.style.display="none";const r=t.mode==="opencode"||t.mode==="codex"||t.mode==="gemini"||t.mode==="antigravity";document.querySelectorAll("[data-claude-only]").forEach(p=>{p.style.display=r?"none":""}),this.selectDurationPreset(""),this.loadSavedRespawnConfig(e),document.getElementById("modalAutoCompactEnabled").checked=t.autoCompactEnabled??!1,document.getElementById("modalAutoCompactThreshold").value=t.autoCompactThreshold??11e4,document.getElementById("modalAutoCompactPrompt").value=t.autoCompactPrompt??"",document.getElementById("modalAutoClearEnabled").checked=t.autoClearEnabled??!1,document.getElementById("modalAutoClearThreshold").value=t.autoClearThreshold??14e4,document.getElementById("modalAutoResumeEnabled").checked=t.autoResumeEnabled??!1,this.updateAutoResumeStatus(e),document.getElementById("modalImageWatcherEnabled").checked=t.imageWatcherEnabled??!0,document.getElementById("modalFlickerFilterEnabled").checked=t.flickerFilterEnabled??!1;const l=parseSessionPrefix(t.name),m=document.getElementById("modalSessionPrefix");l?(m.textContent=l.prefix+": ",m.style.display="",document.getElementById("modalSessionName").value=l.suffix,document.getElementById("modalSessionName").placeholder="Add description..."):(m.style.display="none",m.textContent="",document.getElementById("modalSessionName").value=t.name||"",document.getElementById("modalSessionName").placeholder="Auto (directory name)");const h=t.color||"default";document.getElementById("sessionColorPicker")?.querySelectorAll(".color-swatch").forEach(p=>{p.classList.toggle("selected",p.dataset.color===h)}),this.renderPresetDropdown(),document.getElementById("respawnPresetSelect").value="",document.getElementById("presetDescriptionHint").textContent="";const f=document.querySelector('#sessionOptionsModal .set-rail-item[data-tab="ralph"]'),d=document.querySelector('#sessionOptionsModal .set-rail-item[data-tab="respawn"]');if(r?(f&&(f.style.display="none"),d&&(d.style.display="none"),this.switchOptionsTab("context")):(f&&(f.style.display=""),d&&(d.style.display="")),!r){const p=this.ralphStates.get(e);this.populateRalphForm({enabled:p?.loop?.enabled??t.ralphLoop?.enabled??!1,completionPhrase:p?.loop?.completionPhrase||t.ralphLoop?.completionPhrase||"",maxIterations:p?.loop?.maxIterations||t.ralphLoop?.maxIterations||0,maxTodos:p?.loop?.maxTodos||t.ralphLoop?.maxTodos,todoExpirationMinutes:p?.loop?.todoExpirationMinutes||t.ralphLoop?.todoExpirationMinutes})}const g=document.getElementById("sessionOptionsModal");g.dataset.chipsReady!=="1"&&(g.dataset.chipsReady="1",g.addEventListener("change",p=>{p.target?.closest?.(".set-chip")&&this._syncSettingsChips()})),this._syncSettingsChips(),g.classList.add("active"),this.activeFocusTrap=new FocusTrap(g),this.activeFocusTrap.activate()},async saveSessionName(){if(!this.editingSessionId)return;const e=this.sessions.get(this.editingSessionId),t=e?parseSessionPrefix(e.name):null,s=document.getElementById("modalSessionName").value.trim();let a;t?a=t.prefix+(s?": "+s:""):a=s;try{await this._apiPut(`/api/sessions/${this.editingSessionId}/name`,{name:a})}catch(n){this.showToast("Failed to save session name: "+n.message,"error")}},async autoSaveAutoCompact(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-compact`,{enabled:document.getElementById("modalAutoCompactEnabled").checked,threshold:parseInt(document.getElementById("modalAutoCompactThreshold").value)||11e4,prompt:document.getElementById("modalAutoCompactPrompt").value.trim()||void 0})}catch{}},async autoSaveAutoClear(){if(this.editingSessionId)try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-clear`,{enabled:document.getElementById("modalAutoClearEnabled").checked,threshold:parseInt(document.getElementById("modalAutoClearThreshold").value)||14e4})}catch{}},async autoSaveAutoResume(){if(!this.editingSessionId)return;const e=document.getElementById("modalAutoResumeEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.autoResumeEnabled=e,e||(t.autoResumeAt=void 0)),this.updateAutoResumeStatus(this.editingSessionId),this.showToast(`Auto-resume on usage limit ${e?"enabled":"disabled"}`,"success")}catch(t){this.showToast("Failed to toggle auto-resume: "+t.message,"error")}},updateAutoResumeStatus(e){const t=document.getElementById("autoResumeStatus");if(!t||this.editingSessionId!==e)return;const s=this.sessions.get(e);if(s?.autoResumeAt&&s.autoResumeAt>Date.now()){const a=new Date(s.autoResumeAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});t.textContent=`Usage limit pause active \u2014 resumes at ${a}`,t.classList.add("active")}else t.textContent="",t.classList.remove("active")},async toggleSessionImageWatcher(){if(!this.editingSessionId)return;const e=document.getElementById("modalImageWatcherEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/image-watcher`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.imageWatcherEnabled=e),this.showToast(`Image watcher ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle image watcher","error")}},async toggleFlickerFilter(){if(!this.editingSessionId)return;const e=document.getElementById("modalFlickerFilterEnabled").checked;try{await this._apiPost(`/api/sessions/${this.editingSessionId}/flicker-filter`,{enabled:e});const t=this.sessions.get(this.editingSessionId);t&&(t.flickerFilterEnabled=e),this.showToast(`Flicker filter ${e?"enabled":"disabled"}`,"success")}catch{this.showToast("Failed to toggle flicker filter","error")}},async autoSaveRespawnConfig(){if(!this.editingSessionId)return;const e={updatePrompt:document.getElementById("modalRespawnPrompt").value,sendClear:document.getElementById("modalRespawnSendClear").checked,sendInit:document.getElementById("modalRespawnSendInit").checked,kickstartPrompt:document.getElementById("modalRespawnKickstart").value.trim()||void 0,autoAcceptPrompts:document.getElementById("modalRespawnAutoAccept").checked};try{await this._apiPut(`/api/sessions/${this.editingSessionId}/respawn/config`,e)}catch{}},async loadSavedRespawnConfig(e){try{const s=await(await fetch(`/api/sessions/${e}/respawn/config`)).json();if(s.success&&s.data&&s.data.config){const a=s.data.config;document.getElementById("modalRespawnPrompt").value=a.updatePrompt||"update all the docs and CLAUDE.md",document.getElementById("modalRespawnSendClear").checked=a.sendClear??!0,document.getElementById("modalRespawnSendInit").checked=a.sendInit??!0,document.getElementById("modalRespawnKickstart").value=a.kickstartPrompt||"",document.getElementById("modalRespawnAutoAccept").checked=a.autoAcceptPrompts??!0,a.durationMinutes&&(document.querySelector(`.duration-preset-btn[data-minutes="${a.durationMinutes}"]`)?this.selectDurationPreset(String(a.durationMinutes)):(this.selectDurationPreset("custom"),document.getElementById("modalRespawnDuration").value=a.durationMinutes))}}catch{}},selectDurationPreset(e){document.querySelectorAll(".duration-preset-btn").forEach(n=>n.classList.remove("active"));const t=document.querySelector(`.duration-preset-btn[data-minutes="${e}"]`);t&&t.classList.add("active");const s=document.querySelector(".duration-custom-input"),a=document.getElementById("modalRespawnDuration");e==="custom"?(s.classList.add("visible"),a.focus()):(s.classList.remove("visible"),a.value="")},getSelectedDuration(){const e=document.querySelector(".duration-custom-input"),t=document.getElementById("modalRespawnDuration");if(e.classList.contains("visible"))return t.value?parseInt(t.value):null;{const a=document.querySelector(".duration-preset-btn.active")?.dataset.minutes;return a?parseInt(a):null}},switchOptionsTab(e){document.querySelectorAll("#sessionOptionsModal .set-rail-item").forEach(s=>{s.classList.toggle("active",s.dataset.tab===e)}),document.getElementById("respawn-tab").classList.toggle("hidden",e!=="respawn"),document.getElementById("context-tab").classList.toggle("hidden",e!=="context"),document.getElementById("ralph-tab").classList.toggle("hidden",e!=="ralph"),document.getElementById("summary-tab").classList.toggle("hidden",e!=="summary");const t=document.getElementById("sessionOptionsDoc");t&&(t.scrollTop=0),e==="summary"&&this.editingSessionId&&this.loadRunSummary(this.editingSessionId)},getRalphConfig(){return{enabled:document.getElementById("modalRalphEnabled").checked,completionPhrase:document.getElementById("modalRalphPhrase").value.trim(),maxIterations:parseInt(document.getElementById("modalRalphMaxIterations").value)||0,maxTodos:parseInt(document.getElementById("modalRalphMaxTodos").value)||50,todoExpirationMinutes:parseInt(document.getElementById("modalRalphTodoExpiration").value)||60}},populateRalphForm(e){document.getElementById("modalRalphEnabled").checked=e?.enabled??!1,document.getElementById("modalRalphPhrase").value=e?.completionPhrase||"",document.getElementById("modalRalphMaxIterations").value=e?.maxIterations||0,document.getElementById("modalRalphMaxTodos").value=e?.maxTodos||50,document.getElementById("modalRalphTodoExpiration").value=e?.todoExpirationMinutes||60},async saveRalphConfig(){if(!this.editingSessionId){this.showToast("No session selected","warning");return}const e=this.getRalphConfig();e.enabled&&this.ralphClosedSessions.delete(this.editingSessionId);try{const s=await(await fetch(`/api/sessions/${this.editingSessionId}/ralph-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();if(s.error)throw new Error(s.error);this.showToast("Ralph config saved","success")}catch(t){this.showToast("Failed to save Ralph config: "+t.message,"error")}},startInlineRename(e){const t=this.sessions.get(e);if(!t)return;const s=document.querySelector(`.tab-name[data-session-id="${e}"]`);if(!s)return;this._inlineRenameActive=!0;const a=this.getSessionName(t),n=parseSessionPrefix(t.name),i=s.textContent;for(s.textContent="";s.firstChild;)s.removeChild(s.firstChild);if(n){const c=document.createElement("span");c.textContent=n.prefix+": ",c.style.cssText="color: var(--text-muted); font-size: 0.75rem; white-space: nowrap;",s.appendChild(c)}const o=document.createElement("input");o.type="text",o.value=n?n.suffix:t.name||"",o.placeholder=n?"Add description...":a,o.className="tab-rename-input",o.style.cssText="width: 80px; font-size: 0.75rem; padding: 2px 4px; background: var(--bg-input); border: 1px solid var(--accent); border-radius: 3px; color: var(--text); outline: none;",s.appendChild(o),o.focus(),o.select();const r=async({commit:c})=>{if(!this._inlineRenameActive)return;if(this._inlineRenameActive=!1,this._activeRename=null,!c){this.renderSessionTabs();return}const l=o.value.trim(),m=n?n.prefix+(l?": "+l:""):l;if(s.textContent=m||i,this.sessions.has(e)&&m!==t.name)try{await fetch(`/api/sessions/${e}/name`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:m})})}catch{s.textContent=i,this.showToast("Failed to rename","error")}this.renderSessionTabs()};this._activeRename={sessionId:e,cancel:()=>r({commit:!1})},o.addEventListener("blur",()=>r({commit:!0})),o.addEventListener("keydown",c=>{c.isComposing||c.keyCode===229||(c.key==="Enter"?(c.preventDefault(),o.blur()):c.key==="Escape"&&(o.value="",o.blur()))})},toggleCaseSettings(){const e=document.getElementById("caseSettingsPopover");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeams").checked=s.agentTeams,document.getElementById("caseOpusContext1m").checked=s.opusContext1m,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},getCaseSettings(e){try{const t=localStorage.getItem("caseSettings_"+e);if(t)return JSON.parse(t)}catch{}return{agentTeams:!1,opusContext1m:!0}},saveCaseSettings(e,t){localStorage.setItem("caseSettings_"+e,JSON.stringify(t))},onCaseSettingChanged(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeams").checked,t.opusContext1m=document.getElementById("caseOpusContext1m").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeamsMobile");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1mMobile");a&&(a.checked=t.opusContext1m)},toggleCaseSettingsMobile(){const e=document.getElementById("caseSettingsPopoverMobile");if(e.classList.contains("hidden")){const t=document.getElementById("quickStartCase").value||"testcase",s=this.getCaseSettings(t);document.getElementById("caseAgentTeamsMobile").checked=s.agentTeams,document.getElementById("caseOpusContext1mMobile").checked=s.opusContext1m,e.classList.remove("hidden");const a=n=>{!e.contains(n.target)&&!n.target.classList.contains("btn-case-settings-mobile")&&(e.classList.add("hidden"),document.removeEventListener("click",a))};setTimeout(()=>document.addEventListener("click",a),0)}else e.classList.add("hidden")},onCaseSettingChangedMobile(){const e=document.getElementById("quickStartCase").value||"testcase",t=this.getCaseSettings(e);t.agentTeams=document.getElementById("caseAgentTeamsMobile").checked,t.opusContext1m=document.getElementById("caseOpusContext1mMobile").checked,this.saveCaseSettings(e,t);const s=document.getElementById("caseAgentTeams");s&&(s.checked=t.agentTeams);const a=document.getElementById("caseOpusContext1m");a&&(a.checked=t.opusContext1m)},showCreateCaseModal(){document.getElementById("newCaseName").value="",document.getElementById("newCaseDescription").value="",document.getElementById("linkCaseName").value="",document.getElementById("linkCasePath").value="",["remoteCaseName","remoteCasePath","remoteHostId","remoteHostAddress","remoteHostUsername","remoteHostPort","remoteHostCodexCommand","remoteHostIdentityFile","remoteHostSocksProxy","remoteHostJumpHost","remoteHostExtraSshOptions"].forEach(a=>{const n=document.getElementById(a);n&&(n.value="")}),this._resetCloneForm();const t=document.getElementById("caseCloneTabBtn");t&&(t.style.display=this.isCliAvailable("git")?"":"none"),this.caseModalTab="case-create",this.switchCaseModalTab("case-create");const s=document.getElementById("createCaseModal");s.querySelectorAll(".set-rail-item").forEach(a=>{a.onclick=()=>this.switchCaseModalTab(a.dataset.tab)}),s.querySelectorAll('input[type="text"]').forEach(a=>{a._mobileScrollWired||(a._mobileScrollWired=!0,a.addEventListener("focus",()=>{window.innerWidth<=430&&setTimeout(()=>a.scrollIntoView({behavior:"smooth",block:"center"}),300)}))}),s.classList.add("active"),document.getElementById("newCaseName").focus()},switchCaseModalTab(e){this.caseModalTab=e;const t=document.getElementById("createCaseModal");t.querySelectorAll(".set-rail-item").forEach(n=>{n.classList.toggle("active",n.dataset.tab===e)}),t.querySelectorAll(".set-section").forEach(n=>{n.classList.toggle("hidden",n.id!==e)});const s=document.getElementById("createCaseDoc");s&&(s.scrollTop=0);const a=document.getElementById("caseModalSubmit");e==="case-manage"?(a.style.display="none",this.renderCaseManageList(),this.refreshDockerExports()):(a.style.display="",a.textContent=e==="case-create"?"Create":e==="case-clone"?"Clone":e==="case-remote"?"Link Remote":e==="case-docker"?"Link Docker":"Link"),e==="case-create"?document.getElementById("newCaseName").focus():e==="case-clone"?document.getElementById("cloneRepoUrl").focus():e==="case-link"?document.getElementById("linkCaseName").focus():e==="case-remote"?document.getElementById("remoteCaseName").focus():e==="case-docker"&&document.getElementById("dockerCaseName").focus()},closeCreateCaseModal(){document.getElementById("createCaseModal").classList.remove("active")},async submitCaseModal(){const e=document.getElementById("caseModalSubmit"),t=e.textContent;e.classList.add("loading"),e.textContent=this.caseModalTab==="case-create"?"Creating...":this.caseModalTab==="case-clone"?"Cloning...":"Linking...",e.disabled=!0;try{this.caseModalTab==="case-create"?await this.createCase():this.caseModalTab==="case-clone"?await this.cloneCase():this.caseModalTab==="case-remote"?await this.linkRemoteCase():this.caseModalTab==="case-docker"?await this.linkDockerCase():await this.linkCase()}finally{e.classList.remove("loading"),e.disabled=!1,e.textContent=t}},async createCase(){const e=document.getElementById("newCaseName").value.trim(),t=document.getElementById("newCaseDescription").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}const s=document.getElementById("newCaseDocker")?.checked,a=s?"/api/cases/docker-quickcreate":"/api/cases",n=s?{name:e,description:t,...this._collectDockerQuickSettings()}:{name:e,description:t};try{const o=await(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(o.success)if(this.closeCreateCaseModal(),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e),s){const r=o.data?.capsEnforced===!1?" (resource caps advisory on this engine)":"";this.showToast(`Docker case "${e}" created${r} \u2014 starting session\u2026`,"success"),await this.runClaude()}else this.showToast(`Case "${e}" created`,"success");else this.showToast(o.error||"Failed to create case","error")}catch(i){console.error("Failed to create case:",i),this.showToast("Failed to create case: "+i.message,"error")}},applyDockerTemplate(){const e=document.getElementById("quickDockerTemplate")?.value,s={small:{m:"2g",c:"1",g:""},medium:{m:"",c:"",g:""},large:{m:"8g",c:"4",g:""},gpu:{m:"8g",c:"4",g:"all"}}[e];if(!s)return;const a=(n,i)=>{const o=document.getElementById(n);o&&(o.value=i)};a("quickDockerMemory",s.m),a("quickDockerCpus",s.c),a("quickDockerGpus",s.g)},_collectDockerQuickSettings(){const e=c=>(document.getElementById(c)?.value||"").trim(),t={},s=e("quickDockerMemory");s&&(t.memory=s);const a=e("quickDockerCpus");a&&(t.cpus=a);const n=e("quickDockerGpus");n&&n.toLowerCase()!=="none"&&(t.gpus=n);const i=document.getElementById("quickDockerNetwork")?.value;i&&i!=="bridge"&&(t.network=i);const o=e("quickDockerImage");o&&(t.image=o);const r=document.getElementById("quickDockerMountCreds");return r&&!r.checked&&(t.mountCredentials=!1),t},async linkCase(){const e=document.getElementById("linkCaseName").value.trim(),t=document.getElementById("linkCasePath").value.trim();if(!e){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t){this.showToast("Please enter a folder path","error");return}try{const a=await(await fetch("/api/cases/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,path:t})})).json();a.success?(this.closeCreateCaseModal(),this.showToast(`Case "${e}" linked to ${t}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(a.error||"Failed to link case","error")}catch(s){console.error("Failed to link case:",s),this.showToast("Failed to link case: "+s.message,"error")}},_resetCloneForm(){const e=(o,r)=>{const c=document.getElementById(o);c&&(c.value=r)};e("cloneRepoUrl",""),e("cloneCaseName",""),e("cloneRepoRef","");const t=document.getElementById("cloneShallow");t&&(t.checked=!1);const s=document.getElementById("cloneStartSession");s&&(s.checked=!1);const a=document.getElementById("cloneRepoRefOptions");a&&a.replaceChildren();const n=document.getElementById("cloneRefHint");n&&(n.textContent="Leave blank for the repository's default branch."),this._cloneNameEdited=!1,this._clonePreflight=null,clearTimeout(this._clonePreflightTimer),this._clonePreflightAbort?.abort(),this._clonePreflightAbort=null,this._setCloneStatus("Public repositories only: Codeman clones with no credentials.","");const i=document.getElementById("cloneCaseBrain");if(i){for(const r of i.options){const c=r.dataset.cli;r.hidden=!!c&&!this.isCliAvailable(c)}const o=this.runMode||"claude";i.value=[...i.options].some(r=>r.value===o&&!r.hidden)?o:""}},_setCloneStatus(e,t){const s=document.getElementById("cloneRepoStatus");s&&(s.textContent=e,s.className=`form-hint clone-status${t?" clone-status-"+t:""}`)},_repoNameFromUrl(e){const t=(e||"").trim().replace(/\/+$/,"");return t?(t.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//,"").replace(/^[^@/]*@/,"").split(/[/:]/).filter(Boolean).pop()||"").replace(/\.git$/i,"").replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,64):""},onCloneNameEdited(){this._cloneNameEdited=!!document.getElementById("cloneCaseName")?.value.trim()},onCloneUrlInput(){const e=document.getElementById("cloneRepoUrl")?.value.trim()||"",t=document.getElementById("cloneCaseName");if(t&&!this._cloneNameEdited&&(t.value=this._repoNameFromUrl(e)),clearTimeout(this._clonePreflightTimer),this._clonePreflightAbort?.abort(),this._clonePreflightAbort=null,!e){this._setCloneStatus("Public repositories only: Codeman clones with no credentials.","");return}if(this.isCliAvailable("git")===!1){this._setCloneStatus("git is not installed on the Codeman host, so cloning is unavailable.","err");return}this._setCloneStatus("Checking the repository\u2026",""),this._clonePreflightTimer=setTimeout(()=>this._runClonePreflight(e),450)},async _runClonePreflight(e){const t=new AbortController;this._clonePreflightAbort=t;try{const a=await(await fetch("/api/cases/clone-preflight",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repository:e}),signal:t.signal})).json();if(document.getElementById("cloneRepoUrl")?.value.trim()!==e)return;if(!a.success){this._setCloneStatus(a.error||"Could not check that URL.","err");return}this._applyClonePreflight(a.data,e)}catch(s){if(s.name==="AbortError")return;this._setCloneStatus("Could not reach Codeman to check that URL.","err")}},_applyClonePreflight(e,t){this._clonePreflight=e;const s=e?.parse;if(!s?.cloneable){this._setCloneStatus(s?.message||"That URL cannot be cloned.","err");return}const a=document.getElementById("cloneCaseName");a&&!this._cloneNameEdited&&s.suggestedName&&(a.value=s.suggestedName);const n=s.owner?`${s.provider} ${s.owner}/${s.repo}`:`${s.provider} ${s.repo}`;if(e.gitAvailable===!1){this._setCloneStatus(`${n}: git is not installed on the Codeman host.`,"err");return}const i=e.remote;if(i&&!i.reachable){this._setCloneStatus(`${n}: ${i.failure?.message||"the remote could not be read."}`,"err");return}const o=document.getElementById("cloneRefHint"),r=document.getElementById("cloneRepoRefOptions");if(i&&r){r.replaceChildren();for(const l of[...i.branches||[],...i.tags||[]]){const m=document.createElement("option");m.value=l,r.appendChild(m)}if(o){const l=`${i.branches?.length||0} branches, ${i.tags?.length||0} tags`;o.textContent=i.defaultBranch?`Blank clones the default branch (${i.defaultBranch}). ${l} available.`:`Blank clones the default branch. ${l} available.`}}const c=s.warnings?.[0];this._setCloneStatus(c?`${n}: ${c}`:`${n}: ready to clone.`,c?"warn":"ok")},async cloneCase(){const e=document.getElementById("cloneRepoUrl").value.trim(),t=document.getElementById("cloneCaseName").value.trim(),s=document.getElementById("cloneRepoRef").value.trim(),a=!!document.getElementById("cloneShallow")?.checked,n=document.getElementById("cloneCaseBrain")?.value||"",i=!!document.getElementById("cloneStartSession")?.checked;if(!e){this.showToast("Please enter a repository URL","error");return}if(!t){this.showToast("Please enter a case name","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(t)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}this._setCloneStatus(`Cloning ${e}\u2026 this can take a while for a large repository.`,"");try{const r=await(await fetch("/api/cases/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,repository:e,...s?{ref:s}:{},...a?{shallow:!0}:{}})})).json();if(!r.success){this._setCloneStatus(r.error||"Clone failed.","err"),this.showToast(r.error||"Failed to clone repository","error");return}n&&this.setRunMode(n),this.closeCreateCaseModal(),await this.loadQuickStartCases(t),await this.saveLastUsedCase(t),this.showToast(`Cloned into case "${t}"`,"success");for(const c of r.data?.warnings||[])this.showToast(c,"warning");i&&await this.run()}catch(o){console.error("Failed to clone repository:",o),this._setCloneStatus(`Lost the connection while cloning: ${o.message}. If git finishes, the case still appears in the list.`,"warn"),this.showToast("Clone request interrupted \u2014 watch the case list","error")}},openLinkCasePathPicker(){const e=document.getElementById("linkCasePath");PathPicker.open({title:"Select Existing Project Folder",initialPath:e.value.trim(),directoriesOnly:!0,onSelect:t=>{e.value=t;const s=document.getElementById("linkCaseName");if(!s.value.trim()){const a=t.split("/").filter(Boolean).pop()||"";/^[\p{L}\p{N}_-]+$/u.test(a)&&(s.value=a)}e.focus(),e.setSelectionRange(t.length,t.length)}})},async linkRemoteCase(){const e=document.getElementById("remoteCaseName").value.trim(),t=document.getElementById("remoteCasePath").value.trim(),s=document.getElementById("remoteHostId").value.trim(),a=document.getElementById("remoteHostAddress").value.trim(),n=document.getElementById("remoteHostUsername").value.trim(),i=document.getElementById("remoteHostCodexCommand").value.trim(),o=document.getElementById("remoteHostPort").value.trim(),r=document.getElementById("remoteHostIdentityFile").value.trim(),c=document.getElementById("remoteHostSocksProxy").value.trim(),l=document.getElementById("remoteHostJumpHost").value.trim(),m=document.getElementById("remoteHostExtraSshOptions").value.split(`
16
+ `).map(u=>u.trim()).filter(u=>u.length>0);if(!e||!t||!s||!a||!n){this.showToast("Please complete all required remote fields","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Remote path must be absolute","error");return}let h;if(o&&(h=Number(o),!Number.isInteger(h)||h<1||h>65535)){this.showToast("SSH port must be a number between 1 and 65535","error");return}try{const u={id:s,label:s,host:a,username:n,...h?{port:h}:{},...r?{identityFile:r}:{},...c?{socksProxy:c}:{},...l?{jumpHost:l}:{},...m.length?{extraSshOptions:m}:{},...i?{commands:{codex:i}}:{}},d=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})).json();if(!d.success&&d.errorCode!=="ALREADY_EXISTS")throw new Error(d.error||"Failed to save remote host");const p=await(await fetch("/api/cases/remote-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,remotePath:t})})).json();p.success?(this.closeCreateCaseModal(),this.showToast(`Remote case "${e}" linked`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)):this.showToast(p.error||"Failed to link remote case","error")}catch(u){console.error("Failed to link remote case:",u),this.showToast("Failed to link remote case: "+u.message,"error")}},async linkDockerCase(){const e=document.getElementById("dockerCaseName").value.trim(),t=document.getElementById("dockerWorkspacePath").value.trim(),s=document.getElementById("dockerHostId").value.trim()||"local",a=document.getElementById("dockerImage").value.trim()||"codeman/agent:base",n=document.getElementById("dockerNetwork").value,i=document.getElementById("dockerMemory").value.trim(),o=document.getElementById("dockerCpus").value.trim(),r=document.getElementById("dockerMountCredentials").checked,c=document.getElementById("dockerResumeOnStart").checked,l=document.getElementById("dockerLinkStatus");if(!e||!t){this.showToast("Please enter a case name and workspace path","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(e)||!/^[a-zA-Z0-9_-]+$/.test(s)){this.showToast("Invalid name. Use only letters, numbers, hyphens, underscores.","error");return}if(!t.startsWith("/")){this.showToast("Workspace path must be absolute","error");return}try{l&&(l.textContent="Checking docker daemon + base image...");const m={};i&&(m.memory=i),o&&(m.cpus=o);const h={id:s,label:s,image:a,network:n,mountCredentials:r,resumeOnStart:c,...Object.keys(m).length?{resources:m}:{}};let u=await fetch("/api/docker-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}),f=await u.json();if(!f.success&&f.errorCode==="ALREADY_EXISTS"&&(u=await fetch(`/api/docker-hosts/${encodeURIComponent(s)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}),f=await u.json()),!f.success)throw new Error(f.error||"Failed to save docker host");const g=await(await fetch("/api/cases/docker-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,hostId:s,hostWorkspacePath:t})})).json();if(g.success){this.closeCreateCaseModal();const p=g.data?.capsEnforced===!1?" (resource caps are advisory on this engine)":"";this.showToast(`Docker case "${e}" linked${p}`,"success"),await this.loadQuickStartCases(e),await this.saveLastUsedCase(e)}else l&&(l.textContent=g.error||"Failed to link docker case"),this.showToast(g.error||"Failed to link docker case","error")}catch(m){console.error("Failed to link docker case:",m),l&&(l.textContent=m.message),this.showToast("Failed to link docker case: "+m.message,"error")}},async refreshDockerExports(){const e=document.getElementById("dockerExportsList");if(e)try{const a=(await(await fetch("/api/docker-exports")).json())?.data?.exports||[];if(a.length===0){e.innerHTML='<span class="form-hint">No exports yet. Export a docker case from its tab.</span>';return}e.innerHTML=a.map(n=>{const i=(n.sizeBytes/1e6).toFixed(1),o=escapeHtml(n.name);return`<div class="case-manage-item" style="display:flex; align-items:center; gap:8px; justify-content:space-between;">
17
17
  <span style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${o}">${o} <span class="form-hint">(${i} MB)</span></span>
18
18
  <span style="flex-shrink:0;">
19
19
  <a class="btn-toolbar" href="/api/docker-exports/${encodeURIComponent(n.name)}" download>Download</a>
@@ -21,14 +21,14 @@ Recreate the container to apply the new config? Workspace files and the conversa
21
21
  <button class="btn-toolbar" onclick="app.deleteDockerExport('${o.replace(/'/g,"\\'")}')">Delete</button>
22
22
  </span>
23
23
  </div>`}).join("")}catch(t){e.innerHTML=`<span class="form-hint">Failed to load exports: ${t.message}</span>`}},async exportDockerCaseBundle(e,t="full"){try{const a=await(await fetch(`/api/docker-cases/${encodeURIComponent(e)}/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:t})})).json();a.success?this.showToast(`Exporting "${e}" (${t})... you'll be notified when the bundle is ready`,"info"):this.showToast(a.error||"Export failed","error")}catch(s){this.showToast("Export failed: "+s.message,"error")}},async importDockerBundle(e){const t=prompt("New case name for the imported bundle:",e.split("-")[0]+"-imported");if(!t)return;const s=prompt("Absolute host directory to restore the workspace into:","");if(s)try{const n=await(await fetch("/api/docker-cases/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundle:e,newCaseName:t,destWorkspacePath:s})})).json();n.success?(this.showToast(`Imported as "${t}"`,"success"),await this.loadQuickStartCases(t)):this.showToast(n.error||"Import failed","error")}catch(a){this.showToast("Import failed: "+a.message,"error")}},async deleteDockerExport(e){if(confirm(`Delete export bundle "${e}"?`))try{const s=await(await fetch(`/api/docker-exports/${encodeURIComponent(e)}`,{method:"DELETE"})).json();s.success?(this.showToast("Export deleted","success"),this.refreshDockerExports()):this.showToast(s.error||"Delete failed","error")}catch(t){this.showToast("Delete failed: "+t.message,"error")}},_readRemoteHostFromForm(){const e=document.getElementById("remoteHostId").value.trim(),t=document.getElementById("remoteHostAddress").value.trim(),s=document.getElementById("remoteHostUsername").value.trim(),a=document.getElementById("remoteHostPort").value.trim(),n=document.getElementById("remoteHostIdentityFile").value.trim(),i=document.getElementById("remoteHostSocksProxy").value.trim(),o=document.getElementById("remoteHostJumpHost").value.trim(),r=document.getElementById("remoteHostCodexCommand").value.trim(),c=document.getElementById("remoteHostExtraSshOptions").value.split(`
24
- `).map(d=>d.trim()).filter(d=>d.length>0);let l;if(a){const d=Number(a);Number.isInteger(d)&&d>=1&&d<=65535&&(l=d)}return{id:e,label:e,host:t,username:s,...l?{port:l}:{},...n?{identityFile:n}:{},...i?{socksProxy:i}:{},...o?{jumpHost:o}:{},...c.length?{extraSshOptions:c}:{},...r?{commands:{codex:r}}:{}}},async discoverRemoteSessions(){const e=document.getElementById("remoteDiscoverResults"),t=document.getElementById("remoteDiscoverBtn"),s=this._readRemoteHostFromForm();if(!s.id||!s.host||!s.username){this.showToast("Fill in Host ID, address, and username first","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(s.id)){this.showToast("Invalid Host ID. Use letters, numbers, hyphens, underscores.","error");return}t&&(t.disabled=!0),e&&(e.innerHTML='<div class="form-hint">Discovering\u2026</div>');try{const n=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json();if(!n.success&&n.errorCode!=="ALREADY_EXISTS")throw new Error(n.error||"Failed to save remote host");const o=await(await fetch(`/api/remote-hosts/${encodeURIComponent(s.id)}/sessions`)).json();if(!o.success)throw new Error(o.error||"Discovery failed");this._renderDiscoveredSessions(s.id,o.data.sessions||[])}catch(a){console.error("Discover remote sessions failed:",a),e&&(e.innerHTML=`<div class="form-hint" style="color: var(--error, #e06c75);">${escapeHtml(a.message)}</div>`)}finally{t&&(t.disabled=!1)}},_renderDiscoveredSessions(e,t){const s=document.getElementById("remoteDiscoverResults");if(!s)return;if(!t.length){s.innerHTML='<div class="form-hint">No <code>codeman-*</code> sessions running on this host (or it is unreachable).</div>';return}const a=Math.floor(Date.now()/1e3),n=t.map(i=>{const o=Math.max(0,a-(i.created||0)),r=o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h`:`${Math.floor(o/86400)}d`,c=i.attachedClients!=null?i.attachedClients:i.attached?1:0,l=c>1?`<span class="case-location-badge" style="background: var(--warning, #e5c07b); color: #000;">shared \xB7 ${c} clients</span>`:c===1?'<span class="case-location-badge" style="background: var(--accent, #61afef);">attached</span>':"";return`
24
+ `).map(m=>m.trim()).filter(m=>m.length>0);let l;if(a){const m=Number(a);Number.isInteger(m)&&m>=1&&m<=65535&&(l=m)}return{id:e,label:e,host:t,username:s,...l?{port:l}:{},...n?{identityFile:n}:{},...i?{socksProxy:i}:{},...o?{jumpHost:o}:{},...c.length?{extraSshOptions:c}:{},...r?{commands:{codex:r}}:{}}},async discoverRemoteSessions(){const e=document.getElementById("remoteDiscoverResults"),t=document.getElementById("remoteDiscoverBtn"),s=this._readRemoteHostFromForm();if(!s.id||!s.host||!s.username){this.showToast("Fill in Host ID, address, and username first","error");return}if(!/^[a-zA-Z0-9_-]+$/.test(s.id)){this.showToast("Invalid Host ID. Use letters, numbers, hyphens, underscores.","error");return}t&&(t.disabled=!0),e&&(e.innerHTML='<div class="form-hint">Discovering\u2026</div>');try{const n=await(await fetch("/api/remote-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json();if(!n.success&&n.errorCode!=="ALREADY_EXISTS")throw new Error(n.error||"Failed to save remote host");const o=await(await fetch(`/api/remote-hosts/${encodeURIComponent(s.id)}/sessions`)).json();if(!o.success)throw new Error(o.error||"Discovery failed");this._renderDiscoveredSessions(s.id,o.data.sessions||[])}catch(a){console.error("Discover remote sessions failed:",a),e&&(e.innerHTML=`<div class="form-hint" style="color: var(--error, #e06c75);">${escapeHtml(a.message)}</div>`)}finally{t&&(t.disabled=!1)}},_renderDiscoveredSessions(e,t){const s=document.getElementById("remoteDiscoverResults");if(!s)return;if(!t.length){s.innerHTML='<div class="form-hint">No <code>codeman-*</code> sessions running on this host (or it is unreachable).</div>';return}const a=Math.floor(Date.now()/1e3),n=t.map(i=>{const o=Math.max(0,a-(i.created||0)),r=o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h`:`${Math.floor(o/86400)}d`,c=i.attachedClients!=null?i.attachedClients:i.attached?1:0,l=c>1?`<span class="case-location-badge" style="background: var(--warning, #e5c07b); color: #000;">shared \xB7 ${c} clients</span>`:c===1?'<span class="case-location-badge" style="background: var(--accent, #61afef);">attached</span>':"";return`
25
25
  <div class="remote-discover-item">
26
26
  <div class="remote-discover-info">
27
27
  <span class="remote-discover-name">${escapeHtml(i.name)} ${l}</span>
28
28
  <span class="form-hint">age ${r} \xB7 ${i.windows||1} window(s)</span>
29
29
  </div>
30
30
  <button type="button" class="btn-toolbar" onclick="app.attachDiscoveredSession('${escapeHtml(e)}', '${escapeHtml(i.name)}')">Attach</button>
31
- </div>`}).join("");s.innerHTML=n},async attachDiscoveredSession(e,t){try{const a=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"shell",name:t,attachRemoteSession:{hostId:e,remoteSessionName:t}})})).json();if(!a.success)throw new Error(a.error||"Failed to create session");const n=a.data.session.id;await fetch(`/api/sessions/${n}/shell`,{method:"POST"});const i=this.getTerminalDimensions();i&&await fetch(`/api/sessions/${n}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),this.closeCreateCaseModal(),this.showToast(`Attached to ${t} (detach on close)`,"success"),this.activeSessionId=n,await this.selectSession(n),this.terminal&&typeof this.terminal.focus=="function"&&this.terminal.focus()}catch(s){console.error("Attach discovered session failed:",s),this.showToast("Failed to attach: "+s.message,"error")}},renderCaseManageList(){const e=document.getElementById("caseManageList"),t=this.cases||[];if(t.length===0){e.innerHTML='<div class="form-hint" style="text-align: center; padding: 2rem 0;">No cases yet</div>';return}let s="";t.forEach((a,n)=>{const i=n===0,o=n===t.length-1,r=a.path?a.path.replace(/^\/Users\/[^/]+/,"~"):"";s+=`
31
+ </div>`}).join("");s.innerHTML=n},async attachDiscoveredSession(e,t){try{const a=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"shell",name:t,attachRemoteSession:{hostId:e,remoteSessionName:t}})})).json();if(!a.success)throw new Error(a.error||"Failed to create session");const n=a.data.session.id;await fetch(`/api/sessions/${n}/shell`,{method:"POST"});const i=this.getTerminalDimensions();i&&await fetch(`/api/sessions/${n}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),this.closeCreateCaseModal(),this.showToast(`Attached to ${t} (detach on close)`,"success"),this.activeSessionId=n,await this.selectSession(n),this.terminal&&typeof this.terminal.focus=="function"&&this.terminal.focus()}catch(s){console.error("Attach discovered session failed:",s),this.showToast("Failed to attach: "+s.message,"error")}},renderCaseManageList(){const e=document.getElementById("caseManageList"),t=this.cases||[];if(t.length===0){e.innerHTML='<div class="form-hint" style="text-align: center; padding: 2rem 0;">No cases yet</div>';return}let s="";t.forEach((a,n)=>{const i=n===0,o=n===t.length-1,r=a.path?this._shortenHomePath(a.path):"";s+=`
32
32
  <div class="case-manage-item" data-case="${escapeHtml(a.name)}">
33
33
  <div class="case-manage-info">
34
34
  <span class="case-manage-name">${escapeHtml(a.name)}</span>