@spencerboucher/switchyard 0.8.0 → 0.9.0

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 (149) hide show
  1. package/README.md +3 -3
  2. package/dist/bridge/lines.js +33 -0
  3. package/dist/bridge/switchyard-terminal.js +59 -22
  4. package/dist/switchyard.mjs +3411 -2527
  5. package/dist/terminal/holder.js +142 -51
  6. package/package.json +1 -1
  7. package/web-dist/apple-touch-icon.png +0 -0
  8. package/web-dist/assets/AutomationView-D7Syv1En.js +2 -0
  9. package/web-dist/assets/AutomationView-D7Syv1En.js.map +1 -0
  10. package/web-dist/assets/Checkbox-D6tRfEeI.js +2 -0
  11. package/web-dist/assets/Checkbox-D6tRfEeI.js.map +1 -0
  12. package/web-dist/assets/Copy-B6XSAIUd.js +2 -0
  13. package/web-dist/assets/Copy-B6XSAIUd.js.map +1 -0
  14. package/web-dist/assets/DangerZone-DfYlxDC1.js +2 -0
  15. package/web-dist/assets/DangerZone-DfYlxDC1.js.map +1 -0
  16. package/web-dist/assets/Field-D-Ty7fKT.js +2 -0
  17. package/web-dist/assets/Field-D-Ty7fKT.js.map +1 -0
  18. package/web-dist/assets/InteractionCard-DF1EcSpm.js +6 -0
  19. package/web-dist/assets/InteractionCard-DF1EcSpm.js.map +1 -0
  20. package/web-dist/assets/Menu-BfOszNC4.js +2 -0
  21. package/web-dist/assets/Menu-BfOszNC4.js.map +1 -0
  22. package/web-dist/assets/Overlay-DUQwh6_b.js +2 -0
  23. package/web-dist/assets/Overlay-DUQwh6_b.js.map +1 -0
  24. package/web-dist/assets/Priority-CHmzfoHg.js +2 -0
  25. package/web-dist/assets/Priority-CHmzfoHg.js.map +1 -0
  26. package/web-dist/assets/{SegmentedControl-BZPzNU08.js → SegmentedControl-C_hEVQMB.js} +2 -2
  27. package/web-dist/assets/{SegmentedControl-BZPzNU08.js.map → SegmentedControl-C_hEVQMB.js.map} +1 -1
  28. package/web-dist/assets/Select-Cfql4Nwu.js +2 -0
  29. package/web-dist/assets/Select-Cfql4Nwu.js.map +1 -0
  30. package/web-dist/assets/Switch-DBfzmqkm.js +2 -0
  31. package/web-dist/assets/Switch-DBfzmqkm.js.map +1 -0
  32. package/web-dist/assets/Tabs-BNuL3_Et.js +184 -0
  33. package/web-dist/assets/Tabs-BNuL3_Et.js.map +1 -0
  34. package/web-dist/assets/TextArea-CKybrQyn.js +2 -0
  35. package/web-dist/assets/TextArea-CKybrQyn.js.map +1 -0
  36. package/web-dist/assets/TextLink-OzzyP2-p.js +2 -0
  37. package/web-dist/assets/TextLink-OzzyP2-p.js.map +1 -0
  38. package/web-dist/assets/arrow-down-C-iLrN8I.js +2 -0
  39. package/web-dist/assets/arrow-down-C-iLrN8I.js.map +1 -0
  40. package/web-dist/assets/arrow-up-Dj-VTKx4.js +2 -0
  41. package/web-dist/assets/arrow-up-Dj-VTKx4.js.map +1 -0
  42. package/web-dist/assets/attention-V86Gye3I.js +2 -0
  43. package/web-dist/assets/attention-V86Gye3I.js.map +1 -0
  44. package/web-dist/assets/automations-Cw5Gacgm.js +2 -0
  45. package/web-dist/assets/automations-Cw5Gacgm.js.map +1 -0
  46. package/web-dist/assets/board-B8X7TYYR.js +10 -0
  47. package/web-dist/assets/board-B8X7TYYR.js.map +1 -0
  48. package/web-dist/assets/code-BKroYJmR.js +12 -0
  49. package/web-dist/assets/code-BKroYJmR.js.map +1 -0
  50. package/web-dist/assets/describe-D6KLGKWa.js +5 -0
  51. package/web-dist/assets/describe-D6KLGKWa.js.map +1 -0
  52. package/web-dist/assets/enroll-DwT7AcuS.js +2 -0
  53. package/web-dist/assets/enroll-DwT7AcuS.js.map +1 -0
  54. package/web-dist/assets/index-B3F7WcYf.css +2 -0
  55. package/web-dist/assets/index-hxvDvCS7.js +12 -0
  56. package/web-dist/assets/index-hxvDvCS7.js.map +1 -0
  57. package/web-dist/assets/logic-B46fwD-8.js +2 -0
  58. package/web-dist/assets/logic-B46fwD-8.js.map +1 -0
  59. package/web-dist/assets/more-DQR5uu1c.js +2 -0
  60. package/web-dist/assets/more-DQR5uu1c.js.map +1 -0
  61. package/web-dist/assets/queue-DUg1rS8t.js +2 -0
  62. package/web-dist/assets/queue-DUg1rS8t.js.map +1 -0
  63. package/web-dist/assets/repo-XzzzEI0d.js +2 -0
  64. package/web-dist/assets/repo-XzzzEI0d.js.map +1 -0
  65. package/web-dist/assets/server-BqZ-w6M8.js +2 -0
  66. package/web-dist/assets/server-BqZ-w6M8.js.map +1 -0
  67. package/web-dist/assets/settings-DyUu0tJM.js +8 -0
  68. package/web-dist/assets/settings-DyUu0tJM.js.map +1 -0
  69. package/web-dist/assets/states-ZhrxQa3K.js +56 -0
  70. package/web-dist/assets/states-ZhrxQa3K.js.map +1 -0
  71. package/web-dist/assets/terminal-BOV_MXPZ.js +2 -0
  72. package/web-dist/assets/terminal-BOV_MXPZ.js.map +1 -0
  73. package/web-dist/assets/terminal-login-S5CAd5xA.js +2 -0
  74. package/web-dist/assets/terminal-login-S5CAd5xA.js.map +1 -0
  75. package/web-dist/assets/useBackTo-BIrCq3W2.js +2 -0
  76. package/web-dist/assets/useBackTo-BIrCq3W2.js.map +1 -0
  77. package/web-dist/assets/useNow-Dj7oEiwn.js +2 -0
  78. package/web-dist/assets/useNow-Dj7oEiwn.js.map +1 -0
  79. package/web-dist/assets/useResource-CDGSq2At.js +2 -0
  80. package/web-dist/assets/useResource-CDGSq2At.js.map +1 -0
  81. package/web-dist/icon-192.png +0 -0
  82. package/web-dist/icon-512.png +0 -0
  83. package/web-dist/icon.svg +20 -8
  84. package/web-dist/index.html +3 -4
  85. package/web-dist/manifest.webmanifest +1 -1
  86. package/web-dist/maskable-512.png +0 -0
  87. package/web-dist/sw.js +1 -1
  88. package/web-dist/sw.js.map +1 -1
  89. package/web-dist/assets/AutomationView-GCthHkym.js +0 -2
  90. package/web-dist/assets/AutomationView-GCthHkym.js.map +0 -1
  91. package/web-dist/assets/Badge-CEMI3YyI.js +0 -2
  92. package/web-dist/assets/Badge-CEMI3YyI.js.map +0 -1
  93. package/web-dist/assets/InteractionCard-DaLqafmA.js +0 -6
  94. package/web-dist/assets/InteractionCard-DaLqafmA.js.map +0 -1
  95. package/web-dist/assets/Menu-BcKiEc6X.js +0 -2
  96. package/web-dist/assets/Menu-BcKiEc6X.js.map +0 -1
  97. package/web-dist/assets/Tabs-COH5EMql.js +0 -184
  98. package/web-dist/assets/Tabs-COH5EMql.js.map +0 -1
  99. package/web-dist/assets/TextArea-CeMEPZn4.js +0 -2
  100. package/web-dist/assets/TextArea-CeMEPZn4.js.map +0 -1
  101. package/web-dist/assets/arrow-left-C6YWM6y6.js +0 -2
  102. package/web-dist/assets/arrow-left-C6YWM6y6.js.map +0 -1
  103. package/web-dist/assets/attention-BAdea2kA.js +0 -2
  104. package/web-dist/assets/attention-BAdea2kA.js.map +0 -1
  105. package/web-dist/assets/automations-DSFUzB0w.js +0 -2
  106. package/web-dist/assets/automations-DSFUzB0w.js.map +0 -1
  107. package/web-dist/assets/board-eQ3H8yCp.js +0 -10
  108. package/web-dist/assets/board-eQ3H8yCp.js.map +0 -1
  109. package/web-dist/assets/code-D7JmYMKe.js +0 -13
  110. package/web-dist/assets/code-D7JmYMKe.js.map +0 -1
  111. package/web-dist/assets/copy-oWgGHmkS.js +0 -2
  112. package/web-dist/assets/copy-oWgGHmkS.js.map +0 -1
  113. package/web-dist/assets/describe-C1YimBXJ.js +0 -5
  114. package/web-dist/assets/describe-C1YimBXJ.js.map +0 -1
  115. package/web-dist/assets/dist-B_RpNOcK.js +0 -56
  116. package/web-dist/assets/dist-B_RpNOcK.js.map +0 -1
  117. package/web-dist/assets/enroll-1OCy5r50.js +0 -2
  118. package/web-dist/assets/enroll-1OCy5r50.js.map +0 -1
  119. package/web-dist/assets/index-BhpEXLav.js +0 -11
  120. package/web-dist/assets/index-BhpEXLav.js.map +0 -1
  121. package/web-dist/assets/index-DUeOwDZ6.css +0 -2
  122. package/web-dist/assets/logic-CBvFOyIo.js +0 -2
  123. package/web-dist/assets/logic-CBvFOyIo.js.map +0 -1
  124. package/web-dist/assets/more-RjVyxPaz.js +0 -2
  125. package/web-dist/assets/more-RjVyxPaz.js.map +0 -1
  126. package/web-dist/assets/now-CDjeFSLD.js +0 -2
  127. package/web-dist/assets/now-CDjeFSLD.js.map +0 -1
  128. package/web-dist/assets/plus-BLP-wIYD.js +0 -2
  129. package/web-dist/assets/plus-BLP-wIYD.js.map +0 -1
  130. package/web-dist/assets/save-DEvZPWlS.js +0 -2
  131. package/web-dist/assets/save-DEvZPWlS.js.map +0 -1
  132. package/web-dist/assets/send-BKjswHxB.js +0 -2
  133. package/web-dist/assets/send-BKjswHxB.js.map +0 -1
  134. package/web-dist/assets/server-SxFxIScj.js +0 -2
  135. package/web-dist/assets/server-SxFxIScj.js.map +0 -1
  136. package/web-dist/assets/settings-tH4UuIfJ.js +0 -7
  137. package/web-dist/assets/settings-tH4UuIfJ.js.map +0 -1
  138. package/web-dist/assets/shared-CRX6KSBm.js +0 -3
  139. package/web-dist/assets/shared-CRX6KSBm.js.map +0 -1
  140. package/web-dist/assets/sliders-horizontal-DAoirila.js +0 -2
  141. package/web-dist/assets/sliders-horizontal-DAoirila.js.map +0 -1
  142. package/web-dist/assets/states-DXozulGZ.js +0 -2
  143. package/web-dist/assets/states-DXozulGZ.js.map +0 -1
  144. package/web-dist/assets/terminal-login-CW2rE50W.js +0 -2
  145. package/web-dist/assets/terminal-login-CW2rE50W.js.map +0 -1
  146. package/web-dist/assets/trash-C6X2OLrI.js +0 -2
  147. package/web-dist/assets/trash-C6X2OLrI.js.map +0 -1
  148. package/web-dist/assets/useNow-C_B7JgMM.js +0 -2
  149. package/web-dist/assets/useNow-C_B7JgMM.js.map +0 -1
