镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
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
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { ProviderDriverKind } from "@t3tools/contracts";

const refreshProviders = vi.hoisted(() => vi.fn());
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));

vi.mock("../../state/queries", () => ({
Expand All @@ -15,10 +14,10 @@ vi.mock("../../state/use-composer-drafts", () => ({
}));
vi.mock("../../lib/uuid", () => ({ uuidv4: () => "context-id" }));
vi.mock("../../state/server", () => ({
serverEnvironment: { refreshProviders: Symbol("refreshProviders") },
}));
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: () => refreshProviders,
serverEnvironment: {
providersValueAtom: vi.fn(),
refreshProviders: Symbol("refreshProviders"),
},
}));

import {
Expand Down
138 changes: 28 additions & 110 deletions apps/mobile/src/features/threads/use-composer-command-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThread
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";

const EMPTY_THREAD_SHELLS: ReadonlyArray<EnvironmentThreadShell> = [];
import {
COMPOSER_CONTEXT_MAX_RECORDS,
PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
} from "@t3tools/contracts";
import { COMPOSER_CONTEXT_MAX_RECORDS } from "@t3tools/contracts";
import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
import { pullRequestComposerContext, threadComposerContext } from "../../lib/composerContext";
import { uuidv4 } from "../../lib/uuid";
Expand All @@ -36,20 +33,20 @@ import {
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
createProviderWorkspaceSnapshotRefreshAtomFamily,
dedupeProviderSkillsByName,
getProviderSkillsForSlashMenu,
getProviderSlashCommandsForSlashMenu,
isProviderSkillUserInvocable,
hasCompleteProviderWorkspaceSnapshot,
hasCurrentProviderWorkspaceSnapshot,
resolveProviderSkillsForCwd,
resolveProviderSlashCommandsForCwd,
} from "@t3tools/client-runtime/providerSkills";
import { useAtomRefresh } from "@effect/atom-react";
import { Atom } from "effect/reactivity";
import { useEffect, useRef, useState } from "react";

import type { ComposerEditorSelection } from "../../components/ComposerEditor";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import {
useComposerPathSearch,
useComposerPullRequestSearch,
Expand All @@ -58,9 +55,14 @@ import {
import type { ComposerCommandItem } from "./ComposerCommandPopover";
import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";

const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
const providerWorkspaceSnapshotRefresh = createProviderWorkspaceSnapshotRefreshAtomFamily({
providers: serverEnvironment.providersValueAtom,
refreshProviders: serverEnvironment.refreshProviders,
});

const idleWorkspaceSnapshotRefreshAtom: Atom.Atom<unknown> = Atom.make<void>(undefined).pipe(
Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"),
);

function composerSelectionAtEnd(draftMessage: string): ComposerEditorSelection {
return { start: draftMessage.length, end: draftMessage.length };
Expand Down Expand Up @@ -214,9 +216,6 @@ export function useComposerCommandMenu({
// Thread mentions rank by recency as of when the composer mounted.
const [now] = useState(() => Date.now());
const previousOwnerKeyRef = useRef(ownerKey);
const onSelectionChange = (nextSelection: ComposerEditorSelection) => {
setSelection(nextSelection);
};
useEffect(() => {
const inserted = ownerKey ? readComposerDraftSelection(ownerKey, draftMessage) : null;
if (inserted) {
Expand Down Expand Up @@ -245,109 +244,28 @@ export function useComposerCommandMenu({
const skills = selectedProviderStatus
? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd)
: [];
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
const selectedProviderInstanceId = selectedProviderStatus?.instanceId;
const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(
selectedProviderStatus,
projectCwd,
);
// Record client request time to enforce TTL even when the client clock runs ahead of the server.
const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
const failedRefreshesRef = useRef<{ key: string; count: number } | null>(null);
const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
key: string;
notBefore: number;
} | null>(null);
const workspaceRefreshScopeKey =
const refreshWorkspaceSnapshot = useAtomRefresh(
environmentId && projectCwd && selectedProviderInstanceId
? `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`
: null;
const workspaceSlashCommandsPending =
selectedProviderStatus?.workspaceSnapshots?.some(
(snapshot) => snapshot.cwd === projectCwd && snapshot.slashCommandsPending === true,
) ?? false;
useEffect(() => {
if (
!workspaceSlashCommandsPending ||
!workspaceRefreshRetry ||
workspaceRefreshRetry.key !== workspaceRefreshScopeKey
)
return;
const timeout = setTimeout(
() => {
setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
},
Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
);
return () => clearTimeout(timeout);
}, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
const hadWorkspaceSnapshotRef = useRef(false);
useEffect(() => {
if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
workspaceRefreshKeyRef.current = null;
setWorkspaceRefreshRetry(null);
}
hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
}, [hasWorkspaceSnapshot]);
? providerWorkspaceSnapshotRefresh({
environmentId,
instanceId: selectedProviderInstanceId,
cwd: projectCwd,
})
: idleWorkspaceSnapshotRefreshAtom,
);
// Every draft change rechecks a stale snapshot, including drafts written by
// another surface (a prompt link) that never move the editor selection.
useEffect(() => {
if (!environmentId || !projectCwd || !selectedProviderInstanceId) return;
const key = `${environmentId}:${selectedProviderInstanceId}:${projectCwd}`;
const now = Date.now();
const lastRequest = workspaceRefreshKeyRef.current;
if (
lastRequest?.key === key &&
now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
)
return;
if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, projectCwd, now)) {
// oxlint-disable-next-line react/set-state-in-effect -- A current provider workspace snapshot clears the pending refresh retry.
setWorkspaceRefreshRetry(null);
return;
}
const retry = workspaceRefreshRetry;
if (retry?.key === key && now < retry.notBefore) return;
const request = { key, requestedAt: now };
workspaceRefreshKeyRef.current = request;
const retryLater = () => {
if (workspaceRefreshKeyRef.current !== request) return;
const failed = failedRefreshesRef.current;
const count = failed?.key === key ? failed.count + 1 : 1;
failedRefreshesRef.current = { key, count };
// Keeping the request marker lets the TTL hold off the next scan.
if (count >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return;
workspaceRefreshKeyRef.current = null;
setWorkspaceRefreshRetry({
key,
notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
});
};
void refreshProviders({
environmentId,
input: { instanceId: selectedProviderInstanceId, cwd: projectCwd },
}).then((result) => {
const refreshed =
result._tag === "Success" &&
hasCompleteProviderWorkspaceSnapshot(
result.value.providers.find(
(provider) => provider.instanceId === selectedProviderInstanceId,
),
projectCwd,
);
if (!refreshed) retryLater();
else failedRefreshesRef.current = null;
}, retryLater);
refreshWorkspaceSnapshot();
}, [
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Typing in the draft re-checks whether the provider workspace snapshot needs refreshing.
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Draft changes are the recheck signal.
draftMessage,
environmentId,
projectCwd,
refreshProviders,
selectedProviderInstanceId,
selectedProviderStatus,
workspaceRefreshRetry,
refreshWorkspaceSnapshot,
]);
const onSelectionChange = (nextSelection: ComposerEditorSelection) => {
setSelection(nextSelection);
};

const trigger = (() => {
if (!enabled || selection.start !== selection.end) {
Comment thread
juliusmarminge marked this conversation as resolved.
Resolved
Expand Down
3 changes: 1 addition & 2 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1006,8 +1006,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const refreshWorkspaceSnapshotOnTyping = useProviderWorkspaceSnapshotRefresh({
environmentId,
gitCwd,
selectedProviderEntry,
selectedProviderStatus: selectedProviderStatus,
instanceId: selectedProviderEntry?.instanceId,
});

const selectedPromptEffort = composerProviderState.promptEffort;
Expand Down
158 changes: 22 additions & 136 deletions apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts
Original file line number Diff line number Diff line change
@@ -1,146 +1,32 @@
import {
type EnvironmentId,
PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
type ServerProvider,
} from "@t3tools/contracts";
import { type ProviderInstanceEntry } from "../../providerInstances";
import {
hasCompleteProviderWorkspaceSnapshot,
hasCurrentProviderWorkspaceSnapshot,
} from "@t3tools/client-runtime/providerSkills";
import { useAtomRefresh } from "@effect/atom-react";
import { type EnvironmentId, type ProviderInstanceId } from "@t3tools/contracts";
import { createProviderWorkspaceSnapshotRefreshAtomFamily } from "@t3tools/client-runtime/providerSkills";
import { Atom } from "effect/reactivity";

import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { useStableCallback } from "../../hooks/useStableCallback";

const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
const providerWorkspaceSnapshotRefresh = createProviderWorkspaceSnapshotRefreshAtomFamily({
providers: serverEnvironment.providersValueAtom,
refreshProviders: serverEnvironment.refreshProviders,
});

const idleRefreshAtom: Atom.Atom<unknown> = Atom.make<void>(undefined).pipe(
Atom.withLabel("provider-workspace-snapshot-refresh:idle"),
);

/**
* Keeps the selected provider's workspace snapshot fresh for the composer's
* cwd. Returns a check to run when the user types.
* cwd while mounted. Returns a check to run when the user types.
*/
export function useProviderWorkspaceSnapshotRefresh(input: {
readonly environmentId: EnvironmentId;
readonly gitCwd: string | null;
readonly selectedProviderEntry: ProviderInstanceEntry | undefined;
readonly selectedProviderStatus: ServerProvider | null;
}) {
const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input;
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
// The last scan this composer asked for. A request inside the TTL is not
// repeated, so a client clock ahead of the server's cannot loop rescans.
const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
const failedRefreshesRef = useRef<{ key: string; count: number } | null>(null);
const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
key: string;
notBefore: number;
} | null>(null);
const workspaceRefreshScopeKey =
gitCwd && selectedProviderEntry
? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`
: null;
const workspaceSlashCommandsPending =
selectedProviderStatus?.workspaceSnapshots?.some(
(snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true,
) ?? false;
useEffect(() => {
if (
!workspaceSlashCommandsPending ||
!workspaceRefreshRetry ||
workspaceRefreshRetry.key !== workspaceRefreshScopeKey
)
return;
const timeout = setTimeout(
() => {
setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
},
Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
);
return () => clearTimeout(timeout);
}, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
// Losing a snapshot (the server dropped it) lifts both the TTL and the retry
// cooldown so the next check rescans at once.
const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd);
const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot);
const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0);
if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) {
setHadWorkspaceSnapshot(hasWorkspaceSnapshot);
if (!hasWorkspaceSnapshot) {
setWorkspaceSnapshotLossCount((count) => count + 1);
setWorkspaceRefreshRetry(null);
}
}
const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount);
const refreshWorkspaceSnapshotIfStale = (
now: number,
key: string | null,
retry: { key: string; notBefore: number } | null,
snapshotLossCount: number,
) => {
if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) {
lastWorkspaceSnapshotLossRef.current = snapshotLossCount;
workspaceRefreshKeyRef.current = null;
}
if (key === null || !gitCwd || !selectedProviderEntry) return;
const lastRequest = workspaceRefreshKeyRef.current;
if (
lastRequest?.key === key &&
now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
)
return;
// A pending retry needs no clearing here: its cooldown lapses long before the TTL.
if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return;
if (retry?.key === key && now < retry.notBefore) return;
const request = { key, requestedAt: now };
workspaceRefreshKeyRef.current = request;
const retryLater = () => {
if (workspaceRefreshKeyRef.current !== request) return;
const failed = failedRefreshesRef.current;
const count = failed?.key === key ? failed.count + 1 : 1;
failedRefreshesRef.current = { key, count };
// Keeping the request marker lets the TTL hold off the next scan.
if (count >= WORKSPACE_SNAPSHOT_MAX_ATTEMPTS) return;
workspaceRefreshKeyRef.current = null;
setWorkspaceRefreshRetry({
key,
notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
});
};
void refreshProviders({
environmentId,
input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
}).then((result) => {
const refreshedSnapshot =
result._tag === "Success" &&
hasCompleteProviderWorkspaceSnapshot(
result.value.providers.find(
(provider) => provider.instanceId === selectedProviderEntry.instanceId,
),
gitCwd,
);
if (!refreshedSnapshot) retryLater();
else failedRefreshesRef.current = null;
}, retryLater);
};
const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale);
useEffect(() => {
refreshWorkspaceSnapshotOnChange(
Date.now(),
workspaceRefreshScopeKey,
workspaceRefreshRetry,
workspaceSnapshotLossCount,
);
}, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]);
return useStableCallback(() =>
refreshWorkspaceSnapshotIfStale(
Date.now(),
workspaceRefreshScopeKey,
workspaceRefreshRetry,
workspaceSnapshotLossCount,
),
);
readonly instanceId: ProviderInstanceId | undefined;
}): () => void {
const { environmentId, gitCwd, instanceId } = input;
const atom =
gitCwd && instanceId
? providerWorkspaceSnapshotRefresh({ environmentId, instanceId, cwd: gitCwd })
: idleRefreshAtom;
return useAtomRefresh(atom);
}
Loading
Loading