feat(mtp): move useful stuff over to mtp directly
All checks were successful
Dependency builds / Build web (pull_request) Has been skipped
Dependency builds / Build desktop (pull_request) Has been skipped
Dependency builds / Test native MTP (pull_request) Has been skipped
Dependency builds / Build mobile (pull_request) Has been skipped
/ build-web (push) Successful in 6m14s
/ build-desktop (linux) (push) Successful in 11m36s
/ build-mobile (push) Successful in 24m26s
/ release (push) Successful in 1m39s

This commit is contained in:
Alois 2026-08-27 23:30:33 +02:00
commit 0a304e44f2
Signed by: alois
SSH key fingerprint: SHA256:GBzT2DXvAuGV9XIV5W3WrzVpjU54FThmxHXdbz95J24
22 changed files with 1217 additions and 1870 deletions

View file

@ -9,19 +9,16 @@
"scripts": {
"format": "pnpm exec prettier --write .",
"lint": "eslint src --ext .ts,.tsx",
"test": "vitest run",
"test": "vitest run --passWithNoTests",
"build": "pnpm run test && tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@methanium/ui": "*",
"@tauri-apps/api": "^2.11.1",
"@tensamin/crypto": "workspace:*",
"@tensamin/shared": "workspace:*",
"@tensamin/storage": "workspace:*",
"mtp": "*",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"zod": "^4.4.3"
"react": "^19.2.8"
},
"devDependencies": {
"eslint": "^10.8.0"

View file

@ -0,0 +1,529 @@
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { toast as sonnerToast } from "@methanium/ui";
import { base64ToBytes, ConnectionState, MTPClient } from "mtp";
import createAsyncQueue from "@tensamin/shared/asyncQueue";
import {
mtp as mtpSchemas,
type Calls,
type Communities,
type Contacts,
} from "@tensamin/shared/data";
import { log } from "@tensamin/shared/log";
import { useStorage } from "@tensamin/storage/context";
import {
type BoundSendFn,
MTPContext,
type MTPContextType,
type ProtocolMessage,
removeMissingContacts,
useMessageHandlers,
} from "./mtpContext";
import {
DISCOVERY_TIMEOUT,
INITIAL_SYNC_TIMEOUT,
RECONNECT_JITTER,
RECONNECT_LONG_INTERVAL,
RECONNECT_RESET,
RECONNECT_TRIES,
RETRY_INTERVAL,
STATE_ACK_TIMEOUT,
} from "./values";
type BrowserMtpClient = Awaited<ReturnType<typeof createBrowserClient>>;
function createBrowserClient(
options: Omit<Parameters<typeof MTPClient.create>[0], "schemas">,
) {
return MTPClient.create({
...options,
schemas: mtpSchemas,
throwProtocolErrors: true,
onValidationError: (error) => {
log(1, "mtp", "red", "Failed to validate push message", error);
},
});
}
function abortError(signal: AbortSignal): Error {
return signal.reason instanceof Error
? signal.reason
: new Error("Initial state synchronization was cancelled");
}
function withDeadline<T>(
promise: Promise<T>,
timeoutMs: number,
timeoutMessage: string,
signal: AbortSignal,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
if (signal.aborted) {
reject(abortError(signal));
return;
}
let settled = false;
const finish = (complete: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
signal.removeEventListener("abort", onAbort);
complete();
};
const timeout = setTimeout(
() => finish(() => reject(new Error(timeoutMessage))),
timeoutMs,
);
const onAbort = () => finish(() => reject(abortError(signal)));
signal.addEventListener("abort", onAbort, { once: true });
promise.then(
(value) => finish(() => resolve(value)),
(error: unknown) => finish(() => reject(error)),
);
});
}
async function completeInitialSynchronization(
client: BrowserMtpClient,
subscribe: MTPContextType["subscribe"],
signal: AbortSignal,
syncTimeoutMs = INITIAL_SYNC_TIMEOUT,
ackTimeoutMs = STATE_ACK_TIMEOUT,
): Promise<ProtocolMessage<"ClientStateSync">> {
const stateSync = new Promise<ProtocolMessage<"ClientStateSync">>(
(resolve, reject) => {
let unsubscribeStateSync = () => {};
let unsubscribeNoIota = () => {};
const cleanup = () => {
clearTimeout(timeout);
unsubscribeStateSync();
unsubscribeNoIota();
signal.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(abortError(signal));
};
const timeout = setTimeout(() => {
cleanup();
reject(new Error("Initial state synchronization timed out"));
}, syncTimeoutMs);
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) {
onAbort();
return;
}
unsubscribeStateSync = subscribe("ClientStateSync", (message) => {
cleanup();
resolve(message);
});
unsubscribeNoIota = subscribe("ErrorNoIota", () => {
cleanup();
reject(new Error("No Iota is currently connected"));
});
},
);
const [, state] = await Promise.all([
withDeadline(
client.auth(),
syncTimeoutMs,
"MTP authentication timed out",
signal,
),
stateSync,
]);
await withDeadline(
client.request("ClientStateAck", {
SessionId: state.data.SessionId,
VersionNumber: state.data.VersionNumber,
}),
ackTimeoutMs,
"State acknowledgement timed out",
signal,
);
if (signal.aborted) throw abortError(signal);
return state;
}
function protocolErrorDetails(error: unknown) {
if (typeof error !== "object" || error === null || !("type" in error)) {
return null;
}
const protocolError = error as {
id?: unknown;
type?: unknown;
frame?: unknown;
};
return {
id: protocolError.id,
type: protocolError.type,
frame: protocolError.frame,
};
}
export function BrowserProvider(props: {
children: ReactNode;
blockConnection?: boolean;
}) {
const { load } = useStorage();
const [readyState, setReadyState] = useState<number>(
ConnectionState.Disconnected,
);
const [identified, setIdentified] = useState(false);
const [identifying, setIdentifying] = useState(false);
const [freshCommunities, setFreshCommunities] = useState<Communities>([]);
const [freshContacts, setFreshContacts] = useState<Contacts>([]);
const [freshCalls, setFreshCalls] = useState<Calls>([]);
const clientRef = useRef<BrowserMtpClient | null>(null);
const { addInterceptor, attachSubscriptions, interceptorsRef, subscribe } =
useMessageHandlers();
const connected = readyState === ConnectionState.Connected;
const [mtpUrl, setMtpUrl] = useState<string | null>(null);
useEffect(() => {
load("omega_url").then(setMtpUrl);
}, [load]);
const send: BoundSendFn = useMemo(
() => async (type, data, options) => {
const client = clientRef.current;
if (!client) throw new Error("mtp is not connected");
const response = await client.request(type, data, options);
if (response.type === "GetStates") {
setFreshContacts((contacts) =>
removeMissingContacts(
contacts,
response as ProtocolMessage<"GetStates">,
),
);
}
return response;
},
[],
);
const resolveConnectionRef = useRef(() => {});
useEffect(() => {
if (!mtpUrl) return;
let attempts = 0;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let reconnectResetTimer: ReturnType<typeof setTimeout> | null = null;
let reconnectScheduled = false;
let disposed = false;
let connectionGeneration = 0;
let cleanupConnection = () => {};
const clearReconnectTimer = () => {
if (!reconnectTimer) return;
clearTimeout(reconnectTimer);
reconnectTimer = null;
reconnectScheduled = false;
};
const clearReconnectResetTimer = () => {
if (!reconnectResetTimer) return;
clearTimeout(reconnectResetTimer);
reconnectResetTimer = null;
};
const scheduleReconnect = (error: unknown) => {
if (disposed || reconnectScheduled) return;
attempts += 1;
const shortRetry = attempts <= RECONNECT_TRIES;
if (!shortRetry) {
log(0, "mtp", "red", "Reconnection attempts exhausted", error);
sonnerToast.error("Connection failed", {
id: "mtp-connection-toast",
description:
error instanceof Error
? `${error.message.split(":")[0]}. Retrying in the background.`
: "Connection lost. Retrying in the background.",
icon: null,
duration: Infinity,
closeButton: true,
promise: null,
} as unknown as Parameters<typeof sonnerToast.error>[1]);
} else {
sonnerToast.loading(
`Reconnecting to server... (attempt ${attempts} of ${RECONNECT_TRIES})`,
{ id: "mtp-connection-toast" },
);
}
const baseDelay = shortRetry ? RETRY_INTERVAL : RECONNECT_LONG_INTERVAL;
const jitter = 1 + (Math.random() * 2 - 1) * RECONNECT_JITTER;
reconnectScheduled = true;
reconnectTimer = setTimeout(
() => {
reconnectScheduled = false;
reconnectTimer = null;
void connect();
},
Math.round(baseDelay * jitter),
);
};
async function connect() {
if (disposed || props.blockConnection) return;
const generation = ++connectionGeneration;
let client: BrowserMtpClient | null = null;
let failed = false;
let connectionReady = false;
let detachSubscriptions = () => {};
let unsubscribeNoIota = () => {};
const attemptAbort = new AbortController();
const cleanup = () => {
attemptAbort.abort(
new Error("Initial state synchronization was cancelled"),
);
unsubscribeNoIota();
detachSubscriptions();
client?.disconnect();
if (clientRef.current === client) clientRef.current = null;
clearReconnectResetTimer();
if (generation === connectionGeneration) {
setReadyState(ConnectionState.Disconnected);
setIdentified(false);
setIdentifying(false);
}
};
cleanupConnection = cleanup;
try {
setIdentified(false);
setIdentifying(false);
const [userId, keyring] = await Promise.all([
load("user_id"),
load("mtp_keyring"),
]);
if (!userId || !keyring) throw new Error("Missing login credentials");
const forcedOmikronUrl = await load("forced_omikron_url");
const forcedOmikronPublicKey = await load("forced_omikron_public_key");
let url = null;
let omikronPublicKey = null;
if (forcedOmikronUrl && forcedOmikronPublicKey) {
url = forcedOmikronUrl;
omikronPublicKey = forcedOmikronPublicKey;
} else {
log(2, "mtp", "purple", "Fetching Omikron data.");
const data = await fetch(`${mtpUrl}api/get/omikron/${userId}`, {
signal: AbortSignal.any([
attemptAbort.signal,
AbortSignal.timeout(DISCOVERY_TIMEOUT),
]),
});
if (data.status === 404) {
throw new Error("No Omikron assignment is currently available");
}
if (!data.ok)
throw new Error(`Omikron discovery failed: HTTP ${data.status}`);
const omikronData = (await data.json()) as {
ip_address: string;
port: number;
public_key: string;
};
if (
!omikronData.ip_address ||
!omikronData.port ||
!omikronData.public_key
) {
throw new Error("Invalid Omikron data");
}
url = `https://${omikronData.ip_address}:${omikronData.port}`;
omikronPublicKey = omikronData.public_key;
}
if (!url || !omikronPublicKey) {
throw new Error("Missing Omikron URL or Public Key");
}
log(2, "mtp", "green", "Connecting to: " + url);
client = await createBrowserClient({
url,
credentials: { clientId: userId, keyring: base64ToBytes(keyring) },
hostPublicKey: { value: omikronPublicKey, encoding: "base64" },
descriptor: "client",
pings: true,
logger: (event) => {
if (event.type === "state") {
if (generation !== connectionGeneration) return;
const state = client?.state ?? ConnectionState.Disconnected;
setReadyState(state);
if (
state === ConnectionState.Disconnected &&
clientRef.current === client &&
!failed
) {
failed = true;
const error = new Error("MTP connection lost");
attemptAbort.abort(error);
if (connectionReady) {
cleanup();
scheduleReconnect(error);
}
}
}
if (event.type !== "Pong" && event.type !== "Ping") {
log(
2,
"mtp",
event.type === "state"
? "purple"
: event.direction === "recv"
? "cyan"
: event.direction === "send"
? "gray"
: "blue",
event.type === "state"
? event.data
: event.direction === "recv"
? "< " + event.type
: event.direction === "send"
? "> " + event.type
: event.type,
event,
);
}
},
});
if (disposed || generation !== connectionGeneration) {
client.disconnect();
return;
}
const activeClient = client;
clientRef.current = activeClient;
detachSubscriptions = attachSubscriptions(activeClient);
unsubscribeNoIota = subscribe("ErrorNoIota", () => {
if (clientRef.current !== activeClient || failed) return;
failed = true;
const error = new Error("No Iota is currently connected");
attemptAbort.abort(error);
cleanup();
scheduleReconnect(error);
});
setReadyState(activeClient.state);
setIdentifying(true);
const finalResponse = await completeInitialSynchronization(
activeClient,
subscribe,
attemptAbort.signal,
);
if (disposed || clientRef.current !== activeClient) return;
setFreshContacts(finalResponse.data.Contacts);
setFreshCommunities(finalResponse.data.Communities);
setFreshCalls(finalResponse.data.Calls);
connectionReady = true;
setIdentifying(false);
setIdentified(true);
clearReconnectTimer();
clearReconnectResetTimer();
reconnectResetTimer = setTimeout(() => {
attempts = 0;
reconnectResetTimer = null;
}, RECONNECT_RESET * 1_000);
resolveConnectionRef.current?.();
} catch (connectError) {
if (disposed || generation !== connectionGeneration) {
client?.disconnect();
return;
}
failed = true;
cleanup();
const message =
connectError instanceof Error
? connectError.message
: String(connectError ?? "Unknown error");
log(
0,
"mtp",
"red",
`Connection/authentication attempt failed: ${message}`,
protocolErrorDetails(connectError) ?? connectError,
);
scheduleReconnect(connectError);
}
}
void connect();
return () => {
disposed = true;
clearReconnectTimer();
clearReconnectResetTimer();
cleanupConnection();
setReadyState(ConnectionState.Disconnected);
setIdentified(false);
setIdentifying(false);
sonnerToast.dismiss("mtp-connection-toast");
};
}, [attachSubscriptions, load, mtpUrl, props.blockConnection, subscribe]);
useEffect(() => {
return subscribe("ErrorNoIota", () => {
setIdentified(false);
setIdentifying(false);
sonnerToast.error("We couldn't reach your Iota", {
description:
"Check your network connection and try restarting your Iota",
icon: null,
duration: Infinity,
closeButton: true,
});
resolveConnectionRef.current?.();
});
}, [subscribe]);
useEffect(
() =>
subscribe("GetStates", (message) => {
setFreshContacts((contacts) =>
removeMissingContacts(contacts, message),
);
}),
[subscribe],
);
const loadingDescription = useMemo(() => {
if (!mtpUrl) return "Loading connection details";
if (readyState === ConnectionState.Connecting || !connected) {
return "Establishing transport channel";
}
if (identifying || !identified) return "Waiting for authenticated session";
return "Loading...";
}, [connected, identified, identifying, readyState, mtpUrl]);
const contextReady = connected && identified && mtpUrl !== null;
const mtpRef = useMemo(() => createAsyncQueue<{ send: typeof send }>(), []);
useEffect(() => {
if (connected && identified && mtpUrl) {
mtpRef.set({ send });
}
}, [connected, identified, mtpUrl, send, mtpRef]);
const sendQueued: BoundSendFn = useMemo(
() => async (type, data, options) => {
const mtp = await mtpRef.get();
const response = await mtp.send(type, data, options);
for (const interceptor of interceptorsRef.current) {
void Promise.resolve(interceptor({ type, data, response })).catch(
(error) => {
log(1, "mtp", "yellow", "MTP interceptor failed", error, { type });
},
);
}
return response;
},
[interceptorsRef, mtpRef],
);
return (
<MTPContext.Provider
value={{
send: sendQueued,
subscribe,
addInterceptor,
readyState,
identified,
freshContacts,
freshCommunities,
freshCalls,
contextReady,
loadingDescription,
}}
>
{props.children}
</MTPContext.Provider>
);
}

