@bakers-build/addon-bakers-ui 0.11.1-next.8 → 0.12.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.
@@ -56,6 +56,8 @@ export interface ConductorRow extends Conductor {
56
56
  hostKey: string | undefined;
57
57
  /** The sideloaded machine's name — its display label. */
58
58
  machineLabel: string | undefined;
59
+ /** The sideloaded machine's owner; `null` when the machine is unreadable, `undefined` without a machine. */
60
+ machineOwnerUserId: string | null | undefined;
59
61
  /** Liveness, derived — never the raw `status`. */
60
62
  derivedStatus: ConductorStatus;
61
63
  /**
@@ -393,6 +395,8 @@ export interface ConductorQuery {
393
395
  projectId?: string | undefined;
394
396
  /** The conductors this user OWNS (BB-460 D3) — by owner, never by machine. */
395
397
  ownerUserId?: string | undefined;
398
+ /** One machine's conductors, opened from the Machines tab. */
399
+ machineId?: string | undefined;
396
400
  }
397
401
  /**
398
402
  * One PAGE of the conductor collection as cockpit rows (BB-460 D6).
@@ -343,6 +343,13 @@ function machineOf(raw, machinesById) {
343
343
  return {
344
344
  hostKey: str(machine?.attributes?.host_key),
345
345
  machineLabel: str(machine?.attributes?.name),
346
+ // An unreadable referenced machine is an unknown owner (null), never the
347
+ // conductor's: only a conductor without a machine falls back to its owner.
348
+ machineOwnerUserId: machine
349
+ ? singleRelId(machine.relationships?.owner_user_id)
350
+ : machineId
351
+ ? null
352
+ : undefined,
346
353
  };
347
354
  }
348
355
  const toConductorRow = (raw, ctx, machinesById) => {
@@ -353,7 +360,7 @@ const toConductorRow = (raw, ctx, machinesById) => {
353
360
  const lastSeen = toUnixSeconds(r.attr('last_seen')) ?? 0;
354
361
  const leaseExpiresAt = toUnixSeconds(r.attr('lease_expires_at')) ?? 0;
355
362
  const { currentLoad, maxParallel } = capacityOf(raw, machinesById);
356
- const { hostKey, machineLabel } = machineOf(raw, machinesById);
363
+ const { hostKey, machineLabel, machineOwnerUserId } = machineOf(raw, machinesById);
357
364
  return {
358
365
  ...toConductor(r),
359
366
  workspaceRoot,
@@ -365,6 +372,7 @@ const toConductorRow = (raw, ctx, machinesById) => {
365
372
  conductorName: str(r.attr('conductor_name')),
366
373
  hostKey,
367
374
  machineLabel,
375
+ machineOwnerUserId,
368
376
  // `present: true` because the row IS a control-plane record — which is why
369
377
  // `registry-only` can never come out of this screen.
370
378
  derivedStatus: deriveConductorStatus({
@@ -399,6 +407,8 @@ const conductorParams = (query) => {
399
407
  params.addFilter('project_id.id', query.projectId);
400
408
  if (query.ownerUserId)
401
409
  params.addFilter('owner_user_id.id', query.ownerUserId);
410
+ if (query.machineId)
411
+ params.addFilter('machine.id', query.machineId);
402
412
  return params;
403
413
  };
404
414
  /**
@@ -0,0 +1,22 @@
1
+ import type { DropshClient } from '../../../types.js';
2
+ import type { ListTable, Page } from '../../collection.js';
3
+ /** One machine of the control plane, as the Machines tab lists it. */
4
+ export interface MachineRow {
5
+ id: string;
6
+ name: string;
7
+ /** Online when any of its conductors is. */
8
+ online: boolean;
9
+ /** The machine's reported `current_load`: its active runs. */
10
+ active: number;
11
+ conductorIds: string[];
12
+ ownerUserId: string | null;
13
+ }
14
+ /**
15
+ * The machines of these conductors, grouped from one conductor read with the
16
+ * machine sideloaded.
17
+ *
18
+ * shortcut: a machine without a conductor, or past the first 50 conductors,
19
+ * is not listed; read `bb_machine` directly when that matters.
20
+ */
21
+ export declare const listMachineRows: (client: DropshClient, ownerUserId: string | undefined, nowSeconds: number) => Promise<Page<MachineRow>>;
22
+ export declare const MACHINE_TABLE: ListTable<MachineRow>;
@@ -0,0 +1,89 @@
1
+ import { toUnixSeconds } from '@bakers-build/core';
2
+ import { DrupalJsonApiParams } from 'drupal-jsonapi-params';
3
+ import { deriveConductorStatus } from './liveness.js';
4
+ const relId = (resource, name) => {
5
+ const data = resource.relationships?.[name]?.data;
6
+ return data && !Array.isArray(data) ? data.id : null;
7
+ };
8
+ /**
9
+ * The machines of these conductors, grouped from one conductor read with the
10
+ * machine sideloaded.
11
+ *
12
+ * shortcut: a machine without a conductor, or past the first 50 conductors,
13
+ * is not listed; read `bb_machine` directly when that matters.
14
+ */
15
+ export const listMachineRows = async (client, ownerUserId, nowSeconds) => {
16
+ const params = new DrupalJsonApiParams()
17
+ .addInclude(['machine'])
18
+ .addSort('drupal_internal__id', 'ASC')
19
+ .addPageLimit(50);
20
+ if (ownerUserId)
21
+ params.addFilter('owner_user_id.id', ownerUserId);
22
+ const doc = (await client.get('bb_conductor/bb_conductor', params));
23
+ const machines = new Map();
24
+ for (const included of doc.included ?? []) {
25
+ if (!included.id || included.type !== 'bb_machine--bb_machine')
26
+ continue;
27
+ const attrs = included.attributes ?? {};
28
+ machines.set(included.id, {
29
+ id: included.id,
30
+ name: String(attrs.name || attrs.host_key || '(unnamed)'),
31
+ online: false,
32
+ active: Number(attrs.current_load ?? 0),
33
+ conductorIds: [],
34
+ ownerUserId: relId(included, 'owner_user_id'),
35
+ });
36
+ }
37
+ for (const conductor of doc.data ?? []) {
38
+ const row = machines.get(relId(conductor, 'machine') ?? '');
39
+ if (!row || !conductor.id)
40
+ continue;
41
+ row.conductorIds.push(conductor.id);
42
+ const attrs = conductor.attributes ?? {};
43
+ const status = deriveConductorStatus({
44
+ present: true,
45
+ status: typeof attrs.status === 'string' ? attrs.status : null,
46
+ lastSeen: toUnixSeconds(attrs.last_seen),
47
+ leaseExpiresAt: toUnixSeconds(attrs.lease_expires_at),
48
+ }, nowSeconds);
49
+ row.online ||= status === 'online';
50
+ }
51
+ const rows = [...machines.values()].filter((m) => m.conductorIds.length > 0);
52
+ return { rows, hasNext: false, page: 0, total: rows.length, window: null };
53
+ };
54
+ export const MACHINE_TABLE = {
55
+ noun: 'machine',
56
+ emptyMessage: 'No machines with conductors.',
57
+ columns: [
58
+ {
59
+ key: 'name',
60
+ label: 'NAME',
61
+ width: 0,
62
+ min: 20,
63
+ grow: 2,
64
+ fields: ['name'],
65
+ get: (row) => row.name,
66
+ },
67
+ {
68
+ key: 'status',
69
+ label: 'STATUS',
70
+ width: 10,
71
+ fields: ['status'],
72
+ get: (row) => (row.online ? 'online' : 'offline'),
73
+ },
74
+ {
75
+ key: 'active',
76
+ label: 'ACTIVE',
77
+ width: 8,
78
+ fields: ['current_load'],
79
+ get: (row) => String(row.active),
80
+ },
81
+ {
82
+ key: 'conductors',
83
+ label: 'CONDUCTORS',
84
+ width: 12,
85
+ fields: ['machine'],
86
+ get: (row) => String(row.conductorIds.length),
87
+ },
88
+ ],
89
+ };
@@ -1,7 +1,7 @@
1
1
  import type { ListFilterBadge } from '../../../Component/list-chrome/index.js';
