@spencerboucher/switchyard 0.8.0 → 0.10.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 (161) hide show
  1. package/README.md +4 -4
  2. package/dist/bridge/lines.js +33 -0
  3. package/dist/bridge/switchyard-terminal.js +59 -22
  4. package/dist/switchyard.mjs +9769 -7208
  5. package/dist/terminal/holder.js +172 -55
  6. package/package.json +1 -1
  7. package/web-dist/apple-touch-icon.png +0 -0
  8. package/web-dist/assets/AutomationView-BsTwLnMp.js +2 -0
  9. package/web-dist/assets/AutomationView-BsTwLnMp.js.map +1 -0
  10. package/web-dist/assets/Card-CAFxHoHd.js +2 -0
  11. package/web-dist/assets/Card-CAFxHoHd.js.map +1 -0
  12. package/web-dist/assets/Checkbox-rDvnQnxc.js +2 -0
  13. package/web-dist/assets/Checkbox-rDvnQnxc.js.map +1 -0
  14. package/web-dist/assets/Copy-D8xhl7eJ.js +2 -0
  15. package/web-dist/assets/Copy-D8xhl7eJ.js.map +1 -0
  16. package/web-dist/assets/DangerZone-og55TRug.js +2 -0
  17. package/web-dist/assets/DangerZone-og55TRug.js.map +1 -0
  18. package/web-dist/assets/Field-Dbg_8KTt.js +2 -0
  19. package/web-dist/assets/Field-Dbg_8KTt.js.map +1 -0
  20. package/web-dist/assets/InteractionCard-Yu5wgLC3.js +6 -0
  21. package/web-dist/assets/InteractionCard-Yu5wgLC3.js.map +1 -0
  22. package/web-dist/assets/Menu-euseM8yR.js +2 -0
  23. package/web-dist/assets/Menu-euseM8yR.js.map +1 -0
  24. package/web-dist/assets/Overlay-BNPvMjLX.js +2 -0
  25. package/web-dist/assets/Overlay-BNPvMjLX.js.map +1 -0
  26. package/web-dist/assets/Priority-Ca1B2yFr.js +2 -0
  27. package/web-dist/assets/Priority-Ca1B2yFr.js.map +1 -0
  28. package/web-dist/assets/{SegmentedControl-BZPzNU08.js → SegmentedControl-D2d-NEr-.js} +2 -2
  29. package/web-dist/assets/{SegmentedControl-BZPzNU08.js.map → SegmentedControl-D2d-NEr-.js.map} +1 -1
  30. package/web-dist/assets/Select-C9L1HKMm.js +2 -0
  31. package/web-dist/assets/Select-C9L1HKMm.js.map +1 -0
  32. package/web-dist/assets/StatusChip-BYuVxYS7.js +2 -0
  33. package/web-dist/assets/StatusChip-BYuVxYS7.js.map +1 -0
  34. package/web-dist/assets/Switch-DAcUcSbH.js +2 -0
  35. package/web-dist/assets/Switch-DAcUcSbH.js.map +1 -0
  36. package/web-dist/assets/Tabs-xtagjtA5.js +184 -0
  37. package/web-dist/assets/Tabs-xtagjtA5.js.map +1 -0
  38. package/web-dist/assets/TextArea-CKGHwURx.js +2 -0
  39. package/web-dist/assets/TextArea-CKGHwURx.js.map +1 -0
  40. package/web-dist/assets/TextLink-Bub7sMxr.js +2 -0
  41. package/web-dist/assets/TextLink-Bub7sMxr.js.map +1 -0
  42. package/web-dist/assets/arrow-down-C-iLrN8I.js +2 -0
  43. package/web-dist/assets/arrow-down-C-iLrN8I.js.map +1 -0
  44. package/web-dist/assets/arrow-up-Dj-VTKx4.js +2 -0
  45. package/web-dist/assets/arrow-up-Dj-VTKx4.js.map +1 -0
  46. package/web-dist/assets/attention-CI4dHY81.js +2 -0
  47. package/web-dist/assets/attention-CI4dHY81.js.map +1 -0
  48. package/web-dist/assets/auth-308hUVgi.js +2 -0
  49. package/web-dist/assets/auth-308hUVgi.js.map +1 -0
  50. package/web-dist/assets/automations-BzpsJoa3.js +2 -0
  51. package/web-dist/assets/automations-BzpsJoa3.js.map +1 -0
  52. package/web-dist/assets/bell-DSwa2PAb.js +2 -0
  53. package/web-dist/assets/bell-DSwa2PAb.js.map +1 -0
  54. package/web-dist/assets/board-CeJxBVHC.js +10 -0
  55. package/web-dist/assets/board-CeJxBVHC.js.map +1 -0
  56. package/web-dist/assets/code-DkNQvMI9.js +12 -0
  57. package/web-dist/assets/code-DkNQvMI9.js.map +1 -0
  58. package/web-dist/assets/describe-CVXeUClF.js +5 -0
  59. package/web-dist/assets/describe-CVXeUClF.js.map +1 -0
  60. package/web-dist/assets/enroll-jnKygG4L.js +2 -0
  61. package/web-dist/assets/enroll-jnKygG4L.js.map +1 -0
  62. package/web-dist/assets/index-BHGZTS2e.js +16 -0
  63. package/web-dist/assets/index-BHGZTS2e.js.map +1 -0
  64. package/web-dist/assets/index-D2ml031z.css +2 -0
  65. package/web-dist/assets/logic-B46fwD-8.js +2 -0
  66. package/web-dist/assets/logic-B46fwD-8.js.map +1 -0
  67. package/web-dist/assets/more-DvKHMdBk.js +2 -0
  68. package/web-dist/assets/more-DvKHMdBk.js.map +1 -0
  69. package/web-dist/assets/queue-B2Vl0uSh.js +2 -0
  70. package/web-dist/assets/queue-B2Vl0uSh.js.map +1 -0
  71. package/web-dist/assets/repo-BDS8RBxq.js +2 -0
  72. package/web-dist/assets/repo-BDS8RBxq.js.map +1 -0
  73. package/web-dist/assets/server-BqZ-w6M8.js +2 -0
  74. package/web-dist/assets/server-BqZ-w6M8.js.map +1 -0
  75. package/web-dist/assets/settings-CLt7x9u8.js +8 -0
  76. package/web-dist/assets/settings-CLt7x9u8.js.map +1 -0
  77. package/web-dist/assets/states-C773NlHo.js +56 -0
  78. package/web-dist/assets/states-C773NlHo.js.map +1 -0
  79. package/web-dist/assets/terminal-BOV_MXPZ.js +2 -0
  80. package/web-dist/assets/terminal-BOV_MXPZ.js.map +1 -0
  81. package/web-dist/assets/terminal-login-BK5UjUir.js +2 -0
  82. package/web-dist/assets/terminal-login-BK5UjUir.js.map +1 -0
  83. package/web-dist/assets/useBackTo-BIrCq3W2.js +2 -0
  84. package/web-dist/assets/useBackTo-BIrCq3W2.js.map +1 -0
  85. package/web-dist/assets/useBreakpoint-BphHBrzF.js +2 -0
  86. package/web-dist/assets/useBreakpoint-BphHBrzF.js.map +1 -0
  87. package/web-dist/assets/useNow-Cm-tdyod.js +2 -0
  88. package/web-dist/assets/useNow-Cm-tdyod.js.map +1 -0
  89. package/web-dist/assets/useResource-BBqCoY2q.js +2 -0
  90. package/web-dist/assets/useResource-BBqCoY2q.js.map +1 -0
  91. package/web-dist/icon-192.png +0 -0
  92. package/web-dist/icon-512.png +0 -0
  93. package/web-dist/icon.svg +20 -8
  94. package/web-dist/index.html +7 -4
  95. package/web-dist/manifest.webmanifest +1 -1
  96. package/web-dist/maskable-512.png +0 -0
  97. package/web-dist/sw.js +1 -1
  98. package/web-dist/sw.js.map +1 -1
  99. package/web-dist/assets/AutomationView-GCthHkym.js +0 -2
  100. package/web-dist/assets/AutomationView-GCthHkym.js.map +0 -1
  101. package/web-dist/assets/Badge-CEMI3YyI.js +0 -2
  102. package/web-dist/assets/Badge-CEMI3YyI.js.map +0 -1
  103. package/web-dist/assets/InteractionCard-DaLqafmA.js +0 -6
  104. package/web-dist/assets/InteractionCard-DaLqafmA.js.map +0 -1
  105. package/web-dist/assets/Menu-BcKiEc6X.js +0 -2
  106. package/web-dist/assets/Menu-BcKiEc6X.js.map +0 -1
  107. package/web-dist/assets/Tabs-COH5EMql.js +0 -184
  108. package/web-dist/assets/Tabs-COH5EMql.js.map +0 -1
  109. package/web-dist/assets/TextArea-CeMEPZn4.js +0 -2
  110. package/web-dist/assets/TextArea-CeMEPZn4.js.map +0 -1
  111. package/web-dist/assets/arrow-left-C6YWM6y6.js +0 -2
  112. package/web-dist/assets/arrow-left-C6YWM6y6.js.map +0 -1
  113. package/web-dist/assets/attention-BAdea2kA.js +0 -2
  114. package/web-dist/assets/attention-BAdea2kA.js.map +0 -1
  115. package/web-dist/assets/automations-DSFUzB0w.js +0 -2
  116. package/web-dist/assets/automations-DSFUzB0w.js.map +0 -1
  117. package/web-dist/assets/board-eQ3H8yCp.js +0 -10
  118. package/web-dist/assets/board-eQ3H8yCp.js.map +0 -1
  119. package/web-dist/assets/code-D7JmYMKe.js +0 -13
  120. package/web-dist/assets/code-D7JmYMKe.js.map +0 -1
  121. package/web-dist/assets/copy-oWgGHmkS.js +0 -2
  122. package/web-dist/assets/copy-oWgGHmkS.js.map +0 -1
  123. package/web-dist/assets/describe-C1YimBXJ.js +0 -5
  124. package/web-dist/assets/describe-C1YimBXJ.js.map +0 -1
  125. package/web-dist/assets/dist-B_RpNOcK.js +0 -56
  126. package/web-dist/assets/dist-B_RpNOcK.js.map +0 -1
  127. package/web-dist/assets/enroll-1OCy5r50.js +0 -2
  128. package/web-dist/assets/enroll-1OCy5r50.js.map +0 -1
  129. package/web-dist/assets/index-BhpEXLav.js +0 -11
  130. package/web-dist/assets/index-BhpEXLav.js.map +0 -1
  131. package/web-dist/assets/index-DUeOwDZ6.css +0 -2
  132. package/web-dist/assets/logic-CBvFOyIo.js +0 -2
  133. package/web-dist/assets/logic-CBvFOyIo.js.map +0 -1
  134. package/web-dist/assets/more-RjVyxPaz.js +0 -2
  135. package/web-dist/assets/more-RjVyxPaz.js.map +0 -1
  136. package/web-dist/assets/now-CDjeFSLD.js +0 -2
  137. package/web-dist/assets/now-CDjeFSLD.js.map +0 -1
  138. package/web-dist/assets/plus-BLP-wIYD.js +0 -2
  139. package/web-dist/assets/plus-BLP-wIYD.js.map +0 -1
  140. package/web-dist/assets/save-DEvZPWlS.js +0 -2
  141. package/web-dist/assets/save-DEvZPWlS.js.map +0 -1
  142. package/web-dist/assets/search-C6cn5WOo.js +0 -2
  143. package/web-dist/assets/search-C6cn5WOo.js.map +0 -1
  144. package/web-dist/assets/send-BKjswHxB.js +0 -2
  145. package/web-dist/assets/send-BKjswHxB.js.map +0 -1
  146. package/web-dist/assets/server-SxFxIScj.js +0 -2
  147. package/web-dist/assets/server-SxFxIScj.js.map +0 -1
  148. package/web-dist/assets/settings-tH4UuIfJ.js +0 -7
  149. package/web-dist/assets/settings-tH4UuIfJ.js.map +0 -1
  150. package/web-dist/assets/shared-CRX6KSBm.js +0 -3
  151. package/web-dist/assets/shared-CRX6KSBm.js.map +0 -1
  152. package/web-dist/assets/sliders-horizontal-DAoirila.js +0 -2
  153. package/web-dist/assets/sliders-horizontal-DAoirila.js.map +0 -1
  154. package/web-dist/assets/states-DXozulGZ.js +0 -2
  155. package/web-dist/assets/states-DXozulGZ.js.map +0 -1
  156. package/web-dist/assets/terminal-login-CW2rE50W.js +0 -2
  157. package/web-dist/assets/terminal-login-CW2rE50W.js.map +0 -1
  158. package/web-dist/assets/trash-C6X2OLrI.js +0 -2
  159. package/web-dist/assets/trash-C6X2OLrI.js.map +0 -1
  160. package/web-dist/assets/useNow-C_B7JgMM.js +0 -2
  161. 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);