@@ -1,14 +1,46 @@
1
1
  // packages/pi-runtime/dist/terminal/holder.js
2
- import { chmodSync, existsSync, realpathSync, rmSync, statSync } from "node:fs";
2
+ import { chmodSync, existsSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createServer } from "node:net";
5
5
  import { constants } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+
9
+ // packages/pi-runtime/dist/bridge/lines.js
10
+ var LineSplitter = class {
11
+ onLine;
12
+ buffer = "";
13
+ constructor(onLine) {
14
+ this.onLine = onLine;
15
+ }
16
+ push(text) {
17
+ const buf = this.buffer + text;
18
+ let start = 0;
19
+ for (let nl = buf.indexOf("\n"); nl >= 0; nl = buf.indexOf("\n", start)) {
20
+ this.emit(buf.slice(start, nl));
21
+ start = nl + 1;
22
+ }
23
+ this.buffer = buf.slice(start);
24
+ }
25
+ /** Return and clear the unterminated rest (CR stripped). */
26
+ end() {
27
+ const rest = this.buffer;
28
+ this.buffer = "";
29
+ return rest.endsWith("\r") ? rest.slice(0, -1) : rest;
30
+ }
31
+ emit(raw) {
32
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
33
+ if (line)
34
+ this.onLine(line);
35
+ }
36
+ };
37
+
38
+ // packages/pi-runtime/dist/terminal/holder.js
8
39
  var require2 = createRequire(import.meta.url);
9
40
  var MAX_BUFFER = 2e4;
10
41
  var MAX_TO_EXTENSION = 1e3;
11
42
  var EXIT_WAIT_MS = 5 * 6e4;