2
2
  import type { FullScreenChrome } from '../../../Screen/full-screen.js';
3
3
  import { ListScreen } from '../../../Screen/list-screen.js';
4
- import type { ScreenContext } from '../../../Screen/screen.js';
4
+ import type { ScreenAction, ScreenContext } from '../../../Screen/screen.js';
5
5
  import type { Page } from '../../collection.js';
6
6
  import { type ConductorListContext, type ConductorRow } from '../Data/conductors.js';
7
7
  /**
@@ -16,12 +16,7 @@ export declare class ConductorsScreen extends ListScreen<ConductorRow, Conductor
16
16
  static readonly route: {
17
17
  id: string;
18
18
  path: string;
19
- tab: {
20
- id: string;
21
- label: string;
22
- scope: string;
23
- weight: number;
24
- };
19
+ parent: string;
25
20
  };
26
21
  readonly id: string;
27
22
  readonly frameId = "conductors";
@@ -112,6 +107,8 @@ export declare class ConductorsScreen extends ListScreen<ConductorRow, Conductor
112
107
  protected badges(): readonly ListFilterBadge[];
113
108
  protected renderLoading(): string[];
114
109
  protected chrome(_context: ScreenContext): FullScreenChrome;
110
+ /** Restart runs only on a conductor of a machine the operator owns. */
111
+ private owned;
115
112
  /**
116
113
  * BB-450 review B9 — `s`/`x` are advertised only when the SELECTED row can
117
114
  * actually be acted on: `mine` is the identity gate (B10), not `isLocal`'s
@@ -122,6 +119,7 @@ export declare class ConductorsScreen extends ListScreen<ConductorRow, Conductor
122
119
  * scope for every row, and the log tab inside it is the one place that still
123
120
  * withholds a foreign conductor's log (its `mine` derivation lives there).
124
121
  */
