From 0d4de0295ad6cc859bcbfab2c05362de1c8b8a4c Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Mon, 16 Nov 2026 16:15:21 +0100 Subject: [PATCH] fix(dashboard): start page, shortcut card and favourites, review findings after 0.47.0 - A start or stop the hub runs now ticks the start page's `summary` event: `Phases` tells every change, and one task per event stream derives `attention` and `summary` from one summary per change of the board, the stack list or the phases (it was computed twice per change and client, and never on a phase change). - A shortcut card guards with the rule `serviceUrl` takes its link by: a portless service whose printed link is no web address has nothing to open, not a button to `http://localhost:null`. - `loadOpeners` shares the request under way: the start page's tiles asked for the programs once each. - A tile offers its favourite programs only while the hub answers, and a favourite beside a path closes the path's menu. Bug-Class: stale-snapshot Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + crates/devstack-hub/src/lib.rs | 216 +++++++++++++++++-------- crates/devstack-hub/src/summary.rs | 27 ++-- ui/src/components/FavoriteOpeners.vue | 3 + ui/src/components/PathMenu.test.ts | 60 +++++++ ui/src/components/PathMenu.vue | 2 +- ui/src/components/ShortcutCard.test.ts | 9 ++ ui/src/components/ShortcutCard.vue | 9 +- ui/src/components/StackTile.vue | 3 +- ui/src/stores/hub.ts | 24 ++- ui/src/stores/stores.test.ts | 5 + ui/src/views/HomeView.test.ts | 12 ++ 12 files changed, 288 insertions(+), 90 deletions(-) create mode 100644 ui/src/components/PathMenu.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1aa7e9ef..9f5e69a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,14 @@ and listed with their assets on the that enrolled in between found no node in that list and was given back, and the lane waiting for it failed with "the machine made for the lane was given back". +- **The start page's tiles show a start or stop from another tab.** A + start or stop the hub runs now updates the `summary` event, so every + tab's tile says starting or stopping, not only the one that asked. +- **A shortcut card whose service prints a link that is no web address** + and has no port says there is nothing to open, instead of a button to + `http://localhost:null`. +- **The favourite programs' buttons** stay off a tile while the hub is + not reachable, and close the path's menu when they open it. ## [0.47.0] - 2026-11-13 diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 8fa3cf0f..654811f3 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -156,7 +156,70 @@ enum Phase { /// Starts and stops under way, by stack id: a start waits for a stop, and /// a request for a stack in between is told it is starting or stopping. -type Phases = Arc>>; +/// Every change ticks [`Phases::subscribe`]: the start page's `summary` +/// event shows a start or stop the hub runs in every tab, not only in the +/// one that asked for it. +#[derive(Clone)] +struct Phases { + map: Arc>>, + changed: Arc>, +} + +impl Default for Phases { + fn default() -> Self { + Self { + map: Arc::default(), + changed: Arc::new(watch::channel(0).0), + } + } +} + +impl Phases { + fn get(&self, id: &str) -> Option { + self.map.lock().unwrap().get(id).copied() + } + + fn all(&self) -> HashMap { + self.map.lock().unwrap().clone() + } + + fn set(&self, id: &str, phase: Phase) { + self.map.lock().unwrap().insert(id.to_string(), phase); + self.tick(); + } + + /// Set `Stopping` unless a stop is under way already: `false` then. + fn begin_stop(&self, id: &str) -> bool { + { + let mut p = self.map.lock().unwrap(); + if p.get(id) == Some(&Phase::Stopping) { + return false; + } + p.insert(id.to_string(), Phase::Stopping); + } + self.tick(); + true + } + + /// Forget `phase` of stack `id`, unless another one took its place. + fn end(&self, id: &str, phase: Phase) { + let ended = { + let mut p = self.map.lock().unwrap(); + p.get(id) == Some(&phase) && p.remove(id).is_some() + }; + if ended { + self.tick(); + } + } + + fn tick(&self) { + self.changed.send_modify(|n| *n = n.wrapping_add(1)); + } + + fn subscribe(&self) -> watch::Receiver { + self.changed.subscribe() + } +} #[derive(Clone)] struct AppState { @@ -1623,41 +1686,7 @@ fn hub_events(s: &AppState) -> impl tokio_stream::Stream 0) .map(|at| serde_json::json!({ "type": "activity", "at": at })); - // What needs attention (ADR-0097): again when a stream's glance or the - // stack list (a start failed, a stack stopped) changed, sent only when - // the items did. - let attention = { - let s = s.clone(); - let mut last: Option> = None; - tokio_stream::wrappers::WatchStream::new(s.board.subscribe()) - .map(|_| ()) - .merge(tokio_stream::wrappers::WatchStream::new(s.stacks.clone()).map(|_| ())) - .filter_map(move |()| { - let now = summary::attention(&s); - (last.as_ref() != Some(&now)).then(|| { - last = Some(now.clone()); - serde_json::json!({ "type": "attention", "items": now }) - }) - }) - }; - // Every stack's figures for the start page: on the same changes as - // `attention`, sent only when they changed. A start or stop the hub runs - // moves neither the board nor the list until the daemon comes or goes; - // the page that asked for it shows that on its own. - let glances = { - let s = s.clone(); - let mut last: Option> = None; - tokio_stream::wrappers::WatchStream::new(s.board.subscribe()) - .map(|_| ()) - .merge(tokio_stream::wrappers::WatchStream::new(s.stacks.clone()).map(|_| ())) - .filter_map(move |()| { - let now = summary::glances(&s); - (last.as_ref() != Some(&now)).then(|| { - last = Some(now.clone()); - serde_json::json!({ "type": "summary", "stacks": now }) - }) - }) - }; + let derived = summary_events(s); // A dashboard that fell behind misses a toast, nothing it shows. let notices = tokio_stream::wrappers::BroadcastStream::new(notice::subscribe()).filter_map(|n| n.ok()); @@ -1670,11 +1699,57 @@ fn hub_events(s: &AppState) -> impl tokio_stream::Stream tokio_stream::wrappers::ReceiverStream { + let (tx, rx) = tokio::sync::mpsc::channel(8); + let s = s.clone(); + tokio::spawn(async move { + let mut board = s.board.subscribe(); + let mut stacks = s.stacks.clone(); + let mut phases = s.phases.subscribe(); + let mut attention: Option> = None; + let mut glances: Option> = None; + loop { + let sum = summary::summary(&s); + let now = summary::attention(&sum); + if attention.as_ref() != Some(&now) { + let v = serde_json::json!({ "type": "attention", "items": now }); + if tx.send(v).await.is_err() { + return; + } + attention = Some(now); + } + let now = summary::glances(&sum); + if glances.as_ref() != Some(&now) { + let v = serde_json::json!({ "type": "summary", "stacks": now }); + if tx.send(v).await.is_err() { + return; + } + glances = Some(now); + } + let changed = tokio::select! { + r = board.changed() => r.is_ok(), + r = stacks.changed() => r.is_ok(), + r = phases.changed() => r.is_ok(), + () = tx.closed() => false, + }; + if !changed { + return; + } + } + }); + tokio_stream::wrappers::ReceiverStream::new(rx) +} + fn entry(s: &AppState, id: &str) -> Option { s.stacks .borrow() @@ -2651,13 +2726,13 @@ async fn stack_up( return err(StatusCode::INTERNAL_SERVER_ERROR, "cannot find devstack"); }; s.start_errors.lock().unwrap().remove(&id); - let stopping = s.phases.lock().unwrap().get(&id) == Some(&Phase::Stopping); + let stopping = s.phases.get(&id) == Some(Phase::Stopping); if !stopping { - s.phases.lock().unwrap().insert(id.clone(), Phase::Starting); + s.phases.set(&id, Phase::Starting); return match start_up(&s, &id, &exe, &e, shift.as_deref(), &profile) { Ok(()) => StatusCode::ACCEPTED.into_response(), Err(msg) => { - end_phase(&s.phases, &id, Phase::Starting); + s.phases.end(&id, Phase::Starting); err(StatusCode::INTERNAL_SERVER_ERROR, msg) } }; @@ -2668,14 +2743,12 @@ async fn stack_up( // old one is gone. tokio::spawn(async move { let t0 = Instant::now(); - while s.phases.lock().unwrap().get(&id) == Some(&Phase::Stopping) - && t0.elapsed() < STOP_WAIT - { + while s.phases.get(&id) == Some(Phase::Stopping) && t0.elapsed() < STOP_WAIT { tokio::time::sleep(Duration::from_millis(200)).await; } - s.phases.lock().unwrap().insert(id.clone(), Phase::Starting); + s.phases.set(&id, Phase::Starting); if let Err(msg) = start_up(&s, &id, &exe, &e, shift.as_deref(), &profile) { - end_phase(&s.phases, &id, Phase::Starting); + s.phases.end(&id, Phase::Starting); s.start_errors.lock().unwrap().insert(id, msg); } }); @@ -2686,14 +2759,6 @@ async fn stack_up( /// to exit (the daemon gives its services 90 s, ADR-0009). const STOP_WAIT: Duration = Duration::from_secs(120); -/// Forget `phase` of stack `id`, unless another one took its place. -fn end_phase(phases: &Phases, id: &str, phase: Phase) { - let mut p = phases.lock().unwrap(); - if p.get(id) == Some(&phase) { - p.remove(id); - } -} - /// Run `devstack up` for stack `e` in the background, with `--shift` when /// one is asked (ADR-0082); the stack is `Starting` until it ends. fn start_up( @@ -2730,7 +2795,7 @@ fn start_up( let id = id.to_string(); std::thread::spawn(move || { let ok = child.wait().is_ok_and(|st| st.success()); - end_phase(&phases, &id, Phase::Starting); + phases.end(&id, Phase::Starting); if ok { return; } @@ -2814,12 +2879,8 @@ async fn stack_down( } return err(StatusCode::SERVICE_UNAVAILABLE, "stack not running"); }; - { - let mut phases = s.phases.lock().unwrap(); - if phases.get(&id) == Some(&Phase::Stopping) { - return StatusCode::ACCEPTED.into_response(); // under way already - } - phases.insert(id.clone(), Phase::Stopping); + if !s.phases.begin_stop(&id) { + return StatusCode::ACCEPTED.into_response(); // under way already } let (token, phases, port) = (s.token.clone(), s.phases.clone(), daemon.port); let state = e.repo.join(".devstack"); @@ -2872,7 +2933,7 @@ async fn stack_down( { tokio::time::sleep(Duration::from_millis(200)).await; } - end_phase(&phases, &id, Phase::Stopping); + phases.end(&id, Phase::Stopping); }); StatusCode::ACCEPTED.into_response() } @@ -3467,7 +3528,7 @@ fn daemon_now(s: &AppState, id: &str) -> DaemonNow { let Some(e) = entry(s, id) else { return DaemonNow::Absent { starting: false }; }; - let phase = s.phases.lock().unwrap().get(id).copied(); + let phase = s.phases.get(id); match daemon_in(&e.repo.join(".devstack")) { DaemonNow::Absent { .. } if phase == Some(Phase::Stopping) => DaemonNow::Stopping, DaemonNow::Absent { .. } => DaemonNow::Absent { @@ -4544,3 +4605,32 @@ mod shift_tests { assert!(profile_args(br#"{"profile":"--run"}"#).is_err()); } } + +#[cfg(test)] +mod phases_tests { + use super::{Phase, Phases}; + + /// A start or stop the hub runs is told to every event stream (the + /// start page's tiles in every tab), and only a real change is. + #[test] + fn every_change_of_a_phase_is_told_and_nothing_else() { + let p = Phases::default(); + let mut rx = p.subscribe(); + assert!(!rx.has_changed().unwrap()); + p.set("shop", Phase::Starting); + assert!(rx.has_changed().unwrap(), "a start"); + rx.borrow_and_update(); + // Another phase's end leaves it: nothing to tell. + p.end("shop", Phase::Stopping); + assert!(!rx.has_changed().unwrap()); + p.end("shop", Phase::Starting); + assert!(rx.has_changed().unwrap(), "its end"); + rx.borrow_and_update(); + assert!(p.begin_stop("shop")); + assert!(rx.has_changed().unwrap(), "a stop"); + rx.borrow_and_update(); + assert!(!p.begin_stop("shop"), "under way already"); + assert!(!rx.has_changed().unwrap()); + assert_eq!(p.get("shop"), Some(Phase::Stopping)); + } +} diff --git a/crates/devstack-hub/src/summary.rs b/crates/devstack-hub/src/summary.rs index 4a809369..dec67f71 100644 --- a/crates/devstack-hub/src/summary.rs +++ b/crates/devstack-hub/src/summary.rs @@ -225,7 +225,7 @@ fn overall(stacks: &[StackSummary]) -> &'static str { pub(crate) fn summary(s: &AppState) -> Summary { let entries = s.stacks.borrow().clone(); - let phases = s.phases.lock().unwrap().clone(); + let phases = s.phases.all(); let stacks: Vec = entries .iter() .map(|e| stack(e, phases.get(&e.id).copied(), &s.board.of(&e.id))) @@ -250,15 +250,15 @@ pub(crate) struct Attention { pub item: Item, } -/// What needs attention in every stack, for `/hub/events` (ADR-0097). -pub(crate) fn attention(s: &AppState) -> Vec { - summary(s) - .stacks - .into_iter() +/// What needs attention in every stack of `sum`, for `/hub/events` +/// (ADR-0097). +pub(crate) fn attention(sum: &Summary) -> Vec { + sum.stacks + .iter() .flat_map(|st| { - st.attention.into_iter().map(move |item| Attention { + st.attention.iter().map(move |item| Attention { stack: st.id.clone(), - item, + item: item.clone(), }) }) .collect() @@ -276,13 +276,12 @@ pub(crate) struct StackGlance { pub lanes: usize, } -/// Every stack's figures, for `/hub/events`. -pub(crate) fn glances(s: &AppState) -> Vec { - summary(s) - .stacks - .into_iter() +/// Every stack's figures in `sum`, for `/hub/events`. +pub(crate) fn glances(sum: &Summary) -> Vec { + sum.stacks + .iter() .map(|st| StackGlance { - id: st.id, + id: st.id.clone(), state: st.state, ready: st.ready, total: st.total, diff --git a/ui/src/components/FavoriteOpeners.vue b/ui/src/components/FavoriteOpeners.vue index eabefaa8..cb680ede 100644 --- a/ui/src/components/FavoriteOpeners.vue +++ b/ui/src/components/FavoriteOpeners.vue @@ -10,6 +10,8 @@ import { useHub } from '@/stores/hub'; import Icon from './icons/Icon.vue'; const props = defineProps<{ stackId: string | null; path: string }>(); +/** `opened`: a program was asked to open the path (PathMenu closes its menu). */ +const emit = defineEmits<{ opened: [] }>(); const hub = useHub(); const openerPrefs = useOpenerPrefs(); @@ -19,6 +21,7 @@ watchEffect(() => { }); function openWith(o: Opener) { + emit('opened'); if (props.stackId) void hub.openWith(props.stackId, props.path, o); } diff --git a/ui/src/components/PathMenu.test.ts b/ui/src/components/PathMenu.test.ts new file mode 100644 index 00000000..f922c9f9 --- /dev/null +++ b/ui/src/components/PathMenu.test.ts @@ -0,0 +1,60 @@ +// A tree's path with its menu: a favourite program's button beside it opens +// the path and closes the menu, as the menu's own programs do. +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createApp, h, nextTick } from 'vue'; +import { createPinia, setActivePinia } from 'pinia'; +import { FakeTransport, ok } from '@/test/fake'; + +const t = vi.hoisted(() => ({ current: null as FakeTransport | null })); + +vi.mock('@/api', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + api: () => { + if (!t.current) throw new Error('no fake transport'); + return t.current; + }, + }; +}); + +const { useOpenerPrefs } = await import('@/lib/openers'); +const PathMenu = (await import('./PathMenu.vue')).default; + +let fake: FakeTransport; + +beforeEach(() => { + localStorage.clear(); + setActivePinia(createPinia()); + fake = new FakeTransport(); + t.current = fake; + fake.on('/hub/openers', ok([{ id: 'vscode', label: 'VS Code', kind: 'editor' }])); + fake.on('/hub/open', { status: 204, ok: true, body: null }); + useOpenerPrefs().save({ order: [], hidden: [], favorites: ['vscode'] }); +}); + +async function settle() { + for (let i = 0; i < 5; i++) { + await new Promise((r) => setTimeout(r, 0)); + await nextTick(); + } +} + +describe('PathMenu', () => { + it('closes its menu when a favourite program opens the path', async () => { + const el = document.createElement('div'); + document.body.appendChild(el); + const app = createApp(() => h(PathMenu, { path: '/src/shop', stackId: 'ab12', canOpen: true })); + app.use(createPinia()); + app.mount(el); + await settle(); + el.querySelector('[data-testid="path-menu"]')!.click(); + await settle(); + expect(el.querySelector('[data-testid="path-menu-list"]')).not.toBeNull(); + el.querySelector('[data-testid="path-favorite"]')!.click(); + await settle(); + expect(fake.requests.find((r) => r.path === '/hub/open')?.body).toEqual({ stack: 'ab12', path: '/src/shop', with: 'vscode' }); + expect(el.querySelector('[data-testid="path-menu-list"]')).toBeNull(); + app.unmount(); + }); +}); diff --git a/ui/src/components/PathMenu.vue b/ui/src/components/PathMenu.vue index 677716c8..c4466206 100644 --- a/ui/src/components/PathMenu.vue +++ b/ui/src/components/PathMenu.vue @@ -100,7 +100,7 @@ function openWith(o: Opener) { - + diff --git a/ui/src/components/ShortcutCard.test.ts b/ui/src/components/ShortcutCard.test.ts index a7dd36a3..6aa5eee0 100644 --- a/ui/src/components/ShortcutCard.test.ts +++ b/ui/src/components/ShortcutCard.test.ts @@ -57,4 +57,13 @@ describe('ShortcutCard', () => { expect(el.textContent).toContain('No port or link to open'); app.unmount(); }); + + it('takes a link that is no web address for no link at all', async () => { + // Printed by the service, but not http(s): nothing a browser opens, and + // no port to fall back to (never `http://localhost:null`). + const { el, app } = await mountCard(service({ port: null, url: null, link: 'vscode://file/x' })); + expect(el.querySelector('[data-testid="shortcut-open"]')).toBeNull(); + expect(el.textContent).toContain('No port or link to open'); + app.unmount(); + }); }); diff --git a/ui/src/components/ShortcutCard.vue b/ui/src/components/ShortcutCard.vue index f59fdb17..1da4c017 100644 --- a/ui/src/components/ShortcutCard.vue +++ b/ui/src/components/ShortcutCard.vue @@ -1,7 +1,7 @@ diff --git a/ui/src/components/StackTile.vue b/ui/src/components/StackTile.vue index 55802c15..83bfd291 100644 --- a/ui/src/components/StackTile.vue +++ b/ui/src/components/StackTile.vue @@ -133,7 +133,8 @@ const moreItems = computed(() => items.value.length - shownItems.value.length);
- + +
diff --git a/ui/src/stores/hub.ts b/ui/src/stores/hub.ts index 20463c38..7f6c18d8 100644 --- a/ui/src/stores/hub.ts +++ b/ui/src/stores/hub.ts @@ -259,14 +259,22 @@ export const useHub = defineStore('hub', () => { } /** Ask the hub once what it can open folders with; an older hub knows nothing. */ - async function loadOpeners() { - if (openers.value) return; - try { - const res = await api().request('GET', paths.openers); - openers.value = res.ok && Array.isArray(res.body) ? res.body : []; - } catch { - openers.value = null; - } + // One request for every caller that asks while it is under way: the start + // page's tiles all ask at once. + let openersLoading: Promise | null = null; + function loadOpeners(): Promise { + if (openers.value) return Promise.resolve(); + openersLoading ??= (async () => { + try { + const res = await api().request('GET', paths.openers); + openers.value = res.ok && Array.isArray(res.body) ? res.body : []; + } catch { + openers.value = null; + } finally { + openersLoading = null; + } + })(); + return openersLoading; } /** Open one of a stack's trees with a program the hub found. */ diff --git a/ui/src/stores/stores.test.ts b/ui/src/stores/stores.test.ts index da995afe..86f35599 100644 --- a/ui/src/stores/stores.test.ts +++ b/ui/src/stores/stores.test.ts @@ -107,6 +107,11 @@ describe('hub store', () => { await hub.loadOpeners(); await hub.loadOpeners(); expect(fake.requests.filter((r) => r.path === '/hub/openers')).toHaveLength(1); + // Asked by every tile of the start page at once: still one request. + setActivePinia(createPinia()); + const fresh = useHub(); + await Promise.all([fresh.loadOpeners(), fresh.loadOpeners(), fresh.loadOpeners()]); + expect(fake.requests.filter((r) => r.path === '/hub/openers')).toHaveLength(2); await hub.openWith('shop', '/src/shop', hub.openers![0]); expect(fake.requests.find((r) => r.path === '/hub/open')?.body).toEqual({ stack: 'shop', path: '/src/shop', with: 'vscode' }); }); diff --git a/ui/src/views/HomeView.test.ts b/ui/src/views/HomeView.test.ts index 31052177..181edd31 100644 --- a/ui/src/views/HomeView.test.ts +++ b/ui/src/views/HomeView.test.ts @@ -140,6 +140,18 @@ describe('the start page', () => { unmount(); }); + it('offers no favourite program while the hub is away', async () => { + useOpenerPrefs().save({ order: [], hidden: [], favorites: ['vscode'] }); + const { el, events, unmount } = await mounted([shop]); + await settle(); + expect(tile(el, 'ab12').querySelector('[data-testid="path-favorite"]')).not.toBeNull(); + // The tiles stay from the last list; a program could not be opened. + events.onState?.('error'); + await settle(); + expect(tile(el, 'ab12').querySelector('[data-testid="path-favorite"]')).toBeNull(); + unmount(); + }); + it('marks a favourite from its tile, which moves it first', async () => { const { el, unmount } = await mounted([shop, crm]); expect(names(el)).toEqual(['crm', 'shop']);