traceforge-pcb 1.0.0__py3-none-any.whl

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 (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,683 @@
1
+ /* Traceforge desktop app: chat tabs, project panels, viewer, review, palette. */
2
+ (() => {
3
+ const $ = (s, el = document) => el.querySelector(s);
4
+ const $$ = (s, el = document) => [...el.querySelectorAll(s)];
5
+ const esc = TFmd.esc;
6
+ const h = (html) => { const t = document.createElement("template"); t.innerHTML = html.trim(); return t.content.firstElementChild; };
7
+ const S = { st: null, tabs: new Map(), active: null, quick: null, comps: [], compMap: new Map(), selected: null, hovered: null,
8
+ models: null, commands: null, viewers: {}, files: [], treeOpen: new Set(["."]), editor: { path: null, mtime: null, dirty: false },
9
+ git: null, gitSel: null, rightPane: "pcb", leftPane: "files", reviewSel: null, checks: null };
10
+ S.hover = null;
11
+ Object.defineProperty(S, "hovered", { get() { return S.hover; }, set(v) { S.hover = v; } });
12
+
13
+ async function api(path, opts = {}) {
14
+ const init = { method: opts.method || "GET", headers: { "X-Traceforge-Token": window.TF_TOKEN } };
15
+ if (opts.body !== undefined) { init.body = opts.raw ? opts.body : JSON.stringify(opts.body); if (!opts.raw) init.headers["Content-Type"] = "application/json"; }
16
+ const r = await fetch(path, init);
17
+ let data = null; try { data = await r.json(); } catch (e) { /* empty */ }
18
+ if (!r.ok) throw new Error((data && (data.detail || data.error)) || r.statusText);
19
+ return data;
20
+ }
21
+ function toast(text, err) {
22
+ const t = h(`<div class="toast${err ? " err" : ""}">${esc(text)}</div>`); $("#toasts").append(t); setTimeout(() => t.remove(), err ? 7000 : 3500);
23
+ }
24
+ const guard = (fn) => async (...a) => { try { return await fn(...a); } catch (e) { toast(e.message, true); } };
25
+ function modal(html, onClose) {
26
+ const m = $("#modal"), sheet = $("#sheet"); sheet.innerHTML = html; m.hidden = false; TFmd.hydrateIcons(sheet);
27
+ const close = () => { m.hidden = true; sheet.innerHTML = ""; onClose && onClose(); };
28
+ m.onmousedown = (e) => { if (e.target === m) close(); };
29
+ return close;
30
+ }
31
+ const modalOpen = () => !$("#modal").hidden;
32
+ function confirmBox(title, body, ok) {
33
+ return new Promise((res) => {
34
+ const close = modal(`<h3>${esc(title)}</h3><div class="sec muted">${esc(body)}</div><div class="foot"><button class="btn" id="c-no">Cancel</button><button class="btn accent" id="c-ok">${esc(ok || "Continue")}</button></div>`, () => res(false));
35
+ $("#c-no").onclick = close; $("#c-ok").onclick = () => { $("#modal").hidden = true; $("#sheet").innerHTML = ""; res(true); };
36
+ });
37
+ }
38
+
39
+ // ------------------------------------------------------------------ websocket
40
+ let ws, wsDelay = 400;
41
+ function connect() {
42
+ ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws?token=${encodeURIComponent(window.TF_TOKEN)}`);
43
+ ws.onopen = () => { wsDelay = 400; };
44
+ ws.onmessage = (e) => { try { route(JSON.parse(e.data)); } catch (err) { console.error(err); } };
45
+ ws.onclose = () => { setTimeout(connect, wsDelay); wsDelay = Math.min(wsDelay * 2, 5000); };
46
+ }
47
+ const send = (frame) => ws && ws.readyState === 1 && ws.send(JSON.stringify(frame));
48
+ function route(f) {
49
+ if (f.type === "files_changed") return onFilesChanged(f.kicad);
50
+ const tab = S.tabs.get(f.tab); if (tab) tab.handle(f);
51
+ }
52
+
53
+ // ------------------------------------------------------------------- chat tabs
54
+ class TabView {
55
+ constructor(info) {
56
+ this.info = info; this.id = info.id; this.quick = info.quick; this.el = h('<div class="chat"></div>');
57
+ this.cur = null; this.think = null; this.tools = new Map(); this.atts = []; this.suggest = []; this.review = info.review; this.busy = info.busy; this.empty = true; this.draft = "";
58
+ this.el.addEventListener("click", (e) => {
59
+ const m = e.target.closest(".mention"); if (m) { select(m.dataset.ref); showPane(S.rightPane === "sch" ? "sch" : "pcb"); }
60
+ const cp = e.target.closest(".cp"); if (cp) { navigator.clipboard && navigator.clipboard.writeText(cp.parentElement.querySelector("code").textContent); cp.textContent = "Copied"; setTimeout(() => (cp.textContent = "Copy"), 1200); }
61
+ });
62
+ this.showHello();
63
+ }
64
+ get title() { return this.info.title; }
65
+ scroll(force) { const el = this.el; if (force || el.scrollHeight - el.scrollTop - el.clientHeight < 140) el.scrollTop = el.scrollHeight; }
66
+ clear() { this.el.innerHTML = ""; this.cur = this.think = null; this.tools.clear(); this.empty = true; }
67
+ showHello() {
68
+ this.el.innerHTML = "";
69
+ if (this.quick) { this.el.append(h('<div class="hello"><p class="small">Ask a quick question about this design. Select a component and press <kbd>Ctrl</kbd> <kbd>K</kbd> for ready-made questions.</p></div>')); return; }
70
+ const name = S.st && S.st.name ? esc(S.st.name) : "your design";
71
+ const tips = ["What does this board do?", "Run DRC and summarize the findings", "Review the power supply for mistakes", "List the parts that are hard to source"];
72
+ const el = h(`<div class="hello"><h2>Work on ${name}</h2><div>Ask questions, review the design, or have the agent change it. Changes wait for your approval.</div><div class="tips">${tips.map((t) => `<button class="sug">${esc(t)}</button>`).join("")}</div><p class="small" style="margin-top:22px">Type <kbd>@</kbd> to mention a component, drop in a screenshot or datasheet, or press <kbd>Ctrl</kbd> <kbd>K</kbd> on a selected part.</p></div>`);
73
+ $$(".sug", el).forEach((b) => (b.onclick = () => submit(b.textContent)));
74
+ this.el.append(el); this.empty = true;
75
+ }
76
+ ensure() { if (this.empty) { this.el.innerHTML = ""; this.empty = false; } }
77
+ addUser(text, index, noEdit) {
78
+ this.ensure(); this.cur = null; this.think = null;
79
+ const m = h(`<div class="msg user"><div class="bubble"></div></div>`);
80
+ $(".bubble", m).innerHTML = TFmd.render(text, S.compMap).replace(/^<p>|<\/p>$/g, "");
81
+ $(".bubble", m).style.whiteSpace = "normal";
82
+ if (index != null && !noEdit) {
83
+ const tools = h('<div class="tools"><button class="icon" title="Edit and branch from here"><i data-i="pencil"></i></button></div>');
84
+ $("button", tools).onclick = () => this.edit(m, text, index); m.append(tools); TFmd.hydrateIcons(tools);
85
+ }
86
+ this.el.append(m); this.scroll(true);
87
+ }
88
+ edit(m, text, index) {
89
+ const bubble = $(".bubble", m); bubble.hidden = true; $(".tools", m)?.setAttribute("hidden", "");
90
+ const box = h(`<div class="edit"><textarea></textarea><div class="row"><span class="muted small">Sends from here as a new branch; this chat stays as it is.</span><span class="spacer"></span><button class="btn" data-a="x">Cancel</button><button class="btn accent" data-a="ok">Send as new branch</button></div></div>`);
91
+ $("textarea", box).value = text; m.append(box); $("textarea", box).focus();
92
+ $('[data-a="x"]', box).onclick = () => { box.remove(); bubble.hidden = false; $(".tools", m)?.removeAttribute("hidden"); };
93
+ $('[data-a="ok"]', box).onclick = guard(async () => {
94
+ const next = $("textarea", box).value.trim(); if (!next) return;
95
+ const r = await api(`/api/tabs/${this.id}/branch`, { method: "POST", body: { index } });
96
+ const tab = addTab(r.tab); tab.replay(r.items); await activate(tab.id); S.st = r; renderTabs(); submitTo(tab, next);
97
+ });
98
+ }
99
+ asst() {
100
+ this.ensure();
101
+ if (!this.cur) { const el = h('<div class="msg assistant"><div class="body md"></div></div>'); this.el.append(el); this.cur = { body: $(".body", el), raw: "", pending: false }; }
102
+ return this.cur;
103
+ }
104
+ paint(c) {
105
+ if (c.pending) return; c.pending = true;
106
+ requestAnimationFrame(() => { c.pending = false; c.body.innerHTML = TFmd.render(c.raw, S.compMap); this.scroll(); });
107
+ }
108
+ note(text, err) { this.ensure(); this.cur = null; const n = h(`<div class="note${err ? " err" : ""}"></div>`); n.textContent = text; this.el.append(n); this.scroll(); }
109
+ thinking(text) {
110
+ this.ensure();
111
+ if (!this.think) { const d = h('<details class="think"><summary><span class="spin"></span><span>Thinking</span></summary><div class="tx"></div></details>'); this.el.append(d); this.think = d; this.cur = null; }
112
+ $(".tx", this.think).textContent += text; this.scroll();
113
+ }
114
+ endThink() { if (this.think) { $(".spin", this.think)?.remove(); $("summary span:last-child", this.think).textContent = "Thought"; this.think = null; } }
115
+ toolSummary(input) {
116
+ const v = Object.values(input || {}).find((x) => typeof x === "string"); return v ? v.replace(/\s+/g, " ").slice(0, 120) : "";
117
+ }
118
+ toolCall(d) {
119
+ this.endThink(); this.cur = null; this.ensure();
120
+ const el = h(`<details class="tool"><summary><span class="st"><span class="spin"></span></span><span class="nm">${esc(d.name)}</span><span class="sm">${esc(this.toolSummary(d.input))}</span><i data-i="chev"></i></summary><div class="tb"><b>Input</b><div class="in"></div><b class="rb" hidden>Result</b><div class="out"></div></div></details>`);
121
+ $(".in", el).textContent = JSON.stringify(d.input, null, 2); this.el.append(el); this.tools.set(d.id, el); TFmd.hydrateIcons(el); this.scroll();
122
+ }
123
+ toolResult(d) {
124
+ const el = this.tools.get(d.id); if (!el) return;
125
+ el.classList.add(d.is_error ? "err" : "ok"); $(".st", el).innerHTML = `<i data-i="${d.is_error ? "x" : "check"}"></i>`; TFmd.hydrateIcons(el);
126
+ $(".rb", el).hidden = false; $(".out", el).textContent = String(d.content || "").slice(0, 6000);
127
+ }
128
+ todos(items) {
129
+ let box = this.el.querySelector(".todos"); if (!box) { box = h('<div class="todos"></div>'); this.el.append(box); }
130
+ box.innerHTML = (items || []).map((t) => `<div class="${t.status === "completed" ? "d" : ""}"><span>${t.status === "completed" ? "✓" : t.status === "in_progress" ? "▸" : "○"}</span><span>${esc(t.content || t.text || "")}</span></div>`).join("");
131
+ }
132
+ approval(f) {
133
+ this.endThink(); this.cur = null; this.ensure();
134
+ const args = JSON.stringify(f.arguments, null, 2);
135
+ const el = h(`<div class="card"><h4>${f.dangerous ? "Needs your approval (potentially destructive)" : "Needs your approval"}: <span class="mono">${esc(f.tool)}</span></h4><div class="small muted">${esc(f.summary || "")}</div><pre>${esc(args.length > 1500 ? args.slice(0, 1500) + "\n..." : args)}</pre><div class="opts"><button class="btn ok" data-s="once">Allow once</button><button class="btn" data-s="tool">Always allow this tool</button><button class="btn" data-s="auto">Switch to auto</button><button class="btn bad" data-s="no">No</button></div><div class="why" hidden><input class="input" placeholder="Tell the agent why, or what to do instead (optional)"><button class="btn bad">Deny</button></div></div>`);
136
+ const done = (label) => { $(".opts", el).remove(); $(".why", el)?.remove(); el.classList.add("done"); $("h4", el).append(" · " + label); };
137
+ $$(".opts button", el).forEach((b) => (b.onclick = () => {
138
+ const s = b.dataset.s;
139
+ if (s === "no") { $(".why", el).hidden = false; $(".why input", el).focus(); return; }
140
+ send({ type: "answer", id: f.id, value: { approved: true, scope: s } }); done(b.textContent);
141
+ }));
142
+ $(".why button", el).onclick = () => { send({ type: "answer", id: f.id, value: { approved: false, reason: $(".why input", el).value } }); done("Denied"); };
143
+ $(".why input", el).onkeydown = (e) => { if (e.key === "Enter") $(".why button", el).click(); };
144
+ this.el.append(el); this.scroll(true);
145
+ }
146
+ ask(f) {
147
+ this.endThink(); this.cur = null; this.ensure();
148
+ const opts = f.options && f.options.length ? f.options.map((o) => `<button class="btn">${esc(o)}</button>`).join("") : '<input class="input" placeholder="Your answer"><button class="btn accent">Answer</button>';
149
+ const el = h(`<div class="card"><h4>${esc(f.question)}</h4><div class="opts">${opts}</div></div>`);
150
+ const answer = (v) => { send({ type: "answer", id: f.id, value: v }); $(".opts", el).remove(); el.classList.add("done"); $("h4", el).append(" · " + v); };
151
+ $$("button", el).forEach((b) => (b.onclick = () => { const i = $("input", el); answer(i ? i.value : b.textContent); }));
152
+ this.el.append(el); this.scroll(true);
153
+ }
154
+ replay(items) {
155
+ this.clear(); if (!items.length) { this.showHello(); return; }
156
+ this.ensure();
157
+ for (const it of items) {
158
+ if (it.type === "text" && it.role === "user") this.addUser(it.text, it.index);
159
+ else if (it.type === "text") { const c = this.asst(); c.raw += (c.raw ? "\n\n" : "") + it.text; c.body.innerHTML = TFmd.render(c.raw, S.compMap); }
160
+ else if (it.type === "tool_call") this.toolCall({ id: it.id, name: it.name, input: it.input });
161
+ else if (it.type === "tool_result") this.toolResult({ id: it.id, content: it.content, is_error: it.is_error });
162
+ if (it.type !== "text" || it.role === "user") this.cur = it.type === "text" ? null : this.cur;
163
+ if (it.type === "tool_call") this.cur = null;
164
+ }
165
+ $$(".tool .spin", this.el).forEach((s) => s.remove()); this.cur = null; this.scroll(true);
166
+ }
167
+ setBusy(b) { this.busy = b; renderTabs(); if (S.active === this.id) refreshComposer(); }
168
+ handle(f) {
169
+ switch (f.type) {
170
+ case "user": this.suggest = []; renderSuggest(); this.addUser(f.text, f.index); this.setBusy(true); break;
171
+ case "event": return this.event(f);
172
+ case "show": this.note(f.text); break;
173
+ case "error": this.note(f.text, true); if (S.active === this.id || this.quick) toast(f.text, true); break;
174
+ case "clear": this.clear(); this.showHello(); break;
175
+ case "replay": this.replay(f.items); break;
176
+ case "approval": this.approval(f); break;
177
+ case "ask": this.ask(f); break;
178
+ case "review": this.review = f.files; if (S.active === this.id) { renderReviewBar(); renderChanges(); } break;
179
+ case "suggestions": this.suggest = f.items; if (S.active === this.id) renderSuggest(); break;
180
+ case "turn_end": this.info = f.tab_state; this.endThink(); this.cur = null; this.busy = false; this.review = f.tab_state.review; renderTabs(); if (S.active === this.id) { refreshComposer(); renderReviewBar(); renderChanges(); renderSuggest(); } break;
181
+ }
182
+ }
183
+ event(f) {
184
+ const d = f.data;
185
+ switch (f.kind) {
186
+ case "text": this.endThink(); { const c = this.asst(); c.raw += d; this.paint(c); } break;
187
+ case "thinking": this.thinking(String(d)); break;
188
+ case "tool_call": this.toolCall(d); break;
189
+ case "tool_result": this.toolResult(d); break;
190
+ case "todos": this.todos(d); break;
191
+ case "status": this.note(String(d)); break;
192
+ case "notice": this.note(d && d.message ? d.message : String(d)); break;
193
+ case "error": this.note(String(d), true); break;
194
+ case "usage": this.usage = d; if (S.active === this.id) refreshComposer(); break;
195
+ case "done": this.endThink(); break;
196
+ }
197
+ }
198
+ }
199
+
200
+ function addTab(info) {
201
+ const tab = new TabView(info); S.tabs.set(info.id, tab);
202
+ (tab.quick ? $("#qchat") : $("#chats")).append(tab.el); tab.el.hidden = true; return tab;
203
+ }
204
+ async function activate(id) {
205
+ S.active = id; S.tabs.forEach((t, k) => { if (!t.quick) t.el.hidden = k !== id; });
206
+ const t = S.tabs.get(id); renderTabs(); renderSuggest(); renderReviewBar(); renderChanges(); refreshComposer(); t.scroll(true);
207
+ $("#input").focus();
208
+ }
209
+ function renderTabs() {
210
+ const box = $("#tabs"); box.innerHTML = "";
211
+ S.tabs.forEach((t) => {
212
+ if (t.quick) return;
213
+ const el = h(`<div class="tab${t.id === S.active ? " on" : ""}" role="tab" tabindex="0">${t.busy ? '<span class="dot"></span>' : ""}<span class="t">${esc(t.title)}</span><button class="x" title="Close tab"><i data-i="x"></i></button></div>`);
214
+ el.onclick = () => activate(t.id);
215
+ el.onauxclick = (e) => { if (e.button === 1) closeTab(t.id); };
216
+ $(".x", el).onclick = (e) => { e.stopPropagation(); closeTab(t.id); };
217
+ box.append(el);
218
+ });
219
+ TFmd.hydrateIcons(box);
220
+ }
221
+ const closeTab = guard(async (id) => {
222
+ const r = await api(`/api/tabs/${id}`, { method: "DELETE" });
223
+ const t = S.tabs.get(id); t.el.remove(); S.tabs.delete(id); S.st = r;
224
+ if (S.active === id) { const next = [...S.tabs.values()].find((x) => !x.quick); await activate(next.id); } else renderTabs();
225
+ });
226
+ const newTab = guard(async () => {
227
+ const r = await api("/api/tabs", { method: "POST", body: {} }); S.st = r; const t = addTab(r.tab); await activate(t.id);
228
+ });
229
+
230
+ function tabState() { const t = S.tabs.get(S.active); return t ? t.info.status || {} : {}; }
231
+ function refreshComposer() {
232
+ const t = S.tabs.get(S.active); if (!t || !S.st) return;
233
+ const st = t.info.status || {};
234
+ const fill = (sel, opts, val, fmt) => { const el = $(sel); const html = opts.map((o) => `<option value="${esc(o.v)}"${o.v === val ? " selected" : ""}>${esc(o.l)}</option>`).join(""); if (el.dataset.h !== html) { el.innerHTML = html; el.dataset.h = html; } el.value = val; el.disabled = t.busy; };
235
+ fill("#mode", Object.keys(S.st.modes).map((m) => ({ v: m, l: m[0].toUpperCase() + m.slice(1) })), st.mode || "agent");
236
+ const ms = (S.models ? S.models.models.filter((m) => m.available || m.id === st.model) : []).map((m) => ({ v: m.id, l: m.label }));
237
+ if (st.model && !ms.find((m) => m.v === st.model)) ms.unshift({ v: st.model, l: st.model });
238
+ fill("#model", ms, st.model);
239
+ fill("#effort", S.st.efforts.map((e) => ({ v: e, l: "Effort: " + e })), st.effort || "medium");
240
+ fill("#approval", Object.keys(S.st.approvals).map((a) => ({ v: a, l: "Approve: " + a })), st.approval || "ask");
241
+ $("#approval").title = S.st.approvals[st.approval] || "Approvals"; $("#mode").title = S.st.modes[st.mode] || "Mode";
242
+ const send_ = $("#send"); send_.innerHTML = `<i data-i="${t.busy ? "stop" : "send"}"></i>`; TFmd.hydrateIcons(send_); send_.title = t.busy ? "Stop (Esc)" : "Send (Enter)";
243
+ const u = t.info.usage || {}; const tot = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0);
244
+ const k = (n) => (n >= 1000 ? (n / 1000).toFixed(1) + "k" : n);
245
+ $("#usage").textContent = tot || u.output_tokens ? `${k(tot)} in · ${k(u.output_tokens || 0)} out · context ${st.context_percent || 0}%` : "";
246
+ }
247
+ function renderSuggest() {
248
+ const t = S.tabs.get(S.active), box = $("#suggest"); box.innerHTML = "";
249
+ if (t) requestAnimationFrame(() => t.scroll(true));
250
+ if (!t || t.busy) return;
251
+ (t.suggest || []).forEach((s) => { const b = h(`<button class="sug">${esc(s.label)}</button>`); b.onclick = guard(async () => { if (s.mode && tabState().mode !== s.mode) { S.st = await api(`/api/tabs/${t.id}/settings`, { method: "POST", body: { mode: s.mode } }); await refreshTab(t); } submit(s.prompt); }); box.append(b); });
252
+ }
253
+ async function refreshTab(t) { const r = await api(`/api/tabs/${t.id}/history`); t.info = r.tab; refreshComposer(); renderTabs(); }
254
+ function renderReviewBar() {
255
+ const t = S.tabs.get(S.active), bar = $("#reviewbar"); const files = t && t.review;
256
+ $("#changes-n").hidden = !files; if (files) $("#changes-n").textContent = files.length;
257
+ if (!files) { bar.hidden = true; return; }
258
+ bar.hidden = false;
259
+ bar.innerHTML = `<i data-i="pencil"></i><span><b>${files.length} file${files.length > 1 ? "s" : ""} changed</b> <span class="muted">by the agent</span></span><span class="spacer"></span><button class="btn" data-a="rv">Review</button><button class="btn bad" data-a="rj"><i data-i="undo"></i>Reject</button><button class="btn accent" data-a="ac"><i data-i="check"></i>Accept</button>`;
260
+ TFmd.hydrateIcons(bar);
261
+ $('[data-a="rv"]', bar).onclick = () => { showPane("changes"); setView("right"); };
262
+ $('[data-a="ac"]', bar).onclick = () => accept(t);
263
+ $('[data-a="rj"]', bar).onclick = () => reject(t);
264
+ t.scroll(true);
265
+ }
266
+ const accept = guard(async (t) => { await api(`/api/review/${t.id}/accept`, { method: "POST" }); toast("Changes kept"); t.review = null; renderReviewBar(); renderChanges(); });
267
+ const reject = guard(async (t, paths) => {
268
+ const r = await api(`/api/review/${t.id}/reject`, { method: "POST", body: paths ? { paths } : {} });
269
+ toast(r.restored.length ? `Restored ${r.restored.length} file${r.restored.length > 1 ? "s" : ""}` : "Nothing restored");
270
+ if (r.conflicts.length) toast(`Left alone (you edited them since): ${r.conflicts.join(", ")}`, true);
271
+ refreshAfterRestore();
272
+ });
273
+ function refreshAfterRestore() { loadFiles(); loadGit(); Object.values(S.viewers).forEach((v) => v.load(true)); loadComponents(); if (S.editor.path) openEditor(S.editor.path, true); }
274
+
275
+ function submit(text) { const t = S.tabs.get(S.active); if (t) submitTo(t, text); }
276
+ function submitTo(t, text) {
277
+ text = (text || "").trim(); if (!text && !t.atts.length) return;
278
+ if (t.busy) { toast("This chat is still working. Stop it first, or open a new tab."); return; }
279
+ send({ type: "prompt", tab: t.id, text, attachments: t.atts.map((a) => a.id) });
280
+ t.atts = []; renderChips(t, "#chips"); t.setBusy(true);
281
+ }
282
+
283
+ // ---------------------------------------------------------------- composer
284
+ const input = $("#input");
285
+ function grow(el) { el.style.height = "auto"; el.style.height = Math.min(el.scrollHeight, 220) + "px"; }
286
+ input.addEventListener("input", () => { grow(input); picker(input, "#picker"); });
287
+ input.addEventListener("keydown", (e) => {
288
+ if (pickerKey(e)) return;
289
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); const t = S.tabs.get(S.active); if (!t.busy) { const v = input.value; input.value = ""; grow(input); submit(v); } }
290
+ if (e.key === "Escape") { const t = S.tabs.get(S.active); if (t.busy) send({ type: "cancel", tab: t.id }); }
291
+ });
292
+ $("#send").onclick = () => { const t = S.tabs.get(S.active); if (t.busy) return send({ type: "cancel", tab: t.id }); const v = input.value; input.value = ""; grow(input); submit(v); };
293
+ function mention(ref) { insertAtCaret(input, "@" + ref + " "); showPaneChat(); input.focus(); }
294
+ function showPaneChat() { setView("center"); }
295
+ function insertAtCaret(el, text) {
296
+ const s = el.selectionStart ?? el.value.length, pre = el.value.slice(0, s), post = el.value.slice(s);
297
+ const sp = pre && !/\s$/.test(pre) ? " " : ""; el.value = pre + sp + text + post; const p = (pre + sp + text).length; el.setSelectionRange(p, p); grow(el);
298
+ }
299
+
300
+ let pk = { items: [], i: 0, el: null, box: null, range: null };
301
+ async function picker(el, boxSel) {
302
+ const box = $(boxSel), s = el.selectionStart, before = el.value.slice(0, s);
303
+ let m = before.match(/(^|\s)@([\w./-]*)$/), kind = "@";
304
+ if (!m && /^\/[\w-]*$/.test(before)) { m = [before, "", before.slice(1)]; kind = "/"; }
305
+ if (!m) { box.hidden = true; pk.items = []; return; }
306
+ const q = m[2].toLowerCase(); let items = [];
307
+ if (kind === "@") {
308
+ items = S.comps.filter((c) => c.ref.toLowerCase().startsWith(q) || (q.length > 1 && (c.value || "").toLowerCase().includes(q))).slice(0, 9).map((c) => ({ ins: "@" + c.ref + " ", label: c.ref, sub: [c.value, c.footprint && c.footprint.split(":").pop()].filter(Boolean).join(" · "), tag: c.pcb && c.sch ? "board + schematic" : c.pcb ? "board" : "schematic" }));
309
+ if (q.length > 0 || !items.length) items = items.concat(S.files.filter((f) => (q.length < 3 ? f.path.split("/").pop().toLowerCase().startsWith(q) : f.path.toLowerCase().includes(q))).slice(0, 5).map((f) => ({ ins: "@" + f.path + " ", label: f.path.split("/").pop(), sub: f.path, tag: "file", file: true })));
310
+ } else {
311
+ if (!S.commands) { try { S.commands = (await api("/api/commands")).commands; } catch (e) { S.commands = []; } }
312
+ items = S.commands.filter((c) => c.name.slice(1).startsWith(q)).slice(0, 10).map((c) => ({ ins: c.name + " ", label: c.name, sub: c.summary, tag: "" }));
313
+ }
314
+ if (!items.length) { box.hidden = true; pk.items = []; return; }
315
+ pk = { items, i: 0, el, box, range: [s - m[2].length - (kind === "@" ? 1 : 1), s] };
316
+ drawPicker();
317
+ }
318
+ function drawPicker() {
319
+ pk.box.hidden = false; pk.box.innerHTML = pk.items.map((it, i) => `<div class="opt${i === pk.i ? " on" : ""}" data-i="${i}"><b class="${it.file ? "file" : ""}">${esc(it.label)}</b><span class="s">${esc(it.sub)}</span><span class="g">${esc(it.tag)}</span></div>`).join("");
320
+ $$(".opt", pk.box).forEach((o) => { o.onmousedown = (e) => { e.preventDefault(); pk.i = +o.dataset.i; pickIt(); }; });
321
+ $(".opt.on", pk.box)?.scrollIntoView({ block: "nearest" });
322
+ }
323
+ function pickIt() {
324
+ const it = pk.items[pk.i]; if (!it) return; const el = pk.el;
325
+ el.value = el.value.slice(0, pk.range[0]) + it.ins + el.value.slice(pk.range[1]); const p = pk.range[0] + it.ins.length; el.setSelectionRange(p, p); pk.box.hidden = true; pk.items = []; grow(el); el.focus();
326
+ }
327
+ function pickerKey(e) {
328
+ if (!pk.items.length || pk.box.hidden) return false;
329
+ if (e.key === "ArrowDown") { pk.i = (pk.i + 1) % pk.items.length; drawPicker(); }
330
+ else if (e.key === "ArrowUp") { pk.i = (pk.i - 1 + pk.items.length) % pk.items.length; drawPicker(); }
331
+ else if (e.key === "Enter" || e.key === "Tab") pickIt();
332
+ else if (e.key === "Escape") { pk.box.hidden = true; pk.items = []; }
333
+ else return false;
334
+ e.preventDefault(); return true;
335
+ }
336
+
337
+ // attachments
338
+ async function upload(t, file, chipsSel) {
339
+ const r = await api(`/api/tabs/${t.id}/upload?name=${encodeURIComponent(file.name || "pasted.png")}`, { method: "POST", body: file, raw: true });
340
+ t.atts.push({ id: r.id, name: r.name, kind: r.kind, url: r.kind === "image" ? URL.createObjectURL(file) : null }); renderChips(t, chipsSel);
341
+ }
342
+ function renderChips(t, sel) {
343
+ const box = $(sel); box.innerHTML = "";
344
+ t.atts.forEach((a) => { const c = h(`<span class="att">${a.url ? `<img src="${a.url}" alt="">` : '<i data-i="file"></i>'}<span>${esc(a.name)}</span><button title="Remove"><i data-i="x"></i></button></span>`); $("button", c).onclick = () => { api(`/api/tabs/${t.id}/upload/${a.id}`, { method: "DELETE" }).catch(() => {}); t.atts = t.atts.filter((x) => x !== a); renderChips(t, sel); }; box.append(c); });
345
+ TFmd.hydrateIcons(box);
346
+ }
347
+ const addFiles = guard(async (t, files, sel) => { for (const f of files) await upload(t, f, sel); });
348
+ $("#attach").onclick = () => $("#file").click();
349
+ $("#file").onchange = (e) => { addFiles(S.tabs.get(S.active), [...e.target.files], "#chips"); e.target.value = ""; };
350
+ function wirePaste(el, getTab, sel) {
351
+ el.addEventListener("paste", (e) => { const fs = [...(e.clipboardData?.files || [])]; if (fs.length) { e.preventDefault(); addFiles(getTab(), fs, sel); } });
352
+ }
353
+ wirePaste(input, () => S.tabs.get(S.active), "#chips");
354
+ ["dragenter", "dragover"].forEach((ev) => $("#center").addEventListener(ev, (e) => { if (e.dataTransfer?.types?.includes("Files")) { e.preventDefault(); $("#composer").classList.add("dragging"); } }));
355
+ ["dragleave", "drop"].forEach((ev) => $("#center").addEventListener(ev, (e) => { if (ev === "dragleave" && e.relatedTarget && $("#center").contains(e.relatedTarget)) return; $("#composer").classList.remove("dragging"); }));
356
+ $("#center").addEventListener("drop", (e) => { if (e.dataTransfer?.files?.length) { e.preventDefault(); addFiles(S.tabs.get(S.active), [...e.dataTransfer.files], "#chips"); } });
357
+ for (const [sel, key] of [["#mode", "mode"], ["#model", "model"], ["#effort", "effort"], ["#approval", "approval"]]) {
358
+ $(sel).onchange = guard(async (e) => {
359
+ const t = S.tabs.get(S.active), v = e.target.value;
360
+ if (key === "approval" && (v === "auto" || v === "yolo") && !(await confirmBox(v === "yolo" ? "Enable YOLO approvals?" : "Enable auto approvals?", v === "yolo" ? "Every change and command runs without asking, except destructive commands." : "File edits and simple commands run without asking. Anything chained, destructive or touching credentials still asks. You can review and reject every change afterwards.", "Enable"))) return refreshComposer();
361
+ S.st = await api(`/api/tabs/${t.id}/settings`, { method: "POST", body: { [key]: v } }); await refreshTab(t);
362
+ if (key === "mode") { t.showHello(); }
363
+ });
364
+ }
365
+
366
+ // -------------------------------------------------------------- quick chat
367
+ async function ensureQuick() {
368
+ if (S.quick) return S.quick;
369
+ const r = await api("/api/tabs", { method: "POST", body: { quick: true } }); S.st = r; S.quick = addTab(r.tab); S.quick.el.hidden = false; return S.quick;
370
+ }
371
+ const openQuick = guard(async (prompt) => {
372
+ const q = await ensureQuick(); $("#quick").hidden = false; TFmd.hydrateIcons($("#quick")); S.quick.el.hidden = false;
373
+ if (prompt) submitTo(q, prompt); else $("#qinput").focus();
374
+ });
375
+ const qinput = $("#qinput");
376
+ qinput.addEventListener("input", () => { grow(qinput); picker(qinput, "#picker2"); });
377
+ qinput.addEventListener("keydown", (e) => { if (pickerKey(e)) return; if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); qsend(); } if (e.key === "Escape") { if (S.quick?.busy) send({ type: "cancel", tab: S.quick.id }); else $("#quick").hidden = true; } });
378
+ function qsend() { const v = qinput.value; if (S.quick && !S.quick.busy) { qinput.value = ""; grow(qinput); submitTo(S.quick, v); renderChips(S.quick, "#qchips"); } }
379
+ $("#qsend").onclick = qsend; $("#quick-close").onclick = () => ($("#quick").hidden = true); $("#quick-btn").onclick = () => openQuick();
380
+ wirePaste(qinput, () => S.quick, "#qchips");
381
+ $("#qshot").onclick = guard(async () => {
382
+ const v = S.viewers[S.rightPane === "sch" ? "sch" : "pcb"]; const png = v && (await v.png());
383
+ if (!png) return toast("Nothing in the viewer to capture.", true);
384
+ await upload(S.quick, new File([png], "viewer.png", { type: "image/png" }), "#qchips");
385
+ });
386
+ $("#quick-expand").onclick = () => { const q = S.quick; if (!q) return; q.quick = false; $("#chats").append(q.el); S.quick = null; $("#quick").hidden = true; renderTabs(); activate(q.id); };
387
+ document.body.insertAdjacentHTML("beforeend", '<div id="picker2" hidden style="position:fixed;right:24px;bottom:96px;width:352px" class="" ></div>');
388
+ Object.assign($("#picker2").style, { background: "var(--raised)", border: "1px solid var(--line)", borderRadius: "12px", boxShadow: "var(--shadow)", maxHeight: "240px", overflow: "auto", zIndex: 45, padding: "4px" });
389
+
390
+ // ------------------------------------------------------------ palette (Ctrl+K)
391
+ const ACTIONS = [
392
+ ["Typical wiring diagram", "diagram", (r, v) => `Show the typical application wiring diagram for @${r} (${v}) as a text diagram plus a table of pin connections, then compare it with how @${r} is wired in this design and point out differences.`],
393
+ ["Datasheet summary", "file", (r, v) => `Summarize the datasheet of @${r} (${v}): key electrical limits, operating conditions, and the design constraints that matter for this board. Say which datasheet you used.`],
394
+ ["Pin functions", "chip", (r, v) => `List the pin functions of @${r} (${v}) as a table (pin, name, function, what it connects to in this design), and flag any pin that looks misused or left floating.`],
395
+ ["Find errata", "warn", (r, v) => `Find known errata and common design pitfalls for ${v} (@${r}), and check whether this design is affected by any of them.`],
396
+ ["Show alternatives", "swap", (r, v) => `Suggest pin- or footprint-compatible alternatives for @${r} (${v}), with trade-offs and part numbers I could verify for availability.`],
397
+ ["Explain its role here", "chat", (r, v) => `Explain what @${r} (${v}) does in this circuit, which nets it touches, and what would break if it were removed.`],
398
+ ["Check footprint and placement", "fit", (r, v) => `Check the footprint and placement of @${r} (${v}) on the board: footprint matches the part, decoupling and routing are sensible, and anything violating good layout practice.`],
399
+ ];
400
+ function openPalette() {
401
+ let ref = S.hovered || S.selected, q = "", i = 0, mode = ref ? "actions" : "pick";
402
+ const close = modal(`<input class="pal-in" id="pal-in" placeholder="" autocomplete="off"><div class="pal-target" id="pal-t"></div><div class="pal-list" id="pal-l"></div>`);
403
+ const inp = $("#pal-in");
404
+ const list = () => {
405
+ if (mode === "pick") {
406
+ const f = S.comps.filter((c) => !q || c.ref.toLowerCase().includes(q.toLowerCase().replace(/^@/, "")) || (c.value || "").toLowerCase().includes(q.toLowerCase())).slice(0, 30);
407
+ return f.map((c) => ({ label: c.ref, sub: c.value || "", tag: "select", run: () => { ref = c.ref; mode = "actions"; q = ""; inp.value = ""; draw(); } }));
408
+ }
409
+ const c = S.compMap.get(ref) || { value: "" }, v = c.value || ref;
410
+ const acts = ACTIONS.filter((a) => !q || a[0].toLowerCase().includes(q.toLowerCase())).map((a) => ({ label: a[0], sub: "", tag: "quick chat", run: () => { close(); openQuick(a[2](ref, v)); } }));
411
+ if (q.trim()) acts.push({ label: `Ask about ${ref}: ${q}`, sub: "", tag: "quick chat", run: () => { close(); openQuick(`About @${ref} (${v}): ${q}`); } });
412
+ return acts;
413
+ };
414
+ let items = [];
415
+ const draw = () => {
416
+ const c = ref && S.compMap.get(ref);
417
+ $("#pal-t").innerHTML = mode === "pick" ? "Choose a component, or select one in the board viewer first" : `<span>Component</span><b>${esc(ref)}</b><span>${esc(c ? c.value || "" : "")}</span><span class="spacer"></span><button class="btn" id="pal-ch">Change</button>`;
418
+ inp.placeholder = mode === "pick" ? "Search reference or value" : `What do you want to know about ${ref}?`;
419
+ items = list(); i = Math.min(i, Math.max(items.length - 1, 0));
420
+ $("#pal-l").innerHTML = items.map((it, k) => `<div class="opt${k === i ? " on" : ""}" data-k="${k}"><b>${esc(it.label)}</b><span class="s">${esc(it.sub)}</span><span class="g">${esc(it.tag)}</span></div>`).join("") || '<div class="empty">No matches</div>';
421
+ $$("#pal-l .opt").forEach((o) => (o.onclick = () => items[+o.dataset.k].run()));
422
+ $("#pal-ch")?.addEventListener("click", () => { mode = "pick"; q = ""; inp.value = ""; draw(); inp.focus(); });
423
+ };
424
+ inp.oninput = () => { q = inp.value; i = 0; draw(); };
425
+ inp.onkeydown = (e) => {
426
+ if (e.key === "ArrowDown") { i = Math.min(i + 1, items.length - 1); draw(); e.preventDefault(); }
427
+ else if (e.key === "ArrowUp") { i = Math.max(i - 1, 0); draw(); e.preventDefault(); }
428
+ else if (e.key === "Enter") { items[i] && items[i].run(); e.preventDefault(); }
429
+ else if (e.key === "Escape") close();
430
+ };
431
+ draw(); inp.focus();
432
+ }
433
+
434
+ // ---------------------------------------------------------------- selection
435
+ function select(ref) {
436
+ S.selected = ref || null; Object.values(S.viewers).forEach((v) => v.mark(S.selected));
437
+ if (ref) { const c = S.compMap.get(ref); if (c) { const vk = S.rightPane === "sch" ? (c.sch ? "sch" : "pcb") : c.pcb ? "pcb" : "sch"; if (!["pcb", "sch"].includes(S.rightPane) && false) showPane(vk); } }
438
+ }
439
+ async function loadComponents() {
440
+ try { S.comps = (await api("/api/components")).components; } catch (e) { S.comps = []; }
441
+ S.compMap = new Map(S.comps.map((c) => [c.ref, c]));
442
+ }
443
+
444
+ // ----------------------------------------------------------------- left panels
445
+ function setLeft(p) { S.leftPane = p; $$("#left-seg button").forEach((b) => b.classList.toggle("on", b.dataset.p === p)); renderLeft(); }
446
+ $$("#left-seg button").forEach((b) => (b.onclick = () => setLeft(b.dataset.p)));
447
+ function renderLeft() { ({ files: renderFiles, git: renderGit, history: renderHistory })[S.leftPane](); }
448
+ const loadFiles = guard(async () => { S.files = (await api("/api/files")).files; if (S.leftPane === "files") renderFiles(); });
449
+ function fileIcon(p) { return /\.kicad_pcb$/.test(p) ? "fit" : /\.kicad_sch$/.test(p) ? "chip" : "file"; }
450
+ function renderFiles() {
451
+ const body = $("#left-body"); const filter = body.querySelector("#ffilter")?.value || "";
452
+ body.innerHTML = `<div class="pad"><input class="input" id="ffilter" placeholder="Filter files" value="${esc(filter)}"></div><div class="tree" id="tree"></div>`;
453
+ const tree = $("#tree"); const q = filter.toLowerCase();
454
+ const root = { dirs: {}, files: [] };
455
+ S.files.filter((f) => !q || f.path.toLowerCase().includes(q)).forEach((f) => { const parts = f.path.split("/"); let n = root; parts.slice(0, -1).forEach((d) => (n = n.dirs[d] ||= { dirs: {}, files: [] })); n.files.push({ ...f, name: parts[parts.length - 1] }); });
456
+ const draw = (n, path, depth) => {
457
+ Object.keys(n.dirs).sort().forEach((d) => {
458
+ const p = path ? path + "/" + d : d, open = q || S.treeOpen.has(p);
459
+ const el = h(`<div class="node dir" style="padding-left:${8 + depth * 14}px"><i data-i="${open ? "folder" : "folder"}"></i><span>${esc(d)}</span></div>`); el.onclick = () => { open && !q ? S.treeOpen.delete(p) : S.treeOpen.add(p); renderFiles(); }; tree.append(el);
460
+ if (open) draw(n.dirs[d], p, depth + 1);
461
+ });
462
+ n.files.sort((a, b) => a.name.localeCompare(b.name)).forEach((f) => {
463
+ const el = h(`<div class="node${S.editor.path === f.path ? " on" : ""}" style="padding-left:${8 + depth * 14}px" title="${esc(f.path)}"><i data-i="${fileIcon(f.name)}"></i><span>${esc(f.name)}</span><span class="sz">${f.size > 1024 ? Math.round(f.size / 1024) + " KB" : f.size + " B"}</span></div>`);
464
+ el.onclick = () => openFileFromTree(f.path); el.ondblclick = () => { mention(f.path); }; tree.append(el);
465
+ });
466
+ };
467
+ draw(root, "", 0); TFmd.hydrateIcons(body);
468
+ if (!S.files.length) tree.innerHTML = '<div class="empty"><b>No files yet</b>The project folder is empty.</div>';
469
+ $("#ffilter").oninput = () => { const v = $("#ffilter").value; renderFiles(); const f = $("#ffilter"); f.focus(); f.setSelectionRange(v.length, v.length); };
470
+ }
471
+ function openFileFromTree(path) {
472
+ if (/\.kicad_pcb$/.test(path)) showPane("pcb"); else if (/\.kicad_sch$/.test(path)) showPane("sch"); else openEditor(path); setView("right");
473
+ }
474
+ const loadGit = guard(async () => { S.git = await api("/api/git/status"); if (S.leftPane === "git") renderGit(); });
475
+ function renderGit() {
476
+ const body = $("#left-body"), g = S.git;
477
+ if (!g) { body.innerHTML = '<div class="empty">Loading...</div>'; loadGit(); return; }
478
+ if (!g.repo) { body.innerHTML = '<div class="empty"><b>Not a git repository</b>Track your design history with git.<div style="margin-top:12px"><button class="btn accent" id="ginit">Initialize repository</button></div></div>'; $("#ginit").onclick = guard(async () => { S.git = await api("/api/git/init", { method: "POST", body: {} }); renderGit(); }); return; }
479
+ const staged = g.files.filter((f) => f.index), changes = g.files.filter((f) => f.worktree);
480
+ const row = (f, isStaged) => { const code = isStaged ? f.index : f.worktree; return `<div class="frow${S.gitSel && S.gitSel.path === f.path && S.gitSel.staged === isStaged ? " on" : ""}" data-p="${esc(f.path)}" data-s="${isStaged ? 1 : 0}"><span class="tag ${esc(code)}">${esc(code)}</span><span class="p" title="${esc(f.path)}"><bdi>${esc(f.path)}</bdi></span><button class="icon" data-a="t" title="${isStaged ? "Unstage" : "Stage"}"><i data-i="${isStaged ? "minus" : "plus"}"></i></button></div>`; };
481
+ body.innerHTML = `<div class="pad row"><i data-i="branch"></i><select id="gbranch" style="flex:1">${g.branches.map((b) => `<option${b === g.branch ? " selected" : ""}>${esc(b)}</option>`).join("")}</select><button class="btn" id="gnew" title="New branch">New</button></div>
482
+ <div class="gsec">Staged (${staged.length})${staged.length ? '<span class="spacer"></span><button class="btn" id="gunall">Unstage all</button>' : ""}</div><div>${staged.map((f) => row(f, true)).join("") || '<div class="muted small pad">Nothing staged.</div>'}</div>
483
+ <div class="gsec">Changes (${changes.length})${changes.length ? '<span class="spacer"></span><button class="btn" id="gall">Stage all</button>' : ""}</div><div>${changes.map((f) => row(f, false)).join("") || '<div class="muted small pad">Working tree clean.</div>'}</div>
484
+ <div class="pad commit"><textarea id="gmsg" rows="2" placeholder="Commit message"></textarea><div class="row" style="margin-top:6px"><button class="btn accent" id="gcommit"${staged.length ? "" : " disabled"}>Commit${staged.length ? ` ${staged.length} file${staged.length > 1 ? "s" : ""}` : ""}</button></div></div>
485
+ <div class="gsec">History</div>${g.log.map((c) => `<div class="hist"><div class="t"><span class="mono muted">${esc(c.hash)}</span> ${esc(c.subject)}</div><div class="s">${esc(c.author)} · ${esc(c.when)}</div></div>`).join("") || '<div class="muted small pad">No commits yet.</div>'}`;
486
+ TFmd.hydrateIcons(body);
487
+ $$(".frow", body).forEach((r) => {
488
+ const staged_ = r.dataset.s === "1", path = r.dataset.p;
489
+ r.onclick = (e) => { if (e.target.closest("[data-a]")) return; S.gitSel = { path, staged: staged_ }; showGitDiff(path, staged_); renderGit(); };
490
+ $('[data-a="t"]', r).onclick = guard(async () => { S.git = await api(`/api/git/${staged_ ? "unstage" : "stage"}`, { method: "POST", body: { paths: [path] } }); renderGit(); });
491
+ });
492
+ const bulk = (list, url) => guard(async () => { S.git = await api(url, { method: "POST", body: { paths: list.map((f) => f.path) } }); renderGit(); });
493
+ $("#gall") && ($("#gall").onclick = bulk(changes, "/api/git/stage")); $("#gunall") && ($("#gunall").onclick = bulk(staged, "/api/git/unstage"));
494
+ $("#gcommit").onclick = guard(async () => { S.git = await api("/api/git/commit", { method: "POST", body: { message: $("#gmsg").value } }); toast("Committed"); renderGit(); });
495
+ $("#gbranch").onchange = guard(async (e) => { S.git = await api("/api/git/branch", { method: "POST", body: { name: e.target.value } }); toast("Switched branch"); renderGit(); loadFiles(); });
496
+ $("#gnew").onclick = () => { const close = modal('<h3>New branch</h3><div class="sec"><input class="input" id="bn" placeholder="feature/name"></div><div class="foot"><button class="btn accent" id="bok">Create and switch</button></div>'); $("#bn").focus(); const go = guard(async () => { S.git = await api("/api/git/branch", { method: "POST", body: { name: $("#bn").value, create: true } }); close(); renderGit(); }); $("#bok").onclick = go; $("#bn").onkeydown = (e) => e.key === "Enter" && go(); };
497
+ }
498
+ const showGitDiff = guard(async (path, staged) => {
499
+ const r = await api(`/api/git/diff?path=${encodeURIComponent(path)}&staged=${staged ? "true" : "false"}`);
500
+ S.reviewSel = null; S.gitDiff = { path, text: r.diff, staged }; showPane("changes"); setView("right"); renderChanges();
501
+ });
502
+ const loadHistory = guard(async () => { S.threads = (await api("/api/threads")).threads; if (S.leftPane === "history") renderHistory(); });
503
+ function renderHistory() {
504
+ const body = $("#left-body"); if (!S.threads) { body.innerHTML = '<div class="empty">Loading...</div>'; loadHistory(); return; }
505
+ body.innerHTML = S.threads.map((t) => `<div class="hist" data-id="${esc(t.id)}"><div class="t">${esc(t.title || "Untitled")}</div><div class="s">${esc(t.ago)} · ${t.messages} messages · ${esc(t.mode)}</div></div>`).join("") || '<div class="empty"><b>No chats yet</b>Conversations about this project are saved here, on this computer.</div>';
506
+ $$(".hist", body).forEach((el) => (el.onclick = guard(async () => { const r = await api("/api/tabs", { method: "POST", body: { thread_id: el.dataset.id } }); S.st = r; const t = addTab(r.tab); const hst = await api(`/api/tabs/${t.id}/history`); t.replay(hst.items); t.info = hst.tab; await activate(t.id); setView("center"); })));
507
+ }
508
+
509
+ // ---------------------------------------------------------------- right panes
510
+ function showPane(p) {
511
+ S.rightPane = p; $$("#right-seg button").forEach((b) => b.classList.toggle("on", b.dataset.p === p)); $$("#right-body .pane").forEach((el) => (el.hidden = el.dataset.p !== p));
512
+ if (p === "pcb" || p === "sch") { S.viewers[p].load(); }
513
+ if (p === "changes") renderChanges(); if (p === "checks") renderChecks(); if (p === "editor") renderEditor();
514
+ }
515
+ $$("#right-seg button").forEach((b) => (b.onclick = () => showPane(b.dataset.p)));
516
+
517
+ let diffPZ = null;
518
+ const loadReviewDiff = guard(async (t, path) => {
519
+ const host = $("#dview"); if (!host) return; host.innerHTML = '<div class="empty">Loading...</div>';
520
+ const r = await api(`/api/review/${t.id}/diff?path=${encodeURIComponent(path)}`);
521
+ host.innerHTML = ""; diffPZ && diffPZ.destroy(); diffPZ = null;
522
+ if (r.kind === "binary") { host.innerHTML = '<div class="empty">Binary file changed.</div>'; return; }
523
+ if (r.visual) { r.visual.kind = r.kind; const vbox = h('<div style="display:flex;flex-direction:column;flex:1;min-height:260px"></div>'); host.append(vbox); diffPZ = TFview.visualDiff(vbox, r.visual); }
524
+ const det = h(`<details open><summary class="small muted" style="padding:8px 12px;cursor:pointer">Text diff</summary><div class="diff">${TFmd.diffHtml(r.diff)}</div></details>`); host.append(det);
525
+ });
526
+ function renderChanges() {
527
+ const pane = $('#right-body .pane[data-p="changes"]'); if (S.rightPane !== "changes" && pane.dataset.built) { /* keep DOM warm */ }
528
+ const t = S.tabs.get(S.active); const files = t && t.review;
529
+ pane.dataset.built = 1;
530
+ if (files && files.length) {
531
+ const sel = S.reviewSel && files.find((f) => f.path === S.reviewSel) ? S.reviewSel : files[0].path; const changed = S.reviewSel !== sel || !$("#dview"); S.reviewSel = sel;
532
+ pane.innerHTML = `<div class="vbar"><b>${files.length} changed file${files.length > 1 ? "s" : ""}</b><span class="muted small">by the agent</span><span class="spacer"></span><button class="btn bad" id="rj-all"><i data-i="undo"></i>Reject all</button><button class="btn accent" id="ac-all"><i data-i="check"></i>Accept all</button></div><div class="flist">${files.map((f) => `<div class="frow${f.path === sel ? " on" : ""}" data-p="${esc(f.path)}"><span class="tag ${f.status[0].toUpperCase()}">${f.status[0].toUpperCase()}</span><span class="p" title="${esc(f.path)}"><bdi>${esc(f.path)}</bdi></span><button class="btn" data-a="rj" title="Restore just this file">Reject</button></div>`).join("")}</div><div class="dview" id="dview"></div>`;
533
+ TFmd.hydrateIcons(pane);
534
+ $("#ac-all").onclick = () => accept(t); $("#rj-all").onclick = () => reject(t);
535
+ $$(".frow", pane).forEach((r) => { r.onclick = (e) => { if (e.target.closest("[data-a]")) { reject(t, [r.dataset.p]); return; } S.reviewSel = r.dataset.p; renderChanges(); }; });
536
+ loadReviewDiff(t, sel);
537
+ return;
538
+ }
539
+ if (S.gitDiff) {
540
+ pane.innerHTML = `<div class="vbar"><b>${esc(S.gitDiff.path)}</b><span class="muted small">${S.gitDiff.staged ? "staged" : "working tree"} vs HEAD</span></div><div class="dview"><div class="diff">${TFmd.diffHtml(S.gitDiff.text)}</div></div>`; return;
541
+ }
542
+ pane.innerHTML = '<div class="empty"><b>No pending changes</b>When the agent edits files, you review them here, with before and after renders of the board and schematic, then accept or reject.</div>';
543
+ }
544
+
545
+ async function runChecks(parts) {
546
+ const pane = $('#right-body .pane[data-p="checks"]'); $("#chk-list", pane).innerHTML = '<div class="empty"><span class="spin"></span> Running ERC, DRC and built-in checks...</div>';
547
+ try { S.checks = await api("/api/check", { method: "POST", body: { parts } }); } catch (e) { S.checks = { findings: [], counts: {}, message: e.message }; }
548
+ renderChecks();
549
+ }
550
+ function renderChecks() {
551
+ const pane = $('#right-body .pane[data-p="checks"]'), c = S.checks;
552
+ if (!$("#chk-list", pane)) pane.innerHTML = '<div class="vbar"><b>Checks</b><span class="counts" id="chk-c"></span><span class="spacer"></span><label class="small muted row"><input type="checkbox" id="chk-parts"> Verify parts (network)</label><button class="btn" id="chk-spec" title="Engineering design specification: stackup, rules, current capacity, placement angles">Spec sheet</button><button class="btn accent" id="chk-run">Run checks</button></div><div class="dview" id="chk-list"></div>';
553
+ $("#chk-run").onclick = () => runChecks($("#chk-parts").checked);
554
+ $("#chk-spec").onclick = guard(async () => {
555
+ const r = await api("/api/spec-sheet?format=html");
556
+ if (!r.available) { toast(r.message || "No board yet", true); return; }
557
+ window.open(URL.createObjectURL(new Blob([r.content], { type: "text/html" })), "_blank");
558
+ });
559
+ const list = $("#chk-list", pane);
560
+ if (!c) { list.innerHTML = '<div class="empty"><b>No results yet</b>Run ERC, DRC and design-rule checks on the project. Nothing is changed.</div>'; return; }
561
+ $("#chk-c").innerHTML = ["error", "warning", "info"].filter((k) => c.counts && c.counts[k]).map((k) => `<span class="pill ${k}">${c.counts[k]} ${k}</span>`).join("");
562
+ if (!c.findings.length) { list.innerHTML = `<div class="empty"><b>${esc(c.message || "No findings")}</b>${c.message ? "" : "All checks passed."}</div>`; return; }
563
+ list.innerHTML = c.findings.map((f, i) => `<div class="finding"><span class="sev ${f.severity}"></span><div style="min-width:0"><div>${esc(f.message)}</div><div class="chk">${esc(f.check)}${f.rank ? " · " + esc(f.rank) : ""} · ${esc(f.source)}</div>${f.evidence && f.evidence.length < 260 ? `<div class="small muted">${esc(f.evidence)}</div>` : ""}<div class="refs">${(f.refs || []).map((r) => `<span class="mention" data-ref="${esc(r)}">${esc(r)}</span>`).join("")}</div></div><button class="btn fix" data-i="${i}">Ask agent</button></div>`).join("");
564
+ $$(".mention", list).forEach((m) => (m.onclick = () => { showPane(S.compMap.get(m.dataset.ref)?.pcb ? "pcb" : "sch"); select(m.dataset.ref); }));
565
+ $$(".fix", list).forEach((b) => (b.onclick = () => { const f = c.findings[+b.dataset.i]; setView("center"); input.value = `Look at this check finding and fix it if it is a real problem (${f.check}): ${f.message}${f.refs?.length ? " Affects: " + f.refs.map((r) => "@" + r).join(", ") : ""}`; grow(input); input.focus(); }));
566
+ }
567
+
568
+ // editor
569
+ const openEditor = guard(async (path, quiet) => {
570
+ if (S.editor.dirty && !quiet && S.editor.path !== path && !(await confirmBox("Discard unsaved edits?", `${S.editor.path} has unsaved changes.`, "Discard"))) return;
571
+ const r = await api("/api/file?path=" + encodeURIComponent(path)).catch((e) => { toast(e.message, true); return null; });
572
+ if (!r) return;
573
+ S.editor = { path, mtime: r.mtime, dirty: false, text: r.content }; if (!quiet) showPane("editor"); else renderEditor(); if (S.leftPane === "files") renderFiles();
574
+ });
575
+ function renderEditor() {
576
+ const pane = $('#right-body .pane[data-p="editor"]'), e = S.editor;
577
+ if (!e.path) { pane.innerHTML = '<div class="empty"><b>No file open</b>Pick a file in the Files list to view and edit it: firmware, the YAML spec, notes.</div>'; return; }
578
+ pane.innerHTML = `<div class="vbar"><b>${esc(e.path)}</b><span class="muted small" id="e-d"></span><span class="spacer"></span><button class="btn" id="e-re">Reload</button><button class="btn accent" id="e-save">Save <kbd>Ctrl S</kbd></button></div><div class="ed"><pre id="editor-hl" aria-hidden="true"><code></code></pre><textarea id="editor-ta" spellcheck="false" wrap="off"></textarea></div>`;
579
+ const ta = $("#editor-ta"), hl = $("#editor-hl"), lang = window.TFhl.langFor(e.path);
580
+ ta.value = e.text; const dirty = () => { $("#e-d").textContent = e.dirty ? "unsaved changes" : ""; };
581
+ // highlighted copy under a transparent textarea; very large files stay plain to keep typing fast
582
+ const big = e.text.length > 600000, paint = () => { hl.firstChild.innerHTML = (big ? window.TFhl.highlight(ta.value, null) : window.TFhl.highlight(ta.value, lang)) + "\n"; hl.dataset.lang = big ? "" : lang || ""; };
583
+ let raf = 0; const repaint = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(paint); };
584
+ ta.onscroll = () => { hl.scrollTop = ta.scrollTop; hl.scrollLeft = ta.scrollLeft; }; paint();
585
+ $("#e-d").title = big ? "Large file: syntax colours are off" : lang ? "Syntax: " + lang : "";
586
+ ta.oninput = () => { e.dirty = true; e.text = ta.value; dirty(); repaint(); };
587
+ ta.onkeydown = (ev) => { if (ev.key === "Tab" && !ev.shiftKey) { ev.preventDefault(); document.execCommand("insertText", false, " "); } };
588
+ $("#e-save").onclick = saveEditor; $("#e-re").onclick = () => openEditor(e.path, true); dirty();
589
+ }
590
+ const saveEditor = guard(async () => {
591
+ const e = S.editor; if (!e.path) return;
592
+ try { const r = await api("/api/file", { method: "PUT", body: { path: e.path, content: $("#editor-ta").value, mtime: e.mtime } }); e.mtime = r.mtime; e.dirty = false; $("#e-d").textContent = "saved"; setTimeout(() => ($("#e-d") && (e.dirty ? 0 : ($("#e-d").textContent = ""))), 1500); loadGit(); }
593
+ catch (err) { if (/changed on disk/.test(err.message) && (await confirmBox("File changed on disk", "It was modified since you opened it (probably by the agent). Overwrite it with your version?", "Overwrite"))) { const r = await api("/api/file", { method: "PUT", body: { path: e.path, content: $("#editor-ta").value } }); e.mtime = r.mtime; e.dirty = false; renderEditor(); } else throw err; }
594
+ });
595
+
596
+ // file watching
597
+ let fcTimer = null;
598
+ function onFilesChanged(kicad) {
599
+ clearTimeout(fcTimer);
600
+ fcTimer = setTimeout(() => {
601
+ loadFiles(); loadGit();
602
+ if (kicad) { Object.values(S.viewers).forEach((v) => v.load()); loadComponents(); }
603
+ if (S.editor.path && !S.editor.dirty) openEditor(S.editor.path, true);
604
+ }, 250);
605
+ }
606
+
607
+ // ------------------------------------------------------------------ modals
608
+ function openSettings() {
609
+ api("/api/settings").then((s) => {
610
+ const keyRow = (n, label) => `<label>${label}${s.keys[n] ? ` <span class="tag">set · ${esc(s.keys[n] === "environment" ? "environment" : s.keys[n].includes("/") ? "~/.config/traceforge/.env" : s.keys[n])}</span>` : ""}</label><div class="row"><input class="input" type="password" data-k="${n}" placeholder="${s.keys[n] ? "Replace key" : "Paste key"}" autocomplete="off"><button class="btn" data-save="${n}">Save</button></div>`;
611
+ const close = modal(`<h3>Settings</h3><div class="sec">
612
+ <label>Model provider</label><select id="s-prov" class="input">${["auto", "anthropic", "openai", "gemini"].map((p) => `<option${p === s.provider ? " selected" : ""}>${p}</option>`).join("")}</select>
613
+ ${keyRow("ANTHROPIC_API_KEY", "Anthropic API key")}${keyRow("OPENAI_API_KEY", "OpenAI API key")}${keyRow("GEMINI_API_KEY", "Gemini API key")}
614
+ <div class="small muted" style="margin-top:6px">Keys are stored in ${s.keychain ? "your operating system keychain" : "~/.config/traceforge/.env (mode 600)"} and are never sent back to this page.</div>
615
+ <label>Fab profile (design rules for checks)</label><select id="s-fab" class="input">${s.fabs.map((f) => `<option${f === s.fab ? " selected" : ""}>${f}</option>`).join("")}</select>
616
+ <label>Appearance</label><select id="s-theme" class="input"><option value="dark">Dark</option><option value="light">Light</option></select>
617
+ <label>Updates</label><div class="row"><span class="small muted" id="s-upd">Checked only when you ask; nothing is downloaded.</span><button class="btn" id="s-upd-btn">Check now</button></div>
618
+ <label>Shortcuts</label><div class="small muted" style="line-height:1.9"><kbd>Ctrl/Cmd K</kbd> component actions · <kbd>Ctrl/Cmd Shift Space</kbd> quick chat · <kbd>Ctrl/Cmd T</kbd> new tab · <kbd>@</kbd> mention a part · <kbd>/</kbd> commands · <kbd>Esc</kbd> stop · <kbd>Ctrl/Cmd S</kbd> save file · <kbd>Alt 1-5</kbd> viewer panes</div>
619
+ </div><div class="foot"><button class="btn accent" id="s-done">Done</button></div>`);
620
+ $("#s-theme").value = document.documentElement.dataset.theme; $("#s-theme").onchange = (e) => setTheme(e.target.value);
621
+ $("#s-prov").onchange = guard(async (e) => { await api("/api/settings/prefs", { method: "POST", body: { provider: e.target.value } }); toast("Provider saved"); });
622
+ $("#s-fab").onchange = guard(async (e) => { await api("/api/settings/prefs", { method: "POST", body: { fab: e.target.value } }); toast("Fab profile saved"); });
623
+ $$("[data-save]").forEach((b) => (b.onclick = guard(async () => { const inp = $(`[data-k="${b.dataset.save}"]`); if (!inp.value.trim()) return; const r = await api("/api/settings/key", { method: "POST", body: { name: b.dataset.save, value: inp.value.trim() } }); inp.value = ""; toast("Saved to " + (r.stored_in === "keychain" ? "keychain" : "~/.config/traceforge/.env")); S.models = await api("/api/models"); refreshComposer(); })));
624
+ $("#s-upd-btn").onclick = guard(async () => { $("#s-upd").textContent = "Checking..."; const u = await api("/api/update"); $("#s-upd").textContent = u.message; });
625
+ $("#s-done").onclick = close;
626
+ }).catch((e) => toast(e.message, true));
627
+ }
628
+ function openProject() {
629
+ const state = { path: "" };
630
+ const draw = async (path) => {
631
+ let b; try { b = await api("/api/browse?path=" + encodeURIComponent(path || "")); } catch (e) { toast(e.message, true); return; }
632
+ state.path = b.path;
633
+ const recent = (S.st.recent || []).map((p) => `<div class="opt" data-open="${esc(p)}"><b>${esc(p.split("/").filter(Boolean).pop() || p)}</b><span class="s">${esc(p)}</span></div>`).join("");
634
+ $("#sheet").innerHTML = `<h3>Open a project folder</h3><div class="sec">${recent ? `<label>Recent</label>${recent}` : ""}<label>Browse</label><div class="crumbs">${esc(b.path)}</div><div style="max-height:34vh;overflow:auto;border:1px solid var(--line);border-radius:10px;padding:4px"><div class="opt" data-go="${esc(b.parent)}"><b>..</b><span class="s">parent folder</span></div>${b.dirs.map((d) => `<div class="opt" data-go="${esc(b.path.replace(/\/$/, "") + "/" + d)}"><i data-i="folder"></i><span>${esc(d)}</span></div>`).join("")}</div></div><div class="foot"><span class="muted small" style="margin-right:auto">${b.project ? "KiCad project found here" : "No KiCad project in this folder"}</span>${S.st.root ? '<button class="btn" id="p-x">Cancel</button>' : ""}<button class="btn accent" id="p-ok">Open this folder</button></div>`;
635
+ TFmd.hydrateIcons($("#sheet"));
636
+ $$("[data-go]").forEach((o) => (o.onclick = () => draw(o.dataset.go))); $$("[data-open]").forEach((o) => (o.onclick = () => openPath(o.dataset.open)));
637
+ $("#p-ok").onclick = () => openPath(state.path); $("#p-x")?.addEventListener("click", () => ($("#modal").hidden = true));
638
+ };
639
+ modal("", null); $("#modal").onmousedown = null; draw(S.st.root || "");
640
+ if (window.pywebview && window.pywebview.api && window.pywebview.api.pick_folder) window.pywebview.api.pick_folder().then((p) => p && openPath(p));
641
+ }
642
+ const openPath = guard(async (path) => { await api("/api/workspace", { method: "POST", body: { path } }); location.reload(); });
643
+ $("#project-btn").onclick = openProject;
644
+
645
+ function setTheme(t) { document.documentElement.dataset.theme = t; try { localStorage.setItem("tf-theme", t); } catch (e) { /* private mode */ } $("#theme-btn").innerHTML = `<i data-i="${t === "dark" ? "sun" : "moon"}"></i>`; TFmd.hydrateIcons($("#theme-btn")); }
646
+ $("#theme-btn").onclick = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark");
647
+ $("#settings-btn").onclick = openSettings; $("#palette-btn").onclick = openPalette; $("#newtab").onclick = newTab;
648
+ function setView(v) { $("#app").dataset.view = v; $$("#bottomnav button").forEach((b) => b.classList.toggle("on", b.dataset.v === v)); }
649
+ $$("#bottomnav button").forEach((b) => (b.onclick = () => setView(b.dataset.v)));
650
+
651
+ document.addEventListener("keydown", (e) => {
652
+ const mod = e.ctrlKey || e.metaKey;
653
+ if (mod && e.key.toLowerCase() === "k") { e.preventDefault(); modalOpen() ? ($("#modal").hidden = true) : openPalette(); }
654
+ else if (mod && e.shiftKey && (e.code === "Space" || e.key.toLowerCase() === "q")) { e.preventDefault(); $("#quick").hidden ? openQuick() : ($("#quick").hidden = true); }
655
+ else if (mod && e.key.toLowerCase() === "t" && !e.shiftKey) { e.preventDefault(); newTab(); }
656
+ else if (mod && e.key.toLowerCase() === "s" && S.rightPane === "editor") { e.preventDefault(); saveEditor(); }
657
+ else if (mod && e.key === "/") { e.preventDefault(); input.focus(); }
658
+ else if (e.altKey && /^[1-5]$/.test(e.key)) { e.preventDefault(); showPane(["pcb", "sch", "changes", "checks", "editor"][+e.key - 1]); }
659
+ else if (e.key === "Escape") { if (modalOpen()) $("#modal").hidden = true; else if (!$("#quick").hidden && document.activeElement !== qinput) $("#quick").hidden = true; }
660
+ });
661
+
662
+ // -------------------------------------------------------------------- boot
663
+ async function boot() {
664
+ TFmd.hydrateIcons(); setTheme(document.documentElement.dataset.theme || "dark");
665
+ S.viewers.pcb = new TFview.Viewer($('#right-body .pane[data-p="pcb"]'), "pcb", { api, select, mention, openPalette, edit: (p) => openEditor(p), get selected() { return S.selected; }, get compMap() { return S.compMap; }, set hovered(v) { S.hover = v; }, get hovered() { return S.hover; } });
666
+ S.viewers.sch = new TFview.Viewer($('#right-body .pane[data-p="sch"]'), "sch", S.viewers.pcb.app);
667
+ S.st = await api("/api/state");
668
+ if (!S.st.root) { openProject(); connect(); return; }
669
+ const quickOnly = new URLSearchParams(location.search).get("quick") === "1";
670
+ $("#project-name").textContent = S.st.name; document.title = S.st.name + " · Traceforge";
671
+ connect();
672
+ api("/api/models").then((m) => { S.models = m; refreshComposer(); }).catch(() => {});
673
+ await loadComponents();
674
+ S.st.tabs.forEach((i) => { addTab(i); });
675
+ const first = S.st.tabs.find((t) => !t.quick); await activate(first.id);
676
+ renderTabs(); loadFiles(); loadGit(); showPane(S.st.has_pcb || !S.st.has_sch ? "pcb" : "sch");
677
+ if (quickOnly) { document.body.classList.add("quick-only"); openQuick(); }
678
+ if (S.st.altium.length) toast("Altium files found (" + S.st.altium[0] + "). Traceforge reads KiCad projects; convert the design to KiCad to use it.");
679
+ }
680
+ TabView.prototype.replayInto = TabView.prototype.replay;
681
+ boot().catch((e) => toast(e.message, true));
682
+ window.TF = S;
683
+ })();