122
+ actionForInput(input: string): ScreenAction | undefined;
125
123
  protected actions(): import("../../../Component/footer-actions/index.js").ActionItem[];
126
124
  /**
127
125
  * BB-450 review B6/B10 — a row this screen cannot act on states so,
@@ -1,11 +1,13 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { actionItem } from '../../../Component/footer-actions/index.js';
3
+ import { confirmNavigation } from '../../../Screen/confirm-dialog.js';
3
4
  import { ListScreen } from '../../../Screen/list-screen.js';
4
5
  import { runRowAction } from '../../../Screen/row-action.js';
5
6
  import { resolveWhoCandidate } from '../../user/Data/users.js';
6
7
  import { CONDUCTOR_TABLE, countConductors, listConductorRowPage, listProjectNames, } from '../Data/conductors.js';
7
8
  import { DEFAULT_CONDUCTOR_MINE, hiddenNotice, mineBadges, OwnerIdentity, } from '../Data/own-rows.js';
8
9
  import { createConductorProcessHost } from '../Data/process.js';
10
+ import { restartRunsRequest } from './restart-runs.js';
9
11
  /**
10
12
  * Conductors list — an ordinary {@link ListScreen}, paged and filtered to the
11
13
  * operator's own conductors by default (BB-460 D1).
@@ -18,7 +20,7 @@ export class ConductorsScreen extends ListScreen {
18
20
  static route = {
19
21
  id: 'conductors',
20
22
  path: '/conductors',
21
- tab: { id: 'conductors', label: 'Conductors', scope: 'root', weight: 50 },
23
+ parent: 'machines',
22
24
  };
23
25
  id = ConductorsScreen.route.id;
24
26
  frameId = 'conductors';
@@ -62,18 +64,19 @@ export class ConductorsScreen extends ListScreen {
62
64
  this.projectNames = projectNames;
63
65
  this.ownerId = undefined;
64
66
  this.identityReason = '';
65
- if (this.mine) {
66
- const outcome = await this.identity.resolve(client, context.services.currentUser);
67
- if (outcome.kind === 'resolved') {
68
- this.ownerId = outcome.id;
69
- }
70
- else {
71
- this.identityReason = outcome.reason;
72
- }
67
+ // Resolved even with `mine` off: Restart runs is offered on own rows only.
68
+ const outcome = await this.identity.resolve(client, context.services.currentUser);
69
+ if (outcome.kind === 'resolved') {
70
+ this.ownerId = outcome.id;
73
71
  }
74
- const query = this.ownerId
75
- ? { ownerUserId: this.ownerId }
76
- : {};
72
+ else if (this.mine) {
73
+ this.identityReason = outcome.reason;
74
+ }
75
+ const machineId = context.params?.machineId;
76
+ const query = {
77
+ ...(this.mine && this.ownerId ? { ownerUserId: this.ownerId } : {}),
78
+ ...(machineId ? { machineId } : {}),
79
+ };
77
80
  const rowCtx = {
78
81
  now: context.nowSeconds?.() ?? Math.floor(Date.now() / 1000),
79
82
  exists: existsSync,
@@ -84,7 +87,7 @@ export class ConductorsScreen extends ListScreen {
84
87
  // row count is bounded by the page, so it would under-report exactly when
85
88
  // the collection is large enough for the question to matter.
86
89
  this.hidden =
87
- this.ownerId === undefined || rows.total === null
90
+ !query.ownerUserId || rows.total === null
88
91
  ? null
89
92
  : ((total) => (total === null ? null : total - (rows.total ?? 0)))(await countConductors(client, {}));
90
93
  return rows;
@@ -110,6 +113,15 @@ export class ConductorsScreen extends ListScreen {
110
113
  .join(' · '),
111
114
  };
112
115
  }
116
+ /** Restart runs only on a conductor of a machine the operator owns. */
117
+ owned() {
118
+ const row = this.rows[this.selectedIndex];
119
+ // Like the site: a conductor without a machine falls back to its owner.
120
+ const owner = row?.machineOwnerUserId === undefined
121
+ ? row?.ownerUserId
122
+ : row.machineOwnerUserId;
123
+ return row && this.ownerId && owner === this.ownerId ? row : undefined;
124
+ }
113
125
  /**
114
126
  * BB-450 review B9 — `s`/`x` are advertised only when the SELECTED row can
115
127
  * actually be acted on: `mine` is the identity gate (B10), not `isLocal`'s
@@ -120,9 +132,23 @@ export class ConductorsScreen extends ListScreen {
120
132
  * scope for every row, and the log tab inside it is the one place that still
121
133
  * withholds a foreign conductor's log (its `mine` derivation lives there).
122
134
  */
