Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions scripts/prepare-resources/desktop-bridge-checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,17 @@ export const verifyDesktopBridgeArtifacts = async ({
isDesktopBridgeExpectationStrict,
}) => {
const issues = [];
const chatTransportFormats = new Set();
const isTaggedRelease = isSourceRepoRefVersionTag;
if (!isDesktopBridgeExpectationStrict && isTaggedRelease) {
console.warn(
`[prepare-resources] Desktop bridge required checks downgraded to warnings for source ref ${sourceRepoRef}. ` +
`[prepare-resources] Desktop bridge best-effort checks downgraded to warnings for source ref ${sourceRepoRef}. ` +
'Set ASTRBOT_DESKTOP_STRICT_BRIDGE_EXPECTATIONS=1 to enforce.',
);
}

for (const expectation of getDesktopBridgeExpectations()) {
const expectations = new Set(getDesktopBridgeExpectations());
for (const expectation of expectations) {
const mustPass = shouldEnforceDesktopBridgeExpectation(expectation, {
isDesktopBridgeExpectationStrict,
isTaggedRelease,
Expand All @@ -139,14 +141,28 @@ export const verifyDesktopBridgeArtifacts = async ({
}

const source = await readFile(file, 'utf8');
if (!expectation.pattern.test(source)) {
const message = `[prepare-resources] Expected ${expectation.label} in ${path.relative(projectRoot, file)}. ${expectation.hint || ''} Please sync AstrBot dashboard sources.`;
if (mustPass) {
issues.push(message);
} else {
console.warn(`${message} (compatibility check skipped)`);
}
const scopedSource = expectation.scopePattern
? source.match(expectation.scopePattern)?.[0] || ''
: source;
const primaryMatch = expectation.pattern.test(scopedSource);
const fallbackMatch = expectation.fallbackPattern?.test(source) || false;
if (fallbackMatch) {
expectations.add(expectation.fallbackRequirement);
chatTransportFormats.add('consolidated');
}
if (primaryMatch && expectation.fallbackPattern) chatTransportFormats.add('legacy');
if (primaryMatch || fallbackMatch) continue;

const message = `[prepare-resources] Expected ${expectation.label} in ${path.relative(projectRoot, file)}. ${expectation.hint || ''} Please sync AstrBot dashboard sources.`;
if (mustPass) {
issues.push(message);
} else {
console.warn(`${message} (compatibility check skipped)`);
}
}

if (chatTransportFormats.size > 1) {
issues.push('[prepare-resources] Chat transport preference formats must match across Chat.vue and StandaloneChat.vue.');
}

if (issues.length > 0) {
Expand Down
202 changes: 200 additions & 2 deletions scripts/prepare-resources/desktop-bridge-checks.test.mjs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises';
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

import {
getDesktopBridgeExpectations,
shouldEnforceDesktopBridgeExpectation,
} from './desktop-bridge-expectations.mjs';
import { patchDesktopReleaseUpdateIndicator } from './desktop-bridge-checks.mjs';
import {
patchDesktopReleaseUpdateIndicator,
verifyDesktopBridgeArtifacts,
} from './desktop-bridge-checks.mjs';

test('getDesktopBridgeExpectations returns stable expectation metadata', () => {
const expectations = getDesktopBridgeExpectations();
Expand Down Expand Up @@ -60,6 +63,16 @@ test('shouldEnforceDesktopBridgeExpectation downgrades required expectations on
);
});

test('shouldEnforceDesktopBridgeExpectation enforces explicitly required tagged expectations', () => {
assert.equal(
shouldEnforceDesktopBridgeExpectation(
{ required: true, alwaysRequired: true },
{ isDesktopBridgeExpectationStrict: false, isTaggedRelease: true },
),
true,
);
});

test('shouldEnforceDesktopBridgeExpectation enforces required expectations on non-tagged refs', () => {
assert.equal(
shouldEnforceDesktopBridgeExpectation(
Expand All @@ -70,6 +83,191 @@ test('shouldEnforceDesktopBridgeExpectation enforces required expectations on no
);
});

test('shouldEnforceDesktopBridgeExpectation keeps transport migration required on tagged releases', () => {
const componentExpectation = getDesktopBridgeExpectations().find(
(expectation) => expectation.label === 'chat transport preference read',
);

assert.ok(componentExpectation);
assert.equal(
shouldEnforceDesktopBridgeExpectation(componentExpectation.fallbackRequirement, {
isDesktopBridgeExpectationStrict: false,
isTaggedRelease: true,
}),
true,
);
});

test('verifyDesktopBridgeArtifacts validates chat transport preference compatibility', async (t) => {
const dashboardDir = await mkdtemp(path.join(tmpdir(), 'astrbot-dashboard-'));
t.after(() => rm(dashboardDir, { recursive: true, force: true }));
const writeSource = async (relativePath, source) => {
const file = path.join(dashboardDir, ...relativePath.split('/'));
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, source, 'utf8');
};

await writeSource(
'src/App.vue',
'if (!desktopBridge?.onTrayRestartBackend) { await globalWaitingRef.value?.check?.(prompt); }',
);
await writeSource(
'src/utils/restartAstrBot.ts',
'import { getDesktopRuntimeInfo } from "@/utils/desktopRuntime"; if (hasDesktopRestartCapability) await getDesktopRuntimeInfo();',
);
await writeSource(
'src/layouts/full/vertical-header/VerticalHeader.vue',
'const runtimeInfo = await getDesktopRuntimeInfo(); isDesktopReleaseMode.value = runtimeInfo.isDesktopRuntime;',
);
await writeSource('src/utils/desktopRuntime.ts', 'console.warn("Desktop runtime detection failed");');

const chat = 'src/components/chat/Chat.vue';
const standaloneChat = 'src/components/chat/StandaloneChat.vue';
const chatPreferences = 'src/utils/chatPreferences.ts';
const options = {
dashboardDir,
projectRoot: dashboardDir,
sourceRepoRef: 'master',
isSourceRepoRefVersionTag: false,
isDesktopBridgeExpectationStrict: true,
};

const legacyRead = 'const transportMode = localStorage.getItem("chat.transportMode") === "websocket";';
const legacyWrite = 'localStorage.setItem("chat.transportMode", mode);';
const modernChat = [
'import { chatPreferences } from "@/utils/chatPreferences";',
'const transportMode = ref(',
' chatPreferences().global.transportMode === "websocket" ? "websocket" : "sse",',
');',
'watch(transportMode, (mode) => {',
' chatPreferences((preferences) => {',
' preferences.global.transportMode = mode;',
' });',
'});',
].join('\n');
const modernStandaloneChat = [
'import { chatPreferences } from "@/utils/chatPreferences";',
'const transportMode = ref(',
' chatPreferences().global.transportMode === "websocket" ? "websocket" : "sse",',
');',
].join('\n');
const migrationSource = [
'const CHAT_PREFERENCES_KEY = "astrbot.chat.preferences";',
'export function chatPreferences(update) {',
' let preferences = { global: {}, sessions: {} };',
' try {',
' const target = globalThis.localStorage;',
' const migrated = [];',
' if (storedUsername) {',
' const globalKeys = {',
' "chat.transportMode": "transportMode",',
' };',
' for (const [key, field] of Object.entries(globalKeys)) {',
' const value = target.getItem(key);',
' if (value !== null) {',
' preferences.global[field] ??= value;',
' migrated.push(key);',
' }',
' }',
' }',
' update?.(preferences);',
' if (storedUsername && (update || migrated.length)) {',
' target.setItem(CHAT_PREFERENCES_KEY, JSON.stringify(root));',
' for (const key of migrated) {',
' target.removeItem(key);',
' }',
' }',
' } catch {',
' }',
' return preferences;',
'}',
].join('\n');

await writeSource(chat, [legacyRead, legacyWrite].join('\n'));
await writeSource(standaloneChat, legacyRead);
await verifyDesktopBridgeArtifacts(options);

await writeSource(chat, modernChat);
await writeSource(standaloneChat, modernStandaloneChat);
await writeSource(chatPreferences, migrationSource);
await verifyDesktopBridgeArtifacts(options);

await writeSource(standaloneChat, legacyRead);
await assert.rejects(
verifyDesktopBridgeArtifacts(options),
/chat transport preference formats must match/i,
);
await writeSource(chat, [legacyRead, legacyWrite].join('\n'));
await writeSource(standaloneChat, modernStandaloneChat);
await assert.rejects(
verifyDesktopBridgeArtifacts(options),
/chat transport preference formats must match/i,
);

const dualFormatChat = [
legacyRead,
legacyWrite,
'chatPreferences((preferences) => { preferences.global.transportMode = mode; });',
].join('\n');
const invalidMigration = migrationSource.replace(
'"chat.transportMode": "transportMode"',
'"chat.transportMode": "legacyTransportMode"',
);
await writeSource(chat, dualFormatChat);
await writeSource(standaloneChat, legacyRead);
await writeSource(chatPreferences, invalidMigration);
await assert.rejects(
verifyDesktopBridgeArtifacts(options),
/legacy desktop chat transport preference migration/,
);

const unrelatedMigration = [
'const globalKeys = { "chat.transportMode": "transportMode" };',
'export function chatPreferences() {',
' if (false) {',
' const value = target.getItem(key);',
' preferences.global[field] ??= value;',
' }',
'}',
'function persistOtherPreferences() {',
' target.setItem(CHAT_PREFERENCES_KEY, JSON.stringify(root));',
'}',
].join('\n');
await writeSource(chat, modernChat);
await writeSource(standaloneChat, modernStandaloneChat);
await writeSource(chatPreferences, unrelatedMigration);
await assert.rejects(
verifyDesktopBridgeArtifacts(options),
/legacy desktop chat transport preference migration/,
);

const migrationSourceLines = migrationSource.split('\n');
const tryStart = migrationSourceLines.indexOf(' try {');
const catchStart = migrationSourceLines.indexOf(' } catch {');
const unreachableMigration = [
...migrationSourceLines.slice(0, tryStart + 1),
' if (false) {',
...migrationSourceLines.slice(tryStart + 1, catchStart).map((line) => ` ${line}`),
' }',
...migrationSourceLines.slice(catchStart),
].join('\n');
await writeSource(chatPreferences, unreachableMigration);
await assert.rejects(
verifyDesktopBridgeArtifacts(options),
/legacy desktop chat transport preference migration/,
);

await assert.rejects(
verifyDesktopBridgeArtifacts({
...options,
sourceRepoRef: 'v4.30.0',
isSourceRepoRefVersionTag: true,
isDesktopBridgeExpectationStrict: false,
}),
/legacy desktop chat transport preference migration/,
);
});

test('patchDesktopReleaseUpdateIndicator tolerates minor formatting changes in the upstream source', async () => {
const dashboardDir = await mkdtemp(path.join(tmpdir(), 'astrbot-dashboard-'));
const headerFile = path.join(
Expand Down
56 changes: 48 additions & 8 deletions scripts/prepare-resources/desktop-bridge-expectations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ if (
const CHAT_TRANSPORT_STORAGE_KEY_PATTERN = escapeRegex(CHAT_TRANSPORT_MODE_STORAGE_KEY);
const CHAT_TRANSPORT_WEBSOCKET_PATTERN = escapeRegex(CHAT_TRANSPORT_MODE_WEBSOCKET);
const CHAT_TRANSPORT_READ_HINT =
`Expected chat UI to read localStorage["${CHAT_TRANSPORT_MODE_STORAGE_KEY}"] ` +
`Expected chat UI to read "${CHAT_TRANSPORT_MODE_STORAGE_KEY}" directly or through chatPreferences() ` +
`and recognize "${CHAT_TRANSPORT_MODE_WEBSOCKET}".`;
const CHAT_TRANSPORT_WRITE_HINT =
`Expected chat UI to persist transport mode via localStorage.setItem("${CHAT_TRANSPORT_MODE_STORAGE_KEY}", ...).`;
'Expected chat UI to persist transport mode directly in localStorage or through chatPreferences().';
const CHAT_TRANSPORT_MIGRATION_HINT =
`Expected chatPreferences to migrate the legacy "${CHAT_TRANSPORT_MODE_STORAGE_KEY}" key ` +
'into the current global transportMode preference.';

const DESKTOP_BRIDGE_PATTERNS = {
trayRestartGuard: /if\s*\(\s*!desktopBridge\s*\?\.\s*onTrayRestartBackend\s*\)\s*\{/,
Expand All @@ -41,12 +44,43 @@ const DESKTOP_BRIDGE_PATTERNS = {
/const\s+runtimeInfo\s*=\s*await\s+getDesktopRuntimeInfo\s*\(\s*\)\s*;?[\s\S]*?isDesktopReleaseMode\.value\s*=\s*runtimeInfo\.isDesktopRuntime/,
desktopReleaseModeFlag: /\bisDesktopReleaseMode\b/,
desktopRuntimeProbeWarn: /console\.warn\([\s\S]*desktop runtime/i,
chatTransportPreferenceRead: new RegExp(
legacyChatTransportPreferenceRead: new RegExp(
`localStorage\\.getItem\\(["']${CHAT_TRANSPORT_STORAGE_KEY_PATTERN}["']\\)[\\s\\S]*?["']${CHAT_TRANSPORT_WEBSOCKET_PATTERN}["']`,
),
chatTransportPreferenceWrite: new RegExp(
legacyChatTransportPreferenceWrite: new RegExp(
`localStorage\\.setItem\\(["']${CHAT_TRANSPORT_STORAGE_KEY_PATTERN}["']\\s*,`,
),
chatTransportPreferenceRead: new RegExp(
`chatPreferences\\(\\)\\.global\\.transportMode\\s*===\\s*["']${CHAT_TRANSPORT_WEBSOCKET_PATTERN}["']`,
),
chatTransportPreferenceWrite:
/chatPreferences\(\s*\(\s*(\w+)\s*\)\s*=>\s*\{\s*\1\.global\.transportMode\s*=/,
chatTransportPreferenceMigration: new RegExp(
String.raw`^(?<bodyIndent>[ \t]*)let preferences\b[^\r\n]*;?[ \t]*\r?\n` +
String.raw`^\k<bodyIndent>try\s*\{[ \t]*\r?\n` +
String.raw`^(?<indent>\k<bodyIndent>[ \t]+)const target\s*=.*?;[ \t]*\r?\n` +
String.raw`[\s\S]*?^\k<indent>const migrated(?::\s*string\[\])?\s*=\s*\[\];[ \t]*\r?\n` +
String.raw`^\k<indent>if\s*\(storedUsername\)\s*\{\s*const globalKeys\s*=\s*\{[^{}]*?` +
String.raw`["']${CHAT_TRANSPORT_STORAGE_KEY_PATTERN}["']\s*:\s*["']transportMode["'][^{}]*?\}\s*(?:as const)?;?\s*` +
String.raw`for\s*\(const\s+\[key,\s*field\]\s+of\s+Object\.entries\(globalKeys\)\)\s*\{\s*` +
String.raw`const value\s*=\s*target\.getItem\(key\);?\s*if\s*\(value\s*!==\s*null\)\s*\{\s*` +
String.raw`preferences\.global\[field\]\s*\?\?=\s*value;?\s*migrated\.push\(key\);?\s*\}\s*\}` +
String.raw`[\s\S]*?^\k<indent>\}[ \t]*\r?\n^\k<indent>update\?\.\(preferences\);?[ \t]*\r?\n` +
String.raw`^\k<indent>if\s*\(storedUsername\s*&&\s*\(update\s*\|\|\s*migrated\.length\)\)\s*\{\s*` +
String.raw`target\.setItem\(CHAT_PREFERENCES_KEY,\s*JSON\.stringify\(root\)\);?[\s\S]*?` +
String.raw`^\k<bodyIndent>\}\s*catch\s*\{[\s\S]*?^\k<bodyIndent>return\s+preferences\s*;`,
'm',
),
};

const CHAT_TRANSPORT_MIGRATION = {
filePath: ['src', 'utils', 'chatPreferences.ts'],
pattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceMigration,
scopePattern: /^export function chatPreferences\([\s\S]*?^\}/m,
label: 'legacy desktop chat transport preference migration',
hint: CHAT_TRANSPORT_MIGRATION_HINT,
required: true,
alwaysRequired: true,
};
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved

const DESKTOP_BRIDGE_EXPECTATIONS = [
Expand Down Expand Up @@ -101,21 +135,27 @@ const DESKTOP_BRIDGE_EXPECTATIONS = [
},
{
filePath: ['src', 'components', 'chat', 'Chat.vue'],
pattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceRead,
pattern: DESKTOP_BRIDGE_PATTERNS.legacyChatTransportPreferenceRead,
fallbackPattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceRead,
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
fallbackRequirement: CHAT_TRANSPORT_MIGRATION,
label: 'chat transport preference read',
hint: CHAT_TRANSPORT_READ_HINT,
required: true,
},
{
filePath: ['src', 'components', 'chat', 'Chat.vue'],
pattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceWrite,
pattern: DESKTOP_BRIDGE_PATTERNS.legacyChatTransportPreferenceWrite,
fallbackPattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceWrite,
fallbackRequirement: CHAT_TRANSPORT_MIGRATION,
label: 'chat transport preference write',
hint: CHAT_TRANSPORT_WRITE_HINT,
required: true,
},
{
filePath: ['src', 'components', 'chat', 'StandaloneChat.vue'],
pattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceRead,
pattern: DESKTOP_BRIDGE_PATTERNS.legacyChatTransportPreferenceRead,
fallbackPattern: DESKTOP_BRIDGE_PATTERNS.chatTransportPreferenceRead,
fallbackRequirement: CHAT_TRANSPORT_MIGRATION,
label: 'standalone chat transport preference read',
hint: CHAT_TRANSPORT_READ_HINT,
required: true,
Expand All @@ -131,5 +171,5 @@ export const shouldEnforceDesktopBridgeExpectation = (
if (isDesktopBridgeExpectationStrict) {
return true;
}
return expectation.required && !isTaggedRelease;
return expectation.required && (expectation.alwaysRequired === true || !isTaggedRelease);
};