View file

@ -1,220 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { RequestIdAllocator } from "./requestIds";
vi.mock("@methanium/ui", () => ({
toast: {
dismiss: vi.fn(),
error: vi.fn(),
loading: vi.fn(),
},
}));
vi.mock("@tensamin/shared/log", () => ({ log: vi.fn() }));
vi.mock("@tensamin/storage/context", () => ({
useStorage: () => ({ load: vi.fn() }),
}));
const { completeInitialSynchronization, isPushType, validateResponse } =
await import("./context");
const validState = {
SessionId: 7,
VersionNumber: 2,
CacheSchemaVersion: 0,
SyncMode: "full",
Contacts: [],
Communities: [],
Calls: [],
Messages: [],
DeletedMessageIds: [],
DeletedContactIds: [],
};
function mockInitialSyncClient(
state: { type: string; data: unknown } = {
type: "ClientStateSync",
data: validState,
},
acknowledgement: unknown = { type: "ClientStateAck", data: {} },
) {
const handlers = new Map<string, (message: never) => void>();
const request = vi.fn().mockResolvedValue(acknowledgement);
const client = {
auth: vi.fn(async () => {
handlers.get(state.type)?.(state as never);
}),
subscribe: vi.fn((type: string, handler: (message: never) => void) => {
handlers.set(type, handler);
return () => handlers.delete(type);
}),
request,
disconnect: vi.fn(),
} as unknown as Parameters<typeof completeInitialSynchronization>[0];
return { client, handlers, request };
}
afterEach(() => {
vi.useRealTimers();
});
describe("MTP protocol dispatch", () => {
it("preserves protocol errors for the request layer", () => {
const error = validateResponse("GetStates", {
id: 12,
type: "ErrorInternal",
data: { ErrorType: "temporary" },
});
expect(error.type).toBe("ErrorInternal");
expect(error.id).toBe(12);
});
it("recognizes initial and live presence pushes", () => {
expect(isPushType("GetStates")).toBe(true);
expect(isPushType("ClientChanged")).toBe(true);
expect(isPushType("UnknownMessage")).toBe(false);
});
});
describe("browser initial synchronization", () => {
it("validates state, sends a nonzero acknowledgement, then resolves", async () => {
const { client, request } = mockInitialSyncClient();
const state = await completeInitialSynchronization(
client,
new RequestIdAllocator(),
new AbortController().signal,
);
expect(state.data).toEqual(validState);
expect(request).toHaveBeenCalledWith(
"ClientStateAck",
{ SessionId: 7, VersionNumber: 2 },
{ id: 1 },
);
});
it("does not acknowledge malformed state", async () => {
const { client, request } = mockInitialSyncClient({
type: "ClientStateSync",
data: { ...validState, SyncMode: "invalid" },
});
await expect(
completeInitialSynchronization(
client,
new RequestIdAllocator(),
new AbortController().signal,
),
).rejects.toThrow("Response validation failed");
expect(request).not.toHaveBeenCalled();
});
it("rejects ErrorNoIota during initial synchronization", async () => {
const { client, request } = mockInitialSyncClient({
type: "ErrorNoIota",
data: {},
});
await expect(
completeInitialSynchronization(
client,
new RequestIdAllocator(),
new AbortController().signal,
),
).rejects.toThrow("No Iota is currently connected");
expect(request).not.toHaveBeenCalled();
});
it("rejects an acknowledgement protocol error", async () => {
const { client } = mockInitialSyncClient(undefined, {
type: "ErrorInvalidData",
data: {},
});
await expect(
completeInitialSynchronization(
client,
new RequestIdAllocator(),
new AbortController().signal,
),
).rejects.toThrow("State acknowledgement failed: ErrorInvalidData");
});
it("times out a missing acknowledgement", async () => {
vi.useFakeTimers();
const { client } = mockInitialSyncClient();
vi.mocked(client.request).mockReturnValue(new Promise(() => {}));
const result = completeInitialSynchronization(
client,
new RequestIdAllocator(),
new AbortController().signal,
100,
10,
);
const assertion = expect(result).rejects.toThrow(
"State acknowledgement timed out",
);
await vi.advanceTimersByTimeAsync(10);
await assertion;
});
it("stops immediately when the connection attempt is cancelled", async () => {
const { client } = mockInitialSyncClient();
vi.mocked(client.auth).mockImplementation(() => new Promise(() => {}));
const controller = new AbortController();
const result = completeInitialSynchronization(
client,
new RequestIdAllocator(),
controller.signal,
);
controller.abort(new Error("MTP connection lost"));
await expect(result).rejects.toThrow("MTP connection lost");
});
it("times out authentication while waiting for initial state", async () => {
vi.useFakeTimers();
const { client, handlers } = mockInitialSyncClient();
vi.mocked(client.auth).mockImplementation(() => {
handlers.get("ClientStateSync")?.({
type: "ClientStateSync",
data: validState,
} as never);
return new Promise(() => {});
});
const result = completeInitialSynchronization(
client,
new RequestIdAllocator(),
new AbortController().signal,
100,
10,
);
const assertion = expect(result).rejects.toThrow(
"MTP authentication timed out",
);
await vi.advanceTimersByTimeAsync(100);
await assertion;
});
it("uses a fresh request ID namespace for each connection", async () => {
const first = mockInitialSyncClient();
const second = mockInitialSyncClient();
await completeInitialSynchronization(
first.client,
new RequestIdAllocator(),
new AbortController().signal,
);
await completeInitialSynchronization(
second.client,
new RequestIdAllocator(),
new AbortController().signal,
);
expect(first.request.mock.calls[0]?.[2]).toEqual({ id: 1 });
expect(second.request.mock.calls[0]?.[2]).toEqual({ id: 1 });
});
});

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,7 @@
export { Provider, useMTP } from "./context";
export { RequestIdAllocator } from "./requestIds";
export type {
BoundSendFn,
MTPExchange,
MTPInterceptor,
PushHandler,
ProtocolMessage,
} from "./context";
} from "./mtpContext";

