shapewall 0.3.2 → 0.3.3

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 (75) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/NOTICE +7 -0
  3. package/README.md +1 -1
  4. package/THIRD_PARTY.md +39 -0
  5. package/dist/agent/package-lock.json +2 -2
  6. package/dist/client/assets/BoardChat-DxehB761.js +27 -0
  7. package/dist/client/assets/BuzzDialog-Ix9qJvim.js +1 -0
  8. package/dist/client/assets/ChecksPanel-pA_ueIaJ.js +1 -0
  9. package/dist/client/assets/History-C9N32kCv.js +1 -0
  10. package/dist/client/assets/LocalSettings-DawtKnvi.js +1 -0
  11. package/dist/client/assets/{Management-DmTh1-tA.js → Management-NVFDtSZB.js} +1 -1
  12. package/dist/client/assets/QuickConnect-DO1TjS1t.js +1 -0
  13. package/dist/client/assets/ShareDialog-By0ETg6n.js +2 -0
  14. package/dist/client/assets/app-update-dialog-RGIw24iZ.js +1 -0
  15. package/dist/client/assets/{circle-x-3UxAvczM.js → circle-x-B6KfScOE.js} +1 -1
  16. package/dist/client/assets/index-CsqLdqGx.css +2 -0
  17. package/dist/client/assets/index-DnZarJ3U.js +37 -0
  18. package/dist/client/assets/{refresh-cw-BRHNyCnY.js → refresh-cw-vkgvCCfR.js} +1 -1
  19. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  20. package/dist/client/assets/{shield-check-DMpniYP6.js → shield-check-QzwGhz0t.js} +1 -1
  21. package/dist/client/assets/ui-DI-FGWWK.js +41 -0
  22. package/dist/client/build-info.json +1 -1
  23. package/dist/client/index.html +4 -3
  24. package/dist/client/sw.js +2 -2
  25. package/dist/console/assets/{LocalAccountsApp-IvHd9zWN.js → LocalAccountsApp-VOCZg8dg.js} +1 -1
  26. package/dist/console/assets/{LocalConsole-DOyLou56.js → LocalConsole-CMwAW-mF.js} +1 -1
  27. package/dist/console/assets/{app-update-dialog-Da46CJpv.js → app-update-dialog-Cw6UDqNP.js} +1 -1
  28. package/dist/console/assets/console-DgfWmUEx.js +55 -0
  29. package/dist/console/assets/console-Lis0vvdL.css +2 -0
  30. package/dist/console/build-info.json +1 -1
  31. package/dist/console/console.html +2 -2
  32. package/docs/agents.md +62 -2
  33. package/docs/config.md +1 -1
  34. package/docs/deployment.md +2 -0
  35. package/docs/design-system.md +20 -15
  36. package/docs/hosted.md +19 -0
  37. package/docs/where-to-run.md +88 -0
  38. package/package.json +2 -1
  39. package/src/agent/agent-logos.js +81 -0
  40. package/src/agent/config.js +27 -2
  41. package/src/agent/icon-store.js +100 -0
  42. package/src/agent/identity.js +77 -0
  43. package/src/agent/owner-mcp.js +19 -3
  44. package/src/agent/routes.js +80 -20
  45. package/src/agent/run.js +3 -1
  46. package/src/agent/settings-routes.js +233 -14
  47. package/src/agent/test-timing.js +14 -0
  48. package/src/agent/tools.js +4 -2
  49. package/src/agent/user-settings.js +51 -3
  50. package/src/capture/element-map.js +61 -4
  51. package/src/hosted/agent-presence.js +40 -0
  52. package/src/hosted/app.js +6 -0
  53. package/src/hosted/board-routes.js +7 -0
  54. package/src/hosted/console-routes.js +47 -1
  55. package/src/hosted/events.js +6 -4
  56. package/src/hosted/presence.js +1 -1
  57. package/src/hosted/projects.js +32 -1
  58. package/src/hosted/token-api.js +5 -1
  59. package/src/hosted/token-events.js +5 -2
  60. package/src/hosted/tokens.js +3 -2
  61. package/src/mcp.js +10 -2
  62. package/src/store.js +5 -0
  63. package/dist/client/assets/BoardChat-BeRp6007.js +0 -27
  64. package/dist/client/assets/BuzzDialog-CrYy48hh.js +0 -1
  65. package/dist/client/assets/ChecksPanel-CB820mhj.js +0 -1
  66. package/dist/client/assets/History-Ba909bGJ.js +0 -1
  67. package/dist/client/assets/LocalSettings-ChMi9Zir.js +0 -1
  68. package/dist/client/assets/QuickConnect-CrVweWZB.js +0 -1
  69. package/dist/client/assets/ShareDialog-DO2HhY6g.js +0 -2
  70. package/dist/client/assets/app-update-dialog-C09ODdUQ.js +0 -1
  71. package/dist/client/assets/index-BIjfZKnp.js +0 -37
  72. package/dist/client/assets/index-CXtuJi1K.css +0 -2
  73. package/dist/client/assets/ui-mhL9gsne.js +0 -41
  74. package/dist/console/assets/console-CIBv7cXU.js +0 -55
  75. package/dist/console/assets/console-Fp4k9iyx.css +0 -2
