hopwire 0.5.1 → 0.7.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.
package/dist/bin.js CHANGED
@@ -40,6 +40,8 @@ const quiet = () => spinner?.stop();
40
40
  const fullScreen = keys && color && process.stdout.isTTY === true;
41
41
  const facts = fullScreen ? new Facts() : null;
42
42
  let app = null;
43
+ /** The Settings tab is starting the tunnel again */
44
+ let restarting = false;
43
45
  let held = fullScreen ? [] : null;
44
46
  /** What was written to standard error while the view ran, with its time: shown again after it is gone */
45
47
  const problems = [];
@@ -90,12 +92,16 @@ const hop = () => {
90
92
  * Opens the full-screen view for a tunnel that runs: the terminal goes into raw mode and the alternate screen, and
91
93
  * both are given back when the process exits, however it does.
92
94
  */
93
- function openView(info, known, running) {
95
+ function openView(info, known, running, restart) {
94
96
  let rowWidth = 100;
95
97
  const rows = new TerminalScreen({ look, width: () => rowWidth, version: readVersion(), shortcuts: false });
96
- if ((running.kind === 'http' || running.kind === 'up') && running.webhookSecrets !== undefined) {
97
- rows.checkSignatures(running.webhookSecrets);
98
- }
98
+ const settingsOf = (tunnel) => tunnel.kind === 'http' || tunnel.kind === 'up' ? (tunnel.settings ?? null) : null;
99
+ const signatures = (tunnel) => {
100
+ if ((tunnel.kind === 'http' || tunnel.kind === 'up') && tunnel.webhookSecrets !== undefined) {
101
+ rows.checkSignatures(tunnel.webhookSecrets);
102
+ }
103
+ };
104
+ signatures(running);
99
105
  const dataDir = argv.findIndex((arg) => arg === '--data-dir' || arg.startsWith('--data-dir='));
100
106
  const dataDirValue = dataDir < 0
101
107
  ? null
@@ -129,7 +135,21 @@ function openView(info, known, running) {
129
135
  return response.json();
130
136
  },
131
137
  interrupt: () => process.kill(process.pid, 'SIGINT'),
138
+ applySettings: async (settings) => {
139
+ restarting = true;
140
+ known.reset();
141
+ try {
142
+ const { running: now, problem } = await restart(settings);
143
+ signatures(now);
144
+ return { info: tunnelInfo(now) ?? info, access: settingsOf(now), problem };
145
+ }
146
+ finally {
147
+ known.start();
148
+ restarting = false;
149
+ }
150
+ },
132
151
  },
152
+ settings: settingsOf(running),
133
153
  });
134
154
  known.start();
135
155
  held = null;
