Files
openchamber/packages/ui/src/apps/mobileWidgetSnapshot.ts
T
Serhii DziupinandSerhii Dziupin 86e6a2ae76 Remove verified dead declarations (#2714)
* chore: remove verified dead declarations

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: narrow unused internal exports

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: remove newly exposed dead helpers

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: remove unused deep-link serializer

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: drop two tests that assert on copies of the code

mainLayoutMobileSidebarMount read MainLayout.tsx and SessionSidebar.tsx as
strings and asserted on source substrings down to exact indentation, so it
failed on formatting rather than behaviour. useProjectSessionSelection.test
reimplemented the hook's visitNodes logic inside the test file and asserted
against that copy, so it could not observe the hook at all.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: repair sync suites that had rotted while unrunnable

No runner executed packages/ui, so these drifted from the source unnoticed:
two imported helpers that are no longer exported, one directory-store stub
predated the session field routeMessage reads, and the WebSocket fake missed
the mandatory url-token mint plus the close event the socket wrapper reads.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: stop the web suite failing on timeouts and a hand-copied mock

The Git suites drive a real git binary, so the 5s default made a valid suite
fail differently per run. The gitApiHttp mock listed ~70 export names by hand
and fell behind the source; it now derives every stub from the real module,
which the added shared-UI aliases make resolvable.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: run every suite from one command and in CI

packages/ui (232 files) and packages/vscode (22) had no test script at all, CI
ran neither, and 9 vscode files could never run because Node cannot resolve
their extensionless TypeScript imports. Three electron files sat outside every
script list, one of them importing vitest, which that package does not depend
on. A runner gives each file its own process, since these suites keep
module-level singletons and fail by load order when sharing one.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: delete a superseded repro harness and a completed plan

The issue-2638 harness needed lsof, overrode process.platform and spawned real
servers, and nothing referenced it; event-stream/rebind.test.js now covers the
same hub-pinned-to-the-old-port behaviour. The pairing v2 plan described relay
and the pairing UI as out of scope, both of which shipped.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* docs: point at the theme tools and record the github barrel invariant

convert-vscode-theme and harmonize-theme were referenced nowhere, so the
theme-authoring reference now names them. The github barrel is loaded through
await import('./index.js') and destructured per route, which no static report
can see; documenting that is what stops the next cleanup from deleting it.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: repair merge drift in bridge and route-registry mocks

upstream/main gained upsertProviderConfig on bridge-system-runtime and a
PATCH scheduled-task route after this branch forked. Their test doubles
were never updated to match:
- bridge-system-runtime.test.js: add upsertProviderConfig to the
  opencodeConfig mock so the import resolves.
- sse-routes.test.js: add app.patch to the route registry stub.

---------

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>
2026-08-13 15:30:54 +03:00

128 lines
5.1 KiB
TypeScript

import type { Session } from '@opencode-ai/sdk/v2';
import type { ProjectEntry } from '@/lib/api/types';
import { useUIStore } from '@/stores/useUIStore';
import { resolveGlobalSessionDirectory, useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useSessionPinnedStore } from '@/stores/useSessionPinnedStore';
import { useNotificationStore } from '@/sync/notification-store';
import { compareSessionsByLifecycleOrder, useSessionOrderingStore } from '@/sync/session-ordering';
import { getRuntimeKey } from '@/lib/runtime-switch';
/**
* Builds the lightweight session overview the native iOS widgets render (home medium,
* lock-screen, Control Center). The widget process can't see the WebView, so the native
* shell pulls this snapshot via `window.__OPENCHAMBER_WIDGET_SNAPSHOT__()` on
* background/activate, writes it to the shared App Group, and reloads the widget timelines
* (see SceneDelegate.writeWidgetSnapshot). Mirrors the sidebar's attention logic so the
* widget's "needs attention" mark matches the in-app unread dot exactly:
* needsAttention = unseenCount > 0 && (!isSubtask || notifyOnSubtasks)
*/
export interface MobileWidgetSession {
id: string;
title: string;
/** True when the session needs attention (unread + honouring the subtask setting). */
unread: boolean;
/** Project label for the session's directory (matched project name, else folder name). */
project: string;
}
export interface MobileWidgetSnapshot {
/** Runtime instance that owns all session IDs and paths in this snapshot. */
runtimeKey: string;
/** Count of sessions needing attention — same signal that drives the app-icon badge. */
attentionCount: number;
/** Top-level sessions in the app's shared lifecycle order (capped for the medium widget). */
recentSessions: MobileWidgetSession[];
}
const RECENT_LIMIT = 6;
const parentIdOf = (session: Session): string | null =>
(session as Session & { parentID?: string | null }).parentID ?? null;
const basename = (path: string): string => {
const trimmed = path.replace(/\/+$/, '');
return trimmed.slice(trimmed.lastIndexOf('/') + 1) || trimmed;
};
const normalizeProjectPath = (path: string): string =>
path.replace(/\\/g, '/').replace(/\/+$/, '');
/** Project label for a session directory: longest matching project's name, else the folder name. */
const projectLabelForDirectory = (directory: string | null, projects: ProjectEntry[]): string => {
if (!directory) return '';
let best: ProjectEntry | null = null;
let bestLen = -1;
for (const project of projects) {
const projectPath = normalizeProjectPath(project.path);
if (directory === projectPath || directory.startsWith(`${projectPath}/`)) {
if (projectPath.length > bestLen) {
best = project;
bestLen = projectPath.length;
}
}
}
if (best) {
return best.label?.trim() || basename(best.path);
}
return basename(directory);
};
const buildMobileWidgetSnapshot = (): MobileWidgetSnapshot => {
const sessions = useGlobalSessionsStore.getState().activeSessions;
const unseenBySession = useNotificationStore.getState().index.session.unseenCount;
const notifyOnSubtasks = useUIStore.getState().notifyOnSubtasks;
const projects = useProjectsStore.getState().projects;
const pinnedSessionIds = useSessionPinnedStore.getState().ids;
const sessionOrderRanks = useSessionOrderingStore.getState().rankById;
let attentionCount = 0;
const topLevel: Array<{ session: Session; unread: boolean; project: string }> = [];
for (const session of sessions) {
const isSubtask = parentIdOf(session) !== null;
const unseenCount = unseenBySession[session.id] ?? 0;
const needsAttention = unseenCount > 0 && (!isSubtask || notifyOnSubtasks);
if (needsAttention) {
attentionCount += 1;
}
if (!isSubtask) {
topLevel.push({
session,
unread: needsAttention,
project: projectLabelForDirectory(resolveGlobalSessionDirectory(session), projects),
});
}
}
topLevel.sort((a, b) => compareSessionsByLifecycleOrder(a.session, b.session, pinnedSessionIds, sessionOrderRanks));
const recentSessions = topLevel
.slice(0, RECENT_LIMIT)
.map(({ session, unread, project }) => ({ id: session.id, title: session.title ?? '', unread, project }));
return { runtimeKey: getRuntimeKey(), attentionCount, recentSessions };
};
const SNAPSHOT_GLOBAL_KEY = '__OPENCHAMBER_WIDGET_SNAPSHOT__';
/**
* Exposes the snapshot builder on `window` so the native shell can read it synchronously via
* `evaluateJavaScript`. Returns a JSON string (the bridge wants a primitive result) or `null`
* if building fails, so the native side can skip writing on error rather than clobber a good
* snapshot. Safe to call in any runtime; only the native iOS shell ever invokes it.
*/
export const installMobileWidgetSnapshotBridge = (): void => {
if (typeof window === 'undefined') {
return;
}
(window as typeof window & { [SNAPSHOT_GLOBAL_KEY]?: () => string | null })[SNAPSHOT_GLOBAL_KEY] = () => {
try {
return JSON.stringify(buildMobileWidgetSnapshot());
} catch {
return null;
}
};
};