Skip to content

Commit 8715e87

Browse files
authored
fix(ui): preserve offline drafts and resume canceled queue edits (#133628)
* fix(ui): preserve offline drafts and resume canceled queue edits Unify queue location and captured admission ownership, consolidate draft revision/lineage bookkeeping, and remove obsolete projection adapters. Reserve composer snapshots before synchronous publication and reconcile native persistence using the retained authenticated offline owner. Wake the existing drain after successful queued-edit Cancel without mutating the stored row. Preserve explicit startup routes and own file-icon styles statically so their first offline use cannot cache a rejected load. Fixes #133555 Fixes #133603 Validated owner and native-browser regressions, integration checks, compilers, complete builds, scoped independent review, and real isolated Gateway/provider/browser flows including Cancel and Save. Production code shrinks; persistence formats, CAS, uncertainty and Blob custody stay unchanged. * test(ui): scope cross-agent outbox proof to the active pane Retained hidden panes can contain the same conversation output. Keep strict visible-owner assertions and require one canonical reply and one send instead of querying every cached pane in the page. Keep fixture session and run identities tied to the agent, not its busy flag, and verify that recovery history queries retain the Work owner. Reproduced both page-wide locator failures before correction. The original 26-file selection and fitting siblings pass; timeouts, runtime behavior, and deliberate raw-event fault injection remain unchanged.
1 parent 04295eb commit 8715e87

80 files changed

Lines changed: 1588 additions & 1045 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎ui/src/app/app-host.gateway-lineage.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
/* @vitest-environment jsdom */
2-
31
import { render } from "lit";
2+
/* @vitest-environment jsdom */
43
import { afterEach, describe, expect, it, vi } from "vitest";
54
import type {
65
GatewayBrowserClient,
76
GatewayBrowserClientOptions,
87
GatewayHelloOk,
98
} from "../api/gateway.ts";
109
import type { AgentsListResult } from "../api/types.ts";
10+
import { captureChatOutboxAdmission } from "../lib/chat/outbox-store.ts";
1111
import { createSessionCapability } from "../lib/sessions/index.ts";
1212
import { sessionsResult } from "../lib/sessions/session-capability.test-support.ts";
1313
import {
@@ -194,7 +194,7 @@ describe("Control UI Gateway target lineage", () => {
194194
const composer = document.createElement("div");
195195
try {
196196
expect(
197-
admitQueuedMessageForSession(state, sessionKey, {
197+
admitQueuedMessageForSession(state, captureChatOutboxAdmission(state, sessionKey), {
198198
id: "owner-row",
199199
text: "Original queued message",
200200
createdAt: 1000,

‎ui/src/app/app-shell-gateway.ts‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,20 +29,10 @@ export type StoredOutboxScopeHost = {
2929
hello?: { snapshot?: unknown } | null;
3030
};
3131

32-
export type OutboxStoreRuntime = {
33-
summarizeStoredChatOutboxes: (state: StoredOutboxScopeHost) => {
34-
countsByScope: ReadonlyMap<string, number>;
35-
attentionCountsByScope: ReadonlyMap<string, number>;
36-
draftScopes: ReadonlySet<string>;
37-
total: number;
38-
};
39-
resolveStoredChatOutboxScope: (
40-
state: StoredOutboxScopeHost,
41-
sessionKey: string,
42-
) => { sessionKey: string; agentId?: string };
43-
storedChatOutboxScopeKey: (scope: { sessionKey: string; agentId?: string }) => string;
44-
subscribeStoredChatOutboxChanges: (listener: () => void) => () => void;
45-
};
32+
export type OutboxStoreRuntime = Pick<
33+
typeof import("../lib/chat/outbox-store-projection.ts"),
34+
"summarizeStoredChatOutboxes" | "subscribeStoredChatOutboxChanges"
35+
>;
4636

4737
export interface ShellGatewayHost {
4838
readonly context: ApplicationContext<RouteId> | undefined;

‎ui/src/app/app-shell-view.ts‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -209,24 +209,7 @@ export function renderApplicationShell(host: ShellViewHost) {
209209
const canHoldUpdate =
210210
canUpdate && canCallGatewayMethod(gatewaySnapshot, "update.hold", "operator.admin");
211211
const outboxScopeHost = host.storedOutboxScopeHost(context);
212-
const outboxStoreRuntime = host.outboxStoreRuntime;
213-
const storedOutboxes = outboxStoreRuntime?.summarizeStoredChatOutboxes(outboxScopeHost) ?? null;
214-
const outboxAttentionCountForSession = outboxStoreRuntime
215-
? (sessionKey: string) => {
216-
const scope = outboxStoreRuntime.resolveStoredChatOutboxScope(outboxScopeHost, sessionKey);
217-
const scopeKey = outboxStoreRuntime.storedChatOutboxScopeKey(scope);
218-
return storedOutboxes?.attentionCountsByScope.get(scopeKey) ?? 0;
219-
}
220-
: () => 0;
221-
const hasSessionDraft = outboxStoreRuntime
222-
? (sessionKey: string) => {
223-
const scope = outboxStoreRuntime.resolveStoredChatOutboxScope(outboxScopeHost, sessionKey);
224-
return (
225-
storedOutboxes?.draftScopes.has(outboxStoreRuntime.storedChatOutboxScopeKey(scope)) ===
226-
true
227-
);
228-
}
229-
: EMPTY_SESSION_HAS_DRAFT;
212+
const storedOutboxes = host.outboxStoreRuntime?.summarizeStoredChatOutboxes(outboxScopeHost);
230213
const navigationSnapshot = context.navigation.snapshot;
231214
const overlaySnapshot = context.overlays.snapshot;
232215
// The install keeps running after `update.run` answers, so the reconciliation
@@ -349,8 +332,8 @@ export function renderApplicationShell(host: ShellViewHost) {
349332
restartPending: gatewaySnapshot.restartPending === true,
350333
queuedOutboxCount: storedOutboxes?.total ?? 0,
351334
lastError: gatewaySnapshot.lastError,
352-
outboxAttentionCountForSession,
353-
hasSessionDraft,
335+
outboxAttentionCountForSession: storedOutboxes?.attentionCountForSession ?? (() => 0),
336+
hasSessionDraft: storedOutboxes?.hasSessionDraft ?? EMPTY_SESSION_HAS_DRAFT,
354337
terminalAvailable,
355338
catalogOpenTarget: normalizeCatalogOpenTarget(uiSettings.catalogOpenTarget),
356339
canPairDevice: gatewayConnected && (operatorAccess.canAdmin || operatorAccess.canPair),

‎ui/src/app/bootstrap-location.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
resolveUiConfiguredMainKey,
1111
resolveUiDefaultAgentId,
1212
} from "../lib/sessions/session-key.ts";
13-
import { isDefaultChatLanding } from "../pages/model-setup/first-run.ts";
1413
import type { ApplicationGateway } from "./context.ts";
1514
import { waitForGatewayClient } from "./gateway-readiness.ts";
1615

@@ -19,6 +18,16 @@ type ReleasedSessionQuery = {
1918
sessionKey: string;
2019
};
2120

21+
// Saved selection only fills an implicit landing. Agent paths remain explicit,
22+
// even when first-run setup is eligible to run on that same path.
23+
function isPersistedSessionLanding(location: RouteLocation, basePath: string): boolean {
24+
return (
25+
!new URLSearchParams(location.search + "&" + location.hash.slice(1)).has("session") &&
26+
(routeIdFromPath(location.pathname, basePath) === null ||
27+
/^\/chat\/?$/u.test(location.pathname.slice(basePath.length)))
28+
);
29+
}
30+
2231
function resolvePersistedAgentId(
2332
selectedAgentId: string | null | undefined,
2433
agentsList: AgentsListResult | null,
@@ -110,7 +119,7 @@ export function normalizeInitialApplicationLocation(
110119
fallbackAgentId: string,
111120
mainKey?: string | null,
112121
) {
113-
if (!isDefaultChatLanding(location, basePath, routeIdFromPath) || !sessionKey.trim()) {
122+
if (!isPersistedSessionLanding(location, basePath) || !sessionKey.trim()) {
114123
return location;
115124
}
116125
const agentId = parseAgentSessionKey(sessionKey)?.agentId ?? fallbackAgentId.trim();
@@ -134,7 +143,7 @@ export async function resolveInitialApplicationLocation(params: {
134143
if (releasedLocation) {
135144
return releasedLocation;
136145
}
137-
if (!isDefaultChatLanding(params.location, params.basePath, routeIdFromPath)) {
146+
if (!isPersistedSessionLanding(params.location, params.basePath)) {
138147
return params.location;
139148
}
140149
// Explicit routes must start immediately; only the implicit session landing

‎ui/src/app/bootstrap.agent-selection.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,61 @@
11
import { gatewayOriginScope } from "@openclaw/gateway-client/browser";
2+
import { buildControlUiSessionPath } from "@openclaw/session-url-contract";
3+
import type { RouteLocation } from "@openclaw/uirouter";
24
import { expect, it, vi } from "vitest";
35
import type { RouteId } from "../app-routes.ts";
6+
import { startModelSetupFirstRunRedirectAfterLocation } from "../pages/model-setup/first-run.ts";
47
import { resolveInitialApplicationLocation } from "./bootstrap-location.ts";
58
import { bootstrapApplication } from "./bootstrap.ts";
69
import type { ApplicationContext } from "./context.ts";
710
import { loadGatewaySessionSelection, loadSettings, saveSettings } from "./settings.ts";
811

12+
it.each([
13+
{ agentId: "main", savedAgentId: "work", basePath: "", suffix: "" },
14+
{ agentId: "work", savedAgentId: "main", basePath: "", suffix: "" },
15+
{ agentId: "main", savedAgentId: "work", basePath: "/openclaw", suffix: "/" },
16+
{ agentId: "work", savedAgentId: "main", basePath: "/openclaw", suffix: "/" },
17+
])(
18+
"keeps cold explicit $agentId over saved $savedAgentId at $basePath (suffix '$suffix')",
19+
async ({ agentId, savedAgentId, basePath, suffix }) => {
20+
const pathname = buildControlUiSessionPath({
21+
namespace: "chat",
22+
sessionKey: `agent:${agentId}:main`,
23+
exactKey: true,
24+
basePath,
25+
});
26+
expect(pathname).toBe(`${basePath}/chat/${agentId}`);
27+
const requested = { pathname: `${pathname}${suffix}`, search: "?draft=keep", hash: "#pane" };
28+
let currentLocation: RouteLocation = requested;
29+
const replace = vi.fn((location: RouteLocation) => {
30+
currentLocation = location;
31+
});
32+
const gateway = {
33+
snapshot: { phase: "connecting", client: null, hello: null },
34+
subscribe: vi.fn(() => () => undefined),
35+
} as unknown as ApplicationContext<RouteId>["gateway"];
36+
const initialLocationReady = resolveInitialApplicationLocation({
37+
location: requested,
38+
basePath,
39+
sessionKey: `agent:${savedAgentId}:main`,
40+
selectedAgentId: savedAgentId,
41+
gateway,
42+
agentsList: () => null,
43+
signal: new AbortController().signal,
44+
});
45+
46+
await startModelSetupFirstRunRedirectAfterLocation({
47+
context: { gateway } as ApplicationContext<RouteId>,
48+
enabled: false,
49+
history: { location: () => currentLocation, replace },
50+
initialLocationReady,
51+
});
52+
53+
expect(currentLocation).toEqual(requested);
54+
expect(replace).not.toHaveBeenCalled();
55+
expect(gateway.subscribe).not.toHaveBeenCalled();
56+
},
57+
);
58+
959
it("routes a canonical global session through its persisted agent owner", async () => {
1060
const subscribe = vi.fn(() => () => undefined);
1161

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import { expect, it } from "vitest";
2+
import { createPlaybackMediaFixture } from "../../../test/fixtures/media-playback.js";
3+
import { installMockGateway } from "../test-helpers/control-ui-e2e.ts";
4+
import { createControlUiE2eSuite } from "./control-ui-e2e-suite.test-support.ts";
5+
6+
const suite = createControlUiE2eSuite({ name: "Attachment file styles" });
7+
8+
suite.define(() => {
9+
it("preserves large, preview, and unavailable file visuals in both themes", async () => {
10+
await suite.withPage({ locale: "en-US", serviceWorkers: "block" }, async ({ page }) => {
11+
await page.route("**/style-proof.mp3", (route) =>
12+
route.fulfill({ contentType: "audio/mpeg", body: createPlaybackMediaFixture("mp3") }),
13+
);
14+
await installMockGateway(page, {
15+
historyMessages: [
16+
{
17+
role: "assistant",
18+
content: [
19+
{
20+
type: "attachment",
21+
attachment: {
22+
kind: "document",
23+
label: "report.pdf",
24+
mimeType: "application/pdf",
25+
url: new URL("report.pdf", suite.server.baseUrl).href,
26+
},
27+
},
28+
{
29+
type: "attachment",
30+
attachment: {
31+
kind: "audio",
32+
label: "style-proof.mp3",
33+
mimeType: "audio/mpeg",
34+
url: new URL("style-proof.mp3", suite.server.baseUrl).href,
35+
},
36+
},
37+
{
38+
type: "attachment_error",
39+
attachment: {
40+
code: "file-not-found",
41+
kind: "document",
42+
label: "missing.pdf",
43+
},
44+
},
45+
],
46+
timestamp: 1,
47+
},
48+
],
49+
});
50+
await page.goto(`${suite.server.baseUrl}chat`);
51+
const compact = page.locator('.chat-attachment-file-icon[data-mode="preview-with-favicon"]');
52+
await compact.waitFor({ state: "visible" });
53+
const documentCard = page.locator(".chat-assistant-attachment-card--compact", {
54+
hasText: "report.pdf",
55+
});
56+
const unavailable = page.locator(".chat-assistant-attachment-card--definitive", {
57+
hasText: "missing.pdf",
58+
});
59+
await unavailable.waitFor({ state: "visible" });
60+
61+
for (const theme of ["dark", "light"]) {
62+
await page.evaluate((mode) => {
63+
document.documentElement.dataset.themeMode = mode;
64+
}, theme);
65+
const large = documentCard.locator(".chat-attachment-file-icon");
66+
const largeStyle = await large.evaluate((icon) => {
67+
const style = getComputedStyle(icon);
68+
const overlay = icon.querySelector(".chat-attachment-file-icon__overlay")!;
69+
const glyph = getComputedStyle(overlay);
70+
return {
71+
width: style.width,
72+
height: style.height,
73+
background: style.backgroundImage,
74+
glyphWidth: glyph.width,
75+
glyphHeight: glyph.height,
76+
mask: glyph.maskImage,
77+
webkitMask: glyph.webkitMaskImage,
78+
};
79+
});
80+
expect(largeStyle).toMatchObject({
81+
width: "44px",
82+
height: "44px",
83+
glyphWidth: "14px",
84+
glyphHeight: "14px",
85+
});
86+
expect(largeStyle.background).toContain(`large/shell-${theme}.svg`);
87+
expect(largeStyle.mask).toContain("overlays/pdf.svg");
88+
expect(largeStyle.webkitMask).toBe(largeStyle.mask);
89+
const previewStyle = await compact.evaluate((icon) => {
90+
const style = getComputedStyle(icon);
91+
return { width: style.width, height: style.height, background: style.backgroundImage };
92+
});
93+
expect(previewStyle).toMatchObject({ width: "20px", height: "20px" });
94+
expect(previewStyle.background).toContain(`compact/${theme}/mp3.svg`);
95+
expect(
96+
await documentCard.evaluate((card) => {
97+
const style = getComputedStyle(card);
98+
return [style.display, style.padding];
99+
}),
100+
).toEqual(["block", "0px"]);
101+
const failedStyle = await unavailable.evaluate((card) => {
102+
const icon = card.querySelector(".chat-attachment-file-icon")!;
103+
const metadata = card.querySelector(".chat-assistant-attachment-card__status-meta")!;
104+
const title = card.querySelector(".chat-assistant-attachment-card__title")!;
105+
return {
106+
color: getComputedStyle(card).color,
107+
danger: getComputedStyle(card).getPropertyValue("--danger").trim(),
108+
iconColor: getComputedStyle(icon).color,
109+
statusColor: getComputedStyle(metadata).color,
110+
opacity: getComputedStyle(icon).opacity,
111+
decoration: getComputedStyle(title).textDecorationLine,
112+
thickness: getComputedStyle(title).textDecorationThickness,
113+
display: getComputedStyle(card).display,
114+
padding: getComputedStyle(card).padding,
115+
};
116+
});
117+
expect(failedStyle).toMatchObject({
118+
iconColor: failedStyle.color,
119+
statusColor: failedStyle.color,
120+
opacity: "0.42",
121+
decoration: "line-through",
122+
thickness: "1px",
123+
display: "block",
124+
padding: "0px",
125+
});
126+
expect(failedStyle.color).toBe(
127+
await page.evaluate((color) => {
128+
const sample = document.createElement("span");
129+
sample.style.color = color;
130+
document.body.append(sample);
131+
const resolved = getComputedStyle(sample).color;
132+
sample.remove();
133+
return resolved;
134+
}, failedStyle.danger),
135+
);
136+
}
137+
});
138+
});
139+
});

‎ui/src/e2e/chat-attachment-read-lifecycle.e2e.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import { mkdir, rm } from "node:fs/promises";
22
import path from "node:path";
33
import type { Locator, Page } from "playwright";
44
import { expect, it } from "vitest";
5+
import { storedChatOutboxScopeKey } from "../lib/chat/outbox-store.ts";
56
import {
6-
resolveStoredChatOutboxScope,
7-
storedChatOutboxScopeKey,
8-
} from "../lib/chat/outbox-store.ts";
9-
import type { UiSessionDefaultsHost } from "../lib/sessions/session-key.ts";
7+
resolveUiConversationIdentity,
8+
type UiSessionDefaultsHost,
9+
} from "../lib/sessions/session-key.ts";
1010
import {
1111
controlUiSessionUrl,
1212
installMockGateway,
@@ -81,7 +81,7 @@ async function waitForCommittedAttachmentDraft(
8181
hello: state.hello,
8282
};
8383
});
84-
const storedScope = resolveStoredChatOutboxScope(defaults, sessionKey);
84+
const storedScope = resolveUiConversationIdentity(defaults, sessionKey);
8585
await waitForCommittedComposerDraft(
8686
page,
8787
`chat:v3:${storedChatOutboxScopeKey(storedScope)}`,

0 commit comments

Comments
 (0)