View file

@ -0,0 +1,159 @@
import { createContext, useCallback, useRef } from "react";
import type {
MTPRequestFunction,
MTPResponseFrame,
MTPSubscriptionFunction,
} from "mtp";
import {
mtp as mtpSchemas,
type Calls,
type Communities,
type Contacts,
} from "@tensamin/shared/data";
import { log } from "@tensamin/shared/log";
export type ProtocolMessage<
Type extends keyof typeof mtpSchemas & string = keyof typeof mtpSchemas &
string,
> = MTPResponseFrame<typeof mtpSchemas, Type>;
export type BoundSendFn = MTPRequestFunction<typeof mtpSchemas>;
export type MTPExchange = {
type: keyof typeof mtpSchemas & string;
data: unknown;
response: ProtocolMessage;
};
export type MTPInterceptor = (exchange: MTPExchange) => void | Promise<void>;
export type MTPContextType = {
send: BoundSendFn;
subscribe: MTPSubscriptionFunction<typeof mtpSchemas>;
addInterceptor: (interceptor: MTPInterceptor) => () => void;
readyState: number;
identified: boolean;
freshContacts: Contacts;
freshCommunities: Communities;
freshCalls: Calls;
contextReady: boolean;
loadingDescription: string;
};
export const MTPContext = createContext<MTPContextType | undefined>(undefined);
export function removeMissingContacts(
contacts: Contacts,
message: ProtocolMessage<"GetStates">,
): Contacts {
const missing = new Set(message.data.MissingUserIds ?? []);
return contacts.filter((contact) => !missing.has(contact.UserId));
}
export function useMessageHandlers() {
const interceptorsRef = useRef(new Set<MTPInterceptor>());
const subscriptionHandlersRef = useRef(
new Map<string, Set<(message: ProtocolMessage) => void | Promise<void>>>(),
);
const transportRef = useRef<{
subscribe: MTPSubscriptionFunction<typeof mtpSchemas>;
} | null>(null);
const transportGenerationRef = useRef(0);
const transportUnsubscribersRef = useRef(new Map<string, () => void>());
const lastInitialStateRef = useRef<ProtocolMessage<"GetStates"> | null>(null);
const attachType = useCallback(
<Type extends keyof typeof mtpSchemas & string>(type: Type) => {
const transport = transportRef.current;
if (!transport || transportUnsubscribersRef.current.has(type)) return;
const generation = transportGenerationRef.current;
const unsubscribe = transport.subscribe(type, (message) => {
if (
transportRef.current !== transport ||
transportGenerationRef.current !== generation
)
return;
if (type === "GetStates") {
lastInitialStateRef.current = message as ProtocolMessage<"GetStates">;
}
for (const handler of [
...(subscriptionHandlersRef.current.get(type) ?? []),
]) {
void Promise.resolve(handler(message as ProtocolMessage)).catch(
(error) => {
log(1, "mtp", "red", "Subscription handler failed", error, {
type,
});
},
);
}
});
transportUnsubscribersRef.current.set(type, unsubscribe);
},
[],
);
const attachSubscriptions = useCallback(
(transport: { subscribe: MTPSubscriptionFunction<typeof mtpSchemas> }) => {
for (const unsubscribe of transportUnsubscribersRef.current.values()) {
unsubscribe();
}
transportUnsubscribersRef.current.clear();
transportRef.current = transport;
const generation = ++transportGenerationRef.current;
for (const type of subscriptionHandlersRef.current.keys()) {
attachType(type as keyof typeof mtpSchemas & string);
}
return () => {
if (
transportRef.current !== transport ||
transportGenerationRef.current !== generation
)
return;
transportRef.current = null;
transportGenerationRef.current += 1;
for (const unsubscribe of transportUnsubscribersRef.current.values()) {
unsubscribe();
}
transportUnsubscribersRef.current.clear();
};
},
[attachType],
);
const subscribe = useCallback<MTPSubscriptionFunction<typeof mtpSchemas>>(
(type, handler) => {
const handlers = subscriptionHandlersRef.current.get(type) ?? new Set();
const untypedHandler = handler as (
message: ProtocolMessage,
) => void | Promise<void>;
handlers.add(untypedHandler);
subscriptionHandlersRef.current.set(type, handlers);
attachType(type);
const initialState = lastInitialStateRef.current;
if (type === "GetStates" && initialState) {
void Promise.resolve(untypedHandler(initialState)).catch(
() => undefined,
);
}
return () => {
handlers.delete(untypedHandler);
if (handlers.size !== 0) return;
subscriptionHandlersRef.current.delete(type);
transportUnsubscribersRef.current.get(type)?.();
transportUnsubscribersRef.current.delete(type);
};
},
[attachType],
);
const addInterceptor = useCallback((interceptor: MTPInterceptor) => {
interceptorsRef.current.add(interceptor);
return () => interceptorsRef.current.delete(interceptor);
}, []);
return {
addInterceptor,
attachSubscriptions,
interceptorsRef,
subscribe,
};
}