@@ -12,6 +12,11 @@
12
12
  // POST /api/agent/settings/profiles/:id/default make a connected agent (or "endpoint": the saved
13
13
  // OpenAI-compatible endpoint) the one new chats and fixes use
14
14
  // DELETE /api/agent/settings/profiles/:id remove a connected agent
15
+ // POST /api/agent/settings/identity { id, name?, icon?, tint? } what an agent is called and how
16
+ // it looks (identity.js). `id`: a connected agent, "endpoint", or
17
+ // "default" (the agent a flag or the environment fixes). Display only:
18
+ // no confirmation, no restart, no test, also while it answers
19
+ // POST /api/agent/settings/identity/icon { id, png } an uploaded icon (icon-store.js)
15
20
  //
16
21
  // These are the server owner's settings: which agent runs on their machine
17
22
  // and where their API key goes. Looking local is not enough (a proxy or TCP
@@ -50,9 +55,12 @@ import { legacyProfile, profileForDefault, projectKey, saveUserAgentEntry, userA
50
55
  import { DEFAULT_BRANCH_PREFIX, branchModeSettings, cleanBranchPrefix, repoFilters } from './branch-mode.js'
51
56
  import { batchFixSettings, cleanBatchFixes } from './batch-fixes.js'
52
57
  import { tokenEquals } from '../tokens.js'
58
+ import { cleanAgentName, identityOf, isAgentIcon, isAgentTint, isBuiltInIcon } from './identity.js'
59
+ import { IconError, pruneIcons, saveIcon } from './icon-store.js'
60
+ import { logoForAgent } from './agent-logos.js'
61
+ import { ACP_TEST_TIMEOUT_MS } from './test-timing.js'
53
62
 
54
63
  const TEST_TIMEOUT_MS = 15000
55
- const ACP_TEST_TIMEOUT_MS = 30000
56
64
  const VISION_PROBE_MS = 3000
57
65
  const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
58
66
  // Any of these means a proxy or tunnel stands between the person and us.
@@ -356,6 +364,9 @@ export function settingsRoutes({
356
364
  })
357
365
  const repo = () => config.agent || {}
358
366
  let testing = false
367
+ // Which agent the running test is of: a profile id, or "default" (the
368
+ // default connection). Shown as that agent's state ("Testing the connection").
369
+ let testingId = null
359
370
  let closing = false
360
371
  const pending = new Set()
361
372
  router.close = async () => {
@@ -364,6 +375,15 @@ export function settingsRoutes({
364
375
  }
365
376
  // Shared admission lock: a handshake must not overlap live turns or profile changes.
366
377
  router.isTesting = () => testing
378
+ // { id } while a test runs, else null (routes.js: the agent's state).
379
+ router.testing = () => (testing ? { id: testingId } : null)
380
+ // A test started or ended: every open view hears it, also the ones that
381
+ // did not start it (a reloaded page, another tab).
382
+ const setTesting = (on, id = null) => {
383
+ testing = on
384
+ testingId = on ? id || 'default' : null
385
+ events?.changed('state')
386
+ }
367
387
 
368
388
  const guard = (req, res, next) => {
369
389
  if (closing) return fail(res, 503, 'settings_stopping', 'Agent settings are stopping.')
@@ -378,6 +398,145 @@ export function settingsRoutes({
378
398
  next()
379
399
  }
380
400
 
401
+ // ---- What an agent is called and how it looks (identity.js) ----------------
402
+ //
403
+ // Registered before the admission step below on purpose: a name, an icon
404
+ // and a tint change nothing an agent runs with, so saving them never waits
405
+ // for a turn to end, never stops an agent process and never runs a test.
406
+ // A flag or environment command does not block them either: it fixes the
407
+ // command, not what the board calls it.
408
+
409
+ // The saved place `id` names: { entry, target, known } with `target` the
410
+ // object inside `entry` that holds its label, icon and tint, and `known`
411
+ // the built-in name an empty name falls back to (null: the name is needed).
412
+ const identityTarget = (id, current) => {
413
+ const entry = { ...current, profiles: (current.profiles || []).map((item) => ({ ...item })) }
414
+ const source = settings().sources?.acpCommand
415
+ const fixed = source === 'flag' || source === 'env'
416
+ const legacy = legacyProfile(current, KNOWN_AGENTS)
417
+ const builtIn = (profileId) => KNOWN_AGENTS.find((item) => item.id === profileId)?.label || null
418
+ if (id === 'default') {
419
+ if (fixed) {
420
+ entry.fixedAgent = { ...(current.fixedAgent || {}) }
421
+ return { entry, target: entry.fixedAgent, known: true }
422
+ }
423
+ const running = profileForDefault(current) || legacy
424
+ if (running) return identityTarget(running.id, current)
425
+ return endpointOf(current) ? identityTarget('endpoint', current) : null
426
+ }
427
+ if (id === 'endpoint') return endpointOf(current) ? { entry, target: entry, known: true } : null
428
+ // A default command saved before profiles becomes a profile, as on Connect.
429
+ if (legacy?.id === id) entry.profiles = [{ ...legacy }, ...entry.profiles]
430
+ const profile = entry.profiles.find((item) => item.id === id)
431
+ return profile ? { entry, target: profile, known: builtIn(id) } : null
432
+ }
433
+
434
+ // `current` with { name, icon, tint } (only the keys given) applied to the
435
+ // agent `id`: { entry }, or { status, code, message } when it is refused.
436
+ const withIdentity = (current, id, change) => {
437
+ const found = identityTarget(id, current)
438
+ if (!found) return { status: 404, code: 'unknown_profile', message: 'That agent is not connected.' }
439
+ const { entry, target } = found
440
+ if (Object.hasOwn(change, 'name')) {
441
+ const { name, problem } = cleanAgentName(change.name)
442
+ if (problem) return { status: 400, code: 'invalid_name', message: problem }
443
+ if (name) target.label = name
444
+ else if (found.known === true) delete target.label
445
+ else if (found.known) target.label = found.known
446
+ else return { status: 400, code: 'invalid_name', message: 'name: 1 to 40 characters' }
447
+ }
448
+ if (Object.hasOwn(change, 'icon')) {
449
+ if (change.icon === null || change.icon === '') delete target.icon
450
+ else if (isAgentIcon(change.icon)) target.icon = change.icon
451
+ else return { status: 400, code: 'invalid_icon', message: 'icon: one of the built-in icons, or null for none.' }
452
+ }
453
+ if (Object.hasOwn(change, 'tint')) {
454
+ if (change.tint === null || change.tint === '') delete target.tint
455
+ else if (isAgentTint(change.tint)) target.tint = change.tint
456
+ else return { status: 400, code: 'invalid_tint', message: 'tint: one of the accent colours, or null for none.' }
457
+ }
458
+ if (entry.fixedAgent && !Object.keys(entry.fixedAgent).length) delete entry.fixedAgent
459
+ if (!entry.profiles.length) delete entry.profiles
460
+ delete entry.updatedAt
461
+ return { entry }
462
+ }
463
+
464
+ // A one-click Connect saves the agent and then tests it, which with a real
465
+ // agent takes seconds, and puts the old settings back when the test fails.
466
+ // A name or an icon saved in that window must not be lost or refused:
467
+ // - for the agent being connected, the save waits for the test (the person
468
+ // sees "Saving when the connection test finishes..."), then is applied to
469
+ // the connected agent, or answers that it did not connect;
470
+ // - for any other agent it is saved at once, and remembered (`renamed`) so
471
+ // that a failed test, which writes the old settings back, applies it again.
472
+ // `connecting`: { id, done, renamed } while such a test runs, else null.
473
+ let connecting = null
474
+ const underTest = (id) => {
475
+ if (!connecting || typeof id !== 'string') return false
476
+ const found = identityTarget(id, userAgentEntry(config.dir, env).entry || {})
477
+ return found?.target?.id === connecting.id
478
+ }
479
+
480
+ // Saves the change for `id`. Returns true when saved; otherwise it answered.
481
+ const saveIdentity = async (req, res, id, change) => {
482
+ if (typeof id !== 'string' || !id) return fail(res, 400, 'invalid_identity', 'id: a connected agent, "endpoint" or "default".')
483
+ const waited = underTest(id) ? connecting : null
484
+ if (waited) await waited.done
485
+ const saved = userAgentEntry(config.dir, env)
486
+ if (saved.problem) return fail(res, 409, 'settings_file_invalid', saved.problem)
487
+ const next = withIdentity(saved.entry || {}, id, change)
488
+ if (!next.entry) {
489
+ // The agent it was for did not connect: said in those words.
490
+ if (waited && next.status === 404)
491
+ return fail(res, 409, 'agent_not_connected', `${waited.label} did not connect, so there is nothing to rename. Nothing was changed.`)
492
+ return fail(res, next.status, next.code, next.message)
493
+ }
494
+ try {
495
+ // No reload(): the agents keep running; the name is read fresh wherever it is shown.
496
+ saveUserAgentEntry(config.dir, next.entry, env)
497
+ if (connecting) connecting.renamed.push({ id, change })
498
+ pruneIcons(env)
499
+ } catch (error) {
500
+ return fail(res, 500, 'settings_not_saved', `The settings were not saved: ${error.message}`)
501
+ }
502
+ return true
503
+ }
504
+
505
+ router.post('/identity', guard, async (req, res) => {
506
+ const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}
507
+ const change = Object.fromEntries(['name', 'icon', 'tint'].filter((key) => Object.hasOwn(body, key)).map((key) => [key, body[key]]))
508
+ // An uploaded icon is set by the upload itself, never named from outside.
509
+ if (typeof change.icon === 'string' && !isBuiltInIcon(change.icon))
510
+ return fail(res, 400, 'invalid_icon', 'icon: one of the built-in icons, or null for none.')
511
+ if ((await saveIdentity(req, res, body.id, change)) === true) res.json(view())
512
+ })
513
+
514
+ router.post('/identity/icon', guard, async (req, res) => {
515
+ const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}
516
+ // The agent is being connected: wait here, before the picture is stored
517
+ // (a file no agent uses yet would be cleaned up by another save).
518
+ const waited = underTest(body.id) ? connecting : null
519
+ if (waited) await waited.done
520
+ // Is the agent there? Before anything is stored.
521
+ const saved = userAgentEntry(config.dir, env)
522
+ if (saved.problem) return fail(res, 409, 'settings_file_invalid', saved.problem)
523
+ if (typeof body.id !== 'string' || !identityTarget(body.id, saved.entry || {})) {
524
+ if (waited)
525
+ return fail(res, 409, 'agent_not_connected', `${waited.label} did not connect, so its icon was not saved. Nothing was changed.`)
526
+ return fail(res, 404, 'unknown_profile', 'That agent is not connected.')
527
+ }
528
+ let hash
529
+ try {
530
+ hash = saveIcon(body.png, env)
531
+ } catch (error) {
532
+ if (error instanceof IconError) return fail(res, error.status, error.code, error.message)
533
+ return fail(res, 500, 'settings_not_saved', `The icon was not saved: ${error.message}`)
534
+ }
535
+ if ((await saveIdentity(req, res, body.id, { icon: `upload:${hash}` })) === true) res.json(view())
536
+ // Not saved after all: the file just written is not left behind.
537
+ else pruneIcons(env)
538
+ })
539
+
381
540
  router.use(async (req, res, next) => {
382
541
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next()
383
542
  // Authorize before taking admission so an outsider cannot block turns.
@@ -433,7 +592,12 @@ export function settingsRoutes({
433
592
  })
434
593
 
435
594
  // How an agent is doing (agent-health.js): { state, loginHint }.
436
- const statusOf = (profileId) => (health ? health.status(settings(profileId), processPool) : {})
595
+ // While its connection test runs an agent's state is "testing", not what
596
+ // the last turn left ("Ready"): the page must not look finished.
597
+ const statusOf = (profileId) => {
598
+ const status = health ? health.status(settings(profileId), processPool) : {}
599
+ return testing && testingId === (profileId || 'default') ? { ...status, state: 'testing' } : status
600
+ }
437
601
  const profileList = (entry) => {
438
602
  const legacy = legacyProfile(entry, KNOWN_AGENTS)
439
603
  // Profiles saved without a default connection: the first one (config.js agentSettings).
@@ -442,6 +606,8 @@ export function settingsRoutes({
442
606
  ...profile,
443
607
  command: acpCommand,
444
608
  default: (entry?.backend === 'acp' && entry.acpCommand === acpCommand) || profile.id === fallback,
609
+ // Its default icon: a known agent's product mark (agent-logos.js), or null.
610
+ logo: settings(profile.legacy ? null : profile.id).logo || null,
445
611
  // A legacy command runs as the default connection.
446
612
  ...statusOf(profile.legacy ? null : profile.id),
447
613
  }))
@@ -455,6 +621,7 @@ export function settingsRoutes({
455
621
  const isDefault = backend === 'openai-compatible' && !settings().defaultProfile
456
622
  return {
457
623
  label: entry.label || repo().label || model,
624
+ ...identityOf(entry),
458
625
  model,
459
626
  host: hostOf(baseUrl),
460
627
  default: isDefault,
@@ -482,6 +649,10 @@ export function settingsRoutes({
482
649
  configured: current.configured,
483
650
  problem: current.problem,
484
651
  label: current.label,
652
+ icon: current.icon || null,
653
+ tint: current.tint || null,
654
+ logo: current.logo || null,
655
+ builtInLabel: current.builtInLabel || null,
485
656
  baseUrl: current.baseUrl,
486
657
  model: current.model,
487
658
  host: current.host,
@@ -504,7 +675,12 @@ export function settingsRoutes({
504
675
  // one-click Connect in an unconnected chat panel.
505
676
  detected: detectAgents(env),
506
677
  // Every agent Shapewall knows how to run, found or not (the console's Agents page).
507
- known: KNOWN_AGENTS.map(({ id, label, adapter, cli, install }) => ({ id, label, adapter, cli, install })),
678
+ known: KNOWN_AGENTS.map(({ id, label, adapter, cli, install }) => ({ id, label, adapter, cli, install, logo: logoForAgent(id) })),
679
+ // Icons can be uploaded here (the demo has only the built-in ones).
680
+ iconUpload: true,
681
+ // { id } while a connection test runs (a Connect, or Test connection):
682
+ // the other changes of this page wait for it.
683
+ testing: testing ? { id: testingId } : null,
508
684
  knownKeyHosts: [...KNOWN_KEY_HOSTS],
509
685
  defaultKeyVar: DEFAULT_KEY_VAR,
510
686
  keyVarsSet: keyVarsSet(env),
@@ -571,16 +747,27 @@ export function settingsRoutes({
571
747
  return fail(res, 400, 'invalid_settings', 'The settings must be an object.')
572
748
  // Old clients save only the default connection. Keep their saved profiles.
573
749
  const preserved = input && !Object.hasOwn(input, 'profiles') ? userAgentEntry(config.dir, env).entry?.profiles : undefined
574
- // Branch mode and batch fixes have their own routes (/branch-mode,
575
- // /batch-fixes): a save of the connection keeps them.
750
+ // Branch mode, batch fixes and the icons have their own routes
751
+ // (/branch-mode, /batch-fixes, /identity): a save of the connection keeps them.
576
752
  const savedEntry = userAgentEntry(config.dir, env).entry || {}
577
753
  const branch = Object.fromEntries(
578
- ['branchMode', 'branchPrefix', 'batchFixes']
754
+ ['branchMode', 'branchPrefix', 'batchFixes', 'icon', 'tint', 'fixedAgent']
579
755
  .filter((key) => !Object.hasOwn(input, key) && savedEntry[key] !== undefined)
580
756
  .map((key) => [key, savedEntry[key]]),
581
757
  )
582
758
  const { entry, problems } = validateUserEntry({ ...input, ...(preserved ? { profiles: preserved } : {}), ...branch })
583
759
  if (!entry) return fail(res, 400, 'invalid_settings', problems.join('; '))
760
+ // The form's name field names the agent it saves. When that is a
761
+ // connected agent (the default command is one of the profiles), the name
762
+ // belongs to that agent, the same one the Agents page's Edit changes.
763
+ const named = Object.hasOwn(input, 'label') ? profileForDefault(entry) : null
764
+ if (named) {
765
+ const { name, problem } = cleanAgentName(input.label)
766
+ if (problem) return fail(res, 400, 'invalid_settings', problem.replace(/^name/, 'label'))
767
+ const builtIn = KNOWN_AGENTS.find((item) => item.id === named.id)?.label
768
+ entry.profiles = entry.profiles.map((item) => (item.id === named.id ? { ...item, label: name || builtIn || item.label } : item))
769
+ delete entry.label
770
+ }
584
771
  // A Connect is testing what it saved and may put the old settings back:
585
772
  // a save now would be lost.
586
773
  if (testing) return fail(res, 409, 'test_running', 'A connection test is running. Wait for it, then save.')
@@ -612,6 +799,21 @@ export function settingsRoutes({
612
799
  `The agent command comes from ${source === 'flag' ? '--agent-acp' : 'SHAPEWALL_AGENT_ACP'}, which wins over the board. Change it there, or restart shapewall serve without it.`,
613
800
  )
614
801
  }
802
+ // What the owner calls it, from the confirmation's Name field (empty:
803
+ // its built-in name), and optionally a built-in icon and a tint. An
804
+ // uploaded icon comes after the agent is connected (POST /identity/icon).
805
+ const { name, problem } = cleanAgentName(req.body?.name)
806
+ if (problem) return fail(res, 400, 'invalid_name', problem)
807
+ const look = {}
808
+ if (req.body?.icon) {
809
+ if (!isBuiltInIcon(req.body.icon)) return fail(res, 400, 'invalid_icon', 'icon: one of the built-in icons.')
810
+ look.icon = req.body.icon
811
+ }
812
+ if (req.body?.tint) {
813
+ if (!isAgentTint(req.body.tint)) return fail(res, 400, 'invalid_tint', 'tint: one of the accent colours.')
814
+ look.tint = req.body.tint
815
+ }
816
+ const called = (profileConnect && name) || agent.label
615
817
  const before = userAgentEntry(config.dir, env)
616
818
  // The label and the image toggle belong to the agent connected before.
617
819
  const entry = { ...(before.entry || {}) }
@@ -622,7 +824,7 @@ export function settingsRoutes({
622
824
  entry.profiles = [
623
825
  ...(legacy && legacy.id !== agent.id ? [legacy] : []),
624
826
  ...(entry.profiles || []).filter((item) => item.id !== agent.id),
625
- { id: agent.id, label: agent.label, acpCommand: agent.command },
827
+ { id: agent.id, label: called, acpCommand: agent.command, ...look },
626
828
  ]
627
829
  }
628
830
  if (!profileConnect || !settings().configured) {
@@ -632,21 +834,38 @@ export function settingsRoutes({
632
834
  delete entry.vision
633
835
  }
634
836
  if (!saveEntry(req, res, entry)) return
635
- // Back to what was there: the panel must not claim an agent that does not start.
837
+ let ended
838
+ const job = { id: agent.id, label: called, renamed: [], done: new Promise((resolve) => (ended = resolve)) }
839
+ // Back to what was there: the panel must not claim an agent that does not
840
+ // start. Names and icons other agents were given meanwhile are kept; one
841
+ // for an agent that is not there any more (this one) is dropped.
636
842
  const restore = () => {
637
843
  try {
638
- saveUserAgentEntry(config.dir, before.entry || {}, env)
844
+ let entry = before.entry || {}
845
+ for (const { id, change } of job.renamed) entry = withIdentity(entry, id, change).entry || entry
846
+ saveUserAgentEntry(config.dir, entry, env)
847
+ pruneIcons(env)
639
848
  } finally {
640
849
  reload()
641
850
  }
642
851
  }
643
- testing = true
852
+ connecting = job
853
+ setTesting(true, profileConnect ? agent.id : 'default')
854
+ // The test is over (after any restore): the saves that waited for it go
855
+ // on, and the answer below already shows the agent as it is, not "testing".
856
+ const over = () => {
857
+ if (connecting !== job) return
858
+ connecting = null
859
+ setTesting(false)
860
+ ended()
861
+ }
644
862
  try {
645
863
  const tested = settings(profileConnect ? agent.id : null)
646
864
  const result = await testConnection(tested, { env, fetchImpl, root: config.dir, processPool })
647
865
  health?.record(tested, result)
648
866
  if (!result.ok) restore()
649
- res.json({ connected: result.ok, result: { ...result, label: agent.label }, ...view() })
867
+ over()
868
+ res.json({ connected: result.ok, result: { ...result, label: called }, ...view() })
650
869
  } catch (error) {
651
870
  try {
652
871
  restore()
@@ -655,7 +874,7 @@ export function settingsRoutes({
655
874
  }
656
875
  fail(res, 500, 'test_failed', `The test did not finish: ${redact(error.message)}`)
657
876
  } finally {
658
- testing = false
877
+ over()
659
878
  await res.locals.releaseSettingsOperation?.()
660
879
  }
661
880
  })
@@ -776,7 +995,7 @@ export function settingsRoutes({
776
995
  const profileId = req.body?.profileId ?? null
777
996
  if (profileId !== null && !(userAgentEntry(config.dir, env).entry?.profiles || []).some((item) => item.id === profileId))
778
997
  return fail(res, 400, 'unknown_profile', 'profileId: one of the connected agents.')
779
- testing = true
998
+ setTesting(true, profileId)
780
999
  try {
781
1000
  const tested = settings(profileId)
782
1001
  const result = await testConnection(tested, { env, fetchImpl, root: config.dir, processPool })
@@ -785,7 +1004,7 @@ export function settingsRoutes({
785
1004
  } catch (error) {
786
1005
  fail(res, 500, 'test_failed', `The test did not finish: ${redact(error.message)}`)
787
1006
  } finally {
788
- testing = false
1007
+ setTesting(false)
789
1008
  await res.locals.releaseSettingsOperation?.()
790
1009
  }
791
1010
  })
@@ -0,0 +1,14 @@
1
+ // How long a connection test may take, in one place for the server that
2
+ // runs it and the board that waits for it.
3
+ //
4
+ // A one-click Connect (and Test connection) starts the agent and waits for
5
+ // its ACP handshake. The stub used in tests answers at once; a real agent
6
+ // takes several seconds, and up to ACP_TEST_TIMEOUT_MS before the server
7
+ // gives up. While it runs the server takes no chat message and no other
8
+ // settings change, so the board waits rather than showing an error: for a
9
+ // little longer than the test can last (TEST_WAIT_MS).
10
+ //
11
+ // No Node imports: the board imports this file too.
12
+
13
+ export const ACP_TEST_TIMEOUT_MS = 30000
14
+ export const TEST_WAIT_MS = ACP_TEST_TIMEOUT_MS + 15000
@@ -149,8 +149,10 @@ export const OWNER_TOOLS = [
149
149
  required: ['id', 'body'],
150
150
  additionalProperties: false,
151
151
  },
152
- async run({ config, board }, args) {
153
- return (await addReply(config, board.id, args.id, { body: args.body, author: 'agent' })).comment
152
+ // Signed with the name the owner gave the agent, and marked as an agent's.
153
+ async run({ config, board, agentName }, args) {
154
+ const signed = agentName ? { author: agentName, agent: true } : { author: 'agent' }
155
+ return (await addReply(config, board.id, args.id, { body: args.body, ...signed })).comment
154
156
  },
155
157
  },
156
158
  {
@@ -22,6 +22,7 @@ import { SETTINGS_SOURCE } from './acp/command.js'
22
22
  import { DENIED_KEY_VARS, KEY_VAR_RE, validateAgent } from './config.js'
23
23
  import { cleanBranchPrefix } from './branch-mode.js'
24
24
  import { cleanBatchFixes } from './batch-fixes.js'
25
+ import { IDENTITY_KEYS, cleanAgentName, isAgentIcon, isAgentTint } from './identity.js'
25
26
 
26
27
  export const SETTINGS_FILE_VAR = 'SHAPEWALL_AGENT_SETTINGS_FILE'
27
28
  export const ENTRY_KEYS = [
@@ -37,6 +38,12 @@ export const ENTRY_KEYS = [
37
38
  'branchMode',
38
39
  'branchPrefix',
39
40
  'batchFixes',
41
+ // How the agent looks on the board (identity.js): `icon` and `tint` here
42
+ // are the endpoint's; `fixedAgent` holds the name, icon and tint of an
43
+ // agent whose command a flag or the environment fixes.
44
+ 'icon',
45
+ 'tint',
46
+ 'fixedAgent',
40
47
  ]
41
48
  const SECRET_KEYS = ['apiKey', 'key', 'token', 'secret', 'password']
42
49
  const ACP_COMMAND_MAX = 2000
@@ -46,6 +53,18 @@ const HOST_RE = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9
46
53
 
47
54
  const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
48
55
 
56
+ // The icon and tint of `source` into `target`, each checked (identity.js).
57
+ function readLook(source, target, problems, where) {
58
+ if (source.icon !== undefined) {
59
+ if (!isAgentIcon(source.icon)) problems.push(`${where}icon: a built-in icon or an uploaded one`)
60
+ else target.icon = source.icon
61
+ }
62
+ if (source.tint !== undefined) {
63
+ if (!isAgentTint(source.tint)) problems.push(`${where}tint: one of the accent colours`)
64
+ else target.tint = source.tint
65
+ }
66
+ }
67
+
49
68
  // The settings file, or null when there is no home to put it in.
50
69
  export function userSettingsFile(env = process.env) {
51
70
  if (typeof env[SETTINGS_FILE_VAR] === 'string' && env[SETTINGS_FILE_VAR].trim()) return path.resolve(env[SETTINGS_FILE_VAR].trim())
@@ -78,7 +97,7 @@ export function validateUserEntry(raw) {
78
97
  problems.push(`${key}: keys are never saved; set the key in the environment and name its variable in apiKeyEnv`)
79
98
  else if (!ENTRY_KEYS.includes(key) && key !== 'updatedAt') problems.push(`${key}: not an agent setting`)
80
99
  }
81
- const { keyHosts, acpCommand, profiles, updatedAt, branchMode, branchPrefix, batchFixes, ...rest } = given
100
+ const { keyHosts, acpCommand, profiles, updatedAt, branchMode, branchPrefix, batchFixes, icon, tint, fixedAgent, ...rest } = given
82
101
  const fields = {}
83
102
  for (const key of ['backend', 'baseUrl', 'model', 'apiKeyEnv', 'label', 'vision']) if (rest[key] !== undefined) fields[key] = rest[key]
84
103
  const agentProblems = []
@@ -130,7 +149,7 @@ export function validateUserEntry(raw) {
130
149
  for (const profile of profiles) {
131
150
  if (
132
151
  !isObject(profile) ||
133
- Object.keys(profile).some((key) => !['id', 'label', 'acpCommand'].includes(key)) ||
152
+ Object.keys(profile).some((key) => !['id', 'label', 'acpCommand', 'icon', 'tint'].includes(key)) ||
134
153
  !/^[a-z][a-z0-9-]{0,39}$/.test(profile.id || '') ||
135
154
  profile.id === 'default' ||
136
155
  ids.has(profile.id) ||
@@ -144,12 +163,29 @@ export function validateUserEntry(raw) {
144
163
  }
145
164
  const validated = validateUserEntry({ acpCommand: profile.acpCommand })
146
165
  if (!validated.entry?.acpCommand) problems.push('profiles: each profile needs a valid ACP command')
147
- else checkedProfiles.push({ id: profile.id, label: profile.label.trim(), acpCommand: validated.entry.acpCommand })
166
+ else {
167
+ const checkedProfile = { id: profile.id, label: profile.label.trim(), acpCommand: validated.entry.acpCommand }
168
+ readLook(profile, checkedProfile, problems, 'profiles: ')
169
+ checkedProfiles.push(checkedProfile)
170
+ }
148
171
  ids.add(profile.id)
149
172
  }
150
173
  if (checkedProfiles.length) entry.profiles = checkedProfiles
151
174
  }
152
175
  }
176
+ readLook({ icon, tint }, entry, problems, '')
177
+ if (fixedAgent !== undefined) {
178
+ if (!isObject(fixedAgent) || Object.keys(fixedAgent).some((key) => !IDENTITY_KEYS.includes(key))) {
179
+ problems.push('fixedAgent: { label, icon, tint }')
180
+ } else {
181
+ const fixed = {}
182
+ const { name, problem } = cleanAgentName(fixedAgent.label)
183
+ if (problem) problems.push(`fixedAgent.${problem.replace(/^name/, 'label')}`)
184
+ else if (name) fixed.label = name
185
+ readLook(fixedAgent, fixed, problems, 'fixedAgent.')
186
+ if (Object.keys(fixed).length) entry.fixedAgent = fixed
187
+ }
188
+ }
153
189
  // Agent branch mode (branch-mode.js): the agent works on a branch in a worktree.
154
190
  if (branchMode !== undefined) {
155
191
  if (typeof branchMode !== 'boolean') problems.push('branchMode: true or false')
@@ -208,6 +244,18 @@ export function legacyProfile(entry, known = []) {
208
244
  return { id, label, acpCommand: entry.acpCommand }
209
245
  }
210
246
 
247
+ // The name saved for one of this project's agents, or null when none is
248
+ // saved (the caller then uses the agent's built-in name). `which`: "fixed"
249
+ // (the agent a flag or the environment fixes), "default" (the default
250
+ // connection) or a profile id.
251
+ export function savedAgentName(root, which, env = process.env) {
252
+ const { entry } = userAgentEntry(root, env)
253
+ if (!entry) return null
254
+ if (which === 'fixed') return entry.fixedAgent?.label || null
255
+ if (which === 'default') return (profileForDefault(entry) || implicitDefault(entry))?.label || entry.label || null
256
+ return (entry.profiles || []).find((profile) => profile.id === which)?.label || null
257
+ }
258
+
211
259
  // A file anyone else may write could redirect your key or start a command:
212
260
  // on POSIX the file and its folder must be yours and not group/world-writable.
213
261
  function unsafeOwnership(file) {
@@ -337,9 +337,64 @@ export function hitTest(map, x, y) {
337
337
  return target === undefined ? best : target
338
338
  }
339
339
 
340
- // A short label for the element a comment would pin to (as
341
- // anchors.js describeElement): the last selector step and its text, and
342
- // `large` when it covers a fifth of the page or more.
340
+ // What a reviewer would call an element, from its tag: "Heading", "Button",
341
+ // "Image". Containers are a "Section"; other tags with words in them are "Text".
342
+ const KINDS = {
343
+ h1: 'Heading',
344
+ h2: 'Heading',
345
+ h3: 'Heading',
346
+ h4: 'Heading',
347
+ h5: 'Heading',
348
+ h6: 'Heading',
349
+ a: 'Link',
350
+ button: 'Button',
351
+ summary: 'Button',
352
+ img: 'Image',
353
+ picture: 'Image',
354
+ svg: 'Image',
355
+ video: 'Video',
356
+ input: 'Field',
357
+ textarea: 'Field',
358
+ select: 'Field',
359
+ label: 'Label',
360
+ li: 'List item',
361
+ ul: 'List',
362
+ ol: 'List',
363
+ table: 'Table',
364
+ form: 'Form',
365
+ nav: 'Navigation',
366
+ header: 'Header',
367
+ footer: 'Footer',
368
+ section: 'Section',
369
+ article: 'Section',
370
+ main: 'Section',
371
+ aside: 'Section',
372
+ div: 'Section',
373
+ }
374
+
375
+ // The tag a selector ends on ('' when its last step is an #id).
376
+ export function selectorTag(selector) {
377
+ const last = String(selector || '')
378
+ .split(' > ')
379
+ .pop()
380
+ const match = /^([a-z][a-z0-9-]*)/.exec(last)
381
+ return match ? match[1] : ''
382
+ }
383
+
384
+ // A plain name for an element: its kind and its text ("Heading: Notes that
385
+ // keep up...", "Button: Start free", "Section"). `large`: it covers a big
386
+ // part of the page, so a section says it is the whole of it.
387
+ export function plainLabel(tag, text = '', { large = false, max = 32 } = {}) {
388
+ const words = String(text || '').trim()
389
+ let kind = KINDS[tag] || (words ? 'Text' : 'Element')
390
+ if (large && kind === 'Section') kind = 'Whole section'
391
+ return words ? `${kind}: ${clip(words, max)}` : kind
392
+ }
393
+
394
+ // What hovering shows for the element a comment would pin to (as
395
+ // anchors.js describeElement): `name`, its plain label; `label`, the last
396
+ // selector step and its text (for people who read selectors); and `large`
397
+ // when it covers a fifth of the page or more.
343
398
  export function describeAt(map, position, native) {
344
399
  const item = map.elements[position]
345
400
  const selector = selectorOf(map, position)
@@ -347,9 +402,11 @@ export function describeAt(map, position, native) {
347
402
  const text = item.x || ''
348
403
  const [left, top, width, height] = item.b
349
404
  const area = native?.width && native?.height ? (width * height) / (native.width * native.height) : 0
405
+ const large = area > 0.2
350
406
  return {
407
+ name: plainLabel(item.t, text, { large }),
351
408
  label: `${clip(step, 48)}${text ? ` "${clip(text, 28)}"` : ''}`,
352
- large: area > 0.2,
409
+ large,
353
410
  rect: { left, top, width, height },
354
411
  }
355
412
  }
@@ -0,0 +1,40 @@
1
+ // Is an agent listening? A comment on a hosted board is only acted on while
2
+ // some machine runs `shapewall watch --remote` (or an MCP client) for its
3
+ // project, with a token that has the claim scope. This remembers, per
4
+ // project, when such a token last called the token API or held its event
5
+ // stream open, so the board can say "Agent online: <name>" or "No agent is
6
+ // listening".
7
+ //
8
+ // In memory only, on purpose: it is a few seconds of truth, empty after a
9
+ // restart until the next poll, and never written anywhere. It holds a
10
+ // token's display name and a time, nothing else: no token id, no hash, no
11
+ // address.
12
+
13
+ export const AGENT_PRESENCE_TTL_MS = 90_000
14
+ const PROJECTS_MAX = 5000
15
+
16
+ export function createAgentPresence({ now = () => new Date(), ttlMs = AGENT_PRESENCE_TTL_MS } = {}) {
17
+ const seenAt = new Map()
18
+ const key = (workspaceId, projectId) => `${workspaceId}:${projectId}`
19
+ return {
20
+ // A claim-scoped token of this project was just heard from.
21
+ seen(workspaceId, projectId, name) {
22
+ if (!workspaceId || !projectId) return
23
+ const id = key(workspaceId, projectId)
24
+ // Re-inserted, so the map stays in order of last seen (oldest first).
25
+ seenAt.delete(id)
26
+ seenAt.set(id, { name: String(name || 'agent').slice(0, 80), at: now().getTime() })
27
+ if (seenAt.size > PROJECTS_MAX) seenAt.delete(seenAt.keys().next().value)
28
+ },
29
+ // What board viewers are told: { online, name, lastSeenAt }. `name` and
30
+ // `lastSeenAt` stay after it goes quiet, until the server restarts.
31
+ of(workspaceId, projectId) {
32
+ const entry = seenAt.get(key(workspaceId, projectId))
33
+ if (!entry) return { online: false, name: null, lastSeenAt: null }
34
+ return { online: now().getTime() - entry.at <= ttlMs, name: entry.name, lastSeenAt: new Date(entry.at).toISOString() }
35
+ },
36
+ forget(workspaceId, projectId) {
37
+ seenAt.delete(key(workspaceId, projectId))
38
+ },
39
+ }
40
+ }