Skip to content

Commit c41ca07

Browse files
authored
refactor(ui): adopt @lit/task across remaining page surfaces (#115274)
* refactor(ui): adopt @lit/task across remaining page surfaces * refactor(ui): keep approval history pagination explicit * fix(ui): preserve task refresh ordering
1 parent 7df5834 commit c41ca07

27 files changed

Lines changed: 829 additions & 875 deletions

‎ui/src/components/app-sidebar-session-pr-indicators.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,27 @@ afterEach(() => {
2424
});
2525

2626
describe("SessionPullRequestIndicatorsController", () => {
27+
it("does not schedule a Task invalidation loop when no rows are eligible", async () => {
28+
vi.useFakeTimers();
29+
const host = new TestHost();
30+
const controller = new SessionPullRequestIndicatorsController(host, {
31+
getConnected: () => true,
32+
getRows: () => [],
33+
getSelectedAgentId: () => "main",
34+
getSnapshot: () =>
35+
({
36+
client: {} as GatewayBrowserClient,
37+
hello: { features: { methods: ["controlUi.sessionPullRequests"] } },
38+
}) as ApplicationGatewaySnapshot,
39+
});
40+
41+
controller.hostConnected();
42+
controller.hostUpdated();
43+
await vi.advanceTimersByTimeAsync(0);
44+
45+
expect(host.requestUpdate).not.toHaveBeenCalled();
46+
});
47+
2748
it("refreshes visible PR state and keeps the last value while rate limited", async () => {
2849
vi.useFakeTimers();
2950
const host = new TestHost();

‎ui/src/components/app-sidebar-session-pr-indicators.ts‎

Lines changed: 68 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { initialState, Task, TaskStatus } from "@lit/task";
12
import type { ReactiveController, ReactiveControllerHost } from "lit";
23
import type { GatewayBrowserClient } from "../api/gateway.ts";
34
import type { ApplicationGatewaySnapshot } from "../app/context.ts";
@@ -29,10 +30,8 @@ export class SessionPullRequestIndicatorsController implements ReactiveControlle
2930
private client: GatewayBrowserClient | null = null;
3031
private agentId: string | null = null;
3132
private connected = false;
32-
private epoch = 0;
3333
private eligibleSignature = "";
34-
private refresh: Promise<void> | null = null;
35-
private refreshAgain = false;
34+
private readonly refreshTask: Task;
3635
private refreshTimer: ReturnType<typeof globalThis.setTimeout> | null = null;
3736
private refreshScheduled = false;
3837

@@ -41,6 +40,62 @@ export class SessionPullRequestIndicatorsController implements ReactiveControlle
4140
private readonly options: SessionPullRequestIndicatorsOptions,
4241
) {
4342
host.addController(this);
43+
this.refreshTask = new Task(host, {
44+
autoRun: false,
45+
// Rows are represented by a deterministic primitive so Lit can shallow-compare args.
46+
args: () => [null as GatewayBrowserClient | null, "", ""] as const,
47+
task: async ([client, selectedAgentId, signature], { signal }) => {
48+
if (!client || !signature) {
49+
return initialState;
50+
}
51+
const eligibleRows = this.options
52+
.getRows()
53+
.filter((session) => !session.isChild && session.worktreeId);
54+
const currentSignature = JSON.stringify(
55+
eligibleRows.map((session) => [session.key, session.worktreeId]),
56+
);
57+
if (currentSignature !== signature) {
58+
return initialState;
59+
}
60+
const entries: Array<readonly [string, IndicatorEntry]> = [];
61+
for (const session of eligibleRows) {
62+
if (signal.aborted) {
63+
break;
64+
}
65+
try {
66+
const state = await fetchSessionPullRequestIndicatorState({
67+
client,
68+
pullRequestsAvailable: true,
69+
sessionKey: session.key,
70+
agentId: parseAgentSessionKey(session.key)?.agentId ?? selectedAgentId,
71+
});
72+
if (state !== null && session.worktreeId) {
73+
entries.push([session.key, { state, worktreeId: session.worktreeId }]);
74+
}
75+
} catch {
76+
// Optional metadata: preserve the last-known indicator and retry next poll.
77+
}
78+
}
79+
return { client, entries };
80+
},
81+
onComplete: ({ client, entries }) => {
82+
if (this.options.getSnapshot()?.client !== client) {
83+
return;
84+
}
85+
let changed = false;
86+
for (const [sessionKey, entry] of entries) {
87+
const current = this.states.get(sessionKey);
88+
if (current?.state !== entry.state || current.worktreeId !== entry.worktreeId) {
89+
this.states.set(sessionKey, entry);
90+
changed = true;
91+
}
92+
}
93+
if (changed) {
94+
this.host.requestUpdate();
95+
}
96+
this.scheduleRefreshTimer();
97+
},
98+
});
4499
}
45100

46101
hostConnected(): void {
@@ -95,9 +150,11 @@ export class SessionPullRequestIndicatorsController implements ReactiveControlle
95150
}
96151

97152
private reset(requestUpdate: boolean): void {
98-
this.epoch += 1;
153+
const shouldInvalidate = this.eligibleSignature !== "";
99154
this.eligibleSignature = "";
100-
this.refreshAgain = false;
155+
if (shouldInvalidate) {
156+
void this.refreshTask.run([null, "", ""]);
157+
}
101158
this.clearRefreshTimer();
102159
if (this.states.size === 0) {
103160
return;
@@ -140,102 +197,26 @@ export class SessionPullRequestIndicatorsController implements ReactiveControlle
140197
this.host.requestUpdate();
141198
}
142199
if (eligibleRows.length === 0) {
200+
const shouldInvalidate = this.eligibleSignature !== "";
143201
this.eligibleSignature = "";
144202
this.clearRefreshTimer();
203+
if (shouldInvalidate) {
204+
void this.refreshTask.run([null, "", ""]);
205+
}
145206
return;
146207
}
147208

148209
const signature = JSON.stringify(
149210
eligibleRows.map((session) => [session.key, session.worktreeId]),
150211
);
151212
if (!force && signature === this.eligibleSignature) {
152-
if (this.refresh === null) {
213+
if (this.refreshTask.status !== TaskStatus.PENDING) {
153214
this.scheduleRefreshTimer();
154215
}
155216
return;
156217
}
157218
this.eligibleSignature = signature;
158-
if (this.refresh) {
159-
this.refreshAgain = true;
160-
return;
161-
}
162-
163219
this.clearRefreshTimer();
164-
const epoch = this.epoch;
165-
const refresh = this.load({
166-
client: snapshot.client,
167-
selectedAgentId,
168-
eligibleRows,
169-
epoch,
170-
signature,
171-
});
172-
this.refresh = refresh;
173-
void refresh.finally(() => {
174-
if (this.refresh !== refresh) {
175-
return;
176-
}
177-
this.refresh = null;
178-
if (!this.connected) {
179-
return;
180-
}
181-
if (this.refreshAgain) {
182-
this.refreshAgain = false;
183-
this.refreshVisible(true);
184-
return;
185-
}
186-
if (epoch === this.epoch && signature === this.eligibleSignature) {
187-
this.scheduleRefreshTimer();
188-
}
189-
});
190-
}
191-
192-
private async load(params: {
193-
client: GatewayBrowserClient;
194-
selectedAgentId: string;
195-
eligibleRows: readonly SidebarRecentSession[];
196-
epoch: number;
197-
signature: string;
198-
}): Promise<void> {
199-
for (const session of params.eligibleRows) {
200-
if (!this.isCurrent(params)) {
201-
return;
202-
}
203-
try {
204-
const indicatorState = await fetchSessionPullRequestIndicatorState({
205-
client: params.client,
206-
pullRequestsAvailable: true,
207-
sessionKey: session.key,
208-
agentId: parseAgentSessionKey(session.key)?.agentId ?? params.selectedAgentId,
209-
});
210-
if (indicatorState === null || !this.isCurrent(params)) {
211-
continue;
212-
}
213-
const worktreeId = session.worktreeId;
214-
const current = this.states.get(session.key);
215-
if (
216-
worktreeId &&
217-
(current?.state !== indicatorState || current.worktreeId !== worktreeId)
218-
) {
219-
this.states.set(session.key, { state: indicatorState, worktreeId });
220-
this.host.requestUpdate();
221-
}
222-
} catch {
223-
// Optional metadata: preserve the last-known indicator and retry next poll.
224-
}
225-
}
226-
}
227-
228-
private isCurrent(params: {
229-
client: GatewayBrowserClient;
230-
epoch: number;
231-
signature: string;
232-
}): boolean {
233-
return (
234-
this.connected &&
235-
this.options.getConnected() &&
236-
params.epoch === this.epoch &&
237-
params.signature === this.eligibleSignature &&
238-
this.options.getSnapshot()?.client === params.client
239-
);
220+
void this.refreshTask.run([snapshot.client, selectedAgentId, signature]);
240221
}
241222
}

‎ui/src/components/github-link-hovercard.test.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,16 @@ describe("openclaw-github-link-hovercard-provider", () => {
9595
expect(card?.textContent).toContain("5m ago");
9696
expect(anchor.href).toBe(href);
9797
expect(anchor.getAttribute("aria-describedby")).toBe(card?.id);
98-
expect(request).toHaveBeenCalledWith("controlUi.githubPreview", {
99-
kind: "pull",
100-
number: 99816,
101-
owner: "openclaw",
102-
repo: "openclaw",
103-
});
98+
expect(request).toHaveBeenCalledWith(
99+
"controlUi.githubPreview",
100+
{
101+
kind: "pull",
102+
number: 99816,
103+
owner: "openclaw",
104+
repo: "openclaw",
105+
},
106+
{ signal: expect.any(AbortSignal) },
107+
);
104108

105109
leave(anchor);
106110
expect(document.querySelector(".github-link-hovercard")).toBeNull();

‎ui/src/components/github-link-hovercard.ts‎

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import { initialState, Task } from "@lit/task";
12
import { isRecord } from "@openclaw/normalization-core/record-coerce";
3+
import { ReactiveElement } from "lit";
24
import type { ControlUiGitHubPreview } from "../../../src/gateway/control-ui-contract.js";
35
import type { GatewayBrowserClient } from "../api/gateway.ts";
46
import { i18n, t } from "../i18n/index.ts";
@@ -293,7 +295,7 @@ function anchorFromEvent(event: Event): HTMLAnchorElement | null {
293295
return null;
294296
}
295297

296-
export class GitHubLinkHovercardProvider extends HTMLElement {
298+
export class GitHubLinkHovercardProvider extends ReactiveElement {
297299
client: GatewayBrowserClient | null = null;
298300

299301
private readonly cache = new Map<string, CacheEntry>();
@@ -306,8 +308,30 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
306308
private pointerInside = false;
307309
private renderedPreview: GitHubPreview | null = null;
308310
private renderedUnavailable = false;
309-
private requestVersion = 0;
310311
private stopI18n: (() => void) | null = null;
312+
private readonly previewTask = new Task(this, {
313+
autoRun: false,
314+
args: () => [this.activeTarget] as const,
315+
task: ([target], { signal }) => (target ? this.loadPreview(target, signal) : initialState),
316+
onComplete: (preview) => {
317+
const card = this.card;
318+
if (!card) {
319+
return;
320+
}
321+
this.renderedPreview = preview;
322+
renderPreview(card, preview);
323+
this.positionCard();
324+
},
325+
onError: () => {
326+
const card = this.card;
327+
if (!card) {
328+
return;
329+
}
330+
this.renderedUnavailable = true;
331+
renderUnavailable(card);
332+
this.positionCard();
333+
},
334+
});
311335
private readonly activeAnchorObserver = new MutationObserver(() => {
312336
const anchor = this.activeAnchor;
313337
// The card is portaled outside the routed tree, whose replacement can remove
@@ -317,7 +341,12 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
317341
}
318342
});
319343

320-
connectedCallback(): void {
344+
protected override createRenderRoot(): HTMLElement | DocumentFragment {
345+
return this;
346+
}
347+
348+
override connectedCallback(): void {
349+
super.connectedCallback();
321350
this.style.display = "contents";
322351
this.addEventListener("pointerover", this.handlePointerOver);
323352
this.addEventListener("pointerout", this.handlePointerOut);
@@ -328,7 +357,7 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
328357
this.stopI18n ??= i18n.subscribe(this.handleLocaleChange);
329358
}
330359

331-
disconnectedCallback(): void {
360+
override disconnectedCallback(): void {
332361
this.removeEventListener("pointerover", this.handlePointerOver);
333362
this.removeEventListener("pointerout", this.handlePointerOut);
334363
this.removeEventListener("focusin", this.handleFocusIn);
@@ -338,6 +367,7 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
338367
this.stopI18n?.();
339368
this.stopI18n = null;
340369
this.close();
370+
super.disconnectedCallback();
341371
}
342372

343373
private readonly handleLocaleChange = () => {
@@ -427,15 +457,14 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
427457
this.activeAnchorObserver.observe(this, { childList: true, subtree: true });
428458
this.openTimer = window.setTimeout(() => {
429459
this.openTimer = null;
430-
void this.show(anchor, target);
460+
this.show(anchor, target);
431461
}, delay);
432462
}
433463

434-
private async show(anchor: HTMLAnchorElement, target: GitHubLinkTarget): Promise<void> {
464+
private show(anchor: HTMLAnchorElement, target: GitHubLinkTarget): void {
435465
if (this.activeAnchor !== anchor || this.activeTarget?.href !== target.href) {
436466
return;
437467
}
438-
const version = ++this.requestVersion;
439468
const card = document.createElement("div");
440469
nextHovercardId += 1;
441470
card.id = `openclaw-github-hovercard-${nextHovercardId}`;
@@ -455,24 +484,10 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
455484
this.listenForViewportChanges();
456485
this.positionCard();
457486

458-
try {
459-
const preview = await this.loadPreview(target);
460-
if (version !== this.requestVersion || card !== this.card) {
461-
return;
462-
}
463-
this.renderedPreview = preview;
464-
renderPreview(card, preview);
465-
} catch {
466-
if (version !== this.requestVersion || card !== this.card) {
467-
return;
468-
}
469-
this.renderedUnavailable = true;
470-
renderUnavailable(card);
471-
}
472-
this.positionCard();
487+
void this.previewTask.run([target]);
473488
}
474489

475-
private loadPreview(target: GitHubLinkTarget): Promise<GitHubPreview> {
490+
private loadPreview(target: GitHubLinkTarget, signal: AbortSignal): Promise<GitHubPreview> {
476491
const key = `${target.kind}:${target.owner.toLowerCase()}/${target.repo.toLowerCase()}#${target.number}`;
477492
const now = Date.now();
478493
const cached = this.cache.get(key);
@@ -497,6 +512,7 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
497512
owner: target.owner,
498513
repo: target.repo,
499514
},
515+
{ signal },
500516
);
501517
return parsePreviewResponse(target, response);
502518
};
@@ -527,7 +543,7 @@ export class GitHubLinkHovercardProvider extends HTMLElement {
527543
this.openTimer = null;
528544
}
529545
this.activeAnchorObserver.disconnect();
530-
this.requestVersion += 1;
546+
void this.previewTask.run([null]);
531547
if (this.activeAnchor) {
532548
if (this.describedBy === null) {
533549
this.activeAnchor.removeAttribute("aria-describedby");

0 commit comments

Comments
 (0)