View file

@ -1,44 +0,0 @@
import { describe, expect, it } from "vitest";
import { fromWireData, toWireData } from "./protocolFields";
describe("MTP protocol field translation", () => {
it("maps application message fields to MTP wire fields", () => {
expect(
toWireData({
Messages: [{ Content: "abc", MessageId: 4 }],
}),
).toEqual({
Messages: [{ AppContent: "abc", AppMessageId: 4 }],
});
});
it("maps MTP wire fields back to application fields", () => {
expect(
fromWireData({
AppCreatedAt: 123,
Message: { AppContent: "abc", AppMessageId: 4 },
}),
).toEqual({
CreatedAt: 123,
Message: { Content: "abc", MessageId: 4 },
});
});
it("preserves byte arrays and unrelated fields", () => {
const bytes = new Uint8Array([1, 2, 3]);
const translated = toWireData({ Payload: bytes, Other: "value" }) as {
Payload: Uint8Array;
Other: string;
};
expect(translated.Payload).toBe(bytes);
expect(translated.Other).toBe("value");
});
it("rejects field mapping collisions", () => {
expect(() => toWireData({ Content: "a", AppContent: "b" })).toThrow(
"MTP field translation collision",
);
});
});

View file

@ -1,58 +0,0 @@
const APPLICATION_TO_WIRE_FIELDS = {
Content: "AppContent",
CreatedAt: "AppCreatedAt",
MessageId: "AppMessageId",
} as const;
const WIRE_TO_APPLICATION_FIELDS = {
AppContent: "Content",
AppCreatedAt: "CreatedAt",
AppMessageId: "MessageId",
} as const;
function mapProtocolFields(
value: unknown,
fieldMap: Readonly<Record<string, string>>,
): unknown {
if (
value === null ||
typeof value !== "object" ||
value instanceof Uint8Array
) {
return value;
}
if (Array.isArray(value)) {
return value.map((item) => mapProtocolFields(item, fieldMap));
}
const source = value as Record<string, unknown>;
const target: Record<string, unknown> = {};
for (const [key, child] of Object.entries(source)) {
const mappedKey = fieldMap[key] ?? key;
if (mappedKey in target) {
throw new Error(`MTP field translation collision for ${mappedKey}`);
}
target[mappedKey] = mapProtocolFields(child, fieldMap);
}
return target;
}
export function toWireData(value: unknown): unknown {
return mapProtocolFields(value, APPLICATION_TO_WIRE_FIELDS);
}
export function fromWireData(value: unknown): unknown {
return mapProtocolFields(value, WIRE_TO_APPLICATION_FIELDS);
}
export function fromWireMessage<T extends { data: unknown }>(message: T): T {
return {
...message,
data: fromWireData(message.data),
};
}