135
+ actionForInput(input) {
136
+ const row = input === 'r' ? this.owned() : undefined;
137
+ if (!row)
138
+ return undefined;
139
+ return confirmNavigation(restartRunsRequest({
140
+ level: 'conductor',
141
+ label: row.label,
142
+ conductorIds: [row.id],
143
+ online: row.derivedStatus === 'online',
144
+ }));
145
+ }
123
146
  actions() {
124
147
  const canAct = this.rows[this.selectedIndex]?.mine ?? false;
125
148
  return [
149
+ ...(this.owned()
150
+ ? [actionItem('conductors-restart', 'r', 'restart runs')]
151
+ : []),
126
152
  ...(canAct
127
153
  ? [
128
154
  actionItem('conductors-start', 's', 'start'),
@@ -0,0 +1,38 @@
1
+ import type { FullScreenChrome } from '../../../Screen/full-screen.js';
2
+ import { ListScreen } from '../../../Screen/list-screen.js';
3
+ import type { ScreenAction, ScreenContext } from '../../../Screen/screen.js';
4
+ import type { Page } from '../../collection.js';
5
+ import { type MachineRow } from '../Data/machines.js';
6
+ /**
7
+ * Machines — the root level of the conductor cockpit: the operator's
8
+ * machines, each opening its conductors. `r` restarts the runs of an owned
9
+ * machine behind a confirmation.
10
+ */
11
+ export declare class MachinesScreen extends ListScreen<MachineRow> {
12
+ static readonly route: {
13
+ id: string;
14
+ path: string;
15
+ tab: {
16
+ id: string;
17
+ label: string;
18
+ scope: string;
19
+ weight: number;
20
+ };
21
+ };
22
+ readonly id: string;
23
+ readonly frameId = "machines";
24
+ protected readonly table: import("../../collection.js").ListTable<MachineRow, void>;
25
+ private readonly identity;
26
+ private ownerId;
27
+ protected tableContext(): void;
28
+ protected loadRows(context: ScreenContext): Promise<Page<MachineRow>>;
29
+ protected renderLoading(): string[];
30
+ protected chrome(): FullScreenChrome;
31
+ /** Restart runs only on a machine the operator owns. */
32
+ private owned;
33
+ protected actions(): import("../../../Component/footer-actions/index.js").ActionItem[];
34
+ activate(index: number, context: ScreenContext): boolean;
35
+ handleInput(input: string, context: ScreenContext): boolean;
36
+ actionForInput(input: string): ScreenAction | undefined;
37
+ reset(): void;
38
+ }
@@ -0,0 +1,92 @@
1
+ import { actionItem } from '../../../Component/footer-actions/index.js';
2
+ import { confirmNavigation } from '../../../Screen/confirm-dialog.js';
3
+ import { ListScreen } from '../../../Screen/list-screen.js';
4
+ import { resolveWhoCandidate } from '../../user/Data/users.js';
5
+ import { listMachineRows, MACHINE_TABLE, } from '../Data/machines.js';
6
+ import { OwnerIdentity } from '../Data/own-rows.js';
7
+ import { restartRunsRequest } from './restart-runs.js';
8
+ /**
9
+ * Machines — the root level of the conductor cockpit: the operator's
10
+ * machines, each opening its conductors. `r` restarts the runs of an owned
11
+ * machine behind a confirmation.
12
+ */
13
+ export class MachinesScreen extends ListScreen {
14
+ static route = {
15
+ id: 'machines',
16
+ path: '/machines',
17
+ tab: { id: 'machines', label: 'Machines', scope: 'root', weight: 50 },
18
+ };
19
+ id = MachinesScreen.route.id;
20
+ frameId = 'machines';
21
+ table = MACHINE_TABLE;
22
+ identity = new OwnerIdentity(resolveWhoCandidate);
23
+ ownerId;
24
+ tableContext() { }
25
+ async loadRows(context) {
26
+ if (!context.services)
27
+ throw new Error('Machines requires services');
28
+ const client = context.services.client;
29
+ const outcome = await this.identity.resolve(client, context.services.currentUser);
30
+ this.ownerId = outcome.kind === 'resolved' ? outcome.id : undefined;
31
+ return listMachineRows(client, this.ownerId, context.nowSeconds?.() ?? Math.floor(Date.now() / 1000));
32
+ }
33
+ renderLoading() {
34
+ return ['Loading machines…'];
35
+ }
36
+ chrome() {
37
+ return {
38
+ selectable: this.rows.length,
39
+ selectedIndex: this.selectedIndex,
40
+ rowIds: this.rowNodeIds,
41
+ title: 'bakers.build machines',
42
+ meta: this.countLabel(),
43
+ };
44
+ }
45
+ /** Restart runs only on a machine the operator owns. */
46
+ owned() {
47
+ const row = this.rows[this.selectedIndex];
48
+ return row && this.ownerId && row.ownerUserId === this.ownerId
49
+ ? row
50
+ : undefined;
51
+ }
52
+ actions() {
53
+ return [
54
+ ...(this.owned()
55
+ ? [actionItem('machines-restart', 'r', 'restart runs')]
56
+ : []),
57
+ actionItem('machines-enter', 'Enter', 'conductors'),
58
+ actionItem('machines-tab', 'Tab', 'tabs'),
59
+ ];
60
+ }
61
+ activate(index, context) {
62
+ const row = this.rows[index];
63
+ if (!row || !context.navigate)
64
+ return false;
65
+ context.navigate('conductors', { machineId: row.id });
66
+ return true;
67
+ }
68
+ handleInput(input, context) {
69
+ if (super.handleInput(input, context))
70
+ return true;
71
+ if (input === 'enter')
72
+ return this.activate(this.selectedIndex, context);
73
+ return this.handleCursorInput(input, context);
74
+ }
75
+ actionForInput(input) {
76
+ const row = input === 'r' ? this.owned() : undefined;
77
+ if (!row)
78
+ return undefined;
79
+ return confirmNavigation(restartRunsRequest({
80
+ level: 'machine',
81
+ label: row.name,
82
+ conductorIds: row.conductorIds,
83
+ online: row.online,
84
+ }));
85
+ }
86
+ reset() {
87
+ this.resetList();
88
+ this.identity.reset();
89
+ this.ownerId = undefined;
90
+ super.reset();
91
+ }
92
+ }
@@ -0,0 +1,40 @@
1
+ import type { ConfirmRequest } from '../../../Screen/confirm-dialog.js';
2
+ import type { DropshClient } from '../../../types.js';
3
+ /** One run Restart runs cancels. */
4
+ export interface CoveredRun {
5
+ readonly id: string;
6
+ readonly number: string;
7
+ readonly state: string;
8
+ readonly identifier: string;
9
+ readonly frozen: boolean;
10
+ /** JSON:API returns `error_log` empty (`BbRun::preSave` files it); its size tells whether one exists. */
11
+ readonly errorLogBytes: number;
12
+ }
13
+ /** What Restart runs acts on: a machine (all its conductors) or one conductor. */
14
+ export interface RestartTarget {
15
+ readonly level: 'machine' | 'conductor';
16
+ readonly label: string;
17
+ readonly conductorIds: readonly string[];
18
+ /** Whether the conductor, or any conductor of the machine, is online. */
19
+ readonly online: boolean;
20
+ }
21
+ /**
22
+ * The runs Restart runs cancels: every claimed or running run of these
23
+ * conductors, plus each open ticket's newest run when it failed on one of them.
24
+ *
25
+ * shortcut: the server's rule (`TicketInterventions::restartCoveredRuns`) is
26
+ * mirrored here, and each of the two reads takes one page of 50 (active runs
27
+ * stay below a machine's capacity; failed runs are read newest first by
28
+ * `changed`, then id, as `isNewest`); unify
29
+ * once the site offers a restart endpoint.
30
+ */
31
+ export declare const restartCoveredRuns: (client: DropshClient, conductorIds: readonly string[]) => Promise<CoveredRun[]>;
32
+ /** The error-log line naming Restart runs, its level and the person. */
33
+ export declare const restartNote: (target: RestartTarget, person: string) => string;
34
+ /**
35
+ * Restart runs, for the confirmation dialog: cancel every covered run with a
36
+ * note; the conductor then gives each ticket one fresh run.
37
+ *
38
+ * Confirm reads the set again and writes nothing when it changed.
39
+ */
40
+ export declare const restartRunsRequest: (target: RestartTarget) => ConfirmRequest;
@@ -0,0 +1,145 @@
1
+ import { DrupalJsonApiParams } from 'drupal-jsonapi-params';
2
+ import { CANCELLED_RUN_STATE } from '../../run/Form/edit.js';
3
+ /** Whether `runId` is its ticket's newest run, in the failed-run breaker's order. */
4
+ const isNewest = async (client, ticketId, runId) => {
5
+ const params = new DrupalJsonApiParams()
6
+ .addFilter('ticket_id.id', ticketId)
7
+ .addSort('changed', 'DESC')
8
+ .addSort('drupal_internal__id', 'DESC')
9
+ .addFields('bb_run--bb_run', ['drupal_internal__id'])
10
+ .addPageLimit(1);
11
+ const doc = (await client.get('bb_run/bb_run', params));
12
+ return doc.data?.[0]?.id === runId;
13
+ };
14
+ /** One page of these conductors' runs in `states`, tickets included. */
15
+ const readRuns = async (client, conductorIds, states, order, openTicketsOnly = false) => {
16
+ const params = new DrupalJsonApiParams()
17
+ .addFilter('conductor_id.id', [...conductorIds], 'IN')
18
+ .addFilter('state', states, 'IN')
19
+ .addInclude(['ticket_id'])
20
+ .addFields('bb_run--bb_run', [
21
+ 'state',
22
+ 'drupal_internal__id',
23
+ 'error_log_bytes',
24
+ 'ticket_id',
25
+ ])
26
+ .addFields('bb_ticket--bb_ticket', ['identifier', 'frozen'])
27
+ .addSort('changed', order)
28
+ .addSort('drupal_internal__id', order)
29
+ .addPageLimit(50);
30
+ if (openTicketsOnly)
31
+ params.addFilter('ticket_id.closed', '0');
32
+ const doc = (await client.get('bb_run/bb_run', params));
33
+ const tickets = new Map((doc.included ?? []).map((t) => [t.id ?? '', t.attributes ?? {}]));
34
+ return (doc.data ?? []).map((run) => {
35
+ const ticketId = run.relationships?.ticket_id?.data?.id ?? '';
36
+ const ticket = tickets.get(ticketId) ?? {};
37
+ return {
38
+ ticketId,
39
+ run: {
40
+ id: run.id ?? '',
41
+ number: String(run.attributes?.drupal_internal__id ?? ''),
42
+ state: String(run.attributes?.state ?? ''),
43
+ identifier: String(ticket.identifier ?? '?'),
44
+ frozen: ticket.frozen === true,
45
+ errorLogBytes: Number(run.attributes?.error_log_bytes ?? 0),
46
+ },
47
+ };
48
+ });
49
+ };
50
+ /**
51
+ * The runs Restart runs cancels: every claimed or running run of these
52
+ * conductors, plus each open ticket's newest run when it failed on one of them.
53
+ *
54
+ * shortcut: the server's rule (`TicketInterventions::restartCoveredRuns`) is
55
+ * mirrored here, and each of the two reads takes one page of 50 (active runs
56
+ * stay below a machine's capacity; failed runs are read newest first by
57
+ * `changed`, then id, as `isNewest`); unify
58
+ * once the site offers a restart endpoint.
59
+ */
60
+ export const restartCoveredRuns = async (client, conductorIds) => {
61
+ if (conductorIds.length === 0)
62
+ return [];
63
+ const active = await readRuns(client, conductorIds, ['claimed', 'running'], 'ASC');
64
+ const failed = await readRuns(client, conductorIds, ['failed'], 'DESC', true);
65
+ const covered = active.map(({ run }) => run);
66
+ const seen = new Set();
67
+ for (const { ticketId, run } of failed) {
68
+ // Newest first in isNewest's order: only a ticket's first failed run here can be its newest.
69
+ if (seen.has(ticketId))
70
+ continue;
71
+ seen.add(ticketId);
72
+ if (await isNewest(client, ticketId, run.id))
73
+ covered.push(run);
74
+ }
75
+ return covered;
76
+ };
77
+ /** The error-log line naming Restart runs, its level and the person. */
78
+ export const restartNote = (target, person) => `Restart runs (${target.level} ${target.label}) by ${person}`;
79
+ const runLine = (run) => `${run.identifier} · run #${run.number} · ${run.state}${run.frozen ? ' · frozen: the fresh run follows unfreeze' : ''}`;
80
+ const sameRuns = (a, b) => a
81
+ .map((run) => run.id)
82
+ .sort()
83
+ .join() ===
84
+ b
85
+ .map((run) => run.id)
86
+ .sort()
87
+ .join();
88
+ /**
89
+ * Restart runs, for the confirmation dialog: cancel every covered run with a
90
+ * note; the conductor then gives each ticket one fresh run.
91
+ *
92
+ * Confirm reads the set again and writes nothing when it changed.
93
+ */
94
+ export const restartRunsRequest = (target) => ({
95
+ title: '↻ Restart runs',
96
+ prepare: async (context) => {
97
+ const client = context.services?.client;
98
+ if (!client)
99
+ throw new Error('No connection to read the runs.');
100
+ const runs = await restartCoveredRuns(client, target.conductorIds);
101
+ const name = `${target.level} ${target.label}`;
102
+ if (runs.length === 0)
103
+ return { message: `No runs to restart on ${name}.` };
104
+ return {
105
+ message: `Restart runs on ${name}?`,
106
+ detail: [
107
+ ...runs.map(runLine),
108
+ 'Each run is cancelled; its ticket gets one fresh run.',
109
+ ...(target.online
110
+ ? []
111
+ : [
112
+ 'It is offline: tab and runtime cleanup and the fresh runs follow its next start.',
113
+ ]),
114
+ ].join('\n'),
115
+ confirm: async (confirmContext) => {
116
+ const services = confirmContext.services;
117
+ if (!services)
118
+ throw new Error('No connection to restart the runs.');
119
+ const fresh = await restartCoveredRuns(services.client, target.conductorIds);
120
+ if (!sameRuns(fresh, runs))
121
+ throw new Error('The runs changed since the dialog opened. Open it again.');
122
+ const note = restartNote(target, services.currentUser ?? 'unknown');
123
+ const writer = services.writeClient ?? services.client;
124
+ // A PATCH replaces the stored error log, so read every existing one before writing any.
125
+ const logs = await Promise.all(fresh.map((run) => {
126
+ if (run.errorLogBytes === 0)
127
+ return '';
128
+ if (!writer.runLog)
129
+ throw new Error("Cannot read the runs' error logs to keep them.");
130
+ return writer.runLog(run.id, 'error_log');
131
+ }));
132
+ for (const [i, run] of fresh.entries()) {
133
+ const log = logs[i]?.replace(/[\r\n]+$/, '') ?? '';
134
+ await writer.update('bb_run--bb_run', run.id, {
135
+ attributes: {
136
+ state: CANCELLED_RUN_STATE,
137
+ error_log: log ? `${log}\n${note}` : note,
138
+ },
139
+ });
140
+ }
141
+ return { type: 'runs-restarted', count: fresh.length };
142
+ },
143
+ };
144
+ },
145
+ });
@@ -1,4 +1,4 @@
1
- import type { DropshClient, JsonApiResource } from '../../../types.js';
1
+ import type { DropshClient, JsonApiRelationship, JsonApiResource } from '../../../types.js';
2
2
  import { type Page } from '../../collection.js';
3
3
  import { type TicketCriteria } from './query.js';
4
4
  /** One flat-table row derived from a `bb_ticket` dropsh resource. */
@@ -31,6 +31,9 @@ export interface TicketRow {
31
31
  /** A `(id) → resource` lookup over a document's sideloaded `included` entries.
32
32
  * JSON:API ids are UUIDs (unique across bundles), so id alone keys uniquely. */
33
33
  type IncludedIndex = Map<string, JsonApiResource>;
34
+ /** Read the id of a single-valued relationship linkage (`data` object), or
35
+ * null when the linkage is absent, null, or an (unexpected) array. */
36
+ export declare function singleRelId(rel: JsonApiRelationship | undefined): string | null;
34
37
  /**
35
38
  * The RELATIONSHIPS the row resolves through, and they belong in the fieldset.
36
39
  *
@@ -16,7 +16,7 @@ function indexIncluded(included) {
16
16
  }
17
17
  /** Read the id of a single-valued relationship linkage (`data` object), or
18
18
  * null when the linkage is absent, null, or an (unexpected) array. */
19
- function singleRelId(rel) {
19
+ export function singleRelId(rel) {
20
20
  const data = rel?.data;
21
21
  if (!data || Array.isArray(data))
22
22
  return null;
@@ -49,6 +49,6 @@ export interface UserProfile {
49
49
  position: string;
50
50
  aboutMe: string;
51
51
  }
52
- /** Read one user's username, position (`field_developer_title`) and About me
53
- * (`field_bb_background`). A refusal propagates to the screen's error. */
54
- export declare function loadUserProfile(client: DropshClient, userId: string): Promise<UserProfile>;
52
+ /** Read one user's username, and position and About me from their profile in
53
+ * the workspace (`bb_profile`). A refusal propagates to the screen's error. */
54
+ export declare function loadUserProfile(client: DropshClient, userId: string, workspaceId: string): Promise<UserProfile>;
@@ -111,17 +111,23 @@ export async function resolveWhoCandidate(client, name) {
111
111
  const outcome = await fetchWhoCandidates(client, params);
112
112
  return { ...outcome, rows: outcome.rows.slice(0, 1) };
113
113
  }
114
- /** Read one user's username, position (`field_developer_title`) and About me
115
- * (`field_bb_background`). A refusal propagates to the screen's error. */
116
- export async function loadUserProfile(client, userId) {
117
- const doc = (await client.get(`user/user/${userId}`));
118
- const text = (key) => {
119
- const value = doc?.data?.attributes?.[key];
114
+ /** Read one user's username, and position and About me from their profile in
115
+ * the workspace (`bb_profile`). A refusal propagates to the screen's error. */
116
+ export async function loadUserProfile(client, userId, workspaceId) {
117
+ const user = (await client.get(`user/user/${userId}`));
118
+ const params = new DrupalJsonApiParams()
119
+ .addFilter('uid.id', userId)
120
+ .addFilter('workspace_id.id', workspaceId)
121
+ .addPageLimit(1);
122
+ const profiles = (await client.get('bb_profile/bb_profile', params));
123
+ const text = (resource, key) => {
124
+ const value = resource?.attributes?.[key];
120
125
  return typeof value === 'string' ? value.trim() : '';
121
126
  };
127
+ const profile = profiles?.data?.[0];
122
128
  return {
123
- username: text('name'),
124
- position: text('field_developer_title'),
125
- aboutMe: text('field_bb_background'),
129
+ username: text(user?.data, 'name'),
130
+ position: text(profile, 'position'),
131
+ aboutMe: text(profile, 'background'),
126
132
  };
127
133
  }
@@ -42,7 +42,7 @@ export class WorkspaceMemberOverviewScreen extends AsyncScreen {
42
42
  if (!workspaceId || !userId)
43
43
  throw new Error('Workspace member Overview requires workspaceId and userId');
44
44
  await assertActiveMember(context.services.client, 'bb_workspace', workspaceId, userId);
45
- return loadUserProfile(context.services.client, userId);
45
+ return loadUserProfile(context.services.client, userId, workspaceId);
46
46
  }
47
47
  renderLoading() {
48
48
  return ['Loading member…'];
@@ -2,6 +2,7 @@ import { ConductorLogScreen } from '../Entity/conductor/Screen/conductor-log.js'
2
2
  import { ConductorOverviewScreen } from '../Entity/conductor/Screen/conductor-overview.js';
3
3
  import { ConductorRunsScreen } from '../Entity/conductor/Screen/conductor-runs.js';
4
4
  import { ConductorsScreen } from '../Entity/conductor/Screen/conductors.js';
5
+ import { MachinesScreen } from '../Entity/conductor/Screen/machines.js';
5
6
  import { ProjectConductorsScreen } from '../Entity/conductor/Screen/project-conductors.js';
6
7
  import { ProjectOverviewScreen } from '../Entity/project/Screen/project-overview.js';
7
8
  import { ProjectPickerScreen } from '../Entity/project/Screen/project-picker.js';
@@ -60,6 +61,7 @@ export const bootLocationFor = (route) => {
60
61
  };
61
62
  const BUILT_IN = [
62
63
  MyWorkScreen,
64
+ MachinesScreen,
63
65
  ConductorsScreen,
64
66
  ConductorOverviewScreen,
65
67
  ConductorRunsScreen,
@@ -46,6 +46,12 @@ export interface DropshClient {
46
46
  * that are not an entity create (the addon inbox send).
47
47
  */
48
48
  post(path: string, body: unknown): Promise<unknown>;
49
+ /**
50
+ * A run's stored log text from `_bakers-api/run/{uuid}/log/{kind}` ('' when
51
+ * none). Only the write client built by `bakers ui` carries it: JSON:API
52
+ * returns `log` and `error_log` empty.
53
+ */
54
+ runLog?(runId: string, kind: 'log' | 'error_log'): Promise<string>;
49
55
  }
50
56
  /** A JSON:API relationship linkage. */
51
57
  export interface JsonApiRelationship {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-bakers-ui",
3
- "version": "0.11.1-next.8",
3
+ "version": "0.12.0",
4
4
  "description": "bakers.build TUI: interactive terminal UI (dashboard, projects, tickets) as a dropsh `tui` renderer plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,11 +32,11 @@
32
32
  "zustand": "^5.0.15"
33
33
  },
34
34
  "peerDependencies": {
35
- "@bakers-build/core": "^0.11.1-next.8",
36
- "@bakers-build/message": "^0.11.1-next.8"
35
+ "@bakers-build/core": "^0.12.0",
36
+ "@bakers-build/message": "^0.12.0"
37
37
  },
38
38
  "bakersBuild": {
39
- "commit": "8807d1cd2569de7e4555aa0485037cec48ad1d1e",
40
- "channel": "next"
39
+ "commit": "4c0c7ffab0be833fb9cbb50b0784a949593f08e6",
40
+ "channel": "latest"
41
41
  }
42
42
  }