feat(web): add messages and calls module slices

This commit is contained in:
chick
2026-07-17 20:27:53 +08:00
parent d0fd943082
commit 0c84e8c88e
6 changed files with 856 additions and 0 deletions
+247
View File
@@ -0,0 +1,247 @@
import { useEffect, useRef, useState, type ReactNode } from 'react';
import type { InstanceContext } from '../app-shell.js';
/** Bounded primitives permitted at the Messages presentation boundary. */
export type MessageMetadataValue = string | number | boolean | null;
/** Aggregate SMS metadata only. Message bodies, content, recipients, and credentials are absent. */
export interface SmsAggregate {
readonly total?: number | null;
readonly inbound?: number | null;
readonly outbound?: number | null;
readonly unread?: number | null;
readonly failed?: number | null;
readonly queued?: number | null;
readonly lastActivityAt?: string | null;
}
/** Non-sensitive device identity/status and aggregate counts only. */
export interface DeviceMessageAggregate extends SmsAggregate {
readonly deviceId?: string | null;
readonly label?: string | null;
readonly state?: string | null;
}
export interface MessagesSnapshot {
readonly observedAt?: string;
readonly sms: SmsAggregate;
readonly devices: readonly DeviceMessageAggregate[];
}
export interface MessagesDataSource {
/** Supplied by the authenticated owner; this isolated module defines no network endpoint. */
load(instanceId: string, signal: AbortSignal): Promise<MessagesSnapshot>;
}
export interface MessagesModuleProps {
readonly instance: InstanceContext;
readonly dataSource?: MessagesDataSource;
/** Change this owner-provided value to request another read. */
readonly refreshSignal?: unknown;
}
type ReadState =
| { kind: 'idle'; ownerId: string }
| { kind: 'loading'; ownerId: string; snapshot?: MessagesSnapshot }
| { kind: 'ready'; ownerId: string; snapshot: MessagesSnapshot }
| { kind: 'error'; ownerId: string; snapshot?: MessagesSnapshot };
const SAFE_LOAD_ERROR = 'Messages data could not be loaded.';
const AGGREGATE_FIELDS = [
['Total', 'total'],
['Inbound', 'inbound'],
['Outbound', 'outbound'],
['Unread', 'unread'],
['Failed', 'failed'],
['Queued', 'queued'],
['Last activity', 'lastActivityAt'],
] as const;
function display(value: MessageMetadataValue | undefined): string {
return value == null ? 'Unavailable' : String(value);
}
function Fields({
values,
}: {
values: readonly (readonly [label: string, value: MessageMetadataValue | undefined])[];
}) {
return (
<dl>
{values.map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd>{display(value)}</dd>
</div>
))}
</dl>
);
}
function Section({ label, children }: { label: string; children: ReactNode }) {
return (
<section className="messages-card" aria-label={label}>
<h2>{label}</h2>
{children}
</section>
);
}
function aggregateFields(
aggregate: SmsAggregate,
): readonly (readonly [string, MessageMetadataValue | undefined])[] {
// This constant-key projection is the presentation allowlist. Never enumerate source objects.
return AGGREGATE_FIELDS.map(([label, key]) => [label, aggregate[key]] as const);
}
function SnapshotView({ snapshot }: { snapshot: MessagesSnapshot }) {
return (
<>
{snapshot.observedAt ? <p>Observed {snapshot.observedAt}</p> : null}
<p>Aggregate metadata only; sensitive payload and addressing details are excluded.</p>
<div className="messages-grid">
<Section label="SMS aggregate">
<Fields values={aggregateFields(snapshot.sms)} />
</Section>
<Section label="Device message aggregates">
{snapshot.devices.length ? (
snapshot.devices.map((device, index) => (
<article key={`${device.deviceId ?? device.label ?? 'device'}-${index}`}>
<Fields
values={[
['Device ID', device.deviceId],
['Label', device.label],
['State', device.state],
...aggregateFields(device),
]}
/>
</article>
))
) : (
<p>No device message aggregates were supplied.</p>
)}
</Section>
</div>
<section className="state-panel" aria-label="Messages actions">
<h2>Messages actions</h2>
<p>Sending, deleting, and changing messages are unavailable in this read-only module.</p>
</section>
</>
);
}
export function MessagesModule({ instance, dataSource, refreshSignal }: MessagesModuleProps) {
const requestOwner = useRef(0);
const [retry, setRetry] = useState(0);
const [state, setState] = useState<ReadState>({ kind: 'idle', ownerId: instance.id });
useEffect(() => {
const request = ++requestOwner.current;
const ownerId = instance.id;
const controller = new AbortController();
if (instance.authentication !== 'authenticated' || !dataSource) {
setState({ kind: 'idle', ownerId });
return () => controller.abort();
}
setState((current) => ({
kind: 'loading',
ownerId,
...(current.ownerId === ownerId &&
(current.kind === 'ready' || current.kind === 'error') &&
current.snapshot
? { snapshot: current.snapshot }
: {}),
}));
void dataSource.load(ownerId, controller.signal).then(
(snapshot) => {
if (request === requestOwner.current && !controller.signal.aborted) {
setState({ kind: 'ready', ownerId, snapshot });
}
},
(_reason: unknown) => {
void _reason;
if (request === requestOwner.current && !controller.signal.aborted) {
setState((current) => ({
kind: 'error',
ownerId,
...(current.ownerId === ownerId && current.kind === 'loading' && current.snapshot
? { snapshot: current.snapshot }
: {}),
}));
}
},
);
return () => controller.abort();
}, [dataSource, instance.authentication, instance.id, refreshSignal, retry]);
if (instance.authentication !== 'authenticated') {
return (
<div className="state-panel state-error" role="alert">
Authentication is required before Messages data can be read for this instance.
</div>
);
}
if (!dataSource) {
return (
<div className="state-panel" role="status" aria-label="Messages unavailable">
No safe Messages read data source is available. This console will not invent or call an
uncontracted production endpoint.
</div>
);
}
const retainedSnapshot =
state.ownerId === instance.id && (state.kind === 'loading' || state.kind === 'error')
? state.snapshot
: undefined;
if ((state.kind === 'idle' || state.kind === 'loading') && !retainedSnapshot) {
return (
<p role="status" aria-label="Messages loading status">
Loading Messages
</p>
);
}
if (state.kind === 'error' && !retainedSnapshot) {
return (
<div className="state-panel state-error" role="alert">
<p>Unable to load Messages: {SAFE_LOAD_ERROR}</p>
<button type="button" onClick={() => setRetry((value) => value + 1)}>
Retry loading Messages
</button>
</div>
);
}
const currentSnapshot =
state.kind === 'ready' && state.ownerId === instance.id ? state.snapshot : retainedSnapshot;
if (!currentSnapshot) return null;
return (
<div className="messages-module">
{state.kind === 'loading' ? <p role="status">Refreshing Messages</p> : null}
{state.kind === 'error' ? (
<div className="state-panel state-error" role="alert">
<p>Refresh failed; showing the last known Messages data.</p>
<button type="button" onClick={() => setRetry((value) => value + 1)}>
Retry loading Messages
</button>
</div>
) : null}
{instance.freshness !== 'fresh' ? (
<p className="state-panel" role="status" aria-label="Messages freshness">
Messages data is {instance.freshness}; verify freshness before relying on these values.
</p>
) : null}
<SnapshotView snapshot={currentSnapshot} />
</div>
);
}