43
+ var HOLDER_QUEUE_FULL = "Pi's Switchyard extension is not connected and too many commands are waiting";
12
44
  function ensureSpawnHelper(req = require2) {
13
45
  try {
14
46
  const root = dirname(req.resolve("node-pty/package.json"));
@@ -29,19 +61,9 @@ function signalName(signal) {
29
61
  return String(signal);
30
62
  }
31
63
  function lineReader(socket, onLine) {
32
- let buf = "";
64
+ const lines = new LineSplitter(onLine);
33
65
  socket.setEncoding("utf8");
34
- socket.on("data", (chunk) => {
35
- buf += chunk;
36
- let nl = buf.indexOf("\n");
37
- while (nl >= 0) {
38
- const line = buf.slice(0, nl).replace(/\r$/, "");
39
- buf = buf.slice(nl + 1);
40
- if (line)
41
- onLine(line);
42
- nl = buf.indexOf("\n");
43
- }
44
- });
66
+ socket.on("data", (chunk) => lines.push(chunk));
45
67
  }
46
68
  function write(socket, line) {
47
69
  if (!socket || socket.destroyed)
@@ -52,6 +74,16 @@ function write(socket, line) {
52
74
  } catch {
53
75
  }
54
76
  }
77
+ function lastScreenLines(term, n = 20) {
78
+ const buf = term.buffer.active;
79
+ const out = [];
80
+ for (let i = buf.length - 1; i >= 0 && out.length < n; i--) {
81
+ const text = buf.getLine(i)?.translateToString(true).trimEnd() ?? "";
82
+ if (text.trim())
83
+ out.unshift(text);
84
+ }
85
+ return out;
86
+ }
55
87
  function runHolder(cfg) {
56
88
  ensureSpawnHelper();
57
89
  const pty = require2("node-pty");
@@ -65,7 +97,10 @@ function runHolder(cfg) {
65
97
  const toExtension = [];
66
98
  let gap = false;
67
99
  let exitInfo = null;
100
+ let exitRecord = null;
68
101
  let shuttingDown = false;
102
+ const exitPath = `${cfg.socketPath}.exit.json`;
103
+ let exitDelivered = false;
69
104
  const term = new Terminal({
70
105
  cols: cfg.cols,
71
106
  rows: cfg.rows,
@@ -74,17 +109,12 @@ function runHolder(cfg) {
74
109
  });
75
110
  const serializer = new SerializeAddon();
76
111
  term.loadAddon(serializer);
77
- const proc = pty.spawn(cfg.piBin, cfg.args, {
78
- name: "xterm-256color",
79
- cols: cfg.cols,
80
- rows: cfg.rows,
81
- cwd: cfg.cwd,
82
- env: cfg.env
83
- });
112
+ let proc = null;
113
+ let killRequested = false;
84
114
  const resize = (cols, rows) => {
85
115
  if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 2 || rows < 2)
86
116
  return;
87
- if (exitInfo)
117
+ if (exitInfo || !proc)
88
118
  return;
89
119
  try {
90
120
  proc.resize(cols, rows);
@@ -103,14 +133,25 @@ function runHolder(cfg) {
103
133
  gap = true;
104
134
  }
105
135
  };
106
- const sendExtension = (line) => {
136
+ const sendExtension = (line, rec) => {
107
137
  if (extension && !extension.destroyed) {
108
138
  write(extension, line);
109
139
  return;
110
140
  }
141
+ if (toExtension.length >= MAX_TO_EXTENSION) {
142
+ if (rec && typeof rec.id === "string" && typeof rec.type === "string" && rec.type !== "extension_ui_response") {
143
+ write(control, JSON.stringify({
144
+ type: "response",
145
+ id: rec.id,
146
+ command: rec.type,
147
+ success: false,
148
+ error: HOLDER_QUEUE_FULL,
149
+ holder: true
150
+ }));
151
+ }
152
+ return;
153
+ }
111
154
  toExtension.push(line);
112
- if (toExtension.length > MAX_TO_EXTENSION)
113
- toExtension.shift();
114
155
  };
115
156
  const shutdown = () => {
116
157
  if (shuttingDown)
@@ -123,31 +164,65 @@ function runHolder(cfg) {
123
164
  } catch {
124
165
  }
125
166
  rmSync(cfg.socketPath, { force: true });
167
+ if (exitDelivered)
168
+ rmSync(exitPath, { force: true });
126
169
  setTimeout(() => process.exit(0), 100).unref();
127
170
  };
128
- proc.onData((d) => {
129
- term.write(d);
130
- if (viewers.size === 0)
131
- return;
132
- const line = JSON.stringify({ t: "out", d: Buffer.from(d, "utf8").toString("base64") });
133
- for (const v of viewers)
134
- write(v, line);
135
- });
136
- proc.onExit(({ exitCode, signal }) => {
171
+ const onPiExit = ({ exitCode, signal }, extra) => {
137
172
  exitInfo = { code: exitCode ?? null, signal: signal ? signalName(signal) : null };
138
- const closed = JSON.stringify({ t: "closed", reason: "Pi exited" });
139
- for (const v of viewers) {
140
- write(v, closed);
141
- v.end();
173
+ term.write("", () => {
174
+ const screen = extra ?? lastScreenLines(term);
175
+ exitRecord = JSON.stringify({ type: "holder_exit", ...exitInfo, screen });
176
+ try {
177
+ writeFileSync(exitPath, JSON.stringify({ ...exitInfo, screen, at: (/* @__PURE__ */ new Date()).toISOString() }), {
178
+ mode: 384
179
+ });
180
+ } catch {
181
+ }
182
+ const closed = JSON.stringify({ t: "closed", reason: "Pi exited" });
183
+ for (const v of viewers) {
184
+ write(v, closed);
185
+ v.end();
186
+ }
187
+ viewers.clear();
188
+ if (control && !control.destroyed) {
189
+ write(control, exitRecord);
190
+ exitDelivered = true;
191
+ setTimeout(shutdown, 1e3).unref();
192
+ } else {
193
+ setTimeout(shutdown, killRequested ? 1e3 : EXIT_WAIT_MS).unref();
194
+ }
195
+ });
196
+ };
197
+ const startPi = () => {
198
+ try {
199
+ proc = pty.spawn(cfg.piBin, cfg.args, {
200
+ name: "xterm-256color",
201
+ cols: cfg.cols,
202
+ rows: cfg.rows,
203
+ cwd: cfg.cwd,
204
+ env: cfg.env
205
+ });
206
+ } catch (err) {
207
+ process.stderr.write(`switchyard holder: could not start ${cfg.piBin}: ${err.message}
208
+ `);
209
+ onPiExit({ exitCode: null }, [`Could not start ${cfg.piBin}: ${err.message}`]);
210
+ return;
142
211
  }
143
- viewers.clear();
212
+ const started = proc;
213
+ started.onData((d) => {
214
+ term.write(d);
215
+ if (viewers.size === 0)
216
+ return;
217
+ const line = JSON.stringify({ t: "out", d: Buffer.from(d, "utf8").toString("base64") });
218
+ for (const v of viewers)
219
+ write(v, line);
220
+ });
221
+ started.onExit(onPiExit);
144
222
  if (control && !control.destroyed) {
145
- write(control, JSON.stringify({ type: "holder_exit", ...exitInfo }));
146
- setTimeout(shutdown, 1e3).unref();
147
- } else {
148
- setTimeout(shutdown, EXIT_WAIT_MS).unref();
223
+ write(control, JSON.stringify({ type: "holder_status", piPid: started.pid }));
149
224
  }
150
- });
225
+ };
151
226
  const server = createServer((socket) => {
152
227
  let role = null;
153
228
  socket.on("error", () => {
@@ -173,15 +248,16 @@ function runHolder(cfg) {
173
248
  if (control && control !== socket)
174
249
  control.destroy();
175
250
  control = socket;
176
- write(socket, JSON.stringify({ type: "holder_status", piPid: proc.pid }));
251
+ write(socket, JSON.stringify({ type: "holder_status", piPid: proc?.pid ?? null }));
177
252
  if (gap) {
178
253
  write(socket, JSON.stringify({ type: "holder_gap" }));
179
254
  gap = false;
180
255
  }
181
256
  for (const l of buffer.splice(0))
182
257
  write(socket, l);
183
- if (exitInfo) {
184
- write(socket, JSON.stringify({ type: "holder_exit", ...exitInfo }));
258
+ if (exitRecord) {
259
+ write(socket, exitRecord);
260
+ exitDelivered = true;
185
261
  setTimeout(shutdown, 1e3).unref();
186
262
  }
187
263
  if (extension && !extension.destroyed) {
@@ -215,7 +291,7 @@ function runHolder(cfg) {
215
291
  } catch {
216
292
  }
217
293
  if (rec?.type === "holder_keys") {
218
- if (!exitInfo && typeof rec.data === "string")
294
+ if (!exitInfo && proc && typeof rec.data === "string")
219
295
  proc.write(rec.data);
220
296
  return;
221
297
  }
@@ -230,12 +306,12 @@ function runHolder(cfg) {
230
306
  }
231
307
  if (rec?.type === "holder_kill") {
232
308
  try {
233
- proc.kill(typeof rec.signal === "string" ? rec.signal : "SIGTERM");
309
+ proc?.kill(typeof rec.signal === "string" ? rec.signal : "SIGTERM");
234
310
  } catch {
235
311
  }
236
312
  return;
237
313
  }
238
- sendExtension(line);
314
+ sendExtension(line, rec);
239
315
  return;
240
316
  }
241
317
  let msg;
@@ -245,7 +321,7 @@ function runHolder(cfg) {
245
321
  return;
246
322
  }
247
323
  if (msg?.t === "in" && typeof msg.d === "string") {
248
- if (!exitInfo)
324
+ if (!exitInfo && proc)
249
325
  proc.write(Buffer.from(msg.d, "base64").toString("utf8"));
250
326
  } else if (msg?.t === "resize") {
251
327
  resize(Number(msg.cols), Number(msg.rows));
@@ -260,17 +336,25 @@ function runHolder(cfg) {
260
336
  extension = null;
261
337
  });
262
338
  });
339
+ server.on("error", (err) => {
340
+ process.stderr.write(`switchyard holder: cannot listen on ${cfg.socketPath}: ${err.message}
341
+ `);
342
+ process.exit(1);
343
+ });
344
+ const oldMask = process.umask(63);
263
345
  server.listen(cfg.socketPath, () => {
346
+ process.umask(oldMask);
264
347
  try {
265
348
  chmodSync(cfg.socketPath, 384);
266
349
  } catch {
267
350
  }
351
+ startPi();
268
352
  });
269
353
  process.on("uncaughtException", (err) => {
270
354
  process.stderr.write(`switchyard holder: ${err.stack ?? err.message}
271
355
  `);
272
356
  try {
273
- proc.kill();
357
+ proc?.kill();
274
358
  } catch {
275
359
  }
276
360
  rmSync(cfg.socketPath, { force: true });
@@ -278,6 +362,11 @@ function runHolder(cfg) {
278
362
  });
279
363
  for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"]) {
280
364
  process.on(sig, () => {
365
+ killRequested = true;
366
+ if (!proc) {
367
+ rmSync(cfg.socketPath, { force: true });
368
+ process.exit(0);
369
+ }
281
370
  try {
282
371
  proc.kill(sig);
283
372
  } catch {
@@ -300,6 +389,8 @@ if (isMain()) {
300
389
  runHolder(JSON.parse(raw));
301
390
  }
302
391
  export {
392
+ HOLDER_QUEUE_FULL,
303
393
  ensureSpawnHelper,
394
+ lastScreenLines,
304
395
  runHolder
305
396
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spencerboucher/switchyard",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Self-hosted hub for Pi coding agents: run them on your machines, drive them from your phone, browser or terminal",
5
5
  "license": "MIT",
6
6
  "type": "module",
Binary file
@@ -0,0 +1,2 @@
1
+ import{_ as e,f as t,i as n,m as r,n as i,p as a,t as o,u as s}from"./jsx-runtime-D13aM9HY.js";import{A as c,P as l,_ as u,_t as ee,bt as d,c as f,d as p,gt as m,h,ht as te,i as ne,it as g,n as _,nt as re,r as v,s as ie,t as y,u as b,v as x,vt as ae,yt as oe,z as S}from"./states-ZhrxQa3K.js";import{a as se,i as ce,n as le,t as C}from"./Field-D-Ty7fKT.js";import{t as w}from"./calendar-clock-B8zE4JsX.js";import{n as T,r as E}from"./Copy-B6XSAIUd.js";import{n as D,r as O,t as ue}from"./Priority-CHmzfoHg.js";import{t as de}from"./key-round-VDbE9E4X.js";import{t as fe}from"./play-CjoDg3ws.js";import{i as pe,n as me,r as he}from"./useBackTo-BIrCq3W2.js";import{n as k,r as ge,t as _e}from"./DangerZone-DfYlxDC1.js";import{J as ve,M as ye,T as be,V as xe,X as A,Y as Se,b as j,j as Ce,m as we,z as M}from"./index-hxvDvCS7.js";import{o as Te,t as Ee}from"./Overlay-DUQwh6_b.js";import{n as N,r as P}from"./TextArea-CKybrQyn.js";import{t as F}from"./TextLink-OzzyP2-p.js";import{t as I}from"./SegmentedControl-C_hEVQMB.js";import{t as L}from"./Select-Cfql4Nwu.js";import{t as R}from"./Switch-DBfzmqkm.js";import{E as z,O as De,S as Oe,T as B,a as V,b as ke,d as Ae,f as H,g as je,h as U,i as W,l as G,m as Me,n as Ne,o as Pe,p as K,r as Fe,s as Ie,t as Le,u as Re,v as ze,w as q,x as Be,y as Ve}from"./describe-D6KLGKWa.js";var J={name:`scroll-text`,size:24,node:[[`path`,{d:`M15 12h-5`,key:`r7krc0`}],[`path`,{d:`M15 8h-5`,key:`1khuty`}],[`path`,{d:`M19 17V5a2 2 0 0 0-2-2H4`,key:`zz82l3`}],[`path`,{d:`M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3`,key:`1ph1d7`}]]};J.node;var He=i(J),Y=e(r(),1),X=o(),Ue=e=>`/tasks/${encodeURIComponent(e)}`;function Z(e){return d(e)&&(e.status===404||e.status===405||e.status===501)}function We({summary:e,errorCount:t}){return(0,X.jsxs)(k,{stack:!0,title:`Summary`,testId:`automation-summary`,children:[(0,X.jsx)(`p`,{className:`text-sm break-words`,children:e}),t>0&&(0,X.jsxs)(`p`,{className:`flex items-center gap-1.5 text-sm text-danger`,children:[(0,X.jsx)(x,{"aria-hidden":!0,className:`size-4 shrink-0`}),t===1?`1 field needs attention`:`${t} fields need attention`]})]})}async function Q(e,t,n){return e&&!n?m(q(e,`/preview`)):ae(`/api/automations/preview`,t)}function Ge({automationId:e,dirty:t,getInput:n,currentKey:r}){let[i,a]=(0,Y.useState)({status:`idle`}),o=async()=>{let r=n();if(!r)j.error(`Fix the highlighted fields to preview the task`);else{a({status:`loading`});try{let n=await Q(e,r,t);a({status:`done`,preview:n,key:JSON.stringify(r)})}catch(e){a(Z(e)?{status:`unsupported`}:{status:`error`,error:e})}}};return(0,X.jsxs)(k,{stack:!0,title:`Preview`,description:`See the task an occurrence would create, and when it would run next.`,testId:`automation-preview`,children:[(0,X.jsx)(`div`,{children:(0,X.jsx)(p,{icon:(0,X.jsx)(xe,{className:`size-4`}),busy:i.status===`loading`,onClick:()=>void o(),children:`Preview resulting task`})}),i.status===`unsupported`&&(0,X.jsx)(b,{capability:`Task preview`,reason:`This coordinator does not offer automation previews.`,fallback:`Read the summary above, or save and use Run now to see a real task.`}),i.status===`error`&&(0,X.jsx)(_,{compact:!0,title:`Could not preview`,error:i.error,onRetry:()=>void o()}),i.status===`done`&&(0,X.jsx)(Ke,{preview:i.preview,stale:i.key!==r})]})}function Ke({preview:e,stale:t}){let{task:n}=e;return(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3`,children:[t&&(0,X.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs text-warning`,role:`status`,children:[(0,X.jsx)(x,{"aria-hidden":!0,className:`size-3.5 shrink-0`}),`The form changed since this preview. Preview again to refresh it.`]}),(0,X.jsx)(`p`,{className:`text-sm break-words text-muted`,children:e.summary}),(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2 rounded-md border border-border bg-surface-2 p-3`,children:[(0,X.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-2`,children:[(0,X.jsx)(`h3`,{className:`min-w-0 font-medium break-words`,children:n.title}),(0,X.jsx)(D,{priority:n.priority,muted:!0,className:`shrink-0 text-xs`})]}),n.objective?(0,X.jsx)(`p`,{className:`text-sm break-words whitespace-pre-wrap`,children:n.objective}):(0,X.jsx)(`p`,{className:`text-sm text-muted`,children:`No objective.`}),n.acceptanceCriteria.length>0&&(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`h4`,{className:`flex items-center gap-1 text-xs font-medium text-muted`,children:[(0,X.jsx)(M,{"aria-hidden":!0,className:`size-3.5`}),`Acceptance criteria`]}),(0,X.jsx)(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:n.acceptanceCriteria.map((e,t)=>(0,X.jsx)(`li`,{className:`break-words`,children:e},t))})]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`text-sm font-medium`,children:`Next occurrences`}),e.next.length===0?(0,X.jsx)(`p`,{className:`text-sm text-muted`,children:`No scheduled times: this trigger fires on demand, on a webhook, or when a task is done.`}):(0,X.jsx)(`ol`,{className:`mt-1 flex flex-col gap-0.5 text-sm`,children:e.next.slice(0,5).map(e=>(0,X.jsxs)(`li`,{className:`flex flex-wrap gap-x-2`,children:[(0,X.jsx)(`time`,{dateTime:e,children:K(e)}),(0,X.jsx)(`span`,{className:`text-muted`,children:h(e)})]},e))})]})]})}function qe({label:e,value:t,mono:n=!0}){return(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,X.jsx)(`span`,{className:`text-xs font-medium text-muted`,children:e}),(0,X.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[(0,X.jsx)(`code`,{className:`min-w-0 flex-1 rounded border border-border bg-surface px-2 py-1.5 text-xs break-all select-all ${n?`font-mono`:``}`,children:t}),(0,X.jsx)(p,{size:`sm`,icon:(0,X.jsx)(E,{className:`size-3.5`}),onClick:()=>void T(t,`${e} copied`),"aria-label":`Copy ${e.toLowerCase()}`,children:`Copy`})]})]})}function Je({automation:e}){let[t,n]=(0,Y.useState)(!1),[r,i]=(0,Y.useState)(!1),[a,o]=(0,Y.useState)(null),[s,c]=(0,Y.useState)(!1),l=e.webhookTokenSet||a!==null,u=async()=>{i(!1),n(!0);try{let t=await ae(q(e.id,`/webhook-token`)),n=re.safeParse(t);if(!n.success)throw Error(`The coordinator returned an unexpected token response`);let r=new URL(n.data.url,window.location.origin).toString();o({token:n.data.token,url:r}),j.success(l?`Webhook token rotated`:`Webhook token created`)}catch(e){Z(e)?c(!0):j.error(`Could not issue a webhook token: ${oe(e)}`)}finally{n(!1)}};return(0,X.jsxs)(k,{stack:!0,title:`Webhook`,description:`POST JSON to the URL with the token as a Bearer header. Filters decide which payloads fire.`,testId:`webhook-token`,children:[(0,X.jsx)(`p`,{className:`flex items-center gap-1.5 text-sm`,children:l?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(A,{"aria-hidden":!0,className:`size-4 shrink-0 text-success`}),`A token is set`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Se,{"aria-hidden":!0,className:`size-4 shrink-0 text-muted`}),`No token yet: webhook calls are rejected until you create one`]})}),s?(0,X.jsx)(b,{capability:`Webhook tokens`,reason:`This coordinator does not issue webhook tokens.`}):(0,X.jsx)(`div`,{children:(0,X.jsx)(p,{icon:(0,X.jsx)(de,{className:`size-4`}),busy:t,onClick:()=>l?i(!0):void u(),children:l?`Rotate token`:`Create token`})}),a&&(0,X.jsxs)(`div`,{role:`alert`,className:`flex min-w-0 flex-col gap-3 rounded-md border border-warning bg-warning-soft p-3`,children:[(0,X.jsxs)(`p`,{className:`flex items-center gap-1.5 text-sm font-medium`,children:[(0,X.jsx)(x,{"aria-hidden":!0,className:`size-4 shrink-0 text-warning`}),`This token is shown once. Copy it now.`]}),(0,X.jsx)(qe,{label:`Token`,value:a.token}),(0,X.jsx)(qe,{label:`URL`,value:a.url}),(0,X.jsx)(qe,{label:`Example`,value:Pe(a.token,a.url)}),(0,X.jsx)(`div`,{children:(0,X.jsx)(p,{size:`sm`,onClick:()=>o(null),children:`I have copied it`})})]}),(0,X.jsx)(Ee,{open:r,onClose:()=>i(!1),title:`Rotate webhook token?`,description:`The current token stops working immediately. Update every sender with the new token.`,confirmLabel:`Rotate token`,busy:t,onConfirm:()=>void u()})]})}var Ye=[];function Xe({automationId:e,refreshKey:t,onRun:n}){let r=S(t=>t.occurrences[e]??Ye),i=S(e=>e.tasks),[a,o]=(0,Y.useState)({status:`loading`}),s=(0,Y.useCallback)(async t=>{o(e=>e.status===`done`?e:{status:`loading`});try{let n=await m(q(e,`/history`),{},t);o({status:`done`,items:ze(n)})}catch(e){if(t?.aborted)return;o(Z(e)?{status:`unsupported`}:{status:`error`,error:e})}},[e]);(0,Y.useEffect)(()=>{let e=new AbortController;return s(e.signal),()=>e.abort()},[s,t]);let c=je(a.status===`done`?a.items:[],r);return(0,X.jsxs)(k,{stack:!0,title:`History`,description:`Occurrences of this automation. Routine successes are hidden from the board and appear only here.`,testId:`automation-history`,children:[a.status===`unsupported`&&(0,X.jsx)(b,{capability:`Automation history`,reason:`This coordinator does not serve stored history; only occurrences seen live in this session are shown.`}),a.status===`error`&&(0,X.jsx)(_,{compact:!0,title:`Could not load history`,error:a.error,onRetry:()=>void s()}),a.status===`loading`&&c.length===0?(0,X.jsx)(f,{label:`Loading history…`,className:`py-4`}):c.length===0&&a.status!==`error`?(0,X.jsx)(y,{className:`py-4`,icon:(0,X.jsx)(He,{className:`size-6`}),title:`No occurrences yet`,description:`Occurrences appear here when the trigger fires or you run it.`,action:{label:`Run now`,onClick:n,icon:(0,X.jsx)(fe,{className:`size-4`})}}):(0,X.jsx)(`ol`,{className:`flex flex-col divide-y divide-border`,children:c.map(e=>{let t=Ve(e),n=e.taskId?i[e.taskId]:void 0,r=[e.reason,e.outcome].filter(Boolean).join(` · `);return(0,X.jsxs)(`li`,{className:`flex min-w-0 flex-col gap-1 py-2 first:pt-0 last:pb-0`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,X.jsx)(be,{kind:`occurrence`,value:e.state,size:`sm`}),(0,X.jsx)(`time`,{dateTime:t,className:`text-sm`,children:K(t)}),(0,X.jsx)(`span`,{className:`text-xs text-muted`,children:h(t)})]}),r&&(0,X.jsx)(`p`,{className:`text-sm break-words text-muted`,children:r}),e.taskId&&(0,X.jsxs)(F,{to:Ue(e.taskId),variant:`action`,size:`sm`,className:`self-start`,children:[(0,X.jsx)(`span`,{className:`min-w-0 truncate`,children:n?`Task: ${n.title}`:`Open task`}),n?.hiddenFromBoard&&(0,X.jsx)(`span`,{className:`shrink-0 text-xs text-muted`,children:`(hidden from board)`})]})]},e.id)})})]})}var Ze=`/automations`,Qe=e=>`/automations/${encodeURIComponent(e)}`,$e=`sy:automation-draft`;function et(){let{automationId:e=`new`}=a();return(0,X.jsx)(tt,{automationId:e},e)}function tt({automationId:e}){let t=e===`new`,n=S(e=>e.hydrated),r=z(t?void 0:e),[i,a]=(0,Y.useState)({status:`idle`}),o=(0,Y.useCallback)(async()=>{a({status:`loading`});try{let t=await m(q(e)),n=g.safeParse(t);if(!n.success){a({status:`fatal`,error:Error(`The coordinator returned this automation in an unexpected format.`)});return}B.getState().put(n.data),a({status:`idle`})}catch(e){d(e)&&e.status===404?a({status:`notfound`}):a({status:`error`,error:e})}},[e]),s=!t&&!r;return(0,Y.useEffect)(()=>{s&&i.status===`idle`&&o()},[s,i.status,o]),t?(0,X.jsx)(at,{automation:null}):r?(0,X.jsx)(at,{automation:r}):i.status===`notfound`?(0,X.jsx)(y,{icon:(0,X.jsx)(ye,{className:`size-8`}),title:`Automation not found`,description:`It may have been deleted, or the link is wrong.`,action:{label:`Back to automations`,to:Ze}}):i.status===`error`?(0,X.jsx)(_,{title:`Could not load this automation`,error:i.error,onRetry:()=>void o()}):i.status===`fatal`?(0,X.jsx)(v,{error:i.error}):(0,X.jsx)(f,{label:n?`Loading automation…`:`Loading…`})}function nt(e){let t=Ae({projectId:e,timezone:U()});try{let e=sessionStorage.getItem($e);if(!e)return t;let n=JSON.parse(e);return!n||typeof n!=`object`?t:{...t,...n,filters:Array.isArray(n.filters)?n.filters:[]}}catch{return t}}function rt(e){try{e?sessionStorage.setItem($e,JSON.stringify(e)):sessionStorage.removeItem($e)}catch{}}var $=e=>JSON.stringify(Re(e));function it(e){if(!d(e))return{};let t=e.details,n=Array.isArray(t)?t:t&&typeof t==`object`&&Array.isArray(t.issues)?t.issues:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let{path:t,message:n}=e;if(!Array.isArray(t)||typeof n!=`string`)continue;let i=H(t);i!==`form`&&!r[i]&&(r[i]=n)}return r}function at({automation:e}){let r=t(),i=s(),a=he(Ze),o=we(),d=o===`desktop`,f=l(),m=c(),h=S(e=>e.hosts),g=S(e=>e.profiles),_=S(e=>e.tasks),re=S(e=>e.projects),v=e===null,y=(0,Y.useId)(),b=(0,Y.useRef)(null),[C,w]=(0,Y.useState)(()=>e?G(e):nt(f[0]?.id)),[T,E]=(0,Y.useState)(()=>$(C)),[D,O]=(0,Y.useState)(!1),[ue,de]=(0,Y.useState)({}),[pe,k]=(0,Y.useState)(!1),[ye,be]=(0,Y.useState)(!1),[xe,A]=(0,Y.useState)(!1),[Se,M]=(0,Y.useState)(!1),[Te,N]=(0,Y.useState)(0),P=(0,Y.useRef)(e?.updatedAt),F=$(C),I=F!==T;(0,Y.useEffect)(()=>{if(!e||e.updatedAt===P.current)return;P.current=e.updatedAt;let t=G(e),n=$(t);F===T?(w(t),M(!1)):n!==F&&M(!0),E(n)},[e,F,T]),(0,Y.useEffect)(()=>{v&&rt(C)},[v,C]),(0,Y.useEffect)(()=>{v&&!C.projectId&&f[0]&&w(e=>e.projectId?e:{...e,projectId:f[0].id})},[v,C.projectId,f]);let L=(0,Y.useCallback)((e,t)=>{w(n=>({...n,[e]:t})),de(e=>Object.keys(e).length?{}:e)},[]),R=(0,Y.useMemo)(()=>Oe(C),[C]),z={...ue,...D?R.errors:{}},V=e=>z[e],H=re[C.projectId],je=C.hostId||H?.defaultHostId||null,W=je?h[je]:void 0,Me=C.profileId||H?.defaultProfileId||null,Ne=(0,Y.useCallback)(e=>_[e]?.title,[_]),Pe=(0,Y.useMemo)(()=>ke(Re(C),{projectName:H?.name,hostName:C.hostId?h[C.hostId]?.name??null:null,profileName:C.profileId?g[C.profileId]?.name??null:null,taskTitle:Ne}),[C,H?.name,h,g,Ne]),K=()=>{requestAnimationFrame(()=>{b.current?.querySelector(`[aria-invalid="true"]`)?.focus()})},Fe=()=>(O(!0),R.input||K(),R.input),Ie=async()=>{let t=Fe();if(!t)j.error(`Fix the highlighted fields before saving`);else{k(!0);try{if(v){let e=await ae(`/api/automations`,t);if(!e||typeof e!=`object`||!e.id)throw Error(`The coordinator did not return the new automation`);B.getState().put(e),rt(null),j.success(`Created ${e.name}`),r(Qe(e.id),{replace:!0,state:i.state});return}let n=await ee(q(e.id),t);if(n&&typeof n==`object`&&n.id){B.getState().put(n),P.current=n.updatedAt;let e=G(n);w(e),E($(e))}else E(F);M(!1),O(!1),j.success(`Saved ${t.name}`)}catch(e){let t=it(e);de(t),Object.keys(t).length&&K(),j.error(`Could not save: ${oe(e)}. Your changes are kept.`)}finally{k(!1)}}},Le=async()=>{if(e){be(!0);try{await te(q(e.id)),A(!1),j.success(`Deleted ${e.name}`),a(),B.getState().remove(e.id)}catch(e){j.error(`Could not delete: ${oe(e)}`)}finally{be(!1)}}},{busy:ze,run:Be}=De(()=>N(e=>e+1)),Ve=e?!!ze[e.id]:!1,J=()=>e&&void Be(e),He=()=>{let e=Ae({projectId:f[0]?.id,timezone:U()});w(e),O(!1),rt(null)},Ue=v?`New automation`:e.name,Z=(0,X.jsxs)(X.Fragment,{children:[!v&&(0,X.jsx)(p,{icon:(0,X.jsx)(fe,{className:`size-4`}),busy:Ve,onClick:J,title:I?`Runs the saved version`:void 0,children:`Run now`}),v&&I&&(0,X.jsx)(p,{variant:`ghost`,icon:(0,X.jsx)(Ce,{className:`size-4`}),onClick:He,children:`Discard draft`})]}),Q=e=>(0,X.jsx)(p,{type:`submit`,form:y,variant:`primary`,busy:pe,block:e,icon:(0,X.jsx)(ge,{className:`size-4`}),children:v?`Create automation`:`Save`}),Ke=(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(We,{summary:Pe,errorCount:D?Object.keys(R.errors).length:0}),(0,X.jsx)(Ge,{automationId:e?.id??null,dirty:I,getInput:Fe,currentKey:JSON.stringify(R.input)}),e&&e.trigger.kind===`webhook`&&(0,X.jsx)(Je,{automation:e}),e&&(0,X.jsx)(Xe,{automationId:e.id,refreshKey:Te,onRun:J})]});return(0,X.jsxs)(`div`,{"data-testid":`automation-editor`,className:`flex w-full min-w-0 flex-col gap-4 px-4 pt-4 md:px-6`,children:[(0,X.jsxs)(`header`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,X.jsxs)(n,{to:Ze,onClick:me(a),className:`tap inline-flex items-center gap-1 self-start rounded text-sm text-muted hover:text-text`,children:[(0,X.jsx)(se,{"aria-hidden":!0,className:`size-4`}),`Automations`]}),(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center justify-between gap-2`,children:[(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,X.jsx)(`h1`,{className:`min-w-0 text-lg font-semibold break-words`,children:Ue}),I&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-xs text-muted`,children:[(0,X.jsx)(ve,{"aria-hidden":!0,className:`size-3.5`}),`Unsaved changes`]})]}),(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[Z,d&&Q()]})]})]}),(0,X.jsx)(ie,{subject:`automations`,consequence:`Changes are sent once the coordinator is reachable again.`}),W&&W.connectivity!==`connected`&&(0,X.jsx)(ne,{compact:!0,hostName:W.name,connectivity:W.connectivity,lastSeenAt:W.lastSeenAt,detail:`Occurrences are still recorded; their tasks wait until the host is reachable.`}),Se&&(0,X.jsxs)(`p`,{role:`status`,className:`flex items-start gap-1.5 rounded-md border border-border bg-warning-soft px-3 py-2 text-sm`,children:[(0,X.jsx)(x,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0 text-warning`}),`This automation changed elsewhere. Saving overwrites those changes with yours.`]}),(0,X.jsxs)(`div`,{className:u(`grid min-w-0 gap-4`,d?`grid-cols-[minmax(0,1fr)_minmax(320px,400px)] items-start`:`grid-cols-1`),children:[(0,X.jsxs)(`form`,{id:y,ref:b,noValidate:!0,"aria-label":Ue,onSubmit:e=>{e.preventDefault(),Ie()},className:`flex min-w-0 flex-col gap-4`,children:[(0,X.jsx)(ot,{draft:C,update:L,err:V,projects:f}),(0,X.jsx)(lt,{draft:C,update:L,err:V,tasks:_,projectsById:re,savedAutomation:e,segmented:o!==`mobile`}),(0,X.jsx)(ut,{draft:C,setDraft:w,err:V}),(0,X.jsx)(dt,{draft:C,update:L,err:V}),(0,X.jsx)(pt,{draft:C,update:L,err:V,hosts:m,profiles:Object.values(g).sort((e,t)=>e.name.localeCompare(t.name)),defaultHostName:H?.defaultHostId?h[H.defaultHostId]?.name:void 0,defaultProfileName:H?.defaultProfileId?g[H.defaultProfileId]?.name:void 0,selectedProfileMissing:!!Me&&!g[Me]}),(0,X.jsx)(mt,{draft:C,update:L}),(0,X.jsx)(ht,{draft:C,update:L,err:V}),(0,X.jsx)(gt,{draft:C,update:L,err:V,projectChecks:H?.checks}),z.form&&(0,X.jsx)(le,{children:z.form})]}),(0,X.jsx)(`aside`,{"aria-label":`Summary, preview and history`,className:`flex min-w-0 flex-col gap-4`,children:Ke})]}),!v&&e&&(0,X.jsx)(_e,{description:`Future occurrences stop. Tasks it already created stay on the board; its history is removed.`,children:(0,X.jsx)(p,{variant:`danger`,icon:(0,X.jsx)(ce,{className:`size-4`}),onClick:()=>A(!0),children:`Delete automation`})}),d?(0,X.jsx)(`div`,{className:`h-4`}):(0,X.jsxs)(`div`,{className:`sticky bottom-0 z-10 -mx-4 flex items-center gap-3 border-t border-border bg-surface px-4 py-2 md:-mx-6 md:px-6`,children:[(0,X.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-muted`,children:I?`Unsaved changes`:v?`Not saved yet`:`All changes saved`}),Q()]}),(0,X.jsx)(Ee,{open:xe,onClose:()=>A(!1),title:`Delete ${e?.name??`automation`}?`,description:`Future occurrences stop. Tasks it already created stay on the board; its history is removed.`,confirmLabel:`Delete automation`,confirmIcon:(0,X.jsx)(ce,{className:`size-4`}),busy:ye,onConfirm:()=>void Le()})]})}function ot({draft:e,update:t,err:n,projects:r}){return(0,X.jsxs)(k,{stack:!0,title:`Basics`,children:[(0,X.jsx)(C,{label:`Name`,error:n(`name`),children:n=>(0,X.jsx)(P,{...n,value:e.name,onChange:e=>t(`name`,e.target.value),placeholder:`Daily dependency check`,autoComplete:`off`})}),(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)(C,{label:`Project`,error:n(`projectId`),hint:r.length===0?(0,X.jsxs)(X.Fragment,{children:[`No projects yet.`,` `,(0,X.jsx)(F,{to:`/settings/projects`,children:`Add a project in Settings`}),`.`]}):void 0,children:n=>(0,X.jsxs)(L,{...n,value:e.projectId,onChange:e=>t(`projectId`,e.target.value),children:[(0,X.jsx)(`option`,{value:``,children:`Choose a project`}),r.map(e=>(0,X.jsx)(`option`,{value:e.id,children:e.name},e.id))]})}),(0,X.jsx)(C,{label:`Status`,hint:`Disabled automations keep their history and can still run manually.`,children:n=>(0,X.jsx)(R,{...n,checked:e.enabled,onChange:e=>t(`enabled`,e),label:`Enabled`,onText:`Enabled`,offText:`Disabled`,className:`self-start`})})]})]})}var st=[`manual`,`once`,`cron`,`webhook`,`dependency`],ct={manual:`Runs only when you press Run now (or from the CLI).`,once:`Runs a single time at the chosen moment.`,cron:`Runs on a timezone-aware cron schedule.`,webhook:`Runs when an authenticated JSON POST arrives at this automation's webhook URL.`,dependency:`Runs when the chosen task is done.`};function lt({draft:e,update:t,err:n,tasks:r,projectsById:i,savedAutomation:a,segmented:o}){let s=S(e=>e.hydrated),c=e.triggerKind===`cron`?Be(e.cronExpr):null,l=e.triggerKind===`cron`&&!c?Ie(e.cronExpr,e.cronTimezone.trim()||void 0)??`Valid expression (no plain-language description available)`:null,u=(0,Y.useMemo)(()=>{try{return Intl.supportedValuesOf?.(`timeZone`)}catch{return}},[]),ee=(0,Y.useId)(),d=U(),f=(0,Y.useMemo)(()=>Object.values(r).filter(t=>t.state!==`canceled`||t.id===e.dependencyTaskId).sort((e,t)=>e.title.localeCompare(t.title)),[r,e.dependencyTaskId]),p=e.triggerKind===`once`?Me(e.onceAt):``;return(0,X.jsxs)(k,{stack:!0,title:`Trigger`,description:ct[e.triggerKind],children:[o?(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,X.jsx)(`span`,{"aria-hidden":!0,className:`text-sm font-medium`,children:`Trigger kind`}),(0,X.jsx)(`div`,{className:`overflow-x-auto`,children:(0,X.jsx)(I,{label:`Trigger kind`,value:e.triggerKind,onChange:e=>t(`triggerKind`,e),options:st.map(e=>({value:e,label:V[e]}))})})]}):(0,X.jsx)(C,{label:`Trigger kind`,children:n=>(0,X.jsx)(L,{...n,value:e.triggerKind,onChange:e=>t(`triggerKind`,e.target.value),children:st.map(e=>(0,X.jsx)(`option`,{value:e,children:V[e]},e))})}),e.triggerKind===`once`&&(0,X.jsx)(C,{label:`Run at`,error:n(`onceAt`),hint:`Local time (${d})${p?`; saved as ${p}`:``}.`,children:n=>(0,X.jsx)(P,{...n,type:`datetime-local`,value:e.onceAt,onChange:e=>t(`onceAt`,e.target.value)})}),e.triggerKind===`cron`&&(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)(C,{label:`Cron expression`,error:n(`cronExpr`)??c??void 0,hint:`minute hour day-of-month month day-of-week, e.g. 0 9 * * 1-5`,children:n=>(0,X.jsx)(P,{...n,"aria-invalid":c?!0:n[`aria-invalid`],value:e.cronExpr,onChange:e=>t(`cronExpr`,e.target.value),className:`font-mono`,autoComplete:`off`,spellCheck:!1,autoCapitalize:`off`})}),(0,X.jsx)(C,{label:`Timezone`,error:n(`cronTimezone`),hint:e.cronTimezone.trim()===d?`IANA timezone name; daylight saving is handled.`:(0,X.jsxs)(F,{onClick:()=>t(`cronTimezone`,d),children:[`Use this device's timezone (`,d,`)`]}),children:n=>(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(P,{...n,list:u?ee:void 0,value:e.cronTimezone,onChange:e=>t(`cronTimezone`,e.target.value),autoComplete:`off`,spellCheck:!1,autoCapitalize:`off`}),u&&(0,X.jsx)(`datalist`,{id:ee,children:u.map(e=>(0,X.jsx)(`option`,{value:e},e))})]})}),l&&(0,X.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm sm:col-span-2`,"aria-live":`polite`,"data-testid":`cron-description`,children:[(0,X.jsx)(w,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0 text-muted`}),(0,X.jsx)(`span`,{className:`min-w-0 break-words`,children:l})]})]}),e.triggerKind===`webhook`&&(0,X.jsxs)(`div`,{className:`flex flex-col gap-1 text-sm text-muted`,children:[(0,X.jsxs)(`p`,{children:[`Senders POST a JSON body (up to 256 KB) with`,` `,(0,X.jsx)(`code`,{children:`Authorization: Bearer <token>`}),`. Use the filters below to fire only for matching payloads, and `,(0,X.jsx)(`code`,{children:`{{payload.<path>}}`}),` to copy payload values into the task.`]}),a?a.trigger.kind===`webhook`?(0,X.jsxs)(`p`,{children:[`Token:`,` `,a.webhookTokenSet?`set (see Webhook below to rotate)`:`not created yet`]}):(0,X.jsx)(`p`,{children:`Save to switch this automation to a webhook trigger, then create a token.`}):(0,X.jsx)(`p`,{children:`Save the automation to create its webhook token and URL.`})]}),e.triggerKind===`dependency`&&(0,X.jsx)(C,{label:`When this task is done`,error:n(`dependencyTaskId`),hint:`Fires once each time the task enters Done.`,children:n=>(0,X.jsxs)(L,{...n,value:e.dependencyTaskId,onChange:e=>t(`dependencyTaskId`,e.target.value),children:[(0,X.jsx)(`option`,{value:``,children:`Choose a task`}),e.dependencyTaskId&&!r[e.dependencyTaskId]&&(0,X.jsx)(`option`,{value:e.dependencyTaskId,children:s?`Deleted task`:`Loading task…`}),f.map(e=>(0,X.jsxs)(`option`,{value:e.id,children:[e.title,i[e.projectId]?` (${i[e.projectId].name})`:``,e.state===`done`?` - done`:``]},e.id))]})})]})}function ut({draft:e,setDraft:t,err:n}){let r=(e,n)=>t(t=>({...t,filters:t.filters.map((t,r)=>r===e?{...t,...n}:t)})),i=e.triggerKind===`webhook`;return(0,X.jsxs)(k,{stack:!0,title:`Filters`,description:`Filters apply to webhook payloads. Each row compares a dot path (for example pull_request.base.ref) with an exact value; all rows must match. Payloads that do not match are recorded as Filtered out.`,children:[!i&&(0,X.jsx)(`p`,{className:`text-sm text-muted`,children:`Filters are ignored unless the trigger is Webhook.`}),e.filters.length===0&&(0,X.jsx)(`p`,{className:`text-sm text-muted`,children:`No filters: every payload fires.`}),e.filters.map((e,i)=>(0,X.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-end gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]`,children:[(0,X.jsx)(C,{label:`Path ${i+1}`,error:n(`filters.${i}.path`),children:t=>(0,X.jsx)(P,{...t,value:e.path,onChange:e=>r(i,{path:e.target.value}),placeholder:`action`,className:`font-mono`,autoCapitalize:`off`,spellCheck:!1})}),(0,X.jsx)(C,{label:`Equals ${i+1}`,error:n(`filters.${i}.equals`),className:`col-start-1 row-start-2 sm:col-start-auto sm:row-start-auto`,children:t=>(0,X.jsx)(P,{...t,value:e.equals,onChange:e=>r(i,{equals:e.target.value}),placeholder:`opened`})}),(0,X.jsx)(Te,{label:`Remove filter ${i+1}`,icon:(0,X.jsx)(Ce,{className:`size-4`}),onClick:()=>t(e=>({...e,filters:e.filters.filter((e,t)=>t!==i)}))})]},i)),(0,X.jsx)(`div`,{children:(0,X.jsx)(p,{size:`sm`,icon:(0,X.jsx)(pe,{className:`size-3.5`}),onClick:()=>t(e=>({...e,filters:[...e.filters,{path:``,equals:``}]})),children:`Add filter`})})]})}function dt({draft:e,update:t,err:n}){return(0,X.jsxs)(k,{stack:!0,title:`Task template`,description:`Use ${W.join(`, `)} in the title, objective, criteria and grouping key.`,children:[(0,X.jsx)(C,{label:`Task title`,error:n(`title`),children:n=>(0,X.jsx)(P,{...n,value:e.title,onChange:e=>t(`title`,e.target.value),placeholder:`Triage new issues for {{date}}`})}),(0,X.jsx)(C,{label:`Objective`,error:n(`objective`),children:n=>(0,X.jsx)(N,{...n,minRows:4,value:e.objective,onChange:e=>t(`objective`,e.target.value)})}),(0,X.jsx)(C,{label:`Acceptance criteria`,error:n(`criteria`),hint:`One criterion per line.`,optional:!0,children:n=>(0,X.jsx)(N,{...n,minRows:3,value:e.criteria,onChange:e=>t(`criteria`,e.target.value)})}),(0,X.jsx)(C,{label:`Priority`,error:n(`priority`),children:n=>(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(ue,{priority:e.priority}),(0,X.jsx)(O,{...n,value:e.priority,onChange:e=>t(`priority`,e),className:`sm:max-w-48`})]})})]})}function ft({legend:e,value:t,options:n,onChange:r,hint:i}){let a=(0,Y.useId)();return(0,X.jsxs)(`fieldset`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,X.jsx)(`legend`,{className:`mb-1 text-sm font-medium`,children:e}),(0,X.jsx)(`div`,{className:`grid min-w-0 gap-2 sm:grid-cols-3`,children:n.map(e=>(0,X.jsxs)(`label`,{className:u(`tap flex min-w-0 cursor-pointer items-start gap-2 rounded-md border p-2.5 text-sm`,`has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-1`,t===e.value?`border-accent bg-accent-soft`:`border-border hover:bg-surface-2`),children:[(0,X.jsx)(`input`,{type:`radio`,name:a,value:e.value,checked:t===e.value,onChange:()=>r(e.value),className:`mt-0.5 size-4 shrink-0 accent-[var(--color-accent)]`}),(0,X.jsxs)(`span`,{className:`min-w-0`,children:[(0,X.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,X.jsx)(`span`,{className:`block text-xs text-muted`,children:e.explanation})]})]},e.value))}),i&&(0,X.jsx)(`p`,{className:`text-xs text-muted`,children:i})]})}function pt({draft:e,update:t,err:n,hosts:r,profiles:i,defaultHostName:a,defaultProfileName:o,selectedProfileMissing:s}){return(0,X.jsxs)(k,{stack:!0,title:`Where and how it runs`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)(C,{label:`Host`,error:n(`hostId`),children:n=>(0,X.jsxs)(L,{...n,value:e.hostId,onChange:e=>t(`hostId`,e.target.value),children:[(0,X.jsxs)(`option`,{value:``,children:[`Project default`,a?` (${a})`:``]}),e.hostId&&!r.some(t=>t.id===e.hostId)&&(0,X.jsx)(`option`,{value:e.hostId,children:`Unknown host`}),r.map(e=>(0,X.jsxs)(`option`,{value:e.id,children:[e.name,e.connectivity===`connected`?``:` (${e.connectivity})`]},e.id))]})}),(0,X.jsx)(C,{label:`Profile`,error:n(`profileId`),hint:s?`The selected profile is no longer available.`:void 0,children:n=>(0,X.jsxs)(L,{...n,value:e.profileId,onChange:e=>t(`profileId`,e.target.value),children:[(0,X.jsxs)(`option`,{value:``,children:[`Project default`,o?` (${o})`:``]}),e.profileId&&!i.some(t=>t.id===e.profileId)&&(0,X.jsx)(`option`,{value:e.profileId,children:`Unknown profile`}),i.map(e=>(0,X.jsx)(`option`,{value:e.id,children:e.name},e.id))]})})]}),(0,X.jsx)(ft,{legend:`Mode`,value:e.mode,options:Ne,onChange:e=>t(`mode`,e)}),(0,X.jsx)(C,{label:`Grouping key`,optional:e.mode!==`continue`,error:n(`groupingKey`),hint:`Occurrences with the same rendered key are the same work: Continue reuses that task and overlap checks compare it. Supports template variables, e.g. pr-{{payload.number}}.`,children:n=>(0,X.jsx)(P,{...n,value:e.groupingKey,onChange:e=>t(`groupingKey`,e.target.value),className:`font-mono`,autoCapitalize:`off`,spellCheck:!1})})]})}function mt({draft:e,update:t}){let n=e.triggerKind===`cron`||e.triggerKind===`once`;return(0,X.jsxs)(k,{stack:!0,title:`Overlap and missed runs`,children:[(0,X.jsx)(ft,{legend:`When previous work is still open`,value:e.overlap,options:Fe,onChange:e=>t(`overlap`,e)}),(0,X.jsx)(ft,{legend:`Missed runs`,value:e.missed,options:Le,onChange:e=>t(`missed`,e),hint:n?`A run is missed when the coordinator was down at its scheduled time.`:`Only applies to Schedule and Once triggers.`})]})}function ht({draft:e,update:t,err:n}){return(0,X.jsxs)(k,{stack:!0,title:`Limits`,description:`Continuation prompts the agent to keep going after a turn ends without finishing. It is off by default.`,children:[(0,X.jsx)(C,{label:`Automatic continuation`,children:n=>(0,X.jsx)(R,{...n,checked:e.continuationEnabled,onChange:e=>t(`continuationEnabled`,e),label:`Automatic continuation`,className:`self-start`})}),e.continuationEnabled&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(C,{label:`Continuation objective`,error:n(`continuationObjective`),hint:`What the agent must achieve before it reports done.`,children:n=>(0,X.jsx)(N,{...n,minRows:2,value:e.continuationObjective,onChange:e=>t(`continuationObjective`,e.target.value)})}),(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)(C,{label:`Max continuations`,error:n(`maxContinuations`),hint:`1–50`,children:n=>(0,X.jsx)(P,{...n,type:`number`,inputMode:`numeric`,min:1,max:50,step:1,value:e.maxContinuations,onChange:e=>t(`maxContinuations`,e.target.value)})}),(0,X.jsx)(C,{label:`Max elapsed minutes`,error:n(`maxElapsedMinutes`),hint:`1–1440`,children:n=>(0,X.jsx)(P,{...n,type:`number`,inputMode:`numeric`,min:1,max:1440,step:1,value:e.maxElapsedMinutes,onChange:e=>t(`maxElapsedMinutes`,e.target.value)})}),(0,X.jsx)(C,{label:`Max tokens`,optional:!0,error:n(`maxTokens`),children:n=>(0,X.jsx)(P,{...n,type:`number`,inputMode:`numeric`,min:1,step:1,value:e.maxTokens,onChange:e=>t(`maxTokens`,e.target.value)})}),(0,X.jsx)(C,{label:`Max cost (USD)`,optional:!0,error:n(`maxCostUsd`),children:n=>(0,X.jsx)(P,{...n,type:`number`,inputMode:`decimal`,min:.01,step:.01,value:e.maxCostUsd,onChange:e=>t(`maxCostUsd`,e.target.value)})})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted`,children:`Token and cost limits are enforced only when the provider reports accounting; otherwise the run shows that accounting is unavailable and only the count and time limits apply.`})]})]})}function gt({draft:e,update:t,err:n,projectChecks:r}){let i=r&&r.length>0?`the project's checks (${r.join(`, `)})`:`the project's checks`;return(0,X.jsxs)(k,{stack:!0,title:`Review`,children:[(0,X.jsx)(C,{label:`Checks`,optional:!0,error:n(`checks`),hint:`One command per line. Leave empty to use ${i}.`,children:n=>(0,X.jsx)(N,{...n,minRows:2,value:e.checks,onChange:e=>t(`checks`,e.target.value),className:`font-mono`,spellCheck:!1,autoCapitalize:`off`})}),(0,X.jsx)(C,{label:`Human review`,hint:`When on, finished work waits in Review for you instead of completing on passing checks.`,children:n=>(0,X.jsx)(R,{...n,checked:e.requireHumanReview,onChange:e=>t(`requireHumanReview`,e),label:`Require human review`,onText:`Required`,offText:`Not required`,className:`self-start`})})]})}export{et as default};
2
+ //# sourceMappingURL=AutomationView-D7Syv1En.js.map