View file

@ -1,25 +0,0 @@
import { describe, expect, it } from "vitest";
import { RequestIdAllocator } from "./requestIds";
describe("MTP request ID allocation", () => {
it("allocates nonzero request IDs monotonically", () => {
const ids = new RequestIdAllocator();
expect(ids.allocate()).toBe(1);
expect(ids.allocate()).toBe(2);
expect(new RequestIdAllocator().allocate()).toBe(1);
});
it("does not wrap exhausted request IDs", () => {
const ids = new RequestIdAllocator(0x1_0000_0000);
expect(() => ids.allocate()).toThrow("MTP request ID space exhausted");
});
it("rejects invalid allocator states", () => {
expect(() => new RequestIdAllocator(0)).toThrow(
"invalid MTP request ID allocator state",
);
});
});

View file

@ -1,24 +0,0 @@
const MAX_MTP_REQUEST_ID = 0xffff_ffff;
export class RequestIdAllocator {
#next: number;
constructor(next = 1) {
if (
!Number.isSafeInteger(next) ||
next <= 0 ||
next > MAX_MTP_REQUEST_ID + 1
) {
throw new RangeError("invalid MTP request ID allocator state");
}
this.#next = next;
}
allocate(): number {
if (this.#next > MAX_MTP_REQUEST_ID) {
throw new Error("MTP request ID space exhausted for this connection");
}
return this.#next++;
}
}