@@ -175,7 +195,13 @@ await main({
175
195
  env: process.env,
176
196
  print: (line) => {
177
197
  if (app !== null) {
178
- app.line(line);
198
+ // The lines of a tunnel that is starting again are its facts, as at the first start
199
+ if (restarting && facts !== null) {
200
+ facts.line(line);
201
+ }
202
+ else {
203
+ app.line(line);
204
+ }
179
205
  return;
180
206
  }
181
207
  if (held !== null && facts !== null && screen !== null) {
@@ -192,6 +218,11 @@ await main({
192
218
  error: (line) => {
193
219
  quiet();
194
220
  if (app !== null) {
221
+ if (restarting && facts !== null) {
222
+ // A notice of the start, as at the first one; a start that failed reports itself to the view
223
+ facts.note(line);
224
+ return;
225
+ }
195
226
  problems.push({ at: Date.now(), line });
196
227
  app.problem(line);
197
228
  return;
@@ -254,11 +285,11 @@ await main({
254
285
  }
255
286
  }
256
287
  : undefined,
257
- started: (running) => {
288
+ started: (running, restart) => {
258
289
  quiet();
259
290
  const info = fullScreen && facts !== null ? tunnelInfo(running) : null;
260
291
  if (info !== null && facts !== null) {
261
- app = openView(info, facts, running);
292
+ app = openView(info, facts, running, restart);
262
293
  return;
263
294
  }
264
295
  release();
package/dist/cli.js CHANGED
@@ -21,6 +21,7 @@ import { parseTarget } from './traffic.js';
21
21
  import { ConfigError, isServiceName, loadConfig } from './config.js';
22
22
  import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js';
23
23
  import { commandHelp, overview } from './help.js';
24
+ import { configWithSettings, createConfigFile, saveToConfigFile, settingsOfConfig, } from './settings.js';
24
25
  import { loadOrCreateIdentity } from './identity.js';
25
26
  import { defaultLogName, isFollowablePath } from './log-follow.js';
26
27
  import { DOCS_URL, printable } from './output.js';
@@ -529,7 +530,9 @@ export async function run(argv, io) {
529
530
  }
530
531
  const cwd = io.cwd ?? process.cwd();
531
532
  const { file, shown } = configFile(cwd, values.config);
532
- const config = await loadConfig(file, values.config !== undefined, shown);
533
+ const loaded = await loadConfig(file, values.config !== undefined, shown);
534
+ // The Settings tab restarted the tunnel: its settings stand in for those of the file
535
+ const config = io.view?.settings === undefined ? loaded : configWithSettings(loaded, io.view.settings);
533
536
  // Read before anything starts: a variable that is not set stops the start, like any other mistake in the file
534
537
  const webhookSecrets = new Map(config.services.map((service) => [
535
538
  service.name,
@@ -552,14 +555,44 @@ export async function run(argv, io) {
552
555
  // The edge is only contacted for p2p.relay, and then only through the relay
553
556
  relay: config.relay ? await relayAccess('p2p.relay', store) : undefined,
554
557
  bootstrap: config.share ? parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP) : undefined,
555
- agent: agent ?? config.agent ?? undefined,
558
+ agent: io.view?.settings?.agent ?? agent ?? config.agent ?? undefined,
556
559
  signal: io.signal,
557
560
  });
558
561
  // After the lines of the start, so the mode stays the first line of every tunnel
559
562
  update.print(io.print);
560
- return Object.assign(running, { webhookSecrets });
563
+ // What the file holds, for a save: only keys that differ from it are written
564
+ let inFile = settingsOfConfig(loaded, undefined);
565
+ const settings = {
566
+ current: io.view?.settings ?? settingsOfConfig(loaded, agent),
567
+ file: { shown, exists: true },
568
+ save: async (next) => {
569
+ await saveToConfigFile(file, shown, inFile, next);
570
+ inFile = next;
571
+ return `Saved to ${shown}.`;
572
+ },
573
+ };
574
+ return Object.assign(running, { webhookSecrets, settings });
561
575
  }
562
576
  noMoreArguments(rest, 1, 'hopwire http <port>');
577
+ // The Settings tab restarted the tunnel: its settings stand in for those of the command line
578
+ const wanted = io.view?.settings;
579
+ if (wanted !== undefined) {
580
+ const isPublic = wanted.services[0]?.public ?? false;
581
+ Object.assign(values, {
582
+ share: wanted.share,
583
+ team: wanted.team,
584
+ relay: wanted.relay,
585
+ public: isPublic,
586
+ 'no-ws-capture': !wanted.websocket,
587
+ agent: wanted.agent ? values.agent : undefined,
588
+ 'no-agent': !wanted.agent,
589
+ subdomain: isPublic ? values.subdomain : undefined,
590
+ });
591
+ if (!wanted.share) {
592
+ // What only works with sharing goes with it; a later change that shares again reads the command line anew
593
+ Object.assign(values, { allow: undefined, 'allow-agents': undefined, 'share-logs': undefined });
594
+ }
595
+ }
563
596
  if (values.inspect !== undefined && values['no-inspect']) {
564
597
  throw new UsageError('--inspect and --no-inspect cannot be combined');
565
598
  }
@@ -633,7 +666,44 @@ export async function run(argv, io) {
633
666
  });
634
667
  // After the lines of the start, so the mode stays the first line of every tunnel
635
668
  update.print(io.print);
636
- return Object.assign(running, { webhookSecrets });
669
+ const serviceName = values.name ?? 'default';
670
+ const target = configFile(io.cwd ?? process.cwd(), undefined);
671
+ const view = io.view ?? {};
672
+ const settings = {
673
+ current: {
674
+ share: values.share ?? false,
675
+ team: values.team ?? false,
676
+ relay: values.relay ?? false,
677
+ websocket: !(values['no-ws-capture'] ?? false),
678
+ agent: agentChoice(values) !== false,
679
+ services: [{ name: serviceName, public: values.public ?? false }],
680
+ },
681
+ file: { shown: target.shown, exists: view.created !== undefined },
682
+ save: async (next) => {
683
+ if (view.created !== undefined) {
684
+ await saveToConfigFile(target.file, target.shown, view.created.before, next);
685
+ view.created.before = next;
686
+ return `Saved to ${target.shown}.`;
687
+ }
688
+ // The edge of the account goes into a file with a public service, as hopwire init writes it
689
+ const isPublic = next.services[0]?.public ?? false;
690
+ const account = isPublic ? await readAccount(store) : null;
691
+ const edgeUrl = account === null ? null : await boundEdge(store);
692
+ await createConfigFile({
693
+ file: target.file,
694
+ shown: target.shown,
695
+ serviceName,
696
+ local: new URL(`http://127.0.0.1:${port}`),
697
+ subdomain: values.subdomain ?? null,
698
+ urls: account === null || edgeUrl === null
699
+ ? null
700
+ : { edgeUrl, controlPlaneUrl: account.controlPlaneUrl },
701
+ }, next);
702
+ view.created = { before: next };
703
+ return `Created ${target.shown}; hopwire up starts this tunnel from now on.`;
704
+ },
705
+ };
706
+ return Object.assign(running, { webhookSecrets, settings });
637
707
  }
638
708
  /** 30s, 30m, 2h, 1d as milliseconds. */
639
709
  function parseDuration(value) {
package/dist/main.js CHANGED
@@ -19,7 +19,9 @@ export async function main(proc) {
19
19
  // the rest
20
20
  const { run } = await (proc.load ?? (() => import('./cli.js')))();
21
21
  signal.throwIfAborted();
22
- const running = await run(proc.argv, {
22
+ // The same for every start of this process: the Settings tab changes it before a restart
23
+ const view = {};
24
+ const start = () => run(proc.argv, {
23
25
  print: proc.print,
24
26
  notice: proc.error,
25
27
  env: proc.env,
@@ -29,11 +31,66 @@ export async function main(proc) {
29
31
  openBrowser: proc.openBrowser,
30
32
  input: proc.input,
31
33
  exchange: proc.exchange,
34
+ view,
32
35
  });
33
- if (running !== null && !signal.aborted) {
34
- proc.started?.(running);
36
+ const first = await start();
37
+ if (first === null || signal.aborted) {
38
+ return first;
35
39
  }
36
- return running;
40
+ // What runs now; a restart puts another tunnel in its place, and the process follows that one
41
+ let current = first;
42
+ let restarting = Promise.resolve();
43
+ let ended = () => { };
44
+ const follow = (running) => {
45
+ if ('ended' in running) {
46
+ void running.ended.then((error) => {
47
+ if (current === running) {
48
+ ended(error);
49
+ }
50
+ });
51
+ }
52
+ };
53
+ follow(first);
54
+ const restart = (settings) => {
55
+ const work = restarting.then(async () => {
56
+ const before = view.settings;
57
+ const closed = current;
58
+ // Not followed any more: a tunnel that is closed on purpose has not ended by itself
59
+ current = { ...closed };
60
+ await closed.close();
61
+ let problem = null;
62
+ try {
63
+ view.settings = settings;
64
+ current = (await start()) ?? closed;
65
+ }
66
+ catch (error) {
67
+ problem = error instanceof HopwireError ? error.message : unexpectedFailure(error);
68
+ view.settings = before;
69
+ try {
70
+ current = (await start()) ?? closed;
71
+ }
72
+ catch (again) {
73
+ // Not even as it was: the process stops with that sentence
74
+ const failure = again instanceof HopwireError ? again : new HopwireError(unexpectedFailure(again));
75
+ ended(failure);
76
+ throw failure;
77
+ }
78
+ }
79
+ follow(current);
80
+ return { running: current, problem };
81
+ });
82
+ restarting = work.catch(() => { });
83
+ return work;
84
+ };
85
+ proc.started?.(first, restart);
86
+ return {
87
+ // A stop during a restart waits for it, then closes what runs
88
+ close: () => restarting.then(() => current.close()),
89
+ ended: new Promise((resolve) => {
90
+ ended = resolve;
91
+ }),
92
+ ...('finished' in first ? { finished: first.finished } : {}),
93
+ };
37
94
  }, { on: proc.on, exit: proc.exit, error: proc.error });
38
95
  }
39
96
  catch (error) {
@@ -0,0 +1,256 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { isMap, isNode, isScalar, parseDocument } from 'yaml';
3
+ import { parseConfig } from './config.js';
4
+ import { renderConfig } from './config-template.js';
5
+ import { HopwireError, errorCode } from './errors.js';
6
+ /** The value of one setting. */
7
+ export function settingValue(settings, id) {
8
+ if (id.startsWith('public:')) {
9
+ return settings.services.find((service) => `public:${service.name}` === id)?.public ?? false;
10
+ }
11
+ return settings[id];
12
+ }
13
+ /**
14
+ * The settings with one of them changed, and what follows from it: without sharing there is no team and no relay,
15
+ * the relay is for the team only.
16
+ */
17
+ export function withSetting(settings, id, value) {
18
+ const next = { ...settings, services: settings.services.map((service) => ({ ...service })) };
19
+ if (id.startsWith('public:')) {
20
+ const service = next.services.find((entry) => `public:${entry.name}` === id);
21
+ if (service !== undefined) {
22
+ service.public = value;
23
+ }
24
+ return next;
25
+ }
26
+ next[id] = value;
27
+ if (id === 'relay' && value) {
28
+ next.team = true;
29
+ }
30
+ if (!next.share) {
31
+ next.team = false;
32
+ next.relay = false;
33
+ }
34
+ if (!next.team) {
35
+ next.relay = false;
36
+ }
37
+ return next;
38
+ }
39
+ /** Why a setting cannot be turned on as things are; null when it can. */
40
+ export function unavailable(settings, id) {
41
+ if ((id === 'team' || id === 'relay') && !settings.share) {
42
+ return 'needs sharing';
43
+ }
44
+ return null;
45
+ }
46
+ /** The settings that differ between two states, as the ids of the page. */
47
+ export function changedSettings(before, after) {
48
+ const ids = [
49
+ ...after.services.map((service) => `public:${service.name}`),
50
+ 'share',
51
+ 'team',
52
+ 'relay',
53
+ 'websocket',
54
+ 'agent',
55
+ ];
56
+ return ids.filter((id) => settingValue(before, id) !== settingValue(after, id));
57
+ }
58
+ /** The settings a hopwire.yaml has. */
59
+ export function settingsOfConfig(config, agent) {
60
+ return {
61
+ share: config.share,
62
+ team: config.team,
63
+ relay: config.relay,
64
+ websocket: config.captureWebSocket,
65
+ agent: agent ?? config.agent ?? true,
66
+ services: config.services.map((service) => ({ name: service.name, public: service.public })),
67
+ };
68
+ }
69
+ /** A config with the settings of the page in place of its own. */
70
+ export function configWithSettings(config, settings) {
71
+ return {
72
+ ...config,
73
+ share: settings.share,
74
+ team: settings.team,
75
+ relay: settings.relay,
76
+ captureWebSocket: settings.websocket,
77
+ agent: settings.agent,
78
+ // Without sharing there is nothing these could apply to
79
+ allowAgents: settings.share && config.allowAgents,
80
+ shareLogs: settings.share && config.shareLogs,
81
+ services: config.services.map((service) => ({
82
+ ...service,
83
+ public: settings.services.find((entry) => entry.name === service.name)?.public ?? service.public,
84
+ })),
85
+ };
86
+ }
87
+ /** Where a setting stands in hopwire.yaml, and its value when the file leaves it out. */
88
+ function fileKey(id) {
89
+ if (id.startsWith('public:')) {
90
+ return { path: ['services', id.slice('public:'.length), 'public'], fallback: false };
91
+ }
92
+ switch (id) {
93
+ case 'share':
94
+ return { path: ['p2p', 'share'], fallback: false };
95
+ case 'team':
96
+ return { path: ['p2p', 'team'], fallback: false };
97
+ case 'relay':
98
+ return { path: ['p2p', 'relay'], fallback: false };
99
+ case 'websocket':
100
+ return { path: ['capture', 'websocket'], fallback: true };
101
+ default:
102
+ return { path: ['agent'], fallback: true };
103
+ }
104
+ }
105
+ /** Where a line starts that holds this position of a text. */
106
+ function lineStart(text, at) {
107
+ return text.lastIndexOf('\n', at - 1) + 1;
108
+ }
109
+ /** The position after the end of the line that holds this position; the text gets a last newline when it has none. */
110
+ function afterLine(text, at) {
111
+ const end = text.indexOf('\n', at);
112
+ return end === -1 ? { text: `${text}\n`, at: text.length + 1 } : { text, at: end + 1 };
113
+ }
114
+ /** The indent of the file: the spaces of its first indented line that is not a comment; four when it has none. */
115
+ function indentUnit(text) {
116
+ return /^( +)[^\s#]/m.exec(text)?.[1] ?? ' ';
117
+ }
118
+ /**
119
+ * A text of YAML with one true or false set, by changing that word alone or adding one line: nothing else of the
120
+ * file is written anew, so comments, order, quotes and indentation stay exactly as they are. The YAML library is
121
+ * only asked where things stand.
122
+ */
123
+ export function setBoolean(text, path, value, shown) {
124
+ const document = parseDocument(text, { uniqueKeys: true, logLevel: 'error' });
125
+ const refuse = () => {
126
+ throw new HopwireError(`${path.join('.')} in ${shown} cannot be changed from here; change it in the file.`);
127
+ };
128
+ const word = value ? 'true' : 'false';
129
+ const unit = indentUnit(text);
130
+ let map = document.contents;
131
+ for (let depth = 0; depth < path.length; depth += 1) {
132
+ if (!isMap(map)) {
133
+ return refuse();
134
+ }
135
+ const key = path[depth] ?? '';
136
+ const pair = map.items.find((item) => isScalar(item.key) && item.key.value === key);
137
+ const rest = path.slice(depth);
138
+ // The lines for what is missing from here on: sections first, the value last
139
+ const lines = (from, names) => names
140
+ .map((name, index) => `${from}${unit.repeat(index)}${name}:${index === names.length - 1 ? ` ${word}` : ''}\n`)
141
+ .join('');
142
+ if (pair === undefined) {
143
+ // After the last entry of this mapping, at its indent
144
+ const last = map.items[map.items.length - 1];
145
+ const first = map.items[0];
146
+ if (last === undefined || first === undefined || !isScalar(first.key) || first.key.range == null) {
147
+ return refuse();
148
+ }
149
+ const column = first.key.range[0] - lineStart(text, first.key.range[0]);
150
+ const end = (isNode(last.value) ? last.value.range?.[1] : undefined) ??
151
+ (isNode(last.key) ? last.key.range?.[1] : undefined);
152
+ if (end === undefined) {
153
+ return refuse();
154
+ }
155
+ const place = afterLine(text, Math.max(end - 1, 0));
156
+ return `${place.text.slice(0, place.at)}${lines(' '.repeat(column), rest)}${place.text.slice(place.at)}`;
157
+ }
158
+ const last = depth === path.length - 1;
159
+ if (isScalar(pair.value) && pair.value.value === null && isScalar(pair.key) && pair.key.range != null) {
160
+ // A name with nothing under it (every key commented, or left empty): the value, or the section, goes there
161
+ const keyStart = pair.key.range[0];
162
+ if (last) {
163
+ const colon = text.indexOf(':', pair.key.range[1]);
164
+ return `${text.slice(0, colon + 1)} ${word}${text.slice(colon + 1)}`;
165
+ }
166
+ const place = afterLine(text, keyStart);
167
+ const column = keyStart - lineStart(text, keyStart);
168
+ return `${place.text.slice(0, place.at)}${lines(' '.repeat(column) + unit, rest.slice(1))}${place.text.slice(place.at)}`;
169
+ }
170
+ if (last) {
171
+ if (!isScalar(pair.value) || typeof pair.value.value !== 'boolean' || pair.value.range == null) {
172
+ return refuse();
173
+ }
174
+ const [start, end] = pair.value.range;
175
+ return `${text.slice(0, start)}${word}${text.slice(end)}`;
176
+ }
177
+ map = pair.value;
178
+ }
179
+ return refuse();
180
+ }
181
+ /**
182
+ * The text of a hopwire.yaml with settings changed: only the keys that differ between `before` and `after` are
183
+ * touched, so comments, order and everything else stay as the user wrote them. `before` is what the file held when it
184
+ * was last read or written by this run. The file is read anew for every save: a key it holds already, because it was
185
+ * changed there in the meantime, is left alone, and every other change made there stays.
186
+ */
187
+ export function editConfigText(text, before, after, shown) {
188
+ let edited = text;
189
+ for (const id of changedSettings(before, after)) {
190
+ const document = parseDocument(edited, { uniqueKeys: true, logLevel: 'error' });
191
+ if (document.errors.length > 0) {
192
+ throw new HopwireError(`${shown} is no longer valid YAML; correct the file, then save again.`);
193
+ }
194
+ const { path, fallback } = fileKey(id);
195
+ const inFile = document.getIn(path);
196
+ const now = typeof inFile === 'boolean' ? inFile : fallback;
197
+ const wanted = settingValue(after, id);
198
+ if (now === wanted) {
199
+ continue;
200
+ }
201
+ edited = setBoolean(edited, path, wanted, shown);
202
+ }
203
+ // What is written must be a file hopwire up accepts
204
+ parseConfig(edited, shown);
205
+ return edited;
206
+ }
207
+ /** Writes changed settings into an existing hopwire.yaml. */
208
+ export async function saveToConfigFile(file, shown, before, after) {
209
+ let text;
210
+ try {
211
+ text = await readFile(file, 'utf8');
212
+ }
213
+ catch (error) {
214
+ throw new HopwireError(`${shown} cannot be read (${errorCode(error) ?? 'UNKNOWN'}); nothing was saved.`);
215
+ }
216
+ await writeFile(file, editConfigText(text, before, after, shown));
217
+ }
218
+ /**
219
+ * Creates a hopwire.yaml for a tunnel started with hopwire http, with the text hopwire init writes and the settings of
220
+ * this run. Never replaces a file.
221
+ */
222
+ export async function createConfigFile(target, settings) {
223
+ const isPublic = settings.services[0]?.public ?? false;
224
+ if (isPublic && target.urls === null) {
225
+ throw new HopwireError('A file with a public service names the edge of your account; run hopwire login first. Nothing was saved.');
226
+ }
227
+ const template = renderConfig({
228
+ services: [
229
+ {
230
+ name: target.serviceName,
231
+ local: target.local,
232
+ public: isPublic,
233
+ subdomain: isPublic ? target.subdomain : null,
234
+ logs: [],
235
+ },
236
+ ],
237
+ edgeUrl: isPublic ? (target.urls?.edgeUrl ?? null) : null,
238
+ controlPlaneUrl: isPublic ? (target.urls?.controlPlaneUrl ?? null) : null,
239
+ share: settings.share,
240
+ team: settings.team,
241
+ allowAgents: false,
242
+ shareLogs: false,
243
+ });
244
+ // What the template has no answer for: set on top of it, from the defaults
245
+ const written = { ...settings, relay: false, websocket: true, agent: true };
246
+ const text = editConfigText(template, written, settings, target.shown);
247
+ try {
248
+ // wx: a file that is there is not replaced
249
+ await writeFile(target.file, text, { flag: 'wx' });
250
+ }
251
+ catch (error) {
252
+ throw new HopwireError(errorCode(error) === 'EEXIST'
253
+ ? `${target.shown} exists already and hopwire http does not read it; change it there and start it with hopwire up. Nothing was saved.`
254
+ : `${target.shown} cannot be written (${errorCode(error) ?? 'UNKNOWN'}); nothing was saved.`);
255
+ }
256
+ }
package/dist/tui/app.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import { curlCommand } from '../curl.js';
2
2
  import { printable } from '../output.js';
3
3
  import { formatDuration, paint } from '../terminal.js';
4
+ import { recogniseWebhook } from '../webhook.js';
4
5
  import { FLASH_MS, headerLine, keysLine, rule, statusLine, tabBar } from './chrome.js';
5
6
  import { parseInput } from './input.js';
6
7
  import { Traffic } from './model.js';
7
8
  import { menuItems, requestsLines } from './requests.js';
8
- import { TABS, TAB_KEYS, listWindow, sectionsOf, target } from './state.js';
9
+ import { TAB_KEYS, listWindow, sectionsOf, tabsOf, target, } from './state.js';
10
+ import { settingValue, unavailable, withSetting } from '../settings.js';
11
+ import { changeChoices, settingName, settingRows, settingsLines } from './settings.js';
9
12
  import { helpContent, scrolled, shareItems, shareLines, statusContent, tools, toolsLines } from './tabs.js';
10
13
  /** Rows of the window that are not the tab: two of the header, two rules, two of the footer. */
11
14
  const CHROME_ROWS = 6;
@@ -36,10 +39,24 @@ export class App {
36
39
  detail: null,
37
40
  menu: null,
38
41
  cursor: { share: 0, tools: 0 },
42
+ settings: options.settings == null || options.actions.applySettings === undefined
43
+ ? null
44
+ : {
45
+ access: options.settings,
46
+ atStart: options.settings.current,
47
+ history: [],
48
+ cursor: 0,
49
+ problem: null,
50
+ box: null,
51
+ },
52
+ restarting: false,
39
53
  scroll: { status: 0, help: 0 },
40
54
  flash: null,
41
55
  stopping: false,
42
56
  used: new Set(),
57
+ fixed: new Set(),
58
+ providers: new Set(),
59
+ startedAt: options.ui.now(),
43
60
  extraArgs: options.extraArgs ?? '',
44
61
  };
45
62
  }
@@ -73,6 +90,9 @@ export class App {
73
90
  body = shown.lines;
74
91
  break;
75
92
  }
93
+ case 'settings':
94
+ body = settingsLines(state, ui, width, height);
95
+ break;
76
96
  case 'help': {
77
97
  const shown = scrolled(helpContent(ui), state.scroll.help, height);
78
98
  state.scroll.help = shown.scroll;
@@ -128,7 +148,23 @@ export class App {
128
148
  }
129
149
  }
130
150
  if (original !== null) {
131
- this.flash(replayNote(original.exchange, exchange));
151
+ const failed = original.exchange.response.status >= 400;
152
+ if (failed && exchange.response.status < 400 && !state.fixed.has(original.exchange.id)) {
153
+ // The moment the work was for: the failed request passes
154
+ state.fixed.add(original.exchange.id);
155
+ const tries = state.traffic.entries.filter((entry) => entry.exchange.replayOf === original.exchange.id).length;
156
+ this.flash(fixedNote(original.exchange, exchange, tries));
157
+ }
158
+ else {
159
+ this.flash(replayNote(original.exchange, exchange));
160
+ }
161
+ }
162
+ else if (exchange.source !== 'replay') {
163
+ const webhook = recogniseWebhook(exchange);
164
+ if (webhook !== null && !state.providers.has(webhook.provider)) {
165
+ state.providers.add(webhook.provider);
166
+ this.flash(`First ${providerName(webhook.provider)} webhook of this run${webhook.event === null ? '' : `: ${printable(webhook.event)}`}`);
167
+ }
132
168
  }
133
169
  this.invalidate();
134
170
  }
@@ -152,13 +188,30 @@ export class App {
152
188
  /** What the terminal shows after the view is gone: what ran and what came in. */
153
189
  summary() {
154
190
  const { look } = this.ui;
155
- const { traffic, version } = this.state;
191
+ const { traffic, version, fixed, startedAt } = this.state;
192
+ const muted = (text) => paint(look, text, look.palette.muted);
156
193
  const requests = traffic.requests === 1 ? '1 request' : `${traffic.requests} requests`;
157
194
  const failed = traffic.failed > 0 ? `, ${traffic.failed} failed` : '';
158
- return [
159
- `${paint(look, '●', look.palette.muted)} ${paint(look, 'hopwire', null, true)} ${paint(look, version, look.palette.muted)} stopped after ${requests}${failed}`,
160
- paint(look, ' The traffic is kept: the same command shows it again in the inspector.', look.palette.muted),
195
+ const lines = [
196
+ `${paint(look, '●', look.palette.muted)} ${paint(look, 'hopwire', null, true)} ${muted(version)} stopped after ${requests}${failed}${muted(` · ran ${formatRun(this.ui.now() - startedAt)}`)}`,
161
197
  ];
198
+ const recap = runRecap(traffic.entries.map((entry) => entry.exchange));
199
+ const fact = (label, text) => {
200
+ lines.push(` ${muted(label.padEnd(9))}${text}`);
201
+ };
202
+ if (recap.busiest !== null) {
203
+ fact('Busiest', `${printable(recap.busiest.name)} ${muted(`(${recap.busiest.count} requests)`)}`);
204
+ }
205
+ if (recap.slowest !== null) {
206
+ fact('Slowest', `${printable(recap.slowest.name)} ${muted(formatDuration(recap.slowest.durationMs))}`);
207
+ }
208
+ if (fixed.size > 0) {
209
+ fact('Fixed', fixed.size === 1
210
+ ? '1 failed request passed on replay'
211
+ : `${fixed.size} failed requests passed on replay`);
212
+ }
213
+ lines.push(muted(' The traffic is kept: the same command shows it again in the inspector.'));
214
+ return lines;
162
215
  }
163
216
  /** Input of the terminal: keys and the mouse. */
164
217
  input(chunk) {
@@ -255,6 +308,18 @@ export class App {
255
308
  state.cursor.tools = Number(value);
256
309
  this.copyTool();
257
310
  break;
311
+ case 'setting':
312
+ if (state.settings !== null && state.settings.box === null) {
313
+ state.settings.cursor = Number(value);
314
+ this.settingsKey('enter');
315
+ }
316
+ break;
317
+ case 'choice':
318
+ if (state.settings?.box != null) {
319
+ state.settings.box.choice = Number(value);
320
+ this.settingsKey('enter');
321
+ }
322
+ break;
258
323
  default:
259
324
  break;
260
325
  }
@@ -304,15 +369,20 @@ export class App {
304
369
  this.quit();
305
370
  return;
306
371
  }
307
- const tab = TABS.find((name) => TAB_KEYS[name] === key);
372
+ if (state.tab === 'settings' && state.settings?.box != null) {
373
+ this.settingsKey(key);
374
+ return;
375
+ }
376
+ const tabs = tabsOf(state);
377
+ const tab = tabs.find((name) => TAB_KEYS[name] === key);
308
378
  if (tab !== undefined) {
309
379
  this.show(tab);
310
380
  return;
311
381
  }
312
382
  const inDetail = state.tab === 'requests' && state.detail !== null;
313
383
  if (!inDetail && (key === 'left' || key === 'right')) {
314
- const at = TABS.indexOf(state.tab) + (key === 'right' ? 1 : -1);
315
- this.show(TABS[(at + TABS.length) % TABS.length] ?? 'requests');
384
+ const at = tabs.indexOf(state.tab) + (key === 'right' ? 1 : -1);
385
+ this.show(tabs[(at + tabs.length) % tabs.length] ?? 'requests');
316
386
  return;
317
387
  }
318
388
  switch (state.tab) {
@@ -330,6 +400,9 @@ export class App {
330
400
  case 'tools':
331
401
  this.cursorKey(key, 'tools', tools(state).length, () => this.copyTool());
332
402
  break;
403
+ case 'settings':
404
+ this.settingsKey(key);
405
+ break;
333
406
  case 'status':
334
407
  state.scroll.status += scrollStep(key, this.bodyHeight);
335
408
  break;
@@ -338,6 +411,115 @@ export class App {
338
411
  break;
339
412
  }
340
413
  }
414
+ /** Keys of the Settings tab and of its change box. */
415
+ settingsKey(key) {
416
+ const view = this.state.settings;
417
+ if (view === null) {
418
+ return;
419
+ }
420
+ const settings = view.access.current;
421
+ const rows = settingRows(settings);
422
+ if (view.box !== null) {
423
+ const { box } = view;
424
+ const on = !settingValue(settings, box.id);
425
+ const choices = changeChoices(view.access, on);
426
+ if (key === 'up') {
427
+ box.choice = Math.max(box.choice - 1, 0);
428
+ }
429
+ else if (key === 'down') {
430
+ box.choice = Math.min(box.choice + 1, choices.length - 1);
431
+ }
432
+ else if (key === 'esc' || key === 'q') {
433
+ view.box = null;
434
+ }
435
+ else if (key === 'enter') {
436
+ view.box = null;
437
+ if (box.choice < 2) {
438
+ this.change(withSetting(settings, box.id, on), box.choice === 1, `${settingName(settings, box.id)}: ${on ? 'on' : 'off'}`);
439
+ }
440
+ }
441
+ return;
442
+ }
443
+ const row = rows[view.cursor];
444
+ if (key === 'up') {
445
+ view.cursor = Math.max(view.cursor - 1, 0);
446
+ }
447
+ else if (key === 'down') {
448
+ view.cursor = Math.min(view.cursor + 1, rows.length - 1);
449
+ }
450
+ else if ((key === 'enter' || key === 'space') && row !== undefined) {
451
+ const reason = settingValue(settings, row.id) ? null : unavailable(settings, row.id);
452
+ if (this.state.restarting) {
453
+ this.flash('The tunnel is restarting; one change at a time.', true, false);
454
+ }
455
+ else if (reason !== null) {
456
+ this.flash(`${row.label.trim()} ${reason}.`, true, false);
457
+ }
458
+ else {
459
+ view.box = { id: row.id, choice: 0 };
460
+ }
461
+ }
462
+ else if (key === 's') {
463
+ this.save();
464
+ }
465
+ else if (key === 'u') {
466
+ const before = view.history.pop();
467
+ if (before === undefined) {
468
+ this.flash('Nothing was changed in this run.', true, false);
469
+ }
470
+ else {
471
+ this.change(before, false, 'The last change is undone', false, false);
472
+ }
473
+ }
474
+ }
475
+ /** Restarts the tunnel with changed settings, and saves them when asked. */
476
+ change(next, save, done, remember = true, forRun = true) {
477
+ const { state } = this;
478
+ const view = state.settings;
479
+ const apply = this.actions.applySettings;
480
+ if (view === null || apply === undefined || state.restarting) {
481
+ return;
482
+ }
483
+ const before = view.access.current;
484
+ view.problem = null;
485
+ state.restarting = true;
486
+ this.invalidate();
487
+ void apply(next).then(({ info, access, problem }) => {
488
+ state.restarting = false;
489
+ state.info = info;
490
+ if (access !== null) {
491
+ // What the file is, and whether it exists, is known here; a restart does not change it
492
+ view.access = { ...access, file: view.access.file, save: access.save };
493
+ }
494
+ if (problem !== null) {
495
+ view.problem = problem;
496
+ this.flash(`Not changed: ${problem}`, true);
497
+ }
498
+ else {
499
+ if (remember) {
500
+ view.history.push(before);
501
+ }
502
+ this.flash(`${done}${save || !forRun ? '' : ' for this run'}.`);
503
+ if (save) {
504
+ this.save();
505
+ }
506
+ }
507
+ }, (error) => {
508
+ state.restarting = false;
509
+ this.flash(error instanceof Error ? error.message : 'The tunnel could not be started again.', true);
510
+ });
511
+ }
512
+ /** Writes the settings that run to hopwire.yaml. */
513
+ save() {
514
+ const view = this.state.settings;
515
+ if (view === null) {
516
+ return;
517
+ }
518
+ void view.access.save(view.access.current).then((sentence) => {
519
+ view.access = { ...view.access, file: { ...view.access.file, exists: true } };
520
+ this.flash(sentence);
521
+ }, (error) => this.flash(error instanceof Error ? error.message : 'The file could not be written.', true));
522
+ }
341
523
  quit() {
342
524
  this.state.typing = false;
343
525
  this.state.menu = null;
@@ -424,6 +606,12 @@ export class App {
424
606
  case '/':
425
607
  state.typing = true;
426
608
  break;
609
+ case 'n':
610
+ this.nextFailed();
611
+ break;
612
+ case 'g':
613
+ this.follow();
614
+ break;
427
615
  case 'e':
428
616
  state.failedOnly = !state.failedOnly;
429
617
  this.follow();
@@ -459,6 +647,9 @@ export class App {
459
647
  break;
460
648
  case 'enter':
461
649
  break;
650
+ case 'n':
651
+ this.nextFailed();
652
+ break;
462
653
  default: {
463
654
  const step = scrollStep(key, this.bodyHeight - 4);
464
655
  if (step !== 0) {
@@ -551,6 +742,23 @@ export class App {
551
742
  state.top = window.top;
552
743
  state.selected = shown[to]?.exchange.id ?? null;
553
744
  }
745
+ /** Picks the next failed request after the picked one, from the top again after the last; opens it in a request. */
746
+ nextFailed() {
747
+ const { state } = this;
748
+ const shown = listWindow(state, this.bodyHeight).shown;
749
+ const at = shown.findIndex((entry) => entry.exchange.id === (state.detail?.id ?? state.selected));
750
+ const failed = (entry) => entry.exchange.response.status >= 400;
751
+ const next = shown.find((entry, index) => index > at && failed(entry)) ?? shown.find(failed);
752
+ if (next === undefined) {
753
+ this.flash('No request has failed.', false, false);
754
+ }
755
+ else if (state.detail !== null) {
756
+ this.open(next.exchange.id);
757
+ }
758
+ else {
759
+ this.pick(next.exchange.id);
760
+ }
761
+ }
554
762
  pick(id) {
555
763
  this.state.top = listWindow(this.state, this.bodyHeight).top;
556
764
  this.state.selected = id;
@@ -694,6 +902,51 @@ function scrollStep(key, page) {
694
902
  return 0;
695
903
  }
696
904
  }
905
+ /** The line for a failed request whose replay passed. */
906
+ export function fixedNote(original, replay, tries) {
907
+ return `Fixed: ${printable(original.request.method)} ${printable(original.request.path)} ${original.response.status} → ${replay.response.status}${tries > 1 ? ` on try ${tries}` : ''}`;
908
+ }
909
+ /** A provider as its name is written. */
910
+ function providerName(provider) {
911
+ const names = { github: 'GitHub', gitlab: 'GitLab', paypal: 'PayPal' };
912
+ return names[provider.toLowerCase()] ?? `${provider.slice(0, 1).toUpperCase()}${provider.slice(1)}`;
913
+ }
914
+ /** How long a run took, in the largest unit that says it: 40 s, 12 min, 3 h 5 min. */
915
+ export function formatRun(ms) {
916
+ const seconds = Math.max(Math.round(ms / 1000), 0);
917
+ if (seconds < 60) {
918
+ return `${seconds} s`;
919
+ }
920
+ const minutes = Math.floor(seconds / 60);
921
+ return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
922
+ }
923
+ /** What a run was mostly about: the endpoint that was called most, and the slowest request. Replays are left out. */
924
+ export function runRecap(exchanges) {
925
+ const counts = new Map();
926
+ let slowest = null;
927
+ for (const exchange of exchanges) {
928
+ if (exchange.source === 'replay') {
929
+ continue;
930
+ }
931
+ // The endpoint is the path without its query
932
+ const name = `${exchange.request.method} ${exchange.request.path.split('?')[0] ?? ''}`;
933
+ counts.set(name, (counts.get(name) ?? 0) + 1);
934
+ if (slowest === null || exchange.response.durationMs > slowest.durationMs) {
935
+ slowest = { name, durationMs: exchange.response.durationMs };
936
+ }
937
+ }
938
+ let busiest = null;
939
+ for (const [name, count] of counts) {
940
+ if (busiest === null || count > busiest.count) {
941
+ busiest = { name, count };
942
+ }
943
+ }
944
+ // One endpoint called once is no finding
945
+ return {
946
+ busiest: busiest !== null && busiest.count > 1 ? busiest : null,
947
+ slowest: exchanges.length > 1 ? slowest : null,
948
+ };
949
+ }
697
950
  /** What changed between a request and its replay, in one line. */
698
951
  export function replayNote(original, replay) {
699
952
  const was = original.response;
@@ -1,6 +1,6 @@
1
1
  import { paint } from '../terminal.js';
2
2
  import { shortKey } from '../output.js';
3
- import { TABS, TAB_KEYS, TAB_TITLES, listWindow, target } from './state.js';
3
+ import { TAB_KEYS, TAB_TITLES, listWindow, tabsOf, target } from './state.js';
4
4
  import { clip, sides, width as widthOf } from './text.js';
5
5
  /**
6
6
  * What stands around every tab: the two lines of the header (what runs, and the navigation), and the two lines of
@@ -90,7 +90,7 @@ export function headerLine(state, ui, width) {
90
90
  export function tabBar(state, ui) {
91
91
  const { look } = ui;
92
92
  const line = new LineBuilder().add(' ');
93
- for (const tab of TABS) {
93
+ for (const tab of tabsOf(state)) {
94
94
  const current = tab === state.tab;
95
95
  const problem = tab === 'status' && state.facts.unseenProblems > 0;
96
96
  const label = `${TAB_KEYS[tab]} ${TAB_TITLES[tab]}`;
@@ -155,7 +155,11 @@ export function statusLine(state, ui, width, bodyHeight) {
155
155
  const flash = state.flash !== null && ui.now() - state.flash.at < FLASH_MS
156
156
  ? `${paint(look, '›', state.flash.problem ? palette.err : palette.green, true)} ${state.flash.problem ? paint(look, state.flash.text, palette.err) : state.flash.text}`
157
157
  : null;
158
- const right = state.stopping ? muted(look, 'Stopping…') : (flash ?? hint(state, ui) ?? '');
158
+ const right = state.stopping
159
+ ? muted(look, 'Stopping…')
160
+ : state.restarting
161
+ ? paint(look, 'Restarting the tunnel…', palette.info)
162
+ : (flash ?? hint(state, ui) ?? '');
159
163
  // What just happened matters more than the counts: it gets the room it needs
160
164
  const rightWidth = Math.min(widthOf(right), Math.max(width - 12, 0));
161
165
  return { text: sides(left, `${clip(right, rightWidth)} `, width) };
@@ -194,14 +198,32 @@ export function keysOf(state) {
194
198
  ['space', 'actions', 'space'],
195
199
  ['/', 'filter', '/'],
196
200
  ['e', state.failedOnly ? 'show all' : 'failed only', 'e'],
201
+ ...(state.traffic.failed > 0 ? [['n', 'next failed', 'n']] : []),
197
202
  ...(state.selected !== null || state.top !== null
198
- ? [['end', 'follow newest', 'end']]
203
+ ? [['g', 'newest', 'g']]
199
204
  : []),
200
205
  quit,
201
206
  ];
202
207
  case 'share':
203
208
  case 'tools':
204
209
  return [['↑↓', 'select', 'down'], ['enter', 'copy', 'enter'], quit];
210
+ case 'settings':
211
+ if (state.settings?.box != null) {
212
+ return [
213
+ ['↑↓', 'select', 'down'],
214
+ ['enter', 'choose', 'enter'],
215
+ ['esc', 'cancel', 'esc'],
216
+ ];
217
+ }
218
+ return [
219
+ ['↑↓', 'select', 'down'],
220
+ ['enter', 'change', 'enter'],
221
+ ['s', `save to ${state.settings?.access.file.shown ?? 'hopwire.yaml'}`, 's'],
222
+ ...(state.settings !== null && state.settings.history.length > 0
223
+ ? [['u', 'undo', 'u']]
224
+ : []),
225
+ quit,
226
+ ];
205
227
  default:
206
228
  return [['↑↓', 'scroll', 'down'], quit];
207
229
  }
package/dist/tui/model.js CHANGED
@@ -69,6 +69,13 @@ export class Facts {
69
69
  constructor(now = Date.now) {
70
70
  this.now = now;
71
71
  }
72
+ /** The tunnel is started again with other settings: its lines are the facts from now on. */
73
+ reset() {
74
+ this.facts.length = 0;
75
+ this.started = false;
76
+ this.edge = null;
77
+ this.teammates.clear();
78
+ }
72
79
  /** The tunnel runs: from now on a line is something that happened, not a fact of the start. */
73
80
  start() {
74
81
  this.started = true;
@@ -28,10 +28,12 @@ export function listLines(state, ui, width, height) {
28
28
  continue;
29
29
  }
30
30
  const text = ui.row(entry, width - 2);
31
+ // A failed request whose replay passed keeps its status and gets a mark: it is done with
32
+ const mark = state.fixed.has(entry.exchange.id) ? paint(look, '✓', look.palette.ok, true) : ' ';
31
33
  lines.push({
32
34
  text: index === picked
33
- ? onBackground(`${paint(look, '▌', look.palette.green)} ${fit(text, width - 2)}`, highlight(look))
34
- : ` ${text}`,
35
+ ? onBackground(`${paint(look, '▌', look.palette.green)}${mark}${fit(text, width - 2)}`, highlight(look))
36
+ : ` ${mark}${text}`,
35
37
  hits: hitLine(`row:${entry.exchange.id}`, width),
36
38
  });
37
39
  }
@@ -0,0 +1,179 @@
1
+ import { changedSettings, settingValue, unavailable, } from '../settings.js';
2
+ import { paint, wrap } from '../terminal.js';
3
+ import { bold, muted } from './chrome.js';
4
+ import { hitLine } from './state.js';
5
+ import { after, clip, fit, onBackground, sides } from './text.js';
6
+ /** The rows of the tab, in the order they are shown. */
7
+ export function settingRows(settings) {
8
+ const one = settings.services.length === 1;
9
+ return [
10
+ ...settings.services.map((service) => ({
11
+ id: `public:${service.name}`,
12
+ group: 'Reach',
13
+ label: one ? 'Public URL' : `Public URL of ${service.name}`,
14
+ what: 'a public HTTPS address through the edge',
15
+ })),
16
+ {
17
+ id: 'share',
18
+ group: 'Reach',
19
+ label: 'Share with teammates',
20
+ what: 'direct P2P: connect and watch with your keys',
21
+ },
22
+ { id: 'team', group: 'Reach', label: ' Team only', what: 'only machines of your organisation (Team plan)' },
23
+ {
24
+ id: 'relay',
25
+ group: 'Reach',
26
+ label: ' Relay',
27
+ what: 'through the edge when no direct connection comes about',
28
+ },
29
+ {
30
+ id: 'websocket',
31
+ group: 'Recording',
32
+ label: 'WebSocket messages',
33
+ what: 'both directions, up to 64 KiB per message',
34
+ },
35
+ {
36
+ id: 'agent',
37
+ group: 'Recording',
38
+ label: 'Coding agents',
39
+ what: 'an agent on this machine can read and replay',
40
+ },
41
+ ];
42
+ }
43
+ /** What a change does, in the words the user confirms. Turning something on that opens the service says to whom. */
44
+ export function changeSentence(id, on) {
45
+ if (id.startsWith('public:')) {
46
+ return on
47
+ ? 'Anyone who knows the address can call your service through the Hopwire edge. It needs an account (hopwire login), and the requests pass through the edge.'
48
+ : 'The public address stops working. Requests to it are no longer answered by your service.';
49
+ }
50
+ switch (id) {
51
+ case 'share':
52
+ return on
53
+ ? 'Teammates with your keys can call your service and read the traffic log: headers and bodies as captured, credentials included, earlier runs too. Direct P2P, end-to-end encrypted, no servers of ours.'
54
+ : 'Teammates lose the connection: nobody can call your service or follow the log any more. Team only and Relay go off with it.';
55
+ case 'team':
56
+ return on
57
+ ? 'Only machines of the members of your organisation get in (Team plan). The control plane of your account names their keys and gets the key of this machine; your traffic still passes none.'
58
+ : 'Anyone with your keys gets in again, not only your organisation. Relay goes off with it.';
59
+ case 'relay':
60
+ return on
61
+ ? 'Teammates whose network allows no direct connection come in through the edge of your account. End-to-end encrypted: the edge passes on bytes it cannot read, and sees addresses, your organisation, keys and byte counts. Turns on Team only.'
62
+ : 'Teammates connect directly only. One whose network allows no direct connection no longer gets in.';
63
+ case 'websocket':
64
+ return on
65
+ ? 'The messages of WebSockets are recorded in both directions, up to 64 KiB per message.'
66
+ : 'Only the handshake of a WebSocket is recorded, not its messages.';
67
+ default:
68
+ return on
69
+ ? 'A coding agent on this machine can read the traffic and replay it through hopwire mcp. What it reads goes to its model provider.'
70
+ : 'hopwire mcp can no longer read or replay the traffic of this tunnel.';
71
+ }
72
+ }
73
+ /** The choices of the change box. */
74
+ export function changeChoices(access, on) {
75
+ const turn = on ? 'Turn on' : 'Turn off';
76
+ return [
77
+ `${turn} for this run`,
78
+ access.file.exists ? `${turn} and save to ${access.file.shown}` : `${turn} and create ${access.file.shown}`,
79
+ 'Cancel',
80
+ ];
81
+ }
82
+ function highlight(look) {
83
+ const light = look.palette.mark === null;
84
+ return look.truecolor ? (light ? '48;2;226;232;240' : '48;2;30;41;59') : light ? '48;5;254' : '48;5;237';
85
+ }
86
+ /** The label of a setting without its indent, for sentences. */
87
+ export function settingName(settings, id) {
88
+ return (settingRows(settings)
89
+ .find((row) => row.id === id)
90
+ ?.label.trim() ?? id);
91
+ }
92
+ export function settingsLines(state, ui, width, height) {
93
+ const { look } = ui;
94
+ const { palette } = look;
95
+ const view = state.settings;
96
+ if (view === null) {
97
+ return [];
98
+ }
99
+ const settings = view.access.current;
100
+ const rows = settingRows(settings);
101
+ const labels = Math.max(...rows.map((row) => row.label.length)) + 2;
102
+ const lines = [];
103
+ let group = '';
104
+ rows.forEach((row, index) => {
105
+ if (row.group !== group) {
106
+ group = row.group;
107
+ lines.push({ text: '' }, { text: ` ${bold(look, group)}` });
108
+ }
109
+ const reason = unavailable(settings, row.id);
110
+ const on = settingValue(settings, row.id);
111
+ const value = reason !== null && !on ? muted(look, '-') : on ? paint(look, 'on', palette.ok, true) : muted(look, 'off');
112
+ const current = index === view.cursor;
113
+ const text = `${current ? paint(look, '▌', palette.green) : ' '} ${fit(row.label, labels)}${fit(value, 6)}${muted(look, reason !== null && !on ? reason : row.what)}`;
114
+ lines.push({
115
+ text: current ? onBackground(fit(text, width), highlight(look)) : text,
116
+ hits: hitLine(`setting:${index}`, width),
117
+ });
118
+ });
119
+ const changed = changedSettings(view.atStart, settings).map((id) => `${settingName(settings, id)} ${settingValue(settings, id) ? 'on' : 'off'}`);
120
+ const left = ` ${muted(look, 'Changed in this run:')} ${changed.length === 0 ? muted(look, 'nothing') : changed.join(', ')}`;
121
+ const file = view.access.file.exists
122
+ ? `${muted(look, 'file:')} ${view.access.file.shown} `
123
+ : muted(look, `no ${view.access.file.shown} here yet; saving creates it `);
124
+ lines.push({ text: '' }, { text: sides(left, file, width) });
125
+ if (view.problem !== null && !state.restarting) {
126
+ lines.push({ text: '' });
127
+ for (const part of wrap(`Not changed: ${view.problem}`, Math.max(width - 2, 20))) {
128
+ lines.push({ text: ` ${paint(look, part, palette.err)}` });
129
+ }
130
+ }
131
+ if (state.restarting) {
132
+ lines.push({ text: '' }, { text: ` ${paint(look, 'The tunnel is restarting with the new settings…', palette.info)}` });
133
+ }
134
+ const filled = Array.from({ length: height }, (_, row) => lines[row] ?? { text: '' });
135
+ return view.box === null ? filled : withBox(ui, filled, view, width);
136
+ }
137
+ /** The change box over the rows: what the change does, and the choices. */
138
+ function withBox(ui, lines, view, width) {
139
+ const { look } = ui;
140
+ const { box } = view;
141
+ if (box === null) {
142
+ return lines;
143
+ }
144
+ const settings = view.access.current;
145
+ const on = !settingValue(settings, box.id);
146
+ const inner = Math.min(Math.max(width - 8, 30), 64);
147
+ const title = settingName(settings, box.id);
148
+ const text = [
149
+ ...wrap(changeSentence(box.id, on), inner - 2),
150
+ ...wrap('The tunnel restarts for it; a request that arrives in that moment fails.', inner - 2),
151
+ ];
152
+ const bar = muted(look, '│');
153
+ const content = [
154
+ { text: muted(look, `┌ ${title} ${'─'.repeat(Math.max(inner - title.length - 2, 0))}┐`) },
155
+ ...text.map((part) => ({ text: `${bar} ${fit(part, inner - 2)} ${bar}` })),
156
+ { text: `${bar}${' '.repeat(inner)}${bar}` },
157
+ ...changeChoices(view.access, on).map((choice, index) => {
158
+ const current = index === box.choice;
159
+ const label = ` ${current ? paint(look, '▸', look.palette.green, true) : ' '} ${fit(choice, inner - 4)} `;
160
+ return {
161
+ text: `${bar}${current ? onBackground(label, highlight(look)) : label}${bar}`,
162
+ hits: [{ from: 0, to: inner + 2, id: `choice:${index}` }],
163
+ };
164
+ }),
165
+ { text: muted(look, `└${'─'.repeat(inner)}┘`) },
166
+ ];
167
+ const x = Math.max(Math.min(4, width - inner - 2), 0);
168
+ const y = Math.max(Math.min(2, lines.length - content.length), 0);
169
+ return lines.map((line, row) => {
170
+ const part = content[row - y];
171
+ if (part === undefined) {
172
+ return line;
173
+ }
174
+ return {
175
+ text: `${fit(clip(line.text, x, false), x)}${part.text}${after(line.text, x + inner + 2)}`,
176
+ hits: (part.hits ?? []).map((hit) => ({ ...hit, from: hit.from + x, to: hit.to + x })),
177
+ };
178
+ });
179
+ }
package/dist/tui/state.js CHANGED
@@ -1,15 +1,27 @@
1
1
  import { recogniseWebhook } from '../webhook.js';
2
2
  /** The tabs of the navigation, in the order of the bar. */
3
- export const TABS = ['requests', 'share', 'tools', 'status', 'help'];
3
+ export const TABS = ['requests', 'share', 'tools', 'status', 'settings', 'help'];
4
4
  export const TAB_TITLES = {
5
5
  requests: 'Requests',
6
6
  share: 'Share',
7
7
  tools: 'Tools',
8
8
  status: 'Status',
9
+ settings: 'Settings',
9
10
  help: 'Help',
10
11
  };
11
12
  /** The key of a tab: its number, and ? for the help. */
12
- export const TAB_KEYS = { requests: '1', share: '2', tools: '3', status: '4', help: '?' };
13
+ export const TAB_KEYS = {
14
+ requests: '1',
15
+ share: '2',
16
+ tools: '3',
17
+ status: '4',
18
+ settings: '5',
19
+ help: '?',
20
+ };
21
+ /** The tabs this tunnel has: Settings only where there is something to change (http and up). */
22
+ export function tabsOf(state) {
23
+ return TABS.filter((tab) => tab !== 'settings' || state.settings !== null);
24
+ }
13
25
  /** A hit over a whole line. */
14
26
  export function hitLine(id, width) {
15
27
  return [{ from: 0, to: width, id }];
package/dist/tui/tabs.js CHANGED
@@ -203,7 +203,7 @@ export function helpContent(ui) {
203
203
  return [
204
204
  '',
205
205
  ` ${bold(look, 'Everywhere')}`,
206
- key('1 2 3 4 ?', 'Requests, Share, Tools, Status, Help'),
206
+ key('1 2 3 4 5 ?', 'Requests, Share, Tools, Status, Settings, Help'),
207
207
  key('← →', 'the tab before and after'),
208
208
  key('q', 'stop the tunnel and quit'),
209
209
  '',
@@ -213,7 +213,8 @@ export function helpContent(ui) {
213
213
  key('space', 'what can be done with it: replay, fix, copy as curl, inspector'),
214
214
  key('/', 'filter by text: path, status, provider'),
215
215
  key('e', 'failed requests only'),
216
- key('end, esc', 'follow the newest request again'),
216
+ key('n', 'the next failed request, from the picked one on'),
217
+ key('g, end, esc', 'follow the newest request again'),
217
218
  key('r y i f', 'replay, copy as curl, open in the inspector, fix'),
218
219
  key('o c', 'open the inspector, copy the public URL'),
219
220
  '',
@@ -222,6 +223,10 @@ export function helpContent(ui) {
222
223
  key('↑ ↓', 'scroll; page up and page down for more'),
223
224
  key('esc', 'back to the list'),
224
225
  '',
226
+ ` ${bold(look, 'Settings')}`,
227
+ key('enter', 'change the picked setting: for this run, or saved to hopwire.yaml'),
228
+ key('s u', 'save the settings that run to hopwire.yaml, undo the last change'),
229
+ '',
225
230
  ` ${bold(look, 'Mouse')}`,
226
231
  ` ${'Click a tab, a request, a key in the last line or an address. The wheel scrolls.'}`,
227
232
  ` ${muted(look, 'To select text hold Option (iTerm, Apple Terminal) or Shift (most others) while you drag.')}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopwire",
3
- "version": "0.5.1",
3
+ "version": "0.7.0",
4
4
  "mcpName": "to.hopwire/hopwire",
5
5
  "description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
6
6
  "license": "Apache-2.0",