@@ -92,6 +122,30 @@ function runHolder(cfg) {
92
122
  } catch {
93
123
  }
94
124
  };
125
+ const sizes = /* @__PURE__ */ new Map();
126
+ const apply = (from) => {
127
+ if (cfg.sizing === "latest") {
128
+ const z = from ? sizes.get(from) : void 0;
129
+ if (z)
130
+ resize(z.cols, z.rows);
131
+ return;
132
+ }
133
+ if (sizes.size === 0)
134
+ return;
135
+ let cols = Number.POSITIVE_INFINITY;
136
+ let rows = Number.POSITIVE_INFINITY;
137
+ for (const z of sizes.values()) {
138
+ cols = Math.min(cols, z.cols);
139
+ rows = Math.min(rows, z.rows);
140
+ }
141
+ resize(cols, rows);
142
+ };
143
+ const report = (socket, cols, rows) => {
144
+ if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 2 || rows < 2)
145
+ return;
146
+ sizes.set(socket, { cols, rows });
147
+ apply(socket);
148
+ };
95
149
  const toControl = (line) => {
96
150
  if (control && !control.destroyed) {
97
151
  write(control, line);
@@ -103,14 +157,25 @@ function runHolder(cfg) {
103
157
  gap = true;
104
158
  }
105
159
  };
106
- const sendExtension = (line) => {
160
+ const sendExtension = (line, rec) => {
107
161
  if (extension && !extension.destroyed) {
108
162
  write(extension, line);
109
163
  return;
110
164
  }
165
+ if (toExtension.length >= MAX_TO_EXTENSION) {
166
+ if (rec && typeof rec.id === "string" && typeof rec.type === "string" && rec.type !== "extension_ui_response") {
167
+ write(control, JSON.stringify({
168
+ type: "response",
169
+ id: rec.id,
170
+ command: rec.type,
171
+ success: false,
172
+ error: HOLDER_QUEUE_FULL,
173
+ holder: true
174
+ }));
175
+ }
176
+ return;
177
+ }
111
178
  toExtension.push(line);
112
- if (toExtension.length > MAX_TO_EXTENSION)
113
- toExtension.shift();
114
179
  };
115
180
  const shutdown = () => {
116
181
  if (shuttingDown)
@@ -123,31 +188,65 @@ function runHolder(cfg) {
123
188
  } catch {
124
189
  }
125
190
  rmSync(cfg.socketPath, { force: true });
191
+ if (exitDelivered)
192
+ rmSync(exitPath, { force: true });
126
193
  setTimeout(() => process.exit(0), 100).unref();
127
194
  };
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 }) => {
195
+ const onPiExit = ({ exitCode, signal }, extra) => {
137
196
  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();
197
+ term.write("", () => {
198
+ const screen = extra ?? lastScreenLines(term);
199
+ exitRecord = JSON.stringify({ type: "holder_exit", ...exitInfo, screen });
200
+ try {
201
+ writeFileSync(exitPath, JSON.stringify({ ...exitInfo, screen, at: (/* @__PURE__ */ new Date()).toISOString() }), {
202
+ mode: 384
203
+ });
204
+ } catch {
205
+ }
206
+ const closed = JSON.stringify({ t: "closed", reason: "Pi exited" });
207
+ for (const v of viewers) {
208
+ write(v, closed);
209
+ v.end();
210
+ }
211
+ viewers.clear();
212
+ if (control && !control.destroyed) {
213
+ write(control, exitRecord);
214
+ exitDelivered = true;
215
+ setTimeout(shutdown, 1e3).unref();
216
+ } else {
217
+ setTimeout(shutdown, killRequested ? 1e3 : EXIT_WAIT_MS).unref();
218
+ }
219
+ });
220
+ };
221
+ const startPi = () => {
222
+ try {
223
+ proc = pty.spawn(cfg.piBin, cfg.args, {
224
+ name: "xterm-256color",
225
+ cols: cfg.cols,
226
+ rows: cfg.rows,
227
+ cwd: cfg.cwd,
228
+ env: cfg.env
229
+ });
230
+ } catch (err) {
231
+ process.stderr.write(`switchyard holder: could not start ${cfg.piBin}: ${err.message}
232
+ `);
233
+ onPiExit({ exitCode: null }, [`Could not start ${cfg.piBin}: ${err.message}`]);
234
+ return;
142
235
  }
143
- viewers.clear();
236
+ const started = proc;
237
+ started.onData((d) => {
238
+ term.write(d);
239
+ if (viewers.size === 0)
240
+ return;
241
+ const line = JSON.stringify({ t: "out", d: Buffer.from(d, "utf8").toString("base64") });
242
+ for (const v of viewers)
243
+ write(v, line);
244
+ });
245
+ started.onExit(onPiExit);
144
246
  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();
247
+ write(control, JSON.stringify({ type: "holder_status", piPid: started.pid }));
149
248
  }
150
- });
249
+ };
151
250
  const server = createServer((socket) => {
152
251
  let role = null;
153
252
  socket.on("error", () => {
@@ -173,15 +272,16 @@ function runHolder(cfg) {
173
272
  if (control && control !== socket)
174
273
  control.destroy();
175
274
  control = socket;
176
- write(socket, JSON.stringify({ type: "holder_status", piPid: proc.pid }));
275
+ write(socket, JSON.stringify({ type: "holder_status", piPid: proc?.pid ?? null }));
177
276
  if (gap) {
178
277
  write(socket, JSON.stringify({ type: "holder_gap" }));
179
278
  gap = false;
180
279
  }
181
280
  for (const l of buffer.splice(0))
182
281
  write(socket, l);
183
- if (exitInfo) {
184
- write(socket, JSON.stringify({ type: "holder_exit", ...exitInfo }));
282
+ if (exitRecord) {
283
+ write(socket, exitRecord);
284
+ exitDelivered = true;
185
285
  setTimeout(shutdown, 1e3).unref();
186
286
  }
187
287
  if (extension && !extension.destroyed) {
@@ -195,7 +295,7 @@ function runHolder(cfg) {
195
295
  return;
196
296
  }
197
297
  viewers.add(socket);
198
- resize(Number(hello.cols), Number(hello.rows));
298
+ report(socket, Number(hello.cols), Number(hello.rows));
199
299
  setImmediate(() => {
200
300
  try {
201
301
  const screen = serializer.serialize();
@@ -215,7 +315,7 @@ function runHolder(cfg) {
215
315
  } catch {
216
316
  }
217
317
  if (rec?.type === "holder_keys") {
218
- if (!exitInfo && typeof rec.data === "string")
318
+ if (!exitInfo && proc && typeof rec.data === "string")
219
319
  proc.write(rec.data);
220
320
  return;
221
321
  }
@@ -230,12 +330,12 @@ function runHolder(cfg) {
230
330
  }
231
331
  if (rec?.type === "holder_kill") {
232
332
  try {
233
- proc.kill(typeof rec.signal === "string" ? rec.signal : "SIGTERM");
333
+ proc?.kill(typeof rec.signal === "string" ? rec.signal : "SIGTERM");
234
334
  } catch {
235
335
  }
236
336
  return;
237
337
  }
238
- sendExtension(line);
338
+ sendExtension(line, rec);
239
339
  return;
240
340
  }
241
341
  let msg;
@@ -245,32 +345,42 @@ function runHolder(cfg) {
245
345
  return;
246
346
  }
247
347
  if (msg?.t === "in" && typeof msg.d === "string") {
248
- if (!exitInfo)
348
+ if (!exitInfo && proc)
249
349
  proc.write(Buffer.from(msg.d, "base64").toString("utf8"));
250
350
  } else if (msg?.t === "resize") {
251
- resize(Number(msg.cols), Number(msg.rows));
351
+ report(socket, Number(msg.cols), Number(msg.rows));
252
352
  }
253
353
  });
254
354
  socket.on("close", () => {
255
- if (role === "viewer")
355
+ if (role === "viewer") {
256
356
  viewers.delete(socket);
257
- else if (role === "control" && control === socket)
357
+ if (sizes.delete(socket))
358
+ apply();
359
+ } else if (role === "control" && control === socket)
258
360
  control = null;
259
361
  else if (role === "extension" && extension === socket)
260
362
  extension = null;
261
363
  });
262
364
  });
365
+ server.on("error", (err) => {
366
+ process.stderr.write(`switchyard holder: cannot listen on ${cfg.socketPath}: ${err.message}
367
+ `);
368
+ process.exit(1);
369
+ });
370
+ const oldMask = process.umask(63);
263
371
  server.listen(cfg.socketPath, () => {
372
+ process.umask(oldMask);
264
373
  try {
265
374
  chmodSync(cfg.socketPath, 384);
266
375
  } catch {
267
376
  }
377
+ startPi();
268
378
  });
269
379
  process.on("uncaughtException", (err) => {
270
380
  process.stderr.write(`switchyard holder: ${err.stack ?? err.message}
271
381
  `);
272
382
  try {
273
- proc.kill();
383
+ proc?.kill();
274
384
  } catch {
275
385
  }
276
386
  rmSync(cfg.socketPath, { force: true });
@@ -278,6 +388,11 @@ function runHolder(cfg) {
278
388
  });
279
389
  for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"]) {
280
390
  process.on(sig, () => {
391
+ killRequested = true;
392
+ if (!proc) {
393
+ rmSync(cfg.socketPath, { force: true });
394
+ process.exit(0);
395
+ }
281
396
  try {
282
397
  proc.kill(sig);
283
398
  } catch {
@@ -300,6 +415,8 @@ if (isMain()) {
300
415
  runHolder(JSON.parse(raw));
301
416
  }
302
417
  export {
418
+ HOLDER_QUEUE_FULL,
303
419
  ensureSpawnHelper,
420
+ lastScreenLines,
304
421
  runHolder
305
422
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spencerboucher/switchyard",
3
- "version": "0.8.0",
3
+ "version": "0.10.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{b as c,g as l,h as u,o as d,x as f}from"./StatusChip-BYuVxYS7.js";import{A as ee,P as te,_ as ne,_t as re,bt as p,c as m,d as h,gt as g,h as _,ht as ie,i as ae,it as oe,n as v,nt as y,r as b,s as se,t as x,u as S,v as C,vt as ce,yt as w,z as T}from"./states-C773NlHo.js";import{a as le,i as ue,n as de,t as E}from"./Field-Dbg_8KTt.js";import{t as D}from"./calendar-clock-B8zE4JsX.js";import{n as fe,r as pe}from"./Copy-D8xhl7eJ.js";import{n as me,r as he,t as ge}from"./Priority-Ca1B2yFr.js";import{a as _e,i as O,t as ve,u as ye}from"./useBreakpoint-BphHBrzF.js";import{t as be}from"./key-round-VDbE9E4X.js";import{t as xe}from"./play-CjoDg3ws.js";import{i as k,n as Se,r as Ce}from"./useBackTo-BIrCq3W2.js";import{n as we,t as Te}from"./DangerZone-og55TRug.js";import{x as Ee}from"./index-BHGZTS2e.js";import{o as A,t as De}from"./Overlay-BNPvMjLX.js";import{n as j,r as M}from"./TextArea-CKGHwURx.js";import{t as N}from"./TextLink-Bub7sMxr.js";import{t as P}from"./SegmentedControl-D2d-NEr-.js";import{t as F}from"./Card-CAFxHoHd.js";import{t as I}from"./Select-C9L1HKMm.js";import{t as L}from"./Switch-DAcUcSbH.js";import{E as R,O as Oe,S as ke,T as z,a as B,b as Ae,d as je,f as V,g as H,h as U,i as W,l as G,m as Me,n as Ne,o as Pe,p as K,r as q,s as Fe,t as Ie,u as Le,v as Re,w as J,x as ze,y as Be}from"./describe-CVXeUClF.js";var Y={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`}]]};Y.node;var Ve=i(Y),X=e(r(),1),Z=o(),He=e=>`/tasks/${encodeURIComponent(e)}`;function Q(e){return p(e)&&(e.status===404||e.status===405||e.status===501)}function Ue({summary:e,errorCount:t}){return(0,Z.jsxs)(F,{stack:!0,title:`Summary`,testId:`automation-summary`,children:[(0,Z.jsx)(`p`,{className:`text-sm break-words`,children:e}),t>0&&(0,Z.jsxs)(`p`,{className:`flex items-center gap-1.5 text-sm text-danger`,children:[(0,Z.jsx)(C,{"aria-hidden":!0,className:`size-4 shrink-0`}),t===1?`1 field needs attention`:`${t} fields need attention`]})]})}async function We(e,t,n){return e&&!n?g(J(e,`/preview`)):ce(`/api/automations/preview`,t)}function Ge({automationId:e,dirty:t,getInput:n,currentKey:r}){let[i,a]=(0,X.useState)({status:`idle`}),o=async()=>{let r=n();if(!r)O.error(`Fix the highlighted fields to preview the task`);else{a({status:`loading`});try{let n=await We(e,r,t);a({status:`done`,preview:n,key:JSON.stringify(r)})}catch(e){a(Q(e)?{status:`unsupported`}:{status:`error`,error:e})}}};return(0,Z.jsxs)(F,{stack:!0,title:`Preview`,description:`See the task an occurrence would create, and when it would run next.`,testId:`automation-preview`,children:[(0,Z.jsx)(`div`,{children:(0,Z.jsx)(h,{icon:(0,Z.jsx)(l,{className:`size-4`}),busy:i.status===`loading`,onClick:()=>void o(),children:`Preview resulting task`})}),i.status===`unsupported`&&(0,Z.jsx)(S,{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,Z.jsx)(v,{compact:!0,title:`Could not preview`,error:i.error,onRetry:()=>void o()}),i.status===`done`&&(0,Z.jsx)(Ke,{preview:i.preview,stale:i.key!==r})]})}function Ke({preview:e,stale:t}){let{task:n}=e;return(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3`,children:[t&&(0,Z.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs text-warning`,role:`status`,children:[(0,Z.jsx)(C,{"aria-hidden":!0,className:`size-3.5 shrink-0`}),`The form changed since this preview. Preview again to refresh it.`]}),(0,Z.jsx)(`p`,{className:`text-sm break-words text-muted`,children:e.summary}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2 rounded-md border border-border bg-surface-2 p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-start justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`min-w-0 font-medium break-words`,children:n.title}),(0,Z.jsx)(me,{priority:n.priority,muted:!0,className:`shrink-0 text-xs`})]}),n.objective?(0,Z.jsx)(`p`,{className:`text-sm break-words whitespace-pre-wrap`,children:n.objective}):(0,Z.jsx)(`p`,{className:`text-sm text-muted`,children:`No objective.`}),n.acceptanceCriteria.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`h4`,{className:`flex items-center gap-1 text-xs font-medium text-muted`,children:[(0,Z.jsx)(u,{"aria-hidden":!0,className:`size-3.5`}),`Acceptance criteria`]}),(0,Z.jsx)(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:n.acceptanceCriteria.map((e,t)=>(0,Z.jsx)(`li`,{className:`break-words`,children:e},t))})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Next occurrences`}),e.next.length===0?(0,Z.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,Z.jsx)(`ol`,{className:`mt-1 flex flex-col gap-0.5 text-sm`,children:e.next.slice(0,5).map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-wrap gap-x-2`,children:[(0,Z.jsx)(`time`,{dateTime:e,children:K(e)}),(0,Z.jsx)(`span`,{className:`text-muted`,children:_(e)})]},e))})]})]})}function qe({label:e,value:t,mono:n=!0}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted`,children:e}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[(0,Z.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,Z.jsx)(h,{size:`sm`,icon:(0,Z.jsx)(pe,{className:`size-3.5`}),onClick:()=>void fe(t,`${e} copied`),"aria-label":`Copy ${e.toLowerCase()}`,children:`Copy`})]})]})}function Je({automation:e}){let[t,n]=(0,X.useState)(!1),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),l=e.webhookTokenSet||a!==null,u=async()=>{i(!1),n(!0);try{let t=await ce(J(e.id,`/webhook-token`)),n=y.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}),O.success(l?`Webhook token rotated`:`Webhook token created`)}catch(e){Q(e)?c(!0):O.error(`Could not issue a webhook token: ${w(e)}`)}finally{n(!1)}};return(0,Z.jsxs)(F,{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,Z.jsx)(`p`,{className:`flex items-center gap-1.5 text-sm`,children:l?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ye,{"aria-hidden":!0,className:`size-4 shrink-0 text-success`}),`A token is set`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(f,{"aria-hidden":!0,className:`size-4 shrink-0 text-muted`}),`No token yet: webhook calls are rejected until you create one`]})}),s?(0,Z.jsx)(S,{capability:`Webhook tokens`,reason:`This coordinator does not issue webhook tokens.`}):(0,Z.jsx)(`div`,{children:(0,Z.jsx)(h,{icon:(0,Z.jsx)(be,{className:`size-4`}),busy:t,onClick:()=>l?i(!0):void u(),children:l?`Rotate token`:`Create token`})}),a&&(0,Z.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,Z.jsxs)(`p`,{className:`flex items-center gap-1.5 text-sm font-medium`,children:[(0,Z.jsx)(C,{"aria-hidden":!0,className:`size-4 shrink-0 text-warning`}),`This token is shown once. Copy it now.`]}),(0,Z.jsx)(qe,{label:`Token`,value:a.token}),(0,Z.jsx)(qe,{label:`URL`,value:a.url}),(0,Z.jsx)(qe,{label:`Example`,value:Pe(a.token,a.url)}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(h,{size:`sm`,onClick:()=>o(null),children:`I have copied it`})})]}),(0,Z.jsx)(De,{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=T(t=>t.occurrences[e]??Ye),i=T(e=>e.tasks),[a,o]=(0,X.useState)({status:`loading`}),s=(0,X.useCallback)(async t=>{o(e=>e.status===`done`?e:{status:`loading`});try{let n=await g(J(e,`/history`),{},t);o({status:`done`,items:Re(n)})}catch(e){if(t?.aborted)return;o(Q(e)?{status:`unsupported`}:{status:`error`,error:e})}},[e]);(0,X.useEffect)(()=>{let e=new AbortController;return s(e.signal),()=>e.abort()},[s,t]);let c=H(a.status===`done`?a.items:[],r);return(0,Z.jsxs)(F,{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,Z.jsx)(S,{capability:`Automation history`,reason:`This coordinator does not serve stored history; only occurrences seen live in this session are shown.`}),a.status===`error`&&(0,Z.jsx)(v,{compact:!0,title:`Could not load history`,error:a.error,onRetry:()=>void s()}),a.status===`loading`&&c.length===0?(0,Z.jsx)(m,{label:`Loading history…`,className:`py-4`}):c.length===0&&a.status!==`error`?(0,Z.jsx)(x,{className:`py-4`,icon:(0,Z.jsx)(Ve,{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,Z.jsx)(xe,{className:`size-4`})}}):(0,Z.jsx)(`ol`,{className:`flex flex-col divide-y divide-border`,children:c.map(e=>{let t=Be(e),n=e.taskId?i[e.taskId]:void 0,r=[e.reason,e.outcome].filter(Boolean).join(` · `);return(0,Z.jsxs)(`li`,{className:`flex min-w-0 flex-col gap-1 py-2 first:pt-0 last:pb-0`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,Z.jsx)(d,{kind:`occurrence`,value:e.state,size:`sm`}),(0,Z.jsx)(`time`,{dateTime:t,className:`text-sm`,children:K(t)}),(0,Z.jsx)(`span`,{className:`text-xs text-muted`,children:_(t)})]}),r&&(0,Z.jsx)(`p`,{className:`text-sm break-words text-muted`,children:r}),e.taskId&&(0,Z.jsxs)(N,{to:He(e.taskId),variant:`action`,size:`sm`,className:`self-start`,children:[(0,Z.jsx)(`span`,{className:`min-w-0 truncate`,children:n?`Task: ${n.title}`:`Open task`}),n?.hiddenFromBoard&&(0,Z.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,Z.jsx)(tt,{automationId:e},e)}function tt({automationId:e}){let t=e===`new`,n=T(e=>e.hydrated),r=R(t?void 0:e),[i,a]=(0,X.useState)({status:`idle`}),o=(0,X.useCallback)(async()=>{a({status:`loading`});try{let t=await g(J(e)),n=oe.safeParse(t);if(!n.success){a({status:`fatal`,error:Error(`The coordinator returned this automation in an unexpected format.`)});return}z.getState().put(n.data),a({status:`idle`})}catch(e){p(e)&&e.status===404?a({status:`notfound`}):a({status:`error`,error:e})}},[e]),s=!t&&!r;return(0,X.useEffect)(()=>{s&&i.status===`idle`&&o()},[s,i.status,o]),t?(0,Z.jsx)(at,{automation:null}):r?(0,Z.jsx)(at,{automation:r}):i.status===`notfound`?(0,Z.jsx)(x,{icon:(0,Z.jsx)(Ee,{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,Z.jsx)(v,{title:`Could not load this automation`,error:i.error,onRetry:()=>void o()}):i.status===`fatal`?(0,Z.jsx)(b,{error:i.error}):(0,Z.jsx)(m,{label:n?`Loading automation…`:`Loading…`})}function nt(e){let t=je({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(Le(e));function it(e){if(!p(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=V(t);i!==`form`&&!r[i]&&(r[i]=n)}return r}function at({automation:e}){let r=t(),i=s(),a=Ce(Ze),o=ve(),l=o===`desktop`,u=te(),d=ee(),f=T(e=>e.hosts),p=T(e=>e.profiles),m=T(e=>e.tasks),g=T(e=>e.projects),_=e===null,oe=(0,X.useId)(),v=(0,X.useRef)(null),[y,b]=(0,X.useState)(()=>e?G(e):nt(u[0]?.id)),[x,S]=(0,X.useState)(()=>$(y)),[E,D]=(0,X.useState)(!1),[fe,pe]=(0,X.useState)({}),[me,he]=(0,X.useState)(!1),[ge,ye]=(0,X.useState)(!1),[be,k]=(0,X.useState)(!1),[Ee,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(0),N=(0,X.useRef)(e?.updatedAt),P=$(y),F=P!==x;(0,X.useEffect)(()=>{if(!e||e.updatedAt===N.current)return;N.current=e.updatedAt;let t=G(e),n=$(t);P===x?(b(t),A(!1)):n!==P&&A(!0),S(n)},[e,P,x]),(0,X.useEffect)(()=>{_&&rt(y)},[_,y]),(0,X.useEffect)(()=>{_&&!y.projectId&&u[0]&&b(e=>e.projectId?e:{...e,projectId:u[0].id})},[_,y.projectId,u]);let I=(0,X.useCallback)((e,t)=>{b(n=>({...n,[e]:t})),pe(e=>Object.keys(e).length?{}:e)},[]),L=(0,X.useMemo)(()=>ke(y),[y]),R={...fe,...E?L.errors:{}},B=e=>R[e],V=g[y.projectId],H=y.hostId||V?.defaultHostId||null,W=H?f[H]:void 0,Me=y.profileId||V?.defaultProfileId||null,Ne=(0,X.useCallback)(e=>m[e]?.title,[m]),Pe=(0,X.useMemo)(()=>Ae(Le(y),{projectName:V?.name,hostName:y.hostId?f[y.hostId]?.name??null:null,profileName:y.profileId?p[y.profileId]?.name??null:null,taskTitle:Ne}),[y,V?.name,f,p,Ne]),K=()=>{requestAnimationFrame(()=>{v.current?.querySelector(`[aria-invalid="true"]`)?.focus()})},q=()=>(D(!0),L.input||K(),L.input),Fe=async()=>{let t=q();if(!t)O.error(`Fix the highlighted fields before saving`);else{he(!0);try{if(_){let e=await ce(`/api/automations`,t);if(!e||typeof e!=`object`||!e.id)throw Error(`The coordinator did not return the new automation`);z.getState().put(e),rt(null),O.success(`Created ${e.name}`),r(Qe(e.id),{replace:!0,state:i.state});return}let n=await re(J(e.id),t);if(n&&typeof n==`object`&&n.id){z.getState().put(n),N.current=n.updatedAt;let e=G(n);b(e),S($(e))}else S(P);A(!1),D(!1),O.success(`Saved ${t.name}`)}catch(e){let t=it(e);pe(t),Object.keys(t).length&&K(),O.error(`Could not save: ${w(e)}. Your changes are kept.`)}finally{he(!1)}}},Ie=async()=>{if(e){ye(!0);try{await ie(J(e.id)),k(!1),O.success(`Deleted ${e.name}`),a(),z.getState().remove(e.id)}catch(e){O.error(`Could not delete: ${w(e)}`)}finally{ye(!1)}}},{busy:Re,run:ze}=Oe(()=>M(e=>e+1)),Be=e?!!Re[e.id]:!1,Y=()=>e&&void ze(e),Ve=()=>{let e=je({projectId:u[0]?.id,timezone:U()});b(e),D(!1),rt(null)},He=_?`New automation`:e.name,Q=(0,Z.jsxs)(Z.Fragment,{children:[!_&&(0,Z.jsx)(h,{icon:(0,Z.jsx)(xe,{className:`size-4`}),busy:Be,onClick:Y,title:F?`Runs the saved version`:void 0,children:`Run now`}),_&&F&&(0,Z.jsx)(h,{variant:`ghost`,icon:(0,Z.jsx)(_e,{className:`size-4`}),onClick:Ve,children:`Discard draft`})]}),We=e=>(0,Z.jsx)(h,{type:`submit`,form:oe,variant:`primary`,busy:me,block:e,icon:(0,Z.jsx)(we,{className:`size-4`}),children:_?`Create automation`:`Save`}),Ke=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ue,{summary:Pe,errorCount:E?Object.keys(L.errors).length:0}),(0,Z.jsx)(Ge,{automationId:e?.id??null,dirty:F,getInput:q,currentKey:JSON.stringify(L.input)}),e&&e.trigger.kind===`webhook`&&(0,Z.jsx)(Je,{automation:e}),e&&(0,Z.jsx)(Xe,{automationId:e.id,refreshKey:j,onRun:Y})]});return(0,Z.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,Z.jsxs)(`header`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,Z.jsxs)(n,{to:Ze,onClick:Se(a),className:`tap inline-flex items-center gap-1 self-start rounded text-sm text-muted hover:text-text`,children:[(0,Z.jsx)(le,{"aria-hidden":!0,className:`size-4`}),`Automations`]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`h1`,{className:`min-w-0 text-lg font-semibold break-words`,children:He}),F&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-xs text-muted`,children:[(0,Z.jsx)(c,{"aria-hidden":!0,className:`size-3.5`}),`Unsaved changes`]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[Q,l&&We()]})]})]}),(0,Z.jsx)(se,{subject:`automations`,consequence:`Changes are sent once the coordinator is reachable again.`}),W&&W.connectivity!==`connected`&&(0,Z.jsx)(ae,{compact:!0,hostName:W.name,connectivity:W.connectivity,lastSeenAt:W.lastSeenAt,detail:`Occurrences are still recorded; their tasks wait until the host is reachable.`}),Ee&&(0,Z.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,Z.jsx)(C,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0 text-warning`}),`This automation changed elsewhere. Saving overwrites those changes with yours.`]}),(0,Z.jsxs)(`div`,{className:ne(`grid min-w-0 gap-4`,l?`grid-cols-[minmax(0,1fr)_minmax(320px,400px)] items-start`:`grid-cols-1`),children:[(0,Z.jsxs)(`form`,{id:oe,ref:v,noValidate:!0,"aria-label":He,onSubmit:e=>{e.preventDefault(),Fe()},className:`flex min-w-0 flex-col gap-4`,children:[(0,Z.jsx)(ot,{draft:y,update:I,err:B,projects:u}),(0,Z.jsx)(lt,{draft:y,update:I,err:B,tasks:m,projectsById:g,savedAutomation:e,segmented:o!==`mobile`}),(0,Z.jsx)(ut,{draft:y,setDraft:b,err:B}),(0,Z.jsx)(dt,{draft:y,update:I,err:B}),(0,Z.jsx)(pt,{draft:y,update:I,err:B,hosts:d,profiles:Object.values(p).sort((e,t)=>e.name.localeCompare(t.name)),defaultHostName:V?.defaultHostId?f[V.defaultHostId]?.name:void 0,defaultProfileName:V?.defaultProfileId?p[V.defaultProfileId]?.name:void 0,selectedProfileMissing:!!Me&&!p[Me]}),(0,Z.jsx)(mt,{draft:y,update:I}),(0,Z.jsx)(ht,{draft:y,update:I,err:B}),(0,Z.jsx)(gt,{draft:y,update:I,err:B,projectChecks:V?.checks}),R.form&&(0,Z.jsx)(de,{children:R.form})]}),(0,Z.jsx)(`aside`,{"aria-label":`Summary, preview and history`,className:`flex min-w-0 flex-col gap-4`,children:Ke})]}),!_&&e&&(0,Z.jsx)(Te,{description:`Future occurrences stop. Tasks it already created stay on the board; its history is removed.`,children:(0,Z.jsx)(h,{variant:`danger`,icon:(0,Z.jsx)(ue,{className:`size-4`}),onClick:()=>k(!0),children:`Delete automation`})}),l?(0,Z.jsx)(`div`,{className:`h-4`}):(0,Z.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,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm text-muted`,children:F?`Unsaved changes`:_?`Not saved yet`:`All changes saved`}),We()]}),(0,Z.jsx)(De,{open:be,onClose:()=>k(!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,Z.jsx)(ue,{className:`size-4`}),busy:ge,onConfirm:()=>void Ie()})]})}function ot({draft:e,update:t,err:n,projects:r}){return(0,Z.jsxs)(F,{stack:!0,title:`Basics`,children:[(0,Z.jsx)(E,{label:`Name`,error:n(`name`),children:n=>(0,Z.jsx)(M,{...n,value:e.name,onChange:e=>t(`name`,e.target.value),placeholder:`Daily dependency check`,autoComplete:`off`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(E,{label:`Project`,error:n(`projectId`),hint:r.length===0?(0,Z.jsxs)(Z.Fragment,{children:[`No projects yet.`,` `,(0,Z.jsx)(N,{to:`/settings/projects`,children:`Add a project in Settings`}),`.`]}):void 0,children:n=>(0,Z.jsxs)(I,{...n,value:e.projectId,onChange:e=>t(`projectId`,e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`Choose a project`}),r.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]})}),(0,Z.jsx)(E,{label:`Status`,hint:`Disabled automations keep their history and can still run manually.`,children:n=>(0,Z.jsx)(L,{...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=T(e=>e.hydrated),c=e.triggerKind===`cron`?ze(e.cronExpr):null,l=e.triggerKind===`cron`&&!c?Fe(e.cronExpr,e.cronTimezone.trim()||void 0)??`Valid expression (no plain-language description available)`:null,u=(0,X.useMemo)(()=>{try{return Intl.supportedValuesOf?.(`timeZone`)}catch{return}},[]),d=(0,X.useId)(),f=U(),ee=(0,X.useMemo)(()=>Object.values(r).filter(t=>t.state!==`canceled`||t.id===e.dependencyTaskId).sort((e,t)=>e.title.localeCompare(t.title)),[r,e.dependencyTaskId]),te=e.triggerKind===`once`?Me(e.onceAt):``;return(0,Z.jsxs)(F,{stack:!0,title:`Trigger`,description:ct[e.triggerKind],children:[o?(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-1`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`text-sm font-medium`,children:`Trigger kind`}),(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsx)(P,{label:`Trigger kind`,value:e.triggerKind,onChange:e=>t(`triggerKind`,e),options:st.map(e=>({value:e,label:B[e]}))})})]}):(0,Z.jsx)(E,{label:`Trigger kind`,children:n=>(0,Z.jsx)(I,{...n,value:e.triggerKind,onChange:e=>t(`triggerKind`,e.target.value),children:st.map(e=>(0,Z.jsx)(`option`,{value:e,children:B[e]},e))})}),e.triggerKind===`once`&&(0,Z.jsx)(E,{label:`Run at`,error:n(`onceAt`),hint:`Local time (${f})${te?`; saved as ${te}`:``}.`,children:n=>(0,Z.jsx)(M,{...n,type:`datetime-local`,value:e.onceAt,onChange:e=>t(`onceAt`,e.target.value)})}),e.triggerKind===`cron`&&(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(E,{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,Z.jsx)(M,{...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,Z.jsx)(E,{label:`Timezone`,error:n(`cronTimezone`),hint:e.cronTimezone.trim()===f?`IANA timezone name; daylight saving is handled.`:(0,Z.jsxs)(N,{onClick:()=>t(`cronTimezone`,f),children:[`Use this device's timezone (`,f,`)`]}),children:n=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(M,{...n,list:u?d:void 0,value:e.cronTimezone,onChange:e=>t(`cronTimezone`,e.target.value),autoComplete:`off`,spellCheck:!1,autoCapitalize:`off`}),u&&(0,Z.jsx)(`datalist`,{id:d,children:u.map(e=>(0,Z.jsx)(`option`,{value:e},e))})]})}),l&&(0,Z.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm sm:col-span-2`,"aria-live":`polite`,"data-testid":`cron-description`,children:[(0,Z.jsx)(D,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0 text-muted`}),(0,Z.jsx)(`span`,{className:`min-w-0 break-words`,children:l})]})]}),e.triggerKind===`webhook`&&(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 text-sm text-muted`,children:[(0,Z.jsxs)(`p`,{children:[`Senders POST a JSON body (up to 256 KB) with`,` `,(0,Z.jsx)(`code`,{children:`Authorization: Bearer <token>`}),`. Use the filters below to fire only for matching payloads, and `,(0,Z.jsx)(`code`,{children:`{{payload.<path>}}`}),` to copy payload values into the task.`]}),a?a.trigger.kind===`webhook`?(0,Z.jsxs)(`p`,{children:[`Token:`,` `,a.webhookTokenSet?`set (see Webhook below to rotate)`:`not created yet`]}):(0,Z.jsx)(`p`,{children:`Save to switch this automation to a webhook trigger, then create a token.`}):(0,Z.jsx)(`p`,{children:`Save the automation to create its webhook token and URL.`})]}),e.triggerKind===`dependency`&&(0,Z.jsx)(E,{label:`When this task is done`,error:n(`dependencyTaskId`),hint:`Fires once each time the task enters Done.`,children:n=>(0,Z.jsxs)(I,{...n,value:e.dependencyTaskId,onChange:e=>t(`dependencyTaskId`,e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`Choose a task`}),e.dependencyTaskId&&!r[e.dependencyTaskId]&&(0,Z.jsx)(`option`,{value:e.dependencyTaskId,children:s?`Deleted task`:`Loading task…`}),ee.map(e=>(0,Z.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,Z.jsxs)(F,{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,Z.jsx)(`p`,{className:`text-sm text-muted`,children:`Filters are ignored unless the trigger is Webhook.`}),e.filters.length===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted`,children:`No filters: every payload fires.`}),e.filters.map((e,i)=>(0,Z.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,Z.jsx)(E,{label:`Path ${i+1}`,error:n(`filters.${i}.path`),children:t=>(0,Z.jsx)(M,{...t,value:e.path,onChange:e=>r(i,{path:e.target.value}),placeholder:`action`,className:`font-mono`,autoCapitalize:`off`,spellCheck:!1})}),(0,Z.jsx)(E,{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,Z.jsx)(M,{...t,value:e.equals,onChange:e=>r(i,{equals:e.target.value}),placeholder:`opened`})}),(0,Z.jsx)(A,{label:`Remove filter ${i+1}`,icon:(0,Z.jsx)(_e,{className:`size-4`}),onClick:()=>t(e=>({...e,filters:e.filters.filter((e,t)=>t!==i)}))})]},i)),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(h,{size:`sm`,icon:(0,Z.jsx)(k,{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,Z.jsxs)(F,{stack:!0,title:`Task template`,description:`Use ${W.join(`, `)} in the title, objective, criteria and grouping key.`,children:[(0,Z.jsx)(E,{label:`Task title`,error:n(`title`),children:n=>(0,Z.jsx)(M,{...n,value:e.title,onChange:e=>t(`title`,e.target.value),placeholder:`Triage new issues for {{date}}`})}),(0,Z.jsx)(E,{label:`Objective`,error:n(`objective`),children:n=>(0,Z.jsx)(j,{...n,minRows:4,value:e.objective,onChange:e=>t(`objective`,e.target.value)})}),(0,Z.jsx)(E,{label:`Acceptance criteria`,error:n(`criteria`),hint:`One criterion per line.`,optional:!0,children:n=>(0,Z.jsx)(j,{...n,minRows:3,value:e.criteria,onChange:e=>t(`criteria`,e.target.value)})}),(0,Z.jsx)(E,{label:`Priority`,error:n(`priority`),children:n=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(ge,{priority:e.priority}),(0,Z.jsx)(he,{...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,X.useId)();return(0,Z.jsxs)(`fieldset`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,Z.jsx)(`legend`,{className:`mb-1 text-sm font-medium`,children:e}),(0,Z.jsx)(`div`,{className:`grid min-w-0 gap-2 sm:grid-cols-3`,children:n.map(e=>(0,Z.jsxs)(`label`,{className:ne(`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,Z.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,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted`,children:e.explanation})]})]},e.value))}),i&&(0,Z.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,Z.jsxs)(F,{stack:!0,title:`Where and how it runs`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(E,{label:`Host`,error:n(`hostId`),children:n=>(0,Z.jsxs)(I,{...n,value:e.hostId,onChange:e=>t(`hostId`,e.target.value),children:[(0,Z.jsxs)(`option`,{value:``,children:[`Project default`,a?` (${a})`:``]}),e.hostId&&!r.some(t=>t.id===e.hostId)&&(0,Z.jsx)(`option`,{value:e.hostId,children:`Unknown host`}),r.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,e.connectivity===`connected`?``:` (${e.connectivity})`]},e.id))]})}),(0,Z.jsx)(E,{label:`Profile`,error:n(`profileId`),hint:s?`The selected profile is no longer available.`:void 0,children:n=>(0,Z.jsxs)(I,{...n,value:e.profileId,onChange:e=>t(`profileId`,e.target.value),children:[(0,Z.jsxs)(`option`,{value:``,children:[`Project default`,o?` (${o})`:``]}),e.profileId&&!i.some(t=>t.id===e.profileId)&&(0,Z.jsx)(`option`,{value:e.profileId,children:`Unknown profile`}),i.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]})})]}),(0,Z.jsx)(ft,{legend:`Mode`,value:e.mode,options:Ne,onChange:e=>t(`mode`,e)}),(0,Z.jsx)(E,{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,Z.jsx)(M,{...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,Z.jsxs)(F,{stack:!0,title:`Overlap and missed runs`,children:[(0,Z.jsx)(ft,{legend:`When previous work is still open`,value:e.overlap,options:q,onChange:e=>t(`overlap`,e)}),(0,Z.jsx)(ft,{legend:`Missed runs`,value:e.missed,options:Ie,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,Z.jsxs)(F,{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,Z.jsx)(E,{label:`Automatic continuation`,children:n=>(0,Z.jsx)(L,{...n,checked:e.continuationEnabled,onChange:e=>t(`continuationEnabled`,e),label:`Automatic continuation`,className:`self-start`})}),e.continuationEnabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(E,{label:`Continuation objective`,error:n(`continuationObjective`),hint:`What the agent must achieve before it reports done.`,children:n=>(0,Z.jsx)(j,{...n,minRows:2,value:e.continuationObjective,onChange:e=>t(`continuationObjective`,e.target.value)})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(E,{label:`Max continuations`,error:n(`maxContinuations`),hint:`1–50`,children:n=>(0,Z.jsx)(M,{...n,type:`number`,inputMode:`numeric`,min:1,max:50,step:1,value:e.maxContinuations,onChange:e=>t(`maxContinuations`,e.target.value)})}),(0,Z.jsx)(E,{label:`Max elapsed minutes`,error:n(`maxElapsedMinutes`),hint:`1–1440`,children:n=>(0,Z.jsx)(M,{...n,type:`number`,inputMode:`numeric`,min:1,max:1440,step:1,value:e.maxElapsedMinutes,onChange:e=>t(`maxElapsedMinutes`,e.target.value)})}),(0,Z.jsx)(E,{label:`Max tokens`,optional:!0,error:n(`maxTokens`),children:n=>(0,Z.jsx)(M,{...n,type:`number`,inputMode:`numeric`,min:1,step:1,value:e.maxTokens,onChange:e=>t(`maxTokens`,e.target.value)})}),(0,Z.jsx)(E,{label:`Max cost (USD)`,optional:!0,error:n(`maxCostUsd`),children:n=>(0,Z.jsx)(M,{...n,type:`number`,inputMode:`decimal`,min:.01,step:.01,value:e.maxCostUsd,onChange:e=>t(`maxCostUsd`,e.target.value)})})]}),(0,Z.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,Z.jsxs)(F,{stack:!0,title:`Review`,children:[(0,Z.jsx)(E,{label:`Checks`,optional:!0,error:n(`checks`),hint:`One command per line. Leave empty to use ${i}.`,children:n=>(0,Z.jsx)(j,{...n,minRows:2,value:e.checks,onChange:e=>t(`checks`,e.target.value),className:`font-mono`,spellCheck:!1,autoCapitalize:`off`})}),(0,Z.jsx)(E,{label:`Human review`,hint:`When on, finished work waits in Review for you instead of completing on passing checks.`,children:n=>(0,Z.jsx)(L,{...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-BsTwLnMp.js.map