Use branded ids in mobile runtime flows

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-05-03 20:29:53 -07:00
1 parent 96897ab346
commit b4615a847a
20 files changed
+133 -110

No files matched your search

+3 -2
View File
@@ -1,5 +1,6 @@
import { Link, Stack } from "expo-router";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -19,12 +20,12 @@ export default function ConnectionsRouteScreen() {
} = useRemoteConnections();
const insets = useSafeAreaInsets();
const hasEnvironments = connectedEnvironments.length > 0;
const [expandedId, setExpandedId] = useState<string | null>(null);
const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);
const primaryFg = useThemeColor("--color-primary-foreground");
const accentColor = useThemeColor("--color-icon-muted");
const handleToggle = useCallback((environmentId: string) => {
const handleToggle = useCallback((environmentId: EnvironmentId) => {
setExpandedId((prev) => (prev === environmentId ? null : environmentId));
}, []);
@@ -1,9 +1,10 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
export default function ReviewRoute() {
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: string;
threadId: string;
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
return (
@@ -1,6 +1,7 @@
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { TextInputWrapper } from "expo-paste-input";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useEffect, useMemo, useState } from "react";
import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
@@ -47,8 +48,8 @@ export function ReviewCommentComposerSheet() {
const iconTint = String(useThemeColor("--color-icon"));
const target = useReviewCommentTarget();
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: string;
threadId: string;
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
const [commentText, setCommentText] = useState("");
const [highlightedLinesById, setHighlightedLinesById] = useState<
@@ -1,4 +1,4 @@
import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams } from "expo-router";
import Stack from "expo-router/stack";
import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -360,7 +360,7 @@ export function ReviewSheet() {
setError(null);
try {
const result = await client.orchestration.getTurnDiff({
threadId: ThreadId.make(threadId),
threadId,
fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
toTurnCount: checkpoint.checkpointTurnCount,
});
@@ -1,6 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { EnvironmentId, ThreadId, type GitReviewDiffSection } from "@t3tools/contracts";
import type { EnvironmentId, GitReviewDiffSection, ThreadId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { scopedThreadKey } from "../../lib/scopedEntities";
@@ -79,11 +79,11 @@ const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>
);
function buildThreadKey(input: {
readonly environmentId?: string;
readonly threadId?: string;
readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId;
}): string | null {
return input.environmentId && input.threadId
? scopedThreadKey(EnvironmentId.make(input.environmentId), ThreadId.make(input.threadId))
? scopedThreadKey(input.environmentId, input.threadId)
: null;
}
@@ -92,8 +92,8 @@ function buildSectionCacheKey(threadKey: string, sectionId: string): string {
}
export function useReviewCacheForThread(input: {
readonly environmentId?: string;
readonly threadId?: string;
readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId;
}) {
const threadKey = buildThreadKey(input);
const gitSections = useAtomValue(
@@ -10,9 +10,13 @@ export interface PendingUserInputCardProps {
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (requestId: string, questionId: string, label: string) => void;
readonly onSelectOption: (
requestId: ApprovalRequestId,
questionId: string,
label: string,
) => void;
readonly onChangeCustomAnswer: (
requestId: string,
requestId: ApprovalRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -7,6 +7,7 @@ import type {
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
ThreadId,
} from "@t3tools/contracts";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import * as Haptics from "expo-haptics";
@@ -77,9 +78,13 @@ export interface ThreadDetailScreenProps {
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<void>;
readonly onSelectUserInputOption: (requestId: string, questionId: string, label: string) => void;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
questionId: string,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
requestId: string,
requestId: ApprovalRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -107,7 +112,7 @@ function latestStreamingAssistantMessage(
return null;
}
function useStreamingHaptics(threadId: string, feed: ReadonlyArray<ThreadFeedEntry>) {
function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedEntry>) {
const lastStreamingAssistantRef = useRef<{
readonly id: string;
readonly textLength: number;
@@ -2,6 +2,7 @@ import * as Clipboard from "expo-clipboard";
import * as Haptics from "expo-haptics";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { ThreadId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
@@ -32,7 +33,7 @@ import { relativeTime } from "../../lib/time";
import { messageImageUrl } from "./threadPresentation";
export interface ThreadFeedProps {
readonly threadId: string;
readonly threadId: ThreadId;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly httpBaseUrl: string | null;
readonly bearerToken: string | null;
@@ -1,4 +1,10 @@
import type { GitRunStackedActionResult, ProjectScript, VcsStatusResult } from "@t3tools/contracts";
import type {
EnvironmentId,
GitRunStackedActionResult,
ProjectScript,
ThreadId,
VcsStatusResult,
} from "@t3tools/contracts";
import {
type GitActionRequestInput,
requiresDefaultBranchConfirmation,
@@ -73,8 +79,8 @@ export function ThreadGitControls(props: {
}) {
const router = useRouter();
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: string;
threadId: string;
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
@@ -4,6 +4,7 @@ import {
getGitActionDisabledReason,
requiresDefaultBranchConfirmation,
} from "@t3tools/client-runtime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useLocalSearchParams, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
import { useCallback, useEffect, useMemo } from "react";
@@ -24,8 +25,8 @@ export function GitOverviewSheet() {
const router = useRouter();
const insets = useSafeAreaInsets();
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: string;
threadId: string;
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
const { selectedThread } = useThreadSelection();
const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
@@ -61,7 +61,7 @@ type NewTaskFlowContextValue = {
readonly key: string;
readonly project: EnvironmentScopedProjectShell;
}>;
readonly selectedEnvironmentId: EnvironmentId;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly selectedModelKey: string | null;
readonly workspaceMode: WorkspaceMode;
@@ -144,8 +144,8 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[repositoryGroups],
);
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(
projects[0]?.environmentId ?? "",
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
projects[0]?.environmentId ?? null,
);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
@@ -192,7 +192,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
defaultEnvironmentId: projects[0]?.environmentId ?? null,
projectCount: projects.length,
});
setSelectedEnvironmentId(projects[0]?.environmentId ?? "");
setSelectedEnvironmentId(projects[0]?.environmentId ?? null);
setSelectedProjectKey(null);
setSelectedModelKey(null);
setWorkspaceMode("local");
@@ -211,7 +211,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}, [clearAttachments, projects]);
useEffect(() => {
if (selectedEnvironmentId || projects.length === 0) {
if (selectedEnvironmentId !== null || projects.length === 0) {
return;
}
+6 -5
View File
@@ -1,19 +1,20 @@
import type { Href, Router } from "expo-router";
import type { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { SelectedThreadRef } from "../state/remote-runtime-types";
import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
type ThreadRouteInput =
| Pick<SelectedThreadRef, "environmentId" | "threadId">
| Pick<EnvironmentScopedThreadShell, "environmentId" | "id">;
type PlainThreadRouteInput =
| {
environmentId: string;
threadId: string;
environmentId: EnvironmentId;
threadId: ThreadId;
}
| {
environmentId: string;
id: string;
environmentId: EnvironmentId;
id: ThreadId;
};
export function buildThreadRoutePath(input: ThreadRouteInput | PlainThreadRouteInput): string {
+2 -1
View File
@@ -1,6 +1,7 @@
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as SecureStore from "expo-secure-store";
import type { EnvironmentId } from "@t3tools/contracts";
import type { SavedRemoteConnection } from "./connection";
@@ -58,7 +59,7 @@ export async function saveConnection(connection: SavedRemoteConnection): Promise
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
}
export async function clearSavedConnection(environmentId: string): Promise<void> {
export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
const current = await loadSavedConnections();
const next = pipe(
current,
+21 -18
View File
@@ -1,6 +1,5 @@
import { isToolLifecycleItemType } from "@t3tools/contracts";
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
import type {
ApprovalRequestId,
CommandId,
EnvironmentId,
MessageId,
@@ -130,6 +129,10 @@ function isStalePendingRequestFailureDetail(detail: string | undefined): boolean
);
}
function parseApprovalRequestId(value: unknown): ApprovalRequestId | null {
return typeof value === "string" && value.length > 0 ? ApprovalRequestId.make(value) : null;
}
function parseUserInputQuestions(
payload: Record<string, unknown> | null,
): ReadonlyArray<UserInputQuestion> | null {
@@ -764,7 +767,7 @@ export function derivePendingApprovals(
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const requestId = payload?.requestId;
const requestId = parseApprovalRequestId(payload?.requestId);
const requestKind =
payload?.requestKind === "command" ||
payload?.requestKind === "file-read" ||
@@ -773,9 +776,9 @@ export function derivePendingApprovals(
: requestKindFromRequestType(payload?.requestType);
const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
if (activity.kind === "approval.requested" && typeof requestId === "string" && requestKind) {
openByRequestId.set(requestId as ApprovalRequestId, {
requestId: requestId as ApprovalRequestId,
if (activity.kind === "approval.requested" && requestId && requestKind) {
openByRequestId.set(requestId, {
requestId,
requestKind,
createdAt: activity.createdAt,
...(detail ? { detail } : {}),
@@ -783,17 +786,17 @@ export function derivePendingApprovals(
continue;
}
if (activity.kind === "approval.resolved" && typeof requestId === "string") {
openByRequestId.delete(requestId as ApprovalRequestId);
if (activity.kind === "approval.resolved" && requestId) {
openByRequestId.delete(requestId);
continue;
}
if (
activity.kind === "provider.approval.respond.failed" &&
typeof requestId === "string" &&
requestId &&
isStalePendingRequestFailureDetail(detail)
) {
openByRequestId.delete(requestId as ApprovalRequestId);
openByRequestId.delete(requestId);
}
}
@@ -811,33 +814,33 @@ export function derivePendingUserInputs(
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const requestId = payload?.requestId;
const requestId = parseApprovalRequestId(payload?.requestId);
const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
if (activity.kind === "user-input.requested" && typeof requestId === "string") {
if (activity.kind === "user-input.requested" && requestId) {
const questions = parseUserInputQuestions(payload);
if (!questions) {
continue;
}
openByRequestId.set(requestId as ApprovalRequestId, {
requestId: requestId as ApprovalRequestId,
openByRequestId.set(requestId, {
requestId,
createdAt: activity.createdAt,
questions,
});
continue;
}
if (activity.kind === "user-input.resolved" && typeof requestId === "string") {
openByRequestId.delete(requestId as ApprovalRequestId);
if (activity.kind === "user-input.resolved" && requestId) {
openByRequestId.delete(requestId);
continue;
}
if (
activity.kind === "provider.user-input.respond.failed" &&
typeof requestId === "string" &&
requestId &&
isStalePendingRequestFailureDetail(detail)
) {
openByRequestId.delete(requestId as ApprovalRequestId);
openByRequestId.delete(requestId);
}
}
@@ -3,19 +3,19 @@ import {
type SourceControlDiscoveryTarget,
createSourceControlDiscoveryManager,
} from "@t3tools/client-runtime";
import { EnvironmentId, type SourceControlDiscoveryResult } from "@t3tools/contracts";
import type { EnvironmentId, SourceControlDiscoveryResult } from "@t3tools/contracts";
import { appAtomRegistry } from "./atom-registry";
import { getEnvironmentClient } from "./environment-session-registry";
export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({
export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager<EnvironmentId>({
getRegistry: () => appAtomRegistry,
getClient: (key) => getEnvironmentClient(EnvironmentId.make(key))?.server ?? null,
getClient: (environmentId) => getEnvironmentClient(environmentId)?.server ?? null,
});
export function sourceControlDiscoveryTargetForEnvironment(
environmentId: EnvironmentId | null,
): SourceControlDiscoveryTarget {
): SourceControlDiscoveryTarget<EnvironmentId> {
return { key: environmentId ?? null };
}
@@ -10,7 +10,7 @@ import {
EnvironmentConnectionState,
WsTransport,
} from "@t3tools/client-runtime";
import { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId } from "@t3tools/contracts";
import { resolveRemoteWebSocketConnectionUrl } from "@t3tools/shared/remote";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
@@ -222,7 +222,7 @@ export async function connectSavedEnvironment(
wsBaseUrl: connection.wsBaseUrl,
},
}),
environmentId: EnvironmentId.make(connection.environmentId),
environmentId: connection.environmentId,
},
client,
applyShellEvent: (event, environmentId) => {
@@ -6,7 +6,7 @@ import {
type GitBranch,
type GitActionRequestInput,
} from "@t3tools/client-runtime";
import { CommandId, type GitRunStackedActionResult, ThreadId } from "@t3tools/contracts";
import { CommandId, type GitRunStackedActionResult } from "@t3tools/contracts";
import {
dedupeRemoteBranchesWithLocalMatches,
sanitizeFeatureBranchName,
@@ -43,7 +43,7 @@ export function useSelectedThreadGitActions() {
await client.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: CommandId.make(uuidv4()),
threadId: ThreadId.make(thread.id),
threadId: thread.id,
...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
});
@@ -3,11 +3,11 @@ import { useCallback, useEffect, useMemo } from "react";
import { EnvironmentScopedThreadShell } from "@t3tools/client-runtime";
import {
ApprovalRequestId,
CommandId,
EnvironmentId,
MessageId,
ThreadId,
type ApprovalRequestId,
type EnvironmentId,
type ThreadId,
} from "@t3tools/contracts";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
import { Atom } from "effect/unstable/reactivity";
@@ -90,15 +90,12 @@ function appendDraftMessage(threadKey: string, value: string): void {
}
export function appendReviewCommentToDraft(input: {
readonly environmentId: string;
readonly threadId: string;
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly text: string;
readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
}): void {
const threadKey = scopedThreadKey(
EnvironmentId.make(input.environmentId),
ThreadId.make(input.threadId),
);
const threadKey = scopedThreadKey(input.environmentId, input.threadId);
const current = appAtomRegistry.get(draftMessageByThreadKeyAtom);
const existing = current[threadKey] ?? "";
const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";
@@ -112,14 +109,14 @@ export function appendReviewCommentToDraft(input: {
}
export function useThreadDraftForThread(input: {
readonly environmentId?: string;
readonly threadId?: string;
readonly environmentId?: EnvironmentId;
readonly threadId?: ThreadId;
}) {
const draftMessageByThreadKey = useAtomValue(draftMessageByThreadKeyAtom);
const draftAttachmentsByThreadKey = useAtomValue(draftAttachmentsByThreadKeyAtom);
const threadKey =
input.environmentId && input.threadId
? scopedThreadKey(EnvironmentId.make(input.environmentId), ThreadId.make(input.threadId))
? scopedThreadKey(input.environmentId, input.threadId)
: null;
return {
@@ -222,7 +219,7 @@ function setUserInputDraftCustomAnswer(
}
function useQueueDrain(input: {
readonly dispatchingQueuedMessageId: string | null;
readonly dispatchingQueuedMessageId: MessageId | null;
readonly queuedMessagesByThreadKey: Record<string, ReadonlyArray<QueuedThreadMessage>>;
readonly threads: ReadonlyArray<EnvironmentScopedThreadShell>;
readonly environments: ReadonlyArray<ConnectedEnvironmentSummary>;
@@ -378,10 +375,10 @@ export function useThreadComposerState() {
try {
await client.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: CommandId.make(queuedMessage.commandId),
threadId: ThreadId.make(queuedMessage.threadId),
commandId: queuedMessage.commandId,
threadId: queuedMessage.threadId,
message: {
messageId: MessageId.make(queuedMessage.messageId),
messageId: queuedMessage.messageId,
role: "user",
text: queuedMessage.text,
attachments: queuedMessage.attachments,
@@ -446,30 +443,24 @@ export function useThreadComposerState() {
}, [draftAttachmentsByThreadKey, draftMessageByThreadKey, selectedThreadShell]);
const onSelectUserInputOption = useCallback(
(requestId: string, questionId: string, label: string) => {
(requestId: ApprovalRequestId, questionId: string, label: string) => {
if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(
selectedThreadShell.environmentId,
requestId as ApprovalRequestId,
);
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
setUserInputDraftOption(requestKey, questionId, label);
},
[selectedThreadShell],
);
const onChangeUserInputCustomAnswer = useCallback(
(requestId: string, questionId: string, customAnswer: string) => {
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(
selectedThreadShell.environmentId,
requestId as ApprovalRequestId,
);
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
setUserInputDraftCustomAnswer(requestKey, questionId, customAnswer);
},
[selectedThreadShell],
+15 -10
View File
@@ -1,19 +1,24 @@
import type {
import {
EnvironmentId,
ProjectId,
ScopedProjectRef,
ScopedThreadRef,
ThreadId,
type EnvironmentId as EnvironmentIdType,
type ProjectId as ProjectIdType,
type ScopedProjectRef,
type ScopedThreadRef,
} from "@t3tools/contracts";
export function scopeProjectRef(
environmentId: EnvironmentId,
projectId: ProjectId,
environmentId: EnvironmentIdType,
projectId: ProjectIdType,
): ScopedProjectRef {
return { environmentId, projectId };
}
export function scopeThreadRef(environmentId: EnvironmentId, threadId: ThreadId): ScopedThreadRef {
export function scopeThreadRef(
environmentId: EnvironmentIdType,
threadId: ThreadId,
): ScopedThreadRef {
return { environmentId, threadId };
}
@@ -30,13 +35,13 @@ export function scopedThreadKey(ref: ScopedThreadRef): string {
return scopedRefKey(ref);
}
function parseScopedKey(key: string): { environmentId: EnvironmentId; localId: string } | null {
function parseScopedKey(key: string): { environmentId: EnvironmentIdType; localId: string } | null {
const separatorIndex = key.indexOf(":");
if (separatorIndex <= 0 || separatorIndex >= key.length - 1) {
return null;
}
return {
environmentId: key.slice(0, separatorIndex) as EnvironmentId,
environmentId: EnvironmentId.make(key.slice(0, separatorIndex)),
localId: key.slice(separatorIndex + 1),
};
}
@@ -48,7 +53,7 @@ export function parseScopedProjectKey(key: string): ScopedProjectRef | null {
}
return {
environmentId: parsed.environmentId,
projectId: parsed.localId as ProjectId,
projectId: ProjectId.make(parsed.localId),
};
}
@@ -59,6 +64,6 @@ export function parseScopedThreadKey(key: string): ScopedThreadRef | null {
}
return {
environmentId: parsed.environmentId,
threadId: parsed.localId as ThreadId,
threadId: ThreadId.make(parsed.localId),
};
}
@@ -9,8 +9,8 @@ export interface SourceControlDiscoveryState {
readonly isPending: boolean;
}
export interface SourceControlDiscoveryTarget {
readonly key: string | null;
export interface SourceControlDiscoveryTarget<TKey extends string = string> {
readonly key: TKey | null;
}
export interface SourceControlDiscoveryClient {
@@ -49,16 +49,16 @@ export const EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM = Atom.make(
/* --- Helpers -------------------------------------------------------- */
export function getSourceControlDiscoveryTargetKey(
target: SourceControlDiscoveryTarget,
): string | null {
const key = target.key?.trim();
export function getSourceControlDiscoveryTargetKey<TKey extends string>(
target: SourceControlDiscoveryTarget<TKey>,
): TKey | null {
const key = target.key;
return key && key.length > 0 ? key : null;
}
/* --- Refresh manager ------------------------------------------------ */
export interface SourceControlDiscoveryManagerConfig {
export interface SourceControlDiscoveryManagerConfig<TKey extends string = string> {
/**
* Get the atom registry used to read/write source-control discovery snapshots.
*/
@@ -70,10 +70,12 @@ export interface SourceControlDiscoveryManagerConfig {
* lets mobile or future multi-environment clients provide separate discovery
* clients without changing the state primitive.
*/
readonly getClient: (key: string) => SourceControlDiscoveryClient | null;
readonly getClient: (key: TKey) => SourceControlDiscoveryClient | null;
}
export function createSourceControlDiscoveryManager(config: SourceControlDiscoveryManagerConfig) {
export function createSourceControlDiscoveryManager<TKey extends string = string>(
config: SourceControlDiscoveryManagerConfig<TKey>,
) {
const refreshInFlight = new Map<string, Promise<SourceControlDiscoveryResult | null>>();
const refreshVersions = new Map<string, number>();
@@ -144,7 +146,7 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove
* @param client Optional pre-resolved client, useful in tests.
*/
function refresh(
target: SourceControlDiscoveryTarget,
target: SourceControlDiscoveryTarget<TKey>,
client?: SourceControlDiscoveryClient,
): Promise<SourceControlDiscoveryResult | null> {
const targetKey = getSourceControlDiscoveryTargetKey(target);
@@ -195,7 +197,7 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove
* refresh for that target. If no target is provided, every known target is
* invalidated.
*/
function invalidate(target?: SourceControlDiscoveryTarget): void {
function invalidate(target?: SourceControlDiscoveryTarget<TKey>): void {
if (!target) {
reset();
return;
@@ -217,7 +219,7 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove
* Invalid targets return the inert empty state rather than creating a new
* family atom entry.
*/
function getSnapshot(target: SourceControlDiscoveryTarget): SourceControlDiscoveryState {
function getSnapshot(target: SourceControlDiscoveryTarget<TKey>): SourceControlDiscoveryState {
const targetKey = getSourceControlDiscoveryTargetKey(target);
if (targetKey === null) {
return EMPTY_SOURCE_CONTROL_DISCOVERY_STATE;