ui.ts 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  1. import { escapeHtml } from '../utils/escape-html';
  2. import type { InterviewFileItem, InterviewListItem } from './types';
  3. interface DashboardInterviewItem extends InterviewListItem {
  4. url: string;
  5. mode: string;
  6. resumeSlug: string;
  7. sessionID?: string;
  8. directory?: string;
  9. }
  10. const BRAND_LOGO_URL =
  11. 'https://ohmyopencodeslim.com/android-chrome-512x512.png';
  12. // ─── Shared client-side helpers ────────────────────────────────────
  13. function clipboardHelperJs(): string {
  14. return `
  15. function copyCommand(text, btn) {
  16. var clip = navigator.clipboard && navigator.clipboard.writeText;
  17. var useFallback = function() {
  18. var ta = document.createElement('textarea');
  19. ta.value = text;
  20. ta.style.position = 'fixed';
  21. ta.style.left = '-9999px';
  22. document.body.appendChild(ta);
  23. ta.select();
  24. document.execCommand('copy');
  25. document.body.removeChild(ta);
  26. };
  27. if (clip) {
  28. clip.call(navigator.clipboard, text).catch(useFallback);
  29. } else {
  30. useFallback();
  31. }
  32. btn.textContent = 'Copied!';
  33. btn.classList.add('copied');
  34. setTimeout(function() {
  35. btn.textContent = 'Copy';
  36. btn.classList.remove('copied');
  37. }, 2000);
  38. }`;
  39. }
  40. // ─── Shared styles ─────────────────────────────────────────────────
  41. function sharedStyles(): string {
  42. return `
  43. :root { color-scheme: dark; }
  44. body {
  45. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  46. margin: 0;
  47. background: #000000;
  48. color: #ffffff;
  49. line-height: 1.6;
  50. -webkit-font-smoothing: antialiased;
  51. font-size: 16px;
  52. }
  53. .wrap { max-width: 680px; margin: 0 auto; padding: 56px 24px; }
  54. .brand-header {
  55. display: flex;
  56. flex-direction: column;
  57. align-items: center;
  58. gap: 16px;
  59. margin-bottom: 32px;
  60. text-align: center;
  61. }
  62. .brand-mark {
  63. object-fit: contain;
  64. filter: drop-shadow(0 10px 30px rgba(255,255,255,0.1));
  65. }
  66. h1 { font-size: 28px; font-weight: 600; letter-spacing: -0.02em; margin-bottom: 8px; line-height: 1.2; }
  67. .muted { color: rgba(255,255,255,0.5); font-size: 16px; }
  68. code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; background: rgba(255,255,255,0.08); padding: 2px 6px; border-radius: 4px; font-size: 14px; }
  69. .resume-row {
  70. display: flex;
  71. align-items: center;
  72. gap: 8px;
  73. }
  74. .resume-cmd {
  75. flex: 1;
  76. padding: 8px 12px;
  77. font-size: 13px;
  78. border-radius: 6px;
  79. background: rgba(255,255,255,0.05);
  80. border: 1px solid rgba(255,255,255,0.1);
  81. white-space: nowrap;
  82. overflow-x: auto;
  83. }
  84. .copy-btn {
  85. flex-shrink: 0;
  86. padding: 8px 16px;
  87. border: 1px solid rgba(255,255,255,0.2);
  88. border-radius: 6px;
  89. background: transparent;
  90. color: rgba(255,255,255,0.8);
  91. font-size: 13px;
  92. font-weight: 500;
  93. cursor: pointer;
  94. transition: all 0.2s ease;
  95. }
  96. .copy-btn:hover {
  97. background: rgba(255,255,255,0.1);
  98. border-color: rgba(255,255,255,0.4);
  99. color: #ffffff;
  100. }
  101. .copy-btn.copied {
  102. background: rgba(52, 211, 153, 0.15);
  103. border-color: #34d399;
  104. color: #34d399;
  105. }
  106. .footer { margin-top: 32px; text-align: center; font-size: 13px; color: rgba(255,255,255,0.4); }`;
  107. }
  108. // ─── Dashboard brand image ─────────────────────────────────────────
  109. function brandImage(size: number): string {
  110. return `<img class="brand-mark" src="${BRAND_LOGO_URL}" alt="Oh My Opencode Slim" width="${size}" height="${size}" />`;
  111. }
  112. export function renderDashboardPage(
  113. interviews: DashboardInterviewItem[],
  114. files: InterviewFileItem[],
  115. outputFolder: string,
  116. ): string {
  117. const activeHtml =
  118. interviews.length === 0
  119. ? ''
  120. : interviews
  121. .map((item) => {
  122. const isDisconnected = item.mode === 'session-disconnected';
  123. const statusLabel = isDisconnected ? 'disconnected' : item.status;
  124. const statusClass = isDisconnected
  125. ? 'status-file'
  126. : `status-${item.status}`;
  127. const resumeHint = isDisconnected
  128. ? `<div class="resume-row" style="margin-top:8px"><code class="resume-cmd">/interview ${escapeHtml(item.resumeSlug)}</code><button class="copy-btn" data-cmd="/interview ${escapeHtml(item.resumeSlug)}" title="Copy command">Copy</button></div>`
  129. : '';
  130. return `<a class="interview-card" href="${escapeHtml(item.url)}">
  131. <div class="card-header">
  132. <span class="card-idea">${escapeHtml(item.idea)}</span>
  133. <span class="card-status ${statusClass}">${statusLabel}</span>
  134. </div>
  135. ${item.directory ? `<div class="card-dir">${escapeHtml(item.directory)}</div>` : ''}
  136. <div class="card-meta">
  137. <span>${escapeHtml(new Date(item.createdAt).toLocaleString())}</span>
  138. </div>
  139. ${resumeHint}
  140. </a>`;
  141. })
  142. .join('\n');
  143. // Dedup: skip files whose sessionID matches an active/recovered interview.
  144. // These are already visible in the "Interviews" section above.
  145. const activeSessionIDs = new Set(
  146. interviews
  147. .map((i) => i.sessionID)
  148. .filter((sid): sid is string => typeof sid === 'string'),
  149. );
  150. const unrecoveredFiles = files.filter((f) => {
  151. if (f.sessionID && activeSessionIDs.has(f.sessionID)) return false;
  152. return true;
  153. });
  154. const filesHtml =
  155. unrecoveredFiles.length === 0
  156. ? ''
  157. : unrecoveredFiles
  158. .map(
  159. (item) =>
  160. `<div class="interview-card file-card">
  161. <div class="card-header">
  162. <span class="card-idea">${escapeHtml(item.title)}</span>
  163. <span class="card-status status-file">saved</span>
  164. </div>
  165. ${item.directory ? `<div class="card-dir">${escapeHtml(item.directory)}</div>` : ''}
  166. <div class="card-summary">${escapeHtml(item.summary)}</div>
  167. <div class="resume-row">
  168. <code class="resume-cmd">${escapeHtml(item.resumeCommand)}</code>
  169. <button class="copy-btn" data-cmd="${escapeHtml(item.resumeCommand)}" title="Copy command">Copy</button>
  170. </div>
  171. </div>`,
  172. )
  173. .join('\n');
  174. const totalCount = interviews.length + unrecoveredFiles.length;
  175. const emptyState =
  176. totalCount === 0
  177. ? '<p class="muted" style="text-align:center;padding:48px 0">No interviews yet. Start one with <code>/interview</code> in your OpenCode session.</p>'
  178. : '';
  179. const activeSection =
  180. interviews.length > 0 ? `<h2>Interviews</h2>${activeHtml}` : '';
  181. const fileSection =
  182. unrecoveredFiles.length > 0
  183. ? `<h2>Files without session</h2><p class="muted file-hint">Resume with the command in any OpenCode session.</p>${filesHtml}`
  184. : '';
  185. return `<!doctype html>
  186. <html lang="en">
  187. <head>
  188. <meta charset="utf-8" />
  189. <meta name="viewport" content="width=device-width, initial-scale=1" />
  190. <title>Interviews</title>
  191. <style>
  192. ${sharedStyles()}
  193. .brand-mark { width: 96px; height: 96px; }
  194. h2 { font-size: 18px; font-weight: 500; letter-spacing: 0.05em; text-transform: uppercase; color: rgba(255,255,255,0.4); margin-bottom: 16px; margin-top: 40px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 12px; }
  195. h2:first-of-type { margin-top: 0; }
  196. .file-hint { font-size: 14px; margin-bottom: 16px; margin-top: -8px; }
  197. .interview-card {
  198. display: block;
  199. background: rgba(255,255,255,0.02);
  200. border: 1px solid rgba(255,255,255,0.1);
  201. border-radius: 8px;
  202. padding: 20px 24px;
  203. margin-bottom: 12px;
  204. text-decoration: none;
  205. color: inherit;
  206. transition: all 0.2s ease;
  207. }
  208. .interview-card:hover {
  209. background: rgba(255,255,255,0.06);
  210. border-color: rgba(255,255,255,0.3);
  211. transform: translateX(4px);
  212. }
  213. .file-card {
  214. cursor: default;
  215. }
  216. .file-card:hover {
  217. transform: none;
  218. }
  219. .card-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
  220. .card-idea { font-size: 17px; font-weight: 500; line-height: 1.4; flex: 1; }
  221. .card-status {
  222. font-size: 11px;
  223. text-transform: uppercase;
  224. letter-spacing: 0.05em;
  225. padding: 4px 10px;
  226. border-radius: 999px;
  227. font-weight: 600;
  228. flex-shrink: 0;
  229. }
  230. .status-active { background: rgba(52, 211, 153, 0.15); color: #34d399; }
  231. .status-abandoned { background: rgba(255,255,255,0.08); color: rgba(255,255,255,0.4); }
  232. .status-file { background: rgba(96, 165, 250, 0.15); color: #60a5fa; }
  233. .card-meta { font-size: 13px; color: rgba(255,255,255,0.4); }
  234. .card-summary { font-size: 14px; color: rgba(255,255,255,0.5); margin-bottom: 12px; line-height: 1.5; }
  235. .card-dir { font-size: 12px; color: rgba(255,255,255,0.3); margin-bottom: 8px; font-family: monospace; word-break: break-all; }
  236. .update-banner {
  237. position: fixed;
  238. top: -56px;
  239. left: 0; right: 0;
  240. background: rgba(96, 165, 250, 0.95);
  241. color: #fff;
  242. text-align: center;
  243. padding: 14px 24px;
  244. font-size: 14px;
  245. font-weight: 500;
  246. cursor: pointer;
  247. z-index: 200;
  248. transition: top 0.3s ease;
  249. backdrop-filter: blur(8px);
  250. }
  251. .update-banner.visible { top: 0; }
  252. .update-banner:hover { background: rgba(96, 165, 250, 1); }
  253. .info-box {
  254. font-size: 13px;
  255. color: rgba(255,255,255,0.45);
  256. background: rgba(255,255,255,0.03);
  257. border: 1px solid rgba(255,255,255,0.08);
  258. border-radius: 8px;
  259. padding: 16px 20px;
  260. margin-bottom: 40px;
  261. line-height: 1.7;
  262. }
  263. .info-box strong { color: rgba(255,255,255,0.65); font-weight: 500; }
  264. .info-box code {
  265. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  266. background: rgba(255,255,255,0.08);
  267. padding: 2px 6px;
  268. border-radius: 4px;
  269. font-size: 12px;
  270. word-break: break-all;
  271. }
  272. .settings-row {
  273. display: flex;
  274. align-items: center;
  275. gap: 12px;
  276. margin-top: 12px;
  277. flex-wrap: wrap;
  278. }
  279. .settings-row label {
  280. font-size: 13px;
  281. color: rgba(255,255,255,0.5);
  282. white-space: nowrap;
  283. }
  284. .settings-row select, .settings-row input[type="text"] {
  285. background: rgba(255,255,255,0.05);
  286. border: 1px solid rgba(255,255,255,0.15);
  287. color: #fff;
  288. border-radius: 4px;
  289. padding: 6px 10px;
  290. font-size: 13px;
  291. font-family: inherit;
  292. }
  293. .settings-row input[type="text"] {
  294. flex: 1;
  295. min-width: 200px;
  296. }
  297. .settings-row select:focus, .settings-row input[type="text"]:focus {
  298. border-color: rgba(255,255,255,0.4);
  299. outline: none;
  300. }
  301. .small-btn {
  302. padding: 6px 14px;
  303. border: 1px solid rgba(255,255,255,0.2);
  304. border-radius: 4px;
  305. background: transparent;
  306. color: rgba(255,255,255,0.8);
  307. font-size: 13px;
  308. cursor: pointer;
  309. transition: all 0.2s ease;
  310. }
  311. .small-btn:hover {
  312. background: rgba(255,255,255,0.1);
  313. border-color: rgba(255,255,255,0.4);
  314. color: #fff;
  315. }
  316. .folder-list {
  317. display: flex;
  318. flex-direction: column;
  319. gap: 4px;
  320. margin-top: 8px;
  321. }
  322. .folder-item {
  323. display: flex;
  324. align-items: center;
  325. gap: 8px;
  326. font-size: 13px;
  327. color: rgba(255,255,255,0.5);
  328. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  329. }
  330. .folder-item button {
  331. padding: 2px 8px;
  332. border: 1px solid rgba(255,255,255,0.15);
  333. border-radius: 3px;
  334. background: transparent;
  335. color: rgba(255,255,255,0.4);
  336. font-size: 11px;
  337. cursor: pointer;
  338. }
  339. .folder-item button:hover {
  340. border-color: rgba(255,100,100,0.5);
  341. color: rgba(255,100,100,0.8);
  342. }
  343. </style>
  344. </head>
  345. <body>
  346. <div class="wrap">
  347. <div class="brand-header">
  348. ${brandImage(96)}
  349. <h1>Interviews</h1>
  350. <p class="muted">${totalCount} item${totalCount === 1 ? '' : 's'}</p>
  351. </div>
  352. <div class="info-box">
  353. <strong>Interviews</strong> - live sessions and recovered files. State is pushed from OpenCode sessions to this dashboard.<br>
  354. <strong>Files without session</strong> - <code>.md</code> files in <code>${escapeHtml(outputFolder)}</code> with no frontmatter. Resume with <code>/interview &lt;name&gt;</code>.
  355. </div>
  356. <details style="margin-bottom:24px">
  357. <summary style="cursor:pointer;font-size:13px;color:rgba(255,255,255,0.4);user-select:none">Settings</summary>
  358. <div style="margin-top:12px">
  359. <div class="settings-row">
  360. <label for="scanDays">Scan sessions from last</label>
  361. <select id="scanDays">
  362. <option value="1">1 day</option>
  363. <option value="7">7 days</option>
  364. <option value="30" selected>30 days</option>
  365. <option value="90">90 days</option>
  366. <option value="0">All time</option>
  367. </select>
  368. <button class="small-btn" id="rescanBtn">Rescan</button>
  369. </div>
  370. <div class="settings-row">
  371. <input type="text" id="addFolderInput" placeholder="/path/to/project" />
  372. <button class="small-btn" id="addFolderBtn">Add Folder</button>
  373. </div>
  374. <div class="folder-list" id="folderList"></div>
  375. </div>
  376. </details>
  377. ${emptyState}
  378. ${activeSection}
  379. ${fileSection}
  380. <div class="footer">OH MY OPENCODE SLIM</div>
  381. </div>
  382. <div class="update-banner" id="updateBanner">Dashboard updated - tap to refresh</div>
  383. <script>
  384. ${clipboardHelperJs()}
  385. document.querySelectorAll('.copy-btn').forEach(btn => {
  386. btn.addEventListener('click', (e) => {
  387. e.stopPropagation();
  388. e.preventDefault();
  389. copyCommand(btn.dataset.cmd, btn);
  390. });
  391. });
  392. let lastSig = '';
  393. let bannerTimer = null;
  394. // Use health endpoint for change detection (no auth needed, shows counts)
  395. (async () => { try { const r = await fetch('/api/health'); if (r.ok) lastSig = await r.text(); } catch {} })();
  396. setInterval(async () => {
  397. try {
  398. const res = await fetch('/api/health');
  399. if (!res.ok) return;
  400. const sig = await res.text();
  401. if (sig !== lastSig) {
  402. lastSig = sig;
  403. const banner = document.getElementById('updateBanner');
  404. banner.classList.add('visible');
  405. if (bannerTimer) clearTimeout(bannerTimer);
  406. bannerTimer = setTimeout(() => banner.classList.remove('visible'), 30000);
  407. }
  408. } catch {}
  409. }, 15000);
  410. document.getElementById('updateBanner').addEventListener('click', () => location.reload());
  411. // Settings: load current state
  412. (async () => {
  413. try {
  414. const r = await fetch('/api/settings');
  415. if (!r.ok) return;
  416. const s = await r.json();
  417. const sel = document.getElementById('scanDays');
  418. if (sel && s.scanDays !== undefined) sel.value = String(s.scanDays);
  419. renderFolderList(s.folders || []);
  420. } catch {}
  421. })();
  422. function renderFolderList(folders) {
  423. const list = document.getElementById('folderList');
  424. if (!list) return;
  425. list.innerHTML = '';
  426. folders.forEach(function(dir) {
  427. const item = document.createElement('div');
  428. item.className = 'folder-item';
  429. const span = document.createElement('span');
  430. span.textContent = dir;
  431. span.style.flex = '1';
  432. const btn = document.createElement('button');
  433. btn.textContent = 'Remove';
  434. btn.addEventListener('click', async function() {
  435. await fetch('/api/settings', {
  436. method: 'POST',
  437. headers: { 'content-type': 'application/json' },
  438. body: JSON.stringify({ removeFolder: dir })
  439. });
  440. location.reload();
  441. });
  442. item.appendChild(span);
  443. item.appendChild(btn);
  444. list.appendChild(item);
  445. });
  446. }
  447. document.getElementById('rescanBtn')?.addEventListener('click', async function() {
  448. const days = parseInt(document.getElementById('scanDays').value, 10);
  449. await fetch('/api/settings', {
  450. method: 'POST',
  451. headers: { 'content-type': 'application/json' },
  452. body: JSON.stringify({ scanDays: days, discover: true })
  453. });
  454. location.reload();
  455. });
  456. document.getElementById('addFolderBtn')?.addEventListener('click', async function() {
  457. const input = document.getElementById('addFolderInput');
  458. const dir = input.value.trim();
  459. if (!dir) return;
  460. await fetch('/api/settings', {
  461. method: 'POST',
  462. headers: { 'content-type': 'application/json' },
  463. body: JSON.stringify({ addFolder: dir })
  464. });
  465. input.value = '';
  466. location.reload();
  467. });
  468. </script>
  469. </body>
  470. </html>`;
  471. }
  472. export function renderInterviewPage(
  473. interviewId: string,
  474. resumeSlug: string,
  475. ): string {
  476. const safeTitle = escapeHtml(interviewId);
  477. return `<!doctype html>
  478. <html lang="en">
  479. <head>
  480. <meta charset="utf-8" />
  481. <meta name="viewport" content="width=device-width, initial-scale=1" />
  482. <title>Interview ${safeTitle}</title>
  483. <style>
  484. ${sharedStyles()}
  485. .brand-mark { width: 144px; height: 144px; }
  486. .spec-block-card {
  487. background: rgba(255,255,255,0.01);
  488. border: 1px solid rgba(255,255,255,0.05);
  489. border-radius: 8px;
  490. padding: 24px;
  491. margin-bottom: 20px;
  492. text-align: left;
  493. transition: all 0.2s ease;
  494. }
  495. .spec-block-card:hover {
  496. border-color: rgba(255,255,255,0.15);
  497. background: rgba(255,255,255,0.02);
  498. }
  499. .spec-block-card h3 {
  500. margin-top: 0;
  501. font-size: 18px;
  502. color: #ffffff;
  503. border-bottom: 1px solid rgba(255,255,255,0.08);
  504. padding-bottom: 8px;
  505. margin-bottom: 14px;
  506. }
  507. .spec-block-content {
  508. font-size: 15px;
  509. line-height: 1.6;
  510. color: rgba(255,255,255,0.8);
  511. }
  512. .spec-block-comment-box {
  513. margin-top: 16px;
  514. padding-top: 16px;
  515. border-top: 1px dashed rgba(255,255,255,0.08);
  516. display: flex;
  517. flex-direction: column;
  518. gap: 10px;
  519. }
  520. .spec-block-comment-input {
  521. min-height: 60px !important;
  522. font-size: 14px !important;
  523. padding: 10px !important;
  524. }
  525. .comment-submit-btn {
  526. align-self: flex-end;
  527. background: transparent;
  528. border: 1px solid rgba(255,255,255,0.2);
  529. color: rgba(255,255,255,0.8);
  530. padding: 8px 16px;
  531. border-radius: 6px;
  532. font-size: 13px;
  533. cursor: pointer;
  534. transition: all 0.2s ease;
  535. }
  536. .comment-submit-btn:hover:not(:disabled) {
  537. border-color: #34d399;
  538. color: #34d399;
  539. background: rgba(52,211,153,0.05);
  540. }
  541. .comment-submit-btn:disabled {
  542. opacity: 0.3;
  543. cursor: not-allowed;
  544. }
  545. h1 { font-size: 32px; font-weight: 600; letter-spacing: -0.02em; margin-bottom: 12px; line-height: 1.2; }
  546. h2 { font-size: 18px; font-weight: 500; letter-spacing: 0.05em; text-transform: uppercase; color: rgba(255,255,255,0.4); margin-bottom: 24px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 12px; }
  547. h3 { font-size: 18px; font-weight: 500; margin-bottom: 16px; line-height: 1.4; }
  548. p { margin-top: 0; }
  549. .meta { display: flex; align-items: center; justify-content: space-between; font-size: 13px; color: rgba(255,255,255,0.4); margin-bottom: 16px; letter-spacing: 0.05em; text-transform: uppercase; }
  550. .file-path-container {
  551. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  552. font-size: 13px;
  553. color: rgba(255,255,255,0.6);
  554. background: rgba(255,255,255,0.05);
  555. padding: 8px 12px;
  556. border-radius: 6px;
  557. margin-bottom: 12px;
  558. display: flex;
  559. align-items: center;
  560. gap: 8px;
  561. border: 1px solid rgba(255,255,255,0.08);
  562. }
  563. .file-path-icon {
  564. opacity: 0.5;
  565. }
  566. .download-btn {
  567. margin-left: auto;
  568. background: transparent;
  569. border: 1px solid rgba(255,255,255,0.2);
  570. color: rgba(255,255,255,0.6);
  571. border-radius: 4px;
  572. padding: 4px 10px;
  573. font-size: 12px;
  574. cursor: pointer;
  575. transition: all 0.2s ease;
  576. }
  577. .download-btn:hover {
  578. border-color: rgba(255,255,255,0.5);
  579. color: #ffffff;
  580. }
  581. .question {
  582. background: rgba(255,255,255,0.02);
  583. border: 1px solid rgba(255,255,255,0.1);
  584. border-left: 1px solid rgba(255,255,255,0.1);
  585. border-radius: 6px;
  586. padding: 28px;
  587. margin-bottom: 32px;
  588. transition: all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1);
  589. }
  590. .question:focus-within {
  591. border-color: rgba(255,255,255,0.3);
  592. }
  593. /* Make active question much clearer */
  594. .question.active-question {
  595. background: rgba(255,255,255,0.04);
  596. border-color: rgba(255,255,255,0.4);
  597. border-left: 4px solid #ffffff;
  598. box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.1);
  599. transform: translateX(4px);
  600. }
  601. .options { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; }
  602. .question-hint {
  603. display: flex;
  604. flex-wrap: wrap;
  605. gap: 8px;
  606. margin: -4px 0 16px;
  607. color: rgba(255,255,255,0.5);
  608. font-size: 13px;
  609. line-height: 1.5;
  610. transition: color 0.2s ease;
  611. }
  612. .active-question .question-hint {
  613. color: rgba(255,255,255,0.78);
  614. }
  615. .hint-chip {
  616. display: inline-flex;
  617. align-items: center;
  618. gap: 6px;
  619. padding: 4px 10px;
  620. border-radius: 999px;
  621. background: rgba(255,255,255,0.06);
  622. border: 1px solid rgba(255,255,255,0.08);
  623. }
  624. .hint-chip kbd {
  625. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  626. font-size: 12px;
  627. padding: 2px 6px;
  628. border-radius: 6px;
  629. background: rgba(255,255,255,0.12);
  630. border: 1px solid rgba(255,255,255,0.08);
  631. color: rgba(255,255,255,0.95);
  632. }
  633. .option {
  634. border: 1px solid rgba(255,255,255,0.1);
  635. background: transparent;
  636. color: inherit;
  637. border-radius: 6px;
  638. padding: 14px 18px;
  639. cursor: pointer;
  640. text-align: left;
  641. font-size: 16px;
  642. transition: all 0.2s ease;
  643. display: flex;
  644. align-items: center;
  645. }
  646. .option:hover {
  647. background: rgba(255,255,255,0.06);
  648. border-color: rgba(255,255,255,0.3);
  649. }
  650. .option.selected {
  651. background: #ffffff;
  652. color: #000000;
  653. border-color: #ffffff;
  654. font-weight: 500;
  655. }
  656. .shortcut {
  657. display: inline-flex;
  658. align-items: center;
  659. justify-content: center;
  660. background: rgba(255,255,255,0.1);
  661. color: rgba(255,255,255,0.8);
  662. border-radius: 4px;
  663. min-width: 20px;
  664. height: 20px;
  665. padding: 0 4px;
  666. font-size: 12px;
  667. margin-right: 12px;
  668. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  669. }
  670. .option.selected .shortcut {
  671. background: rgba(0,0,0,0.15);
  672. color: rgba(0,0,0,0.9);
  673. }
  674. .option-text {
  675. flex: 1;
  676. line-height: 1.4;
  677. }
  678. .recommended-badge {
  679. font-size: 11px;
  680. text-transform: uppercase;
  681. letter-spacing: 0.05em;
  682. background: rgba(255,255,255,0.15);
  683. color: rgba(255,255,255,0.9);
  684. padding: 4px 8px;
  685. border-radius: 999px;
  686. margin-left: 12px;
  687. font-weight: 600;
  688. }
  689. .option.selected .recommended-badge {
  690. background: rgba(0,0,0,0.15);
  691. color: rgba(0,0,0,0.8);
  692. }
  693. .submit-shortcut {
  694. display: inline-block;
  695. margin-left: 10px;
  696. padding: 3px 8px;
  697. border-radius: 999px;
  698. background: rgba(0,0,0,0.08);
  699. color: rgba(0,0,0,0.7);
  700. font-size: 12px;
  701. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  702. }
  703. textarea {
  704. width: 100%;
  705. box-sizing: border-box;
  706. min-height: 140px;
  707. border-radius: 6px;
  708. border: 1px solid rgba(255,255,255,0.15);
  709. background: rgba(0,0,0,0.6);
  710. color: inherit;
  711. padding: 16px;
  712. font-family: inherit;
  713. font-size: 16px;
  714. line-height: 1.5;
  715. resize: vertical;
  716. outline: none;
  717. transition: border-color 0.2s ease;
  718. }
  719. textarea:focus {
  720. border-color: rgba(255,255,255,0.5);
  721. box-shadow: 0 0 0 1px rgba(255,255,255,0.1);
  722. }
  723. .hidden-textarea {
  724. display: none;
  725. }
  726. button.primary {
  727. background: #ffffff;
  728. color: #000000;
  729. border: 0;
  730. border-radius: 6px;
  731. padding: 16px 24px;
  732. font-size: 16px;
  733. font-weight: 600;
  734. cursor: pointer;
  735. width: 100%;
  736. transition: opacity 0.2s ease, transform 0.1s ease;
  737. }
  738. button.primary:hover:not(:disabled) {
  739. opacity: 0.9;
  740. transform: translateY(-1px);
  741. }
  742. button.primary:active:not(:disabled) {
  743. transform: translateY(1px);
  744. }
  745. button.primary:disabled {
  746. opacity: 0.3;
  747. cursor: not-allowed;
  748. }
  749. .footer {
  750. margin-top: 32px;
  751. text-align: center;
  752. font-size: 13px;
  753. color: rgba(255,255,255,0.4);
  754. }
  755. .back-link {
  756. display: inline-flex;
  757. align-items: center;
  758. gap: 6px;
  759. color: rgba(255,255,255,0.5);
  760. text-decoration: none;
  761. font-size: 14px;
  762. padding: 8px 0;
  763. transition: color 0.2s ease;
  764. position: relative;
  765. z-index: 200;
  766. }
  767. .back-link:hover { color: #ffffff; }
  768. .status-completed { color: #34d399; }
  769. /* Loading State Overlay */
  770. .loading-overlay {
  771. position: fixed;
  772. top: 0; left: 0; right: 0; bottom: 0;
  773. background: rgba(0, 0, 0, 0.85);
  774. display: flex;
  775. flex-direction: column;
  776. align-items: center;
  777. justify-content: center;
  778. z-index: 100;
  779. opacity: 0;
  780. pointer-events: none;
  781. backdrop-filter: blur(8px);
  782. transition: opacity 0.3s ease;
  783. }
  784. .loading-overlay.active {
  785. opacity: 1;
  786. pointer-events: all;
  787. }
  788. .loading-overlay .status-text {
  789. font-size: 15px;
  790. letter-spacing: 0.1em;
  791. text-transform: uppercase;
  792. color: #ffffff;
  793. font-weight: 500;
  794. }
  795. /* ── Completed Mode ─────────────────────────────────────────── */
  796. .section-label {
  797. font-size: 11px;
  798. font-weight: 700;
  799. letter-spacing: 0.12em;
  800. text-transform: uppercase;
  801. color: rgba(255,255,255,0.28);
  802. margin-bottom: 14px;
  803. }
  804. .spec-block {
  805. background: rgba(255,255,255,0.02);
  806. border: 1px solid rgba(255,255,255,0.08);
  807. border-radius: 6px;
  808. padding: 20px 24px;
  809. margin-bottom: 32px;
  810. color: rgba(255,255,255,0.72);
  811. font-size: 15px;
  812. line-height: 1.75;
  813. }
  814. .spec-block p { margin: 0 0 10px; }
  815. .spec-block p:last-child { margin-bottom: 0; }
  816. .spec-block strong { color: rgba(255,255,255,0.95); font-weight: 600; }
  817. .spec-block code {
  818. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  819. font-size: 13px;
  820. background: rgba(255,255,255,0.08);
  821. padding: 1px 5px;
  822. border-radius: 3px;
  823. }
  824. .qa-list { margin-bottom: 12px; }
  825. .qa-card {
  826. background: rgba(255,255,255,0.02);
  827. border: 1px solid rgba(255,255,255,0.08);
  828. border-radius: 6px;
  829. padding: 18px 22px;
  830. margin-bottom: 10px;
  831. }
  832. .qa-row { display: flex; gap: 14px; align-items: flex-start; }
  833. .qa-row + .qa-row { margin-top: 12px; }
  834. .qa-badge {
  835. display: inline-flex;
  836. align-items: center;
  837. justify-content: center;
  838. width: 22px;
  839. height: 22px;
  840. border-radius: 50%;
  841. font-size: 10px;
  842. font-weight: 700;
  843. flex-shrink: 0;
  844. margin-top: 2px;
  845. font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  846. }
  847. .qa-badge-q { background: rgba(255,255,255,0.12); color: rgba(255,255,255,0.85); }
  848. .qa-badge-a { background: rgba(52,211,153,0.15); color: #34d399; }
  849. .qa-divider { height: 1px; background: rgba(255,255,255,0.05); margin: 12px 0; }
  850. .qa-text { font-size: 15px; line-height: 1.55; padding-top: 2px; }
  851. .qa-text-q { color: rgba(255,255,255,0.82); }
  852. .qa-text-a { color: rgba(255,255,255,0.52); }
  853. .qa-empty {
  854. color: rgba(255,255,255,0.25);
  855. font-size: 14px;
  856. text-align: center;
  857. padding: 20px 0;
  858. font-style: italic;
  859. }
  860. .nudge-actions {
  861. display: flex;
  862. gap: 12px;
  863. margin-top: 32px;
  864. margin-bottom: 8px;
  865. }
  866. .nudge-btn {
  867. flex: 1;
  868. background: transparent;
  869. border: 1px solid rgba(255,255,255,0.15);
  870. color: rgba(255,255,255,0.65);
  871. border-radius: 6px;
  872. padding: 13px 16px;
  873. font-size: 14px;
  874. font-weight: 500;
  875. cursor: pointer;
  876. transition: all 0.2s ease;
  877. letter-spacing: 0.01em;
  878. }
  879. .nudge-btn:hover:not(:disabled) {
  880. border-color: rgba(255,255,255,0.4);
  881. color: #ffffff;
  882. background: rgba(255,255,255,0.04);
  883. }
  884. .nudge-btn.nudge-confirm {
  885. border-color: rgba(52,211,153,0.25);
  886. color: rgba(52,211,153,0.8);
  887. }
  888. .nudge-btn.nudge-confirm:hover:not(:disabled) {
  889. border-color: rgba(52,211,153,0.6);
  890. color: #34d399;
  891. background: rgba(52,211,153,0.05);
  892. }
  893. .nudge-btn:disabled { opacity: 0.3; cursor: not-allowed; }
  894. /* ── TOC Sidebar ──────────────────────────────────────────────── */
  895. .toc-sidebar {
  896. position: fixed;
  897. top: 0; left: 0; bottom: 0;
  898. width: 240px;
  899. background: rgba(255,255,255,0.02);
  900. border-right: 1px solid rgba(255,255,255,0.06);
  901. padding: 24px 0 80px;
  902. overflow-y: auto;
  903. z-index: 50;
  904. display: none;
  905. }
  906. .toc-sidebar.visible { display: block; }
  907. .toc-header {
  908. font-size: 11px;
  909. font-weight: 700;
  910. letter-spacing: 0.12em;
  911. text-transform: uppercase;
  912. color: rgba(255,255,255,0.28);
  913. padding: 0 20px 14px;
  914. border-bottom: 1px solid rgba(255,255,255,0.05);
  915. margin-bottom: 8px;
  916. }
  917. .toc-item {
  918. display: block;
  919. padding: 7px 20px;
  920. font-size: 13px;
  921. color: rgba(255,255,255,0.5);
  922. text-decoration: none;
  923. cursor: pointer;
  924. transition: all 0.15s ease;
  925. border-left: 2px solid transparent;
  926. line-height: 1.4;
  927. }
  928. .toc-item:hover {
  929. color: rgba(255,255,255,0.85);
  930. background: rgba(255,255,255,0.03);
  931. }
  932. .toc-item.active {
  933. color: #ffffff;
  934. border-left-color: #ffffff;
  935. background: rgba(255,255,255,0.04);
  936. }
  937. body.toc-visible .wrap {
  938. margin-left: 240px;
  939. }
  940. /* ── Chat Panel ───────────────────────────────────────────────── */
  941. .chat-panel {
  942. position: fixed;
  943. bottom: 0; left: 0; right: 0;
  944. background: rgba(0,0,0,0.92);
  945. backdrop-filter: blur(12px);
  946. border-top: 1px solid rgba(255,255,255,0.08);
  947. padding: 12px 20px;
  948. z-index: 60;
  949. display: none;
  950. gap: 10px;
  951. align-items: center;
  952. }
  953. .chat-panel.visible { display: flex; }
  954. body.chat-visible .wrap { padding-bottom: 72px; }
  955. body.toc-visible .chat-panel { left: 240px; }
  956. .chat-input {
  957. flex: 1;
  958. background: rgba(255,255,255,0.06);
  959. border: 1px solid rgba(255,255,255,0.1);
  960. border-radius: 8px;
  961. color: #ffffff;
  962. font-family: inherit;
  963. font-size: 14px;
  964. padding: 10px 14px;
  965. outline: none;
  966. transition: border-color 0.2s ease;
  967. }
  968. .chat-input:focus { border-color: rgba(255,255,255,0.35); }
  969. .chat-input::placeholder { color: rgba(255,255,255,0.3); }
  970. .chat-send {
  971. flex-shrink: 0;
  972. background: #ffffff;
  973. color: #000000;
  974. border: 0;
  975. border-radius: 8px;
  976. padding: 10px 18px;
  977. font-size: 14px;
  978. font-weight: 600;
  979. cursor: pointer;
  980. transition: opacity 0.2s ease;
  981. }
  982. .chat-send:hover:not(:disabled) { opacity: 0.85; }
  983. .chat-send:disabled { opacity: 0.3; cursor: not-allowed; }
  984. </style>
  985. </head>
  986. <body>
  987. <nav id="tocSidebar" class="toc-sidebar"></nav>
  988. <div class="wrap">
  989. <a href="/" class="back-link">← All Interviews</a>
  990. <div class="brand-header">
  991. ${brandImage(144)}
  992. </div>
  993. <h1 id="idea">Connecting...</h1>
  994. <p class="muted" id="summary">Preparing interview session</p>
  995. <div class="meta">
  996. <span id="status">INITIALIZING</span>
  997. <span>OH MY OPENCODE SLIM</span>
  998. </div>
  999. <div id="filePathContainer" class="file-path-container" style="display: none;">
  1000. <span class="file-path-icon">📄</span>
  1001. <span id="markdownPath"></span>
  1002. <button id="downloadBtn" class="download-btn" type="button">Download</button>
  1003. </div>
  1004. <div id="resumeRow" class="resume-row" style="display:none;">
  1005. <code id="resumeCmd" class="resume-cmd"></code>
  1006. <button class="copy-btn" id="copyResumeBtn" type="button">Copy</button>
  1007. </div>
  1008. <div id="questions"></div>
  1009. <div id="nudgeActions" class="nudge-actions" style="display:none;">
  1010. <button class="nudge-btn" id="moreQuestionsBtn" type="button">Ask more questions</button>
  1011. <button class="nudge-btn nudge-confirm" id="confirmCompleteBtn" type="button">Confirm complete ✓</button>
  1012. </div>
  1013. <button class="primary" id="submitButton" disabled>Submit Answers <span class="submit-shortcut">⌘↵</span></button>
  1014. <div class="footer" id="submitStatus"></div>
  1015. </div>
  1016. <div class="loading-overlay" id="loadingOverlay">
  1017. <div class="status-text" id="loadingText">Processing...</div>
  1018. </div>
  1019. <div class="chat-panel" id="chatPanel">
  1020. <input type="text" id="chatInput" class="chat-input" placeholder="Send a message to the agent - add a section, revise content, ask questions..." autocomplete="off" />
  1021. <button class="chat-send" id="chatSendBtn" type="button" disabled>Send</button>
  1022. </div>
  1023. <script>
  1024. ${clipboardHelperJs()}
  1025. const interviewId = ${JSON.stringify(interviewId).replace(/</g, '\\u003c')};
  1026. const resumeSlug = ${JSON.stringify(resumeSlug).replace(/</g, '\\u003c')};
  1027. const state = {
  1028. data: null,
  1029. answers: {},
  1030. activeQuestionIndex: 0,
  1031. lastQuestionIds: [],
  1032. lastSig: null,
  1033. customMode: {},
  1034. isSubmitting: false,
  1035. };
  1036. function updateSubmitButton() {
  1037. const button = document.getElementById('submitButton');
  1038. if (!state.data) {
  1039. button.disabled = true;
  1040. return;
  1041. }
  1042. const questions = state.data.questions || [];
  1043. const allAnswered = questions.every((question) =>
  1044. (state.answers[question.id] || '').trim().length > 0,
  1045. );
  1046. button.disabled =
  1047. state.data.isBusy ||
  1048. state.isSubmitting ||
  1049. !questions.length ||
  1050. !allAnswered;
  1051. const hideSubmit = ['completed', 'session-disconnected'];
  1052. button.style.display = hideSubmit.includes(state.data.mode) ? 'none' : '';
  1053. const overlay = document.getElementById('loadingOverlay');
  1054. const overlayText = document.getElementById('loadingText');
  1055. if (state.data.isBusy) {
  1056. overlay.classList.add('active');
  1057. overlayText.textContent = "Agent Thinking...";
  1058. } else {
  1059. overlay.classList.remove('active');
  1060. }
  1061. }
  1062. function getOptionButtonId(questionId, index) {
  1063. return 'opt-' + questionId + '-' + index;
  1064. }
  1065. function createOption(question, option, index, isCustom) {
  1066. const button = document.createElement('button');
  1067. button.type = 'button';
  1068. button.className = 'option';
  1069. button.id = getOptionButtonId(question.id, index);
  1070. const shortcut = index < 9 ? (index + 1) : '';
  1071. if (shortcut) {
  1072. const kbd = document.createElement('span');
  1073. kbd.className = 'shortcut';
  1074. kbd.textContent = shortcut;
  1075. button.appendChild(kbd);
  1076. }
  1077. const text = document.createElement('span');
  1078. text.className = 'option-text';
  1079. text.textContent = isCustom ? 'Custom' : option;
  1080. button.appendChild(text);
  1081. // Visual marking for suggested/recommended answers
  1082. if (!isCustom && question.suggested === option) {
  1083. const badge = document.createElement('span');
  1084. badge.className = 'recommended-badge';
  1085. badge.textContent = 'Recommended';
  1086. button.appendChild(badge);
  1087. }
  1088. button.addEventListener('click', () => {
  1089. const questions = state.data?.questions || [];
  1090. const qIdx = questions.findIndex(q => q.id === question.id);
  1091. if (qIdx !== -1) {
  1092. state.activeQuestionIndex = qIdx;
  1093. updateActiveQuestionFocus();
  1094. }
  1095. handleOptionSelect(question, option, isCustom);
  1096. });
  1097. return button;
  1098. }
  1099. function handleOptionSelect(question, option, isCustom) {
  1100. const textarea = document.getElementById('answer-' + question.id);
  1101. if (isCustom) {
  1102. state.customMode[question.id] = true;
  1103. state.answers[question.id] = state.customMode[question.id]
  1104. ? state.answers[question.id] || ''
  1105. : '';
  1106. updateTextareaVisibility(question.id);
  1107. updateOptionsDOM(question.id);
  1108. if (textarea) {
  1109. textarea.focus();
  1110. }
  1111. } else {
  1112. state.customMode[question.id] = false;
  1113. state.answers[question.id] = option;
  1114. updateTextareaVisibility(question.id);
  1115. advanceToNextQuestion(question.id);
  1116. }
  1117. updateSubmitButton();
  1118. updateOptionsDOM(question.id);
  1119. }
  1120. function updateTextareaVisibility(questionId) {
  1121. const textarea = document.getElementById('answer-' + questionId);
  1122. if (!textarea) return;
  1123. if (state.customMode[questionId]) {
  1124. textarea.classList.remove('hidden-textarea');
  1125. } else {
  1126. textarea.classList.add('hidden-textarea');
  1127. }
  1128. }
  1129. function advanceToNextQuestion(currentQuestionId) {
  1130. const questions = state.data?.questions || [];
  1131. const currentIndex = questions.findIndex(q => q.id === currentQuestionId);
  1132. if (currentIndex >= 0 && currentIndex < questions.length - 1) {
  1133. state.activeQuestionIndex = currentIndex + 1;
  1134. updateActiveQuestionFocus();
  1135. const nextQuestion = questions[currentIndex + 1];
  1136. const nextEl = document.getElementById('question-' + nextQuestion.id);
  1137. if (nextEl) {
  1138. nextEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
  1139. }
  1140. } else if (currentIndex === questions.length - 1) {
  1141. const submitBtn = document.getElementById('submitButton');
  1142. if (submitBtn && !submitBtn.disabled) {
  1143. submitBtn.scrollIntoView({ behavior: 'smooth', block: 'center' });
  1144. }
  1145. }
  1146. }
  1147. function updateOptionsDOM(questionId) {
  1148. const question = (state.data?.questions || []).find(q => q.id === questionId);
  1149. if (!question) return;
  1150. const predefined = question.options || [];
  1151. const currentAnswer = state.answers[question.id];
  1152. predefined.forEach((opt, idx) => {
  1153. const btn = document.getElementById(getOptionButtonId(questionId, idx));
  1154. if (btn) {
  1155. if (currentAnswer === opt) btn.classList.add('selected');
  1156. else btn.classList.remove('selected');
  1157. }
  1158. });
  1159. const customBtn = document.getElementById(getOptionButtonId(questionId, predefined.length));
  1160. if (customBtn) {
  1161. if (state.customMode[questionId]) {
  1162. customBtn.classList.add('selected');
  1163. } else {
  1164. customBtn.classList.remove('selected');
  1165. }
  1166. }
  1167. }
  1168. function updateActiveQuestionFocus() {
  1169. const questions = state.data?.questions || [];
  1170. questions.forEach((q, idx) => {
  1171. const wrapper = document.getElementById('question-' + q.id);
  1172. if (wrapper) {
  1173. if (idx === state.activeQuestionIndex) {
  1174. wrapper.classList.add('active-question');
  1175. } else {
  1176. wrapper.classList.remove('active-question');
  1177. }
  1178. }
  1179. });
  1180. }
  1181. function scrollToActiveQuestion(behavior) {
  1182. const questions = state.data?.questions || [];
  1183. const activeQ = questions[state.activeQuestionIndex];
  1184. if (!activeQ) return;
  1185. const wrapper = document.getElementById('question-' + activeQ.id);
  1186. if (wrapper) {
  1187. wrapper.scrollIntoView({ behavior, block: 'center' });
  1188. }
  1189. }
  1190. function syncActiveQuestionIndex(questions) {
  1191. if (!questions.length) {
  1192. state.activeQuestionIndex = 0;
  1193. state.lastQuestionIds = [];
  1194. return;
  1195. }
  1196. const nextQuestionIds = questions.map((question) => question.id);
  1197. const previousQuestionIds = state.lastQuestionIds || [];
  1198. const activeQuestionId = previousQuestionIds[state.activeQuestionIndex];
  1199. const nextActiveIndex = activeQuestionId
  1200. ? nextQuestionIds.indexOf(activeQuestionId)
  1201. : -1;
  1202. if (nextActiveIndex >= 0) {
  1203. state.activeQuestionIndex = nextActiveIndex;
  1204. } else {
  1205. state.activeQuestionIndex = 0;
  1206. }
  1207. state.lastQuestionIds = nextQuestionIds;
  1208. }
  1209. function isTextEntryTarget(target) {
  1210. return target &&
  1211. (target.tagName === 'TEXTAREA' ||
  1212. target.tagName === 'INPUT' ||
  1213. target.isContentEditable);
  1214. }
  1215. function isShortcutBlockedTarget(target) {
  1216. if (!target) return false;
  1217. return !!target.closest(
  1218. 'button, a, select, summary, textarea, input, [contenteditable="true"]',
  1219. );
  1220. }
  1221. document.addEventListener('keydown', (e) => {
  1222. const isSubmitShortcut =
  1223. (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) ||
  1224. (e.key === 's' && (e.metaKey || e.ctrlKey));
  1225. if (isSubmitShortcut) {
  1226. const submitBtn = document.getElementById('submitButton');
  1227. if (submitBtn && !submitBtn.disabled) {
  1228. submitBtn.click();
  1229. e.preventDefault();
  1230. }
  1231. return;
  1232. }
  1233. if (isTextEntryTarget(e.target)) return;
  1234. if (e.ctrlKey || e.metaKey || e.altKey) return;
  1235. const questions = state.data?.questions || [];
  1236. if (!questions.length) return;
  1237. if (e.key === 'Enter') {
  1238. if (e.repeat) {
  1239. e.preventDefault();
  1240. return;
  1241. }
  1242. if (isShortcutBlockedTarget(e.target)) return;
  1243. if (state.data.isBusy || state.isSubmitting) return;
  1244. const activeQ = questions[state.activeQuestionIndex];
  1245. if (!activeQ) return;
  1246. const answer = (state.answers[activeQ.id] || '').trim();
  1247. if (!answer) return;
  1248. const isLastQuestion =
  1249. state.activeQuestionIndex === questions.length - 1;
  1250. if (isLastQuestion) {
  1251. const submitBtn = document.getElementById('submitButton');
  1252. if (submitBtn && !submitBtn.disabled) {
  1253. submitBtn.click();
  1254. }
  1255. } else {
  1256. advanceToNextQuestion(activeQ.id);
  1257. }
  1258. e.preventDefault();
  1259. return;
  1260. }
  1261. const num = parseInt(e.key, 10);
  1262. if (num >= 1 && num <= 9) {
  1263. const activeQ = questions[state.activeQuestionIndex];
  1264. if (!activeQ) return;
  1265. const options = activeQ.options || [];
  1266. if (!options.length) return;
  1267. const idx = num - 1;
  1268. if (idx < options.length) {
  1269. handleOptionSelect(activeQ, options[idx], false);
  1270. e.preventDefault();
  1271. } else if (idx === options.length) {
  1272. handleOptionSelect(activeQ, 'Custom', true);
  1273. e.preventDefault();
  1274. }
  1275. }
  1276. if (e.key === 'ArrowDown') {
  1277. if (state.activeQuestionIndex < questions.length - 1) {
  1278. state.activeQuestionIndex++;
  1279. updateActiveQuestionFocus();
  1280. const wrapper = document.getElementById('question-' + questions[state.activeQuestionIndex].id);
  1281. if (wrapper) wrapper.scrollIntoView({ behavior: 'smooth', block: 'center' });
  1282. e.preventDefault();
  1283. }
  1284. }
  1285. if (e.key === 'ArrowUp') {
  1286. if (state.activeQuestionIndex > 0) {
  1287. state.activeQuestionIndex--;
  1288. updateActiveQuestionFocus();
  1289. const wrapper = document.getElementById('question-' + questions[state.activeQuestionIndex].id);
  1290. if (wrapper) wrapper.scrollIntoView({ behavior: 'smooth', block: 'center' });
  1291. e.preventDefault();
  1292. }
  1293. }
  1294. });
  1295. // ── Completed-mode helpers ───────────────────────────────────
  1296. function parseDocument(doc) {
  1297. if (!doc) return { spec: '', qaPairs: [] };
  1298. // Strip frontmatter (---...---) to prevent frontmatter lines from
  1299. // matching section headers or being parsed as content
  1300. let content = doc;
  1301. const fmMatch = content.match(/^---\\n[\\s\\S]*?\\n---\\n/);
  1302. if (fmMatch) content = content.slice(fmMatch[0].length);
  1303. const lines = content.split('\\n');
  1304. const specLines = [];
  1305. const qaLines = [];
  1306. let section = null;
  1307. for (const line of lines) {
  1308. if (/^## Current spec\\b/i.test(line)) { section = 'spec'; continue; }
  1309. if (/^## Q&A history\\b/i.test(line)) { section = 'qa'; continue; }
  1310. if (/^#{1,6} /.test(line)) { section = null; continue; }
  1311. if (section === 'spec') specLines.push(line);
  1312. else if (section === 'qa') qaLines.push(line);
  1313. }
  1314. const qaPairs = [];
  1315. let current = null;
  1316. for (const line of qaLines) {
  1317. const trimmed = line.trim();
  1318. if (trimmed.startsWith('Q: ')) {
  1319. if (current) qaPairs.push(current);
  1320. current = { q: trimmed.slice(3), a: '' };
  1321. } else if (trimmed.startsWith('A: ') && current) {
  1322. current.a = trimmed.slice(3);
  1323. } else if (trimmed && current && current.a) {
  1324. current.a += ' ' + trimmed;
  1325. }
  1326. }
  1327. if (current) qaPairs.push(current);
  1328. return { spec: specLines.join('\\n').trim(), qaPairs };
  1329. }
  1330. // simpleMarkdown: safe because escaping happens BEFORE markdown
  1331. // processing. Adding raw HTML output from user content would break
  1332. // this safety - always use textContent for user data.
  1333. function simpleMarkdown(text) {
  1334. if (!text) return '';
  1335. const escaped = text
  1336. .replace(/&/g, '&amp;')
  1337. .replace(/</g, '&lt;')
  1338. .replace(/>/g, '&gt;');
  1339. const formatted = escaped
  1340. .replace(/\\*\\*(.+?)\\*\\*/g, '<strong>$1</strong>')
  1341. .replace(/\`([^\`]+)\`/g, '<code>$1</code>');
  1342. const paragraphs = formatted.split(/\\n\\n+/).filter(p => p.trim());
  1343. return paragraphs.map(p => \`<p>\${p.replace(/\\n/g, '<br>')}</p>\`).join('');
  1344. }
  1345. async function submitBlockComment(sectionTitle, commentText, button) {
  1346. if (!commentText.trim()) return;
  1347. button.disabled = true;
  1348. const submitStatus = document.getElementById('submitStatus');
  1349. submitStatus.textContent = '';
  1350. try {
  1351. const res = await fetch('/api/interviews/' + encodeURIComponent(interviewId) + '/block-comment', {
  1352. method: 'POST',
  1353. headers: { 'content-type': 'application/json' },
  1354. body: JSON.stringify({ section: sectionTitle, comment: commentText }),
  1355. });
  1356. const payload = await res.json();
  1357. if (res.ok) {
  1358. submitStatus.textContent = 'Feedback queued for block: ' + sectionTitle;
  1359. const input = button.previousElementSibling;
  1360. if (input) input.value = '';
  1361. refresh().catch(() => {});
  1362. } else {
  1363. submitStatus.textContent = payload.error || 'Failed to submit comment.';
  1364. }
  1365. } catch (err) {
  1366. submitStatus.textContent = 'Error submitting block connection feedback.';
  1367. } finally {
  1368. button.disabled = false;
  1369. }
  1370. }
  1371. function renderCompletedView(data) {
  1372. const container = document.getElementById('questions');
  1373. const frag = document.createDocumentFragment();
  1374. const blocks = data.blocks || [];
  1375. if (blocks.length > 0) {
  1376. const specLabel = document.createElement('div');
  1377. specLabel.className = 'section-label';
  1378. specLabel.textContent = 'Interactive Specifications (11 Sections)';
  1379. frag.appendChild(specLabel);
  1380. for (const block of blocks) {
  1381. const card = document.createElement('div');
  1382. card.className = 'spec-block-card';
  1383. const header = document.createElement('h3');
  1384. header.textContent = block.title;
  1385. card.appendChild(header);
  1386. const content = document.createElement('div');
  1387. content.className = 'spec-block-content';
  1388. content.innerHTML = simpleMarkdown(block.content);
  1389. card.appendChild(content);
  1390. // Per-block comment integration for micro annotations
  1391. const commentBox = document.createElement('div');
  1392. commentBox.className = 'spec-block-comment-box';
  1393. const textarea = document.createElement('textarea');
  1394. textarea.className = 'spec-block-comment-input';
  1395. textarea.placeholder = 'Provide review comment/revision for ' + block.title + '...';
  1396. commentBox.appendChild(textarea);
  1397. const sendBtn = document.createElement('button');
  1398. sendBtn.className = 'comment-submit-btn';
  1399. sendBtn.type = 'button';
  1400. sendBtn.textContent = 'Revise Section';
  1401. sendBtn.addEventListener('click', () => {
  1402. submitBlockComment(block.title, textarea.value, sendBtn);
  1403. });
  1404. commentBox.appendChild(sendBtn);
  1405. card.appendChild(commentBox);
  1406. frag.appendChild(card);
  1407. }
  1408. } else {
  1409. // Fallback legacy parse if blocks array isn't populated
  1410. const { spec, qaPairs } = parseDocument(data.document);
  1411. // Spec section
  1412. if (spec) {
  1413. const specLabel = document.createElement('div');
  1414. specLabel.className = 'section-label';
  1415. specLabel.textContent = 'Current Spec';
  1416. frag.appendChild(specLabel);
  1417. const specBlock = document.createElement('div');
  1418. specBlock.className = 'spec-block';
  1419. specBlock.innerHTML = simpleMarkdown(spec);
  1420. frag.appendChild(specBlock);
  1421. }
  1422. }
  1423. // Q&A section
  1424. const qaLabel = document.createElement('div');
  1425. qaLabel.className = 'section-label';
  1426. qaLabel.textContent = 'Q&A History';
  1427. frag.appendChild(qaLabel);
  1428. const { qaPairs } = parseDocument(data.document);
  1429. if (!qaPairs.length) {
  1430. const empty = document.createElement('p');
  1431. empty.className = 'qa-empty';
  1432. empty.textContent = 'No Q&A recorded.';
  1433. frag.appendChild(empty);
  1434. } else {
  1435. const qaList = document.createElement('div');
  1436. qaList.className = 'qa-list';
  1437. for (const pair of qaPairs) {
  1438. const card = document.createElement('div');
  1439. card.className = 'qa-card';
  1440. const qRow = document.createElement('div');
  1441. qRow.className = 'qa-row';
  1442. const qBadge = document.createElement('span');
  1443. qBadge.className = 'qa-badge qa-badge-q';
  1444. qBadge.textContent = 'Q';
  1445. const qText = document.createElement('span');
  1446. qText.className = 'qa-text qa-text-q';
  1447. qText.textContent = pair.q;
  1448. qRow.appendChild(qBadge);
  1449. qRow.appendChild(qText);
  1450. card.appendChild(qRow);
  1451. const divider = document.createElement('div');
  1452. divider.className = 'qa-divider';
  1453. card.appendChild(divider);
  1454. const aRow = document.createElement('div');
  1455. aRow.className = 'qa-row';
  1456. const aBadge = document.createElement('span');
  1457. aBadge.className = 'qa-badge qa-badge-a';
  1458. aBadge.textContent = 'A';
  1459. const aText = document.createElement('span');
  1460. aText.className = 'qa-text qa-text-a';
  1461. aText.textContent = pair.a || '-';
  1462. aRow.appendChild(aBadge);
  1463. aRow.appendChild(aText);
  1464. card.appendChild(aRow);
  1465. qaList.appendChild(card);
  1466. }
  1467. frag.appendChild(qaList);
  1468. }
  1469. container.replaceChildren(frag);
  1470. }
  1471. // ── TOC Sidebar ──────────────────────────────────────────────
  1472. function updateTocSidebar(data) {
  1473. const sidebar = document.getElementById('tocSidebar');
  1474. const blocks = data.blocks || [];
  1475. const isDone = ['completed', 'session-disconnected'].includes(data.mode);
  1476. if (!isDone || !blocks.length) {
  1477. sidebar.classList.remove('visible');
  1478. document.body.classList.remove('toc-visible');
  1479. return;
  1480. }
  1481. sidebar.classList.add('visible');
  1482. document.body.classList.add('toc-visible');
  1483. sidebar.innerHTML = '';
  1484. const header = document.createElement('div');
  1485. header.className = 'toc-header';
  1486. header.textContent = 'Sections';
  1487. sidebar.appendChild(header);
  1488. blocks.forEach((block) => {
  1489. const item = document.createElement('a');
  1490. item.className = 'toc-item';
  1491. item.textContent = block.title;
  1492. item.addEventListener('click', () => {
  1493. const cards = document.querySelectorAll('.spec-block-card h3');
  1494. for (const h3 of cards) {
  1495. if (h3.textContent === block.title) {
  1496. h3.closest('.spec-block-card').scrollIntoView({ behavior: 'smooth', block: 'start' });
  1497. break;
  1498. }
  1499. }
  1500. document.querySelectorAll('.toc-item').forEach((el) => el.classList.remove('active'));
  1501. item.classList.add('active');
  1502. });
  1503. sidebar.appendChild(item);
  1504. });
  1505. }
  1506. // ── Chat Panel ───────────────────────────────────────────────
  1507. function updateChatPanel(data) {
  1508. const panel = document.getElementById('chatPanel');
  1509. const input = document.getElementById('chatInput');
  1510. const sendBtn = document.getElementById('chatSendBtn');
  1511. const isDone = ['completed', 'session-disconnected'].includes(data.mode);
  1512. if (!isDone) {
  1513. panel.classList.remove('visible');
  1514. document.body.classList.remove('chat-visible');
  1515. return;
  1516. }
  1517. panel.classList.add('visible');
  1518. document.body.classList.add('chat-visible');
  1519. const busy = data.isBusy || false;
  1520. sendBtn.disabled = busy;
  1521. input.disabled = busy;
  1522. if (busy) {
  1523. input.placeholder = 'Agent is processing...';
  1524. } else {
  1525. input.placeholder = 'Send a message to the agent - add a section, revise content, ask questions...';
  1526. }
  1527. }
  1528. async function sendChatMessage() {
  1529. const input = document.getElementById('chatInput');
  1530. const sendBtn = document.getElementById('chatSendBtn');
  1531. const message = input.value.trim();
  1532. if (!message) return;
  1533. sendBtn.disabled = true;
  1534. input.value = '';
  1535. const submitStatus = document.getElementById('submitStatus');
  1536. submitStatus.textContent = '';
  1537. try {
  1538. const res = await fetch('/api/interviews/' + encodeURIComponent(interviewId) + '/chat', {
  1539. method: 'POST',
  1540. headers: { 'content-type': 'application/json' },
  1541. body: JSON.stringify({ message }),
  1542. });
  1543. const payload = await res.json();
  1544. if (res.ok) {
  1545. submitStatus.textContent = 'Chat message sent to agent.';
  1546. refresh().catch(() => {});
  1547. schedulePoll();
  1548. } else {
  1549. submitStatus.textContent = payload.message || payload.error || 'Failed to send chat message.';
  1550. sendBtn.disabled = false;
  1551. }
  1552. } catch (_err) {
  1553. submitStatus.textContent = 'Network error sending chat message.';
  1554. sendBtn.disabled = false;
  1555. }
  1556. }
  1557. document.getElementById('chatSendBtn').addEventListener('click', sendChatMessage);
  1558. document.getElementById('chatInput').addEventListener('keydown', (e) => {
  1559. if (e.key === 'Enter' && !e.shiftKey) {
  1560. e.preventDefault();
  1561. sendChatMessage();
  1562. }
  1563. });
  1564. function renderQuestions(questions) {
  1565. const sig = JSON.stringify([questions, state.data?.mode]);
  1566. const container = document.getElementById('questions');
  1567. const previousActiveQuestionId =
  1568. state.lastQuestionIds[state.activeQuestionIndex];
  1569. syncActiveQuestionIndex(questions);
  1570. if (state.lastSig === sig) {
  1571. questions.forEach((q) => updateOptionsDOM(q.id));
  1572. updateActiveQuestionFocus();
  1573. return;
  1574. }
  1575. state.lastSig = sig;
  1576. container.replaceChildren();
  1577. if (!questions.length && !state.data?.isBusy) {
  1578. const doneModes = ['completed', 'session-disconnected'];
  1579. if (doneModes.includes(state.data?.mode)) {
  1580. renderCompletedView(state.data);
  1581. } else {
  1582. const empty = document.createElement('p');
  1583. empty.className = 'muted';
  1584. empty.style.textAlign = 'center';
  1585. empty.style.padding = '48px 0';
  1586. empty.textContent = 'No active questions right now.';
  1587. container.appendChild(empty);
  1588. }
  1589. return;
  1590. }
  1591. questions.forEach((question, idx) => {
  1592. const wrapper = document.createElement('div');
  1593. wrapper.className = 'question';
  1594. wrapper.id = 'question-' + question.id;
  1595. if (question.suggested && !state.answers[question.id]) {
  1596. state.answers[question.id] = question.suggested;
  1597. state.customMode[question.id] = false;
  1598. }
  1599. const title = document.createElement('h3');
  1600. title.textContent = question.question;
  1601. wrapper.appendChild(title);
  1602. const predefined = question.options || [];
  1603. if (predefined.length) {
  1604. const hint = document.createElement('div');
  1605. hint.className = 'question-hint';
  1606. hint.innerHTML =
  1607. '<span class="hint-chip"><kbd>1-9</kbd><span>Choose an option</span></span>' +
  1608. '<span class="hint-chip"><kbd>Enter</kbd><span>Accept selected answer</span></span>';
  1609. wrapper.appendChild(hint);
  1610. }
  1611. if (predefined.length) {
  1612. const options = document.createElement('div');
  1613. options.className = 'options';
  1614. predefined.forEach((option, optIdx) => {
  1615. options.appendChild(createOption(question, option, optIdx, false));
  1616. });
  1617. options.appendChild(createOption(question, 'Custom', predefined.length, true));
  1618. wrapper.appendChild(options);
  1619. }
  1620. const textarea = document.createElement('textarea');
  1621. textarea.id = 'answer-' + question.id;
  1622. textarea.placeholder = 'Type your answer here...';
  1623. textarea.value = state.customMode[question.id] ? (state.answers[question.id] || '') : '';
  1624. if (!state.customMode[question.id]) {
  1625. textarea.classList.add('hidden-textarea');
  1626. }
  1627. textarea.addEventListener('focus', () => {
  1628. state.activeQuestionIndex = idx;
  1629. updateActiveQuestionFocus();
  1630. });
  1631. textarea.addEventListener('input', () => {
  1632. state.answers[question.id] = textarea.value;
  1633. updateSubmitButton();
  1634. updateOptionsDOM(question.id);
  1635. });
  1636. wrapper.appendChild(textarea);
  1637. container.appendChild(wrapper);
  1638. });
  1639. updateActiveQuestionFocus();
  1640. questions.forEach(q => updateOptionsDOM(q.id));
  1641. const currentActiveQuestionId = questions[state.activeQuestionIndex]?.id;
  1642. if (
  1643. questions.length > 0 &&
  1644. previousActiveQuestionId !== currentActiveQuestionId
  1645. ) {
  1646. scrollToActiveQuestion('smooth');
  1647. }
  1648. }
  1649. function render(data) {
  1650. state.data = data;
  1651. document.getElementById('idea').textContent = data.interview.idea || 'Interview';
  1652. const doneModes = ['completed', 'session-disconnected'];
  1653. const isDone = doneModes.includes(data.mode);
  1654. const summaryEl = document.getElementById('summary');
  1655. if (isDone) {
  1656. summaryEl.style.display = 'none';
  1657. } else {
  1658. summaryEl.style.display = '';
  1659. summaryEl.textContent = data.summary || 'Session in progress.';
  1660. }
  1661. const statusEl = document.getElementById('status');
  1662. statusEl.textContent = data.mode.toUpperCase();
  1663. statusEl.className = isDone ? 'status-completed' : '';
  1664. // Render Markdown Path - always visible in completed mode
  1665. const pathContainer = document.getElementById('filePathContainer');
  1666. const pathElement = document.getElementById('markdownPath');
  1667. const mdPath = data.markdownPath || (data.interview && data.interview.markdownPath);
  1668. if (mdPath || isDone) {
  1669. if (mdPath) {
  1670. // Show just the filename for absolute paths
  1671. pathElement.textContent = mdPath.startsWith('/')
  1672. ? mdPath.split('/').pop() || mdPath
  1673. : mdPath;
  1674. } else {
  1675. pathElement.textContent = 'interview.md';
  1676. }
  1677. pathContainer.style.display = 'flex';
  1678. } else {
  1679. pathContainer.style.display = 'none';
  1680. }
  1681. // Resume command - only in session-disconnected mode
  1682. var resumeRow = document.getElementById('resumeRow');
  1683. if (resumeRow) {
  1684. var showResume = data.mode === 'session-disconnected';
  1685. resumeRow.style.display = showResume ? 'flex' : 'none';
  1686. if (showResume) {
  1687. document.getElementById('resumeCmd').textContent = '/interview ' + resumeSlug;
  1688. }
  1689. }
  1690. // Nudge actions - only for completed (live session)
  1691. // session-disconnected can't nudge (no session to receive it)
  1692. const nudgeActions = document.getElementById('nudgeActions');
  1693. const moreBtn = document.getElementById('moreQuestionsBtn');
  1694. const confirmBtn = document.getElementById('confirmCompleteBtn');
  1695. const canNudge = data.mode === 'completed';
  1696. if (nudgeActions) nudgeActions.style.display = canNudge ? 'flex' : 'none';
  1697. if (moreBtn) moreBtn.disabled = data.isBusy;
  1698. if (confirmBtn) confirmBtn.disabled = data.isBusy;
  1699. renderQuestions(data.questions || []);
  1700. updateSubmitButton();
  1701. updateTocSidebar(data);
  1702. updateChatPanel(data);
  1703. // If we transitioned to a non-terminal state and connection/polling is stopped, restart them
  1704. const terminalModes = ['abandoned', 'completed', 'session-disconnected'];
  1705. if (!terminalModes.includes(data.mode)) {
  1706. if (!sseConnected && !activeEs) {
  1707. connectSse();
  1708. }
  1709. if (!sseConnected && !pollFallbackTimer) {
  1710. schedulePoll();
  1711. }
  1712. }
  1713. }
  1714. async function refresh() {
  1715. const url = '/api/interviews/' + encodeURIComponent(interviewId) + '/state';
  1716. const response = await fetch(url);
  1717. const data = await response.json();
  1718. if (!response.ok) throw new Error(data.error || 'Failed to load state');
  1719. render(data);
  1720. }
  1721. function scrollToTop() {
  1722. window.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
  1723. }
  1724. document.getElementById('submitButton').addEventListener('click', async () => {
  1725. if (!state.data || state.isSubmitting) return;
  1726. document.getElementById('submitButton').blur();
  1727. const answers = (state.data.questions || []).map((question) => {
  1728. return {
  1729. questionId: question.id,
  1730. answer: (state.answers[question.id] || '').trim(),
  1731. };
  1732. });
  1733. state.isSubmitting = true;
  1734. updateSubmitButton();
  1735. const overlay = document.getElementById('loadingOverlay');
  1736. const overlayText = document.getElementById('loadingText');
  1737. overlay.classList.add('active');
  1738. overlayText.textContent = "Submitting Answers...";
  1739. scrollToTop();
  1740. try {
  1741. const response = await fetch('/api/interviews/' + encodeURIComponent(interviewId) + '/answers', {
  1742. method: 'POST',
  1743. headers: { 'content-type': 'application/json' },
  1744. body: JSON.stringify({ answers }),
  1745. });
  1746. const payload = await response.json();
  1747. document.getElementById('submitStatus').textContent = payload.message || (response.ok ? 'Answers submitted successfully.' : 'Submission failed.');
  1748. } catch (err) {
  1749. document.getElementById('submitStatus').textContent = 'Error submitting answers.';
  1750. }
  1751. state.isSubmitting = false;
  1752. updateSubmitButton();
  1753. try {
  1754. await refresh();
  1755. } catch (_error) {
  1756. overlay.classList.remove('active');
  1757. }
  1758. });
  1759. document.getElementById('downloadBtn').addEventListener('click', () => {
  1760. if (!state.data || !state.data.document) return;
  1761. const blob = new Blob([state.data.document], { type: 'text/markdown' });
  1762. const url = URL.createObjectURL(blob);
  1763. const a = document.createElement('a');
  1764. a.href = url;
  1765. const mdPath = state.data.markdownPath || 'interview.md';
  1766. a.download = mdPath.split('/').pop() || 'interview.md';
  1767. document.body.appendChild(a);
  1768. a.click();
  1769. document.body.removeChild(a);
  1770. URL.revokeObjectURL(url);
  1771. });
  1772. document.getElementById('copyResumeBtn').addEventListener('click', function(e) {
  1773. e.stopPropagation();
  1774. e.preventDefault();
  1775. var cmd = document.getElementById('resumeCmd').textContent;
  1776. if (cmd) copyCommand(cmd, this);
  1777. });
  1778. async function sendNudge(action) {
  1779. const moreBtn = document.getElementById('moreQuestionsBtn');
  1780. const confirmBtn = document.getElementById('confirmCompleteBtn');
  1781. if (moreBtn) moreBtn.disabled = true;
  1782. if (confirmBtn) confirmBtn.disabled = true;
  1783. document.getElementById('submitStatus').textContent = '';
  1784. try {
  1785. const url =
  1786. '/api/interviews/' +
  1787. encodeURIComponent(interviewId) +
  1788. '/nudge';
  1789. const res = await fetch(url, {
  1790. method: 'POST',
  1791. headers: { 'content-type': 'application/json' },
  1792. body: JSON.stringify({ action }),
  1793. });
  1794. if (!res.ok) {
  1795. const err = await res.json().catch(() => ({}));
  1796. document.getElementById('submitStatus').textContent =
  1797. err.error || 'Request failed.';
  1798. if (moreBtn) moreBtn.disabled = false;
  1799. if (confirmBtn) confirmBtn.disabled = false;
  1800. } else {
  1801. try { await refresh(); } catch (_) {}
  1802. schedulePoll(); // Restart polling - nudge may reactivate interview
  1803. }
  1804. } catch (_err) {
  1805. document.getElementById('submitStatus').textContent = 'Network error.';
  1806. if (moreBtn) moreBtn.disabled = false;
  1807. if (confirmBtn) confirmBtn.disabled = false;
  1808. }
  1809. }
  1810. document.getElementById('moreQuestionsBtn').addEventListener('click', () => sendNudge('more-questions'));
  1811. document.getElementById('confirmCompleteBtn').addEventListener('click', () => sendNudge('confirm-complete'));
  1812. // ── Real-time updates via SSE ─────────────────────────────────
  1813. let sseConnected = false;
  1814. let pollFallbackTimer = null;
  1815. let activeEs = null;
  1816. function connectSse() {
  1817. if (activeEs) {
  1818. activeEs.close();
  1819. }
  1820. const sseUrl = '/api/interviews/' + encodeURIComponent(interviewId) + '/events';
  1821. const es = new EventSource(sseUrl);
  1822. activeEs = es;
  1823. es.addEventListener('state', (e) => {
  1824. sseConnected = true;
  1825. if (pollFallbackTimer) {
  1826. clearTimeout(pollFallbackTimer);
  1827. pollFallbackTimer = null;
  1828. }
  1829. try {
  1830. const data = JSON.parse(e.data);
  1831. render(data);
  1832. } catch (_) {}
  1833. });
  1834. es.onerror = () => {
  1835. sseConnected = false;
  1836. es.close();
  1837. activeEs = null;
  1838. const terminalModes = ['abandoned', 'completed', 'session-disconnected'];
  1839. if (state.data && terminalModes.includes(state.data.mode)) {
  1840. return;
  1841. }
  1842. // Retry SSE after 3s, fall back to polling in the meantime
  1843. if (!pollFallbackTimer) schedulePoll();
  1844. setTimeout(() => connectSse(), 3000);
  1845. };
  1846. }
  1847. function schedulePoll() {
  1848. // Only poll if SSE is not connected
  1849. if (sseConnected) return;
  1850. const terminalModes = ['abandoned', 'completed', 'session-disconnected'];
  1851. if (state.data && terminalModes.includes(state.data.mode)) {
  1852. return;
  1853. }
  1854. pollFallbackTimer = setTimeout(async () => {
  1855. try { await refresh(); } catch (_) {}
  1856. pollFallbackTimer = null;
  1857. if (!sseConnected) {
  1858. schedulePoll();
  1859. }
  1860. }, 2500);
  1861. }
  1862. refresh().catch((error) => {
  1863. document.getElementById('submitStatus').textContent = error.message || 'Failed to load interview.';
  1864. });
  1865. connectSse();
  1866. </script>
  1867. </body>
  1868. </html>`;
  1869. }