258
packages/mtp/src/tauri.tsx Normal file
View file

@ -0,0 +1,258 @@
import {
type ReactNode,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import {
ConnectionState,
MTPProxyConnection,
type MTPFrame,
type MTPProxyAdapter,
} from "mtp";
import {
mtp as mtpSchemas,
type Calls,
type Communities,
type Contacts,
} from "@tensamin/shared/data";
import { log } from "@tensamin/shared/log";
import {
type BoundSendFn,
MTPContext,
type ProtocolMessage,
removeMissingContacts,
useMessageHandlers,
} from "./mtpContext";
type NativeSnapshot = {
generation: number;
readyState: number;
identified: boolean;
state?: unknown;
error?: string;
};
function createTauriAdapter() {
const subscriptions = new Map<string, Set<(message: MTPFrame) => void>>();
const adapter: MTPProxyAdapter = {
request: (type, data) =>
invoke<MTPFrame>("mtp_request", { typeName: type, data }),
subscribe(type, handler) {
const handlers = subscriptions.get(type) ?? new Set();
handlers.add(handler);
subscriptions.set(type, handlers);
return () => {
handlers.delete(handler);
if (handlers.size === 0) subscriptions.delete(type);
};
},
};
return {
adapter,
dispatch(message: MTPFrame) {
for (const handler of subscriptions.get(message.type) ?? [])
handler(message);
},
};
}
export function TauriProvider(props: {
children: ReactNode;
blockConnection?: boolean;
}) {
const [snapshot, setSnapshot] = useState<NativeSnapshot>({
generation: 0,
readyState: ConnectionState.Disconnected,
identified: false,
});
const [freshContacts, setFreshContacts] = useState<Contacts>([]);
const [freshCommunities, setFreshCommunities] = useState<Communities>([]);
const [freshCalls, setFreshCalls] = useState<Calls>([]);
const generationRef = useRef(0);
const { addInterceptor, attachSubscriptions, interceptorsRef, subscribe } =
useMessageHandlers();
const [{ bridge, connection }] = useState(() => {
const bridge = createTauriAdapter();
return {
bridge,
connection: new MTPProxyConnection(bridge.adapter, {
schemas: mtpSchemas,
throwProtocolErrors: true,
onValidationError: (error) => {
log(1, "mtp", "red", "Failed to validate native MTP message", error);
},
}),
};
});
const applySnapshot = useCallback(async (next: NativeSnapshot) => {
if (next.generation < generationRef.current) return;
generationRef.current = next.generation;
if (next.error)
log(0, "android", "orange", "MTP connection failed", next.error);
if (!next.identified) {
setSnapshot(next);
return;
}
if (next.state === undefined) {
setSnapshot({
...next,
identified: false,
error: "Native MTP connection omitted initial state",
});
return;
}
try {
const state = await mtpSchemas.ClientStateSync.response.parseAsync(
next.state,
);
setFreshContacts(state.Contacts);
setFreshCommunities(state.Communities);
setFreshCalls(state.Calls);
setSnapshot(next);
} catch (error) {
log(0, "mtp", "red", "Invalid native MTP state", error);
setSnapshot({
...next,
identified: false,
error: "Invalid ClientStateSync payload",
});
}
}, []);
const dispatchMessage = useCallback(
(message: MTPFrame) => {
bridge.dispatch(message);
},
[bridge],
);
useEffect(() => {
return attachSubscriptions(connection);
}, [attachSubscriptions, connection]);
useEffect(
() =>
subscribe("GetStates", (message) => {
setFreshContacts((contacts) =>
removeMissingContacts(contacts, message),
);
}),
[subscribe],
);
useEffect(() => {
if (props.blockConnection) return;
let disposed = false;
let unlisten: UnlistenFn | undefined;
void (async () => {
try {
const nextUnlisten = await listen<
| { kind: "state"; snapshot: NativeSnapshot }
| { kind: "message"; generation: number; message: MTPFrame }
| { kind: "log"; level: number; message: string; details?: unknown }
>("mtp://event", ({ payload }) => {
if (disposed) return;
if (payload.kind === "state") {
void applySnapshot(payload.snapshot);
} else if (payload.kind === "message") {
if (payload.generation === generationRef.current) {
dispatchMessage(payload.message);
}
} else {
log(
payload.level,
"android",
"orange",
payload.message,
payload.details,
);
}
});
if (disposed) nextUnlisten();
else unlisten = nextUnlisten;
} catch (error) {
log(0, "mtp", "red", "Failed to subscribe to native MTP events", error);
}
try {
const current = await invoke<NativeSnapshot>("mtp_status");
if (!disposed) await applySnapshot(current);
} catch (error) {
log(0, "mtp", "red", "Failed to load native MTP status", error);
}
})();
return () => {
disposed = true;
unlisten?.();
};
}, [applySnapshot, dispatchMessage, props.blockConnection]);
useEffect(() => {
if (props.blockConnection) return;
const updateVisibility = () => {
void invoke("mtp_set_ui_visible", {
visible: document.visibilityState === "visible" && document.hasFocus(),
});
};
updateVisibility();
document.addEventListener("visibilitychange", updateVisibility);
window.addEventListener("focus", updateVisibility);
window.addEventListener("blur", updateVisibility);
return () => {
document.removeEventListener("visibilitychange", updateVisibility);
window.removeEventListener("focus", updateVisibility);
window.removeEventListener("blur", updateVisibility);
void invoke("mtp_set_ui_visible", { visible: false });
};
}, [props.blockConnection]);
const send = useCallback<BoundSendFn>(
async (type, data, options) => {
const response = await connection.request(type, data, options);
if (response.type === "GetStates") {
setFreshContacts((contacts) =>
removeMissingContacts(
contacts,
response as ProtocolMessage<"GetStates">,
),
);
}
for (const interceptor of interceptorsRef.current) {
void Promise.resolve(interceptor({ type, data, response })).catch(
(error) => {
log(1, "mtp", "yellow", "MTP interceptor failed", error, { type });
},
);
}
return response;
},
[connection, interceptorsRef],
);
const connected = snapshot.readyState === ConnectionState.Connected;
return (
<MTPContext.Provider
value={{
send,
subscribe,
addInterceptor,
readyState: snapshot.readyState,
identified: snapshot.identified,
freshContacts,
freshCommunities,
freshCalls,
contextReady: connected && snapshot.identified,
loadingDescription: connected
? "Waiting for authenticated session"
: "Establishing native transport channel",
}}
>
{props.children}
</MTPContext.Provider>
);
}