Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a24129976d | ||
|
|
b4615a847a | ||
|
|
96897ab346 | ||
|
|
3aaa338f3b | ||
|
|
d7969264de | ||
|
|
f7748a0d65 |
No files matched your search
@@ -16,7 +16,6 @@
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"unicorn/no-array-sort": "off",
|
||||
"react-in-jsx-scope": "off",
|
||||
"eslint/no-shadow": "off",
|
||||
"eslint/no-await-in-loop": "off"
|
||||
|
||||
@@ -52,6 +52,7 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
|
||||
@@ -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";
|
||||
@@ -15,7 +15,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
@@ -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(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { memo, useCallback, useEffect, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import {
|
||||
attachTerminalSession,
|
||||
useTerminalSession,
|
||||
|
||||
@@ -14,10 +14,8 @@ import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-re
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { buildThreadTerminalNavigation } from "../../lib/routes";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
attachTerminalSession,
|
||||
useKnownTerminalSessions,
|
||||
|
||||
@@ -101,6 +101,7 @@ export function buildTerminalMenuSessions(input: {
|
||||
sessionsById.set(input.currentSession.terminalId, input.currentSession);
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
return Array.from(sessionsById.values()).sort((left, right) =>
|
||||
left.terminalId.localeCompare(right.terminalId, undefined, { numeric: true }),
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -46,7 +46,7 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { CLAUDE_AGENT_EFFORT_OPTIONS, type ClaudeAgentEffort } from "./claudeEffortOptions";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ export function ThreadNavigationDrawer(props: {
|
||||
title: group.projects[0]?.project.title ?? group.title,
|
||||
threads: group.projects
|
||||
.flatMap((projectGroup) => projectGroup.threads)
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
.sort(compareThreadActivity),
|
||||
})),
|
||||
[repositoryGroups],
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,11 +16,11 @@ import { buildTemporaryWorktreeBranchName, sanitizeFeatureBranchName } from "@t3
|
||||
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import { getEnvironmentClient } from "../../state/environment-session-registry";
|
||||
import { environmentRuntimeManager } from "../../state/use-environment-runtime";
|
||||
import { gitBranchManager } from "../../state/use-git-branches";
|
||||
import { useRemoteCatalog } from "../../state/use-remote-catalog";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
setPendingConnectionError,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import type { EnvironmentSession } from "./remote-runtime-types";
|
||||
|
||||
const environmentSessions = new Map<EnvironmentId, EnvironmentSession>();
|
||||
const environmentConnectionListeners = new Set<() => void>();
|
||||
|
||||
export function getEnvironmentSession(environmentId: EnvironmentId): EnvironmentSession | null {
|
||||
return environmentSessions.get(environmentId) ?? null;
|
||||
}
|
||||
|
||||
export function getEnvironmentClient(environmentId: EnvironmentId) {
|
||||
return getEnvironmentSession(environmentId)?.client ?? null;
|
||||
}
|
||||
|
||||
export function setEnvironmentSession(
|
||||
environmentId: EnvironmentId,
|
||||
session: EnvironmentSession,
|
||||
): void {
|
||||
environmentSessions.set(environmentId, session);
|
||||
}
|
||||
|
||||
export function removeEnvironmentSession(environmentId: EnvironmentId): EnvironmentSession | null {
|
||||
const session = getEnvironmentSession(environmentId);
|
||||
environmentSessions.delete(environmentId);
|
||||
return session;
|
||||
}
|
||||
|
||||
export function drainEnvironmentSessions(): ReadonlyArray<EnvironmentSession> {
|
||||
const sessions = [...environmentSessions.values()];
|
||||
environmentSessions.clear();
|
||||
return sessions;
|
||||
}
|
||||
|
||||
export function notifyEnvironmentConnectionListeners() {
|
||||
for (const listener of environmentConnectionListeners) listener();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to environment-connection changes (connect / disconnect / reconnect).
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
export function subscribeEnvironmentConnections(listener: () => void): () => void {
|
||||
environmentConnectionListeners.add(listener);
|
||||
return () => {
|
||||
environmentConnectionListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
type SourceControlDiscoveryClient,
|
||||
type SourceControlDiscoveryTarget,
|
||||
createSourceControlDiscoveryManager,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId, SourceControlDiscoveryResult } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
|
||||
export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager<EnvironmentId>({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
getClient: (environmentId) => getEnvironmentClient(environmentId)?.server ?? null,
|
||||
});
|
||||
|
||||
export function sourceControlDiscoveryTargetForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
): SourceControlDiscoveryTarget<EnvironmentId> {
|
||||
return { key: environmentId ?? null };
|
||||
}
|
||||
|
||||
export function refreshSourceControlDiscoveryForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
client?: SourceControlDiscoveryClient | null,
|
||||
): Promise<SourceControlDiscoveryResult | null> {
|
||||
return sourceControlDiscoveryManager.refresh(
|
||||
sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
client ?? undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function invalidateSourceControlDiscoveryForEnvironment(
|
||||
environmentId: EnvironmentId | null,
|
||||
): void {
|
||||
sourceControlDiscoveryManager.invalidate(
|
||||
sourceControlDiscoveryTargetForEnvironment(environmentId),
|
||||
);
|
||||
}
|
||||
|
||||
export function resetSourceControlDiscoveryState(): void {
|
||||
sourceControlDiscoveryManager.reset();
|
||||
}
|
||||
|
||||
export function resetSourceControlDiscoveryStateForTests(): void {
|
||||
resetSourceControlDiscoveryState();
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { uuidv4 } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { getEnvironmentClient } from "./use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
|
||||
export const gitActionManager = createGitActionManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "@t3tools/client-runtime";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { getEnvironmentClient } from "./use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
|
||||
export const gitBranchManager = createGitBranchManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
|
||||
@@ -14,7 +14,7 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "./use-remote-environment-registry";
|
||||
} from "./environment-session-registry";
|
||||
|
||||
/**
|
||||
* Singleton git status manager for the mobile app.
|
||||
|
||||
@@ -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";
|
||||
@@ -21,13 +21,21 @@ import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/co
|
||||
import { terminalDebugLog } from "../features/terminal/terminalDebugLog";
|
||||
import { clearSavedConnection, loadSavedConnections, saveConnection } from "../lib/storage";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types";
|
||||
import {
|
||||
drainEnvironmentSessions,
|
||||
notifyEnvironmentConnectionListeners,
|
||||
removeEnvironmentSession,
|
||||
setEnvironmentSession,
|
||||
} from "./environment-session-registry";
|
||||
import { type ConnectedEnvironmentSummary } from "./remote-runtime-types";
|
||||
import {
|
||||
invalidateSourceControlDiscoveryForEnvironment,
|
||||
resetSourceControlDiscoveryState,
|
||||
} from "./source-control-discovery-manager";
|
||||
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
|
||||
import { shellSnapshotManager } from "./use-shell-snapshot";
|
||||
import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session";
|
||||
|
||||
const environmentSessions = new Map<EnvironmentId, EnvironmentSession>();
|
||||
const environmentConnectionListeners = new Set<() => void>();
|
||||
const terminalMetadataUnsubscribers = new Map<EnvironmentId, () => void>();
|
||||
|
||||
interface RemoteEnvironmentLocalState {
|
||||
@@ -57,10 +65,6 @@ const savedConnectionsByIdAtom = Atom.make<Record<EnvironmentId, SavedRemoteConn
|
||||
Atom.withLabel("mobile:saved-connections"),
|
||||
);
|
||||
|
||||
function notifyEnvironmentConnectionListeners() {
|
||||
for (const listener of environmentConnectionListeners) listener();
|
||||
}
|
||||
|
||||
function getSavedConnectionsById(): Record<EnvironmentId, SavedRemoteConnection> {
|
||||
return appAtomRegistry.get(savedConnectionsByIdAtom);
|
||||
}
|
||||
@@ -121,17 +125,6 @@ function useRemoteEnvironmentLocalState(): RemoteEnvironmentLocalState {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to environment-connection changes (connect / disconnect / reconnect).
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
export function subscribeEnvironmentConnections(listener: () => void): () => void {
|
||||
environmentConnectionListeners.add(listener);
|
||||
return () => {
|
||||
environmentConnectionListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function setEnvironmentConnectionStatus(
|
||||
environmentId: EnvironmentId,
|
||||
state: ConnectedEnvironmentSummary["connectionState"],
|
||||
@@ -144,21 +137,17 @@ function setEnvironmentConnectionStatus(
|
||||
}));
|
||||
}
|
||||
|
||||
export function getEnvironmentClient(environmentId: EnvironmentId) {
|
||||
return environmentSessions.get(environmentId)?.client ?? null;
|
||||
}
|
||||
|
||||
export async function disconnectEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
options?: { readonly removeSaved?: boolean },
|
||||
) {
|
||||
const session = environmentSessions.get(environmentId);
|
||||
environmentSessions.delete(environmentId);
|
||||
const session = removeEnvironmentSession(environmentId);
|
||||
notifyEnvironmentConnectionListeners();
|
||||
await session?.connection.dispose();
|
||||
terminalMetadataUnsubscribers.get(environmentId)?.();
|
||||
terminalMetadataUnsubscribers.delete(environmentId);
|
||||
shellSnapshotManager.invalidate({ environmentId });
|
||||
invalidateSourceControlDiscoveryForEnvironment(environmentId);
|
||||
terminalSessionManager.invalidateEnvironment(environmentId);
|
||||
environmentRuntimeManager.invalidate({ environmentId });
|
||||
|
||||
@@ -233,7 +222,7 @@ export async function connectSavedEnvironment(
|
||||
wsBaseUrl: connection.wsBaseUrl,
|
||||
},
|
||||
}),
|
||||
environmentId: EnvironmentId.make(connection.environmentId),
|
||||
environmentId: connection.environmentId,
|
||||
},
|
||||
client,
|
||||
applyShellEvent: (event, environmentId) => {
|
||||
@@ -258,7 +247,7 @@ export async function connectSavedEnvironment(
|
||||
},
|
||||
});
|
||||
|
||||
environmentSessions.set(connection.environmentId, {
|
||||
setEnvironmentSession(connection.environmentId, {
|
||||
client,
|
||||
connection: environmentConnection,
|
||||
});
|
||||
@@ -342,16 +331,16 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
for (const session of environmentSessions.values()) {
|
||||
for (const session of drainEnvironmentSessions()) {
|
||||
void session.connection.dispose();
|
||||
}
|
||||
environmentSessions.clear();
|
||||
for (const unsubscribe of terminalMetadataUnsubscribers.values()) {
|
||||
unsubscribe();
|
||||
}
|
||||
terminalMetadataUnsubscribers.clear();
|
||||
environmentRuntimeManager.invalidate();
|
||||
shellSnapshotManager.invalidate();
|
||||
resetSourceControlDiscoveryState();
|
||||
terminalSessionManager.invalidate();
|
||||
notifyEnvironmentConnectionListeners();
|
||||
};
|
||||
|
||||
@@ -11,7 +11,8 @@ import {
|
||||
|
||||
import { uuidv4 } from "../lib/uuid";
|
||||
import { environmentRuntimeManager } from "./use-environment-runtime";
|
||||
import { getEnvironmentClient, useRemoteEnvironmentState } from "./use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
import { useRemoteEnvironmentState } from "./use-remote-environment-registry";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
|
||||
export function useSelectedThreadCommands(input: {
|
||||
|
||||
@@ -6,14 +6,15 @@ 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,
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { uuidv4 } from "../lib/uuid";
|
||||
import { getEnvironmentClient, setPendingConnectionError } from "./use-remote-environment-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
import { setPendingConnectionError } from "./use-remote-environment-registry";
|
||||
import { gitActionManager, showGitActionResult } from "./use-git-action-state";
|
||||
import { gitBranchManager } from "./use-git-branches";
|
||||
import { gitStatusManager } from "./use-git-status";
|
||||
@@ -42,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 } : {}),
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
|
||||
import { useGitActionState } from "./use-git-action-state";
|
||||
import { useGitBranches } from "./use-git-branches";
|
||||
import { useSourceControlDiscovery } from "./use-source-control-discovery";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
|
||||
|
||||
@@ -19,6 +20,7 @@ export function useSelectedThreadGitState() {
|
||||
[selectedThread?.environmentId, selectedThreadCwd],
|
||||
);
|
||||
const gitActionState = useGitActionState(selectedThreadGitTarget);
|
||||
const sourceControlDiscovery = useSourceControlDiscovery(selectedThread?.environmentId ?? null);
|
||||
|
||||
const selectedThreadBranchTarget = useMemo(
|
||||
() => ({
|
||||
@@ -39,6 +41,7 @@ export function useSelectedThreadGitState() {
|
||||
|
||||
return {
|
||||
gitOperationLabel: gitActionState.currentLabel,
|
||||
sourceControlDiscovery,
|
||||
selectedThreadBranches,
|
||||
selectedThreadBranchesLoading: selectedThreadBranchState.isPending,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM,
|
||||
EMPTY_SOURCE_CONTROL_DISCOVERY_STATE,
|
||||
type SourceControlDiscoveryState,
|
||||
getSourceControlDiscoveryTargetKey,
|
||||
sourceControlDiscoveryStateAtom,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "./environment-session-registry";
|
||||
import {
|
||||
refreshSourceControlDiscoveryForEnvironment,
|
||||
sourceControlDiscoveryTargetForEnvironment,
|
||||
} from "./source-control-discovery-manager";
|
||||
|
||||
export function useSourceControlDiscovery(
|
||||
environmentId: EnvironmentId | null,
|
||||
): SourceControlDiscoveryState {
|
||||
useEffect(() => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refresh = () => {
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
void refreshSourceControlDiscoveryForEnvironment(environmentId, client.server);
|
||||
};
|
||||
|
||||
refresh();
|
||||
return subscribeEnvironmentConnections(refresh);
|
||||
}, [environmentId]);
|
||||
|
||||
const target = sourceControlDiscoveryTargetForEnvironment(environmentId);
|
||||
const targetKey = getSourceControlDiscoveryTargetKey(target);
|
||||
const state = useAtomValue(
|
||||
targetKey !== null
|
||||
? sourceControlDiscoveryStateAtom(targetKey)
|
||||
: EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM,
|
||||
);
|
||||
return targetKey === null ? EMPTY_SOURCE_CONTROL_DISCOVERY_STATE : state;
|
||||
}
|
||||
@@ -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";
|
||||
@@ -30,9 +30,9 @@ import {
|
||||
} from "../lib/threadActivity";
|
||||
import { uuidv4 } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "../state/atom-registry";
|
||||
import { getEnvironmentClient } from "./environment-session-registry";
|
||||
import type { ConnectedEnvironmentSummary } from "../state/remote-runtime-types";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
setPendingConnectionError,
|
||||
useRemoteConnectionStatus,
|
||||
} from "../state/use-remote-environment-registry";
|
||||
@@ -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,7 +15,7 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
subscribeEnvironmentConnections,
|
||||
} from "./use-remote-environment-registry";
|
||||
} from "./environment-session-registry";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
|
||||
function shouldKeepThreadDetailWarm(state: ThreadDetailState): boolean {
|
||||
|
||||
@@ -506,6 +506,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||
|
||||
@@ -514,6 +515,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(fullDiff.includes("README.md"), true);
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
@@ -68,9 +69,14 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
@@ -102,6 +108,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
@@ -113,6 +120,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
@@ -123,6 +131,67 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults to hide whitespace changes", async () => {
|
||||
const projectId = ProjectId.make("project-default-whitespace");
|
||||
const threadId = ThreadId.make("thread-default-whitespace");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ const make = Effect.gen(function* () {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -131,6 +132,7 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
|
||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -157,6 +159,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace ?? true,
|
||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||
|
||||
return {
|
||||
|
||||
@@ -114,6 +114,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
@@ -121,5 +122,80 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
expect(diff).toContain("+line 04999");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("can hide indentation churn when changes wrap existing lines", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
const componentPath = path.join(tmp, "Component.tsx");
|
||||
yield* writeTextFile(
|
||||
componentPath,
|
||||
[
|
||||
"export function View() {",
|
||||
" return (",
|
||||
" <section>",
|
||||
" <h1>Title</h1>",
|
||||
" <p>Body</p>",
|
||||
" </section>",
|
||||
" );",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
});
|
||||
yield* writeTextFile(
|
||||
componentPath,
|
||||
[
|
||||
"export function View() {",
|
||||
" return (",
|
||||
" <section>",
|
||||
" {isReady ? (",
|
||||
" <div>",
|
||||
" <h1>Title</h1>",
|
||||
" <p>Body</p>",
|
||||
" </div>",
|
||||
" ) : null}",
|
||||
" </section>",
|
||||
" );",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const normalDiff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(normalDiff).toContain("diff --git");
|
||||
expect(normalDiff).toContain("- <h1>Title</h1>");
|
||||
expect(normalDiff).toContain("+ <h1>Title</h1>");
|
||||
expect(whitespaceIgnoredDiff).toContain("diff --git");
|
||||
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
|
||||
expect(whitespaceIgnoredDiff).toContain("+ <div>");
|
||||
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
|
||||
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -259,10 +259,20 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
];
|
||||
|
||||
const result = yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
args: diffArgs,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface DiffCheckpointsInput {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
|
||||
@@ -580,6 +580,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "createRepository",
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
|
||||
@@ -237,6 +237,7 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
|
||||
@@ -117,6 +117,10 @@ import {
|
||||
} from "./vcs/VcsDriverRegistry.ts";
|
||||
import { layer as VcsProvisioningServiceLayer } from "./vcs/VcsProvisioningService.ts";
|
||||
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
|
||||
import {
|
||||
SourceControlRepositoryService,
|
||||
type SourceControlRepositoryServiceShape,
|
||||
} from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
|
||||
@@ -330,6 +334,7 @@ const buildAppUnderTest = (options?: {
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
sourceControlRepositoryService?: Partial<SourceControlRepositoryServiceShape>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
@@ -545,6 +550,11 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlRepositoryService)({
|
||||
...options?.layers?.sourceControlRepositoryService,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectSetupScriptRunner)({
|
||||
|
||||
@@ -54,6 +54,7 @@ import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
|
||||
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
|
||||
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
|
||||
@@ -161,15 +162,15 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProjectConfig.layer),
|
||||
);
|
||||
|
||||
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
);
|
||||
|
||||
const GitManagerLayerLive = GitManager.layer.pipe(
|
||||
Layer.provideMerge(ProjectSetupScriptRunnerLive),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(
|
||||
SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(TextGeneration.layer),
|
||||
);
|
||||
|
||||
@@ -183,11 +184,17 @@ const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
);
|
||||
|
||||
const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
|
||||
@@ -211,6 +211,58 @@ describe("GitHubCli.layer", () => {
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("creates repositories and parses clone URLs from create output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
"✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
expect(mockRun).toHaveBeenNthCalledWith(1, {
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: ["repo", "create", "octocat/codething-mvp", "--private"],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("falls back to constructed URLs when create output omits a URL", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
|
||||
import { TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import {
|
||||
@@ -62,6 +66,12 @@ export interface GitHubCliShape {
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
@@ -160,6 +170,43 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `gh repo create` prints the canonical URL of the new repository on stdout
|
||||
* (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
|
||||
* follow-up `gh repo view`, which can race GitHub's GraphQL eventual
|
||||
* consistency window and falsely report the just-created repo as missing.
|
||||
*/
|
||||
function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
stdout: string,
|
||||
repository: string,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
const fallbackHost = "github.com";
|
||||
const match = stdout.match(/https?:\/\/[^\s]+/);
|
||||
if (match) {
|
||||
const cleaned = match[0].replace(/\.git$/, "");
|
||||
try {
|
||||
const parsed = new URL(cleaned);
|
||||
const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
if (segments.length === 2) {
|
||||
const nameWithOwner = `${segments[0]}/${segments[1]}`;
|
||||
return {
|
||||
nameWithOwner,
|
||||
url: `${parsed.origin}/${nameWithOwner}`,
|
||||
sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the input-derived defaults below.
|
||||
}
|
||||
}
|
||||
return {
|
||||
nameWithOwner: repository,
|
||||
url: `https://${fallbackHost}/${repository}`,
|
||||
sshUrl: `git@${fallbackHost}:${repository}.git`,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitHubJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
@@ -281,6 +328,15 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "create", input.repository, `--${input.visibility}`],
|
||||
}).pipe(
|
||||
Effect.map((result) =>
|
||||
deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
|
||||
),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
|
||||
@@ -130,6 +130,10 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
github
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
github
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
github
|
||||
.getDefaultBranch(input)
|
||||
|
||||
@@ -175,7 +175,7 @@ layer("GitLabCli.layer", (it) => {
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code.git",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
}),
|
||||
@@ -217,6 +217,67 @@ layer("GitLabCli.layer", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates repositories under an explicit namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun
|
||||
.mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "octocat/t3code",
|
||||
web_url: "https://gitlab.com/octocat/t3code",
|
||||
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
|
||||
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
const result = yield* glab.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "public",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["api", "namespaces/octocat"],
|
||||
}),
|
||||
);
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
"path=t3code",
|
||||
"--raw-field",
|
||||
"name=t3code",
|
||||
"--raw-field",
|
||||
"visibility=public",
|
||||
"--raw-field",
|
||||
"namespace_id=1234",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
|
||||
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
decodeGitLabMergeRequestJson,
|
||||
@@ -66,6 +66,12 @@ export interface GitLabCliShape {
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
@@ -161,12 +167,16 @@ const RawGitLabDefaultBranchSchema = Schema.Struct({
|
||||
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
return {
|
||||
nameWithOwner: raw.path_with_namespace,
|
||||
url: raw.http_url_to_repo || raw.web_url,
|
||||
url: raw.web_url,
|
||||
sshUrl: raw.ssh_url_to_repo,
|
||||
};
|
||||
}
|
||||
@@ -174,7 +184,7 @@ function normalizeRepositoryCloneUrls(
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch",
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
@@ -228,6 +238,19 @@ function toSummaryWithOptionalUpdatedAt(
|
||||
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
|
||||
}
|
||||
|
||||
function parseRepositoryPath(repository: string): {
|
||||
readonly namespacePath: string | null;
|
||||
readonly projectPath: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const projectPath = parts.at(-1) ?? repository.trim();
|
||||
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
|
||||
return { namespacePath, projectPath };
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitLabCli")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
|
||||
@@ -320,6 +343,59 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) => {
|
||||
const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
|
||||
const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
|
||||
? execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
)
|
||||
: Effect.succeed(null);
|
||||
|
||||
return namespaceId.pipe(
|
||||
Effect.flatMap((resolvedNamespaceId) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
`path=${projectPath}`,
|
||||
"--raw-field",
|
||||
`name=${projectPath}`,
|
||||
"--raw-field",
|
||||
`visibility=${input.visibility}`,
|
||||
...(resolvedNamespaceId === null
|
||||
? []
|
||||
: ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
|
||||
],
|
||||
}),
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
},
|
||||
createMergeRequest: (input) => {
|
||||
const sourceProject = sourceProjectIdentifier(input.source);
|
||||
return execute({
|
||||
|
||||
@@ -92,6 +92,10 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
|
||||
gitlab
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
gitlab
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
gitlab
|
||||
.getDefaultBranch(input)
|
||||
|
||||
@@ -115,6 +115,9 @@ Logged in to github.com account juliusmarminge (keyring)
|
||||
},
|
||||
],
|
||||
);
|
||||
const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
|
||||
assert.ok(bitbucket);
|
||||
assert.strictEqual("executable" in bitbucket, false);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
@@ -204,9 +207,9 @@ Logged in as bitbucket-user
|
||||
},
|
||||
{
|
||||
kind: "bitbucket",
|
||||
auth: "authenticated",
|
||||
account: Option.some("bitbucket-user"),
|
||||
detail: Option.none(),
|
||||
auth: "unknown",
|
||||
account: Option.none(),
|
||||
detail: Option.some("Bitbucket provider support is not available yet."),
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
@@ -13,20 +13,22 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
|
||||
interface DiscoveryProbe {
|
||||
readonly label: string;
|
||||
readonly executable: string;
|
||||
readonly versionArgs: ReadonlyArray<string>;
|
||||
readonly executable?: string;
|
||||
readonly versionArgs?: ReadonlyArray<string>;
|
||||
readonly implemented: boolean;
|
||||
readonly installHint: string;
|
||||
}
|
||||
|
||||
type VcsProbe = DiscoveryProbe & {
|
||||
readonly kind: VcsDriverKind;
|
||||
readonly executable: string;
|
||||
readonly versionArgs: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
type ProviderProbe = DiscoveryProbe & {
|
||||
readonly kind: SourceControlProviderKind;
|
||||
readonly authArgs: ReadonlyArray<string>;
|
||||
readonly parseAuth: (input: AuthProbeInput) => SourceControlProviderAuth;
|
||||
readonly authArgs?: ReadonlyArray<string>;
|
||||
readonly parseAuth?: (input: AuthProbeInput) => SourceControlProviderAuth;
|
||||
};
|
||||
|
||||
interface AuthProbeInput {
|
||||
@@ -38,7 +40,7 @@ interface AuthProbeInput {
|
||||
interface DiscoveryProbeResult<Kind extends string> {
|
||||
readonly kind: Kind;
|
||||
readonly label: string;
|
||||
readonly executable: string;
|
||||
readonly executable?: string;
|
||||
readonly implemented: boolean;
|
||||
readonly status: "available" | "missing";
|
||||
readonly version: Option.Option<string>;
|
||||
@@ -101,12 +103,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
|
||||
{
|
||||
kind: "bitbucket",
|
||||
label: "Bitbucket",
|
||||
executable: "bb",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseBitbucketAuth,
|
||||
implemented: false,
|
||||
installHint: "Install a Bitbucket CLI (`bb`) and authenticate it for your Bitbucket workspace.",
|
||||
installHint: "Bitbucket provider support is not available yet.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -266,37 +264,6 @@ function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
|
||||
});
|
||||
}
|
||||
|
||||
function parseBitbucketAuth(input: AuthProbeInput): SourceControlProviderAuth {
|
||||
const output = combinedAuthOutput(input);
|
||||
const account = matchFirst(output, [
|
||||
/Logged in to .* as\s+([^\s(]+)/iu,
|
||||
/Logged in as\s+([^\s(]+)/iu,
|
||||
/account:\s*([^\s(]+)/iu,
|
||||
/user:\s*([^\s(]+)/iu,
|
||||
/username:\s*([^\s(]+)/iu,
|
||||
]);
|
||||
const host = parseCliHost(output) ?? "bitbucket.org";
|
||||
|
||||
if (input.exitCode !== 0) {
|
||||
return providerAuth({
|
||||
status: "unauthenticated",
|
||||
host,
|
||||
detail:
|
||||
firstSafeAuthLine(output) ?? "Authenticate the Bitbucket CLI before enabling Bitbucket.",
|
||||
});
|
||||
}
|
||||
|
||||
if (account) {
|
||||
return providerAuth({ status: "authenticated", account, host });
|
||||
}
|
||||
|
||||
return providerAuth({
|
||||
status: "unknown",
|
||||
host,
|
||||
detail: firstSafeAuthLine(output) ?? "Bitbucket CLI auth status could not be parsed.",
|
||||
});
|
||||
}
|
||||
|
||||
export interface SourceControlDiscoveryShape {
|
||||
readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
|
||||
}
|
||||
@@ -314,12 +281,27 @@ export const layer = Layer.effect(
|
||||
|
||||
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
|
||||
input: DiscoveryProbe & { readonly kind: Kind },
|
||||
): Effect.Effect<DiscoveryProbeResult<Kind>> =>
|
||||
process
|
||||
): Effect.Effect<DiscoveryProbeResult<Kind>> => {
|
||||
const executable = input.executable;
|
||||
const versionArgs = input.versionArgs;
|
||||
|
||||
if (!executable || !versionArgs) {
|
||||
return Effect.succeed({
|
||||
kind: input.kind,
|
||||
label: input.label,
|
||||
implemented: input.implemented,
|
||||
status: "missing" as const,
|
||||
version: Option.none<string>(),
|
||||
installHint: input.installHint,
|
||||
detail: Option.some(input.installHint),
|
||||
} satisfies DiscoveryProbeResult<Kind>);
|
||||
}
|
||||
|
||||
return process
|
||||
.run({
|
||||
operation: "source-control.discovery.probe",
|
||||
command: input.executable,
|
||||
args: input.versionArgs,
|
||||
command: executable,
|
||||
args: versionArgs,
|
||||
cwd: config.cwd,
|
||||
timeoutMs: 5_000,
|
||||
maxOutputBytes: 8_000,
|
||||
@@ -331,7 +313,7 @@ export const layer = Layer.effect(
|
||||
({
|
||||
kind: input.kind,
|
||||
label: input.label,
|
||||
executable: input.executable,
|
||||
executable,
|
||||
implemented: input.implemented,
|
||||
status: "available" as const,
|
||||
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
|
||||
@@ -345,7 +327,7 @@ export const layer = Layer.effect(
|
||||
Effect.succeed({
|
||||
kind: input.kind,
|
||||
label: input.label,
|
||||
executable: input.executable,
|
||||
executable,
|
||||
implemented: input.implemented,
|
||||
status: "missing" as const,
|
||||
version: Option.none<string>(),
|
||||
@@ -354,10 +336,22 @@ export const layer = Layer.effect(
|
||||
} satisfies DiscoveryProbeResult<Kind>),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const probeProvider = (input: ProviderProbe) =>
|
||||
probe(input).pipe(
|
||||
Effect.flatMap((item) => {
|
||||
const executable = input.executable;
|
||||
const authArgs = input.authArgs;
|
||||
const parseAuth = input.parseAuth;
|
||||
|
||||
if (!executable || !authArgs || !parseAuth) {
|
||||
return Effect.succeed({
|
||||
...item,
|
||||
auth: unknownAuth(input.installHint),
|
||||
} satisfies SourceControlProviderDiscoveryItem);
|
||||
}
|
||||
|
||||
if (item.status !== "available") {
|
||||
return Effect.succeed({
|
||||
...item,
|
||||
@@ -368,8 +362,8 @@ export const layer = Layer.effect(
|
||||
return process
|
||||
.run({
|
||||
operation: "source-control.discovery.auth",
|
||||
command: input.executable,
|
||||
args: input.authArgs,
|
||||
command: executable,
|
||||
args: authArgs,
|
||||
cwd: config.cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
@@ -381,7 +375,7 @@ export const layer = Layer.effect(
|
||||
(result) =>
|
||||
({
|
||||
...item,
|
||||
auth: input.parseAuth(result),
|
||||
auth: parseAuth(result),
|
||||
}) satisfies SourceControlProviderDiscoveryItem,
|
||||
),
|
||||
Effect.catch((cause) =>
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
SourceControlProviderInfo,
|
||||
SourceControlProviderKind,
|
||||
SourceControlRepositoryCloneUrls,
|
||||
SourceControlRepositoryVisibility,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface SourceControlProviderContext {
|
||||
@@ -50,6 +51,11 @@ export interface SourceControlProviderShape {
|
||||
readonly context?: SourceControlProviderContext;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProviderContext;
|
||||
|
||||
@@ -58,6 +58,7 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
|
||||
getChangeRequest: () => unsupported("getChangeRequest"),
|
||||
createChangeRequest: () => unsupported("createChangeRequest"),
|
||||
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
|
||||
createRepository: () => unsupported("createRepository"),
|
||||
getDefaultBranch: () => unsupported("getDefaultBranch"),
|
||||
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { GitCommandError, type SourceControlProviderError } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import {
|
||||
GitVcsDriver,
|
||||
type ExecuteGitResult,
|
||||
type GitVcsDriverShape,
|
||||
} from "../vcs/GitVcsDriver.ts";
|
||||
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
|
||||
import type { SourceControlProviderShape } from "./SourceControlProvider.ts";
|
||||
import { SourceControlRepositoryService, layer } from "./SourceControlRepositoryService.ts";
|
||||
|
||||
const CLONE_URLS = {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://github.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
};
|
||||
|
||||
function makeProvider(
|
||||
overrides: Partial<SourceControlProviderShape> = {},
|
||||
): SourceControlProviderShape {
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
|
||||
never,
|
||||
SourceControlProviderError
|
||||
>;
|
||||
|
||||
return {
|
||||
kind: "github",
|
||||
listChangeRequests: () => unsupported("listChangeRequests"),
|
||||
getChangeRequest: () => unsupported("getChangeRequest"),
|
||||
createChangeRequest: () => unsupported("createChangeRequest"),
|
||||
getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
|
||||
createRepository: () => Effect.succeed(CLONE_URLS),
|
||||
getDefaultBranch: () => Effect.succeed(null),
|
||||
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function processOutput(): ExecuteGitResult {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly provider?: SourceControlProviderShape;
|
||||
readonly git?: Partial<GitVcsDriverShape>;
|
||||
}) {
|
||||
return layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlProviderRegistry)({
|
||||
get: () => Effect.succeed(input.provider ?? makeProvider()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(GitVcsDriver)({
|
||||
execute: () => Effect.succeed(processOutput()),
|
||||
ensureRemote: () => Effect.succeed("origin"),
|
||||
pushCurrentBranch: () =>
|
||||
Effect.succeed({
|
||||
status: "pushed" as const,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: "origin/feature/remote-v1",
|
||||
setUpstream: true,
|
||||
}),
|
||||
...input.git,
|
||||
}),
|
||||
),
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-repos-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("looks up repositories through the requested provider without search", () => {
|
||||
const calls: Array<{ cwd: string; repository: string }> = [];
|
||||
const provider = makeProvider({
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ cwd: input.cwd, repository: input.repository });
|
||||
return CLONE_URLS;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.lookupRepository({
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
cwd: "/workspace",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
|
||||
assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
|
||||
}).pipe(Effect.provide(makeLayer({ provider })));
|
||||
});
|
||||
|
||||
it.effect("clones a looked-up repository into the requested destination", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const parent = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3-source-control-clone-parent-",
|
||||
});
|
||||
const destinationPath = `${parent}/t3code`;
|
||||
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.cloneRepository({
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
destinationPath,
|
||||
protocol: "https",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
cwd: destinationPath,
|
||||
remoteUrl: CLONE_URLS.url,
|
||||
repository: { provider: "github", ...CLONE_URLS },
|
||||
});
|
||||
assert.deepStrictEqual(cloneCalls, [
|
||||
{
|
||||
cwd: parent,
|
||||
args: ["clone", CLONE_URLS.url, "t3code"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
git: {
|
||||
execute: (input) =>
|
||||
Effect.sync(() => {
|
||||
cloneCalls.push({ cwd: input.cwd, args: input.args });
|
||||
return processOutput();
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
|
||||
const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
|
||||
const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
|
||||
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
|
||||
const provider = makeProvider({
|
||||
createRepository: (input) =>
|
||||
Effect.sync(() => {
|
||||
createCalls.push({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
visibility: input.visibility,
|
||||
});
|
||||
return CLONE_URLS;
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.publishRepository({
|
||||
cwd: "/workspace",
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "private",
|
||||
remoteName: "origin",
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
repository: { provider: "github", ...CLONE_URLS },
|
||||
remoteName: "origin",
|
||||
remoteUrl: CLONE_URLS.sshUrl,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: "origin/feature/remote-v1",
|
||||
status: "pushed",
|
||||
});
|
||||
assert.deepStrictEqual(createCalls, [
|
||||
{ cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
|
||||
]);
|
||||
assert.deepStrictEqual(remoteCalls, [
|
||||
{ cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
|
||||
]);
|
||||
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
provider,
|
||||
git: {
|
||||
ensureRemote: (input) =>
|
||||
Effect.sync(() => {
|
||||
remoteCalls.push(input);
|
||||
return "origin";
|
||||
}),
|
||||
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
|
||||
Effect.sync(() => {
|
||||
pushCalls.push({ cwd, remoteName: options?.remoteName });
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: "origin/feature/remote-v1",
|
||||
setUpstream: true,
|
||||
};
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("publishes to the remote name returned by ensureRemote", () => {
|
||||
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.publishRepository({
|
||||
cwd: "/workspace",
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "private",
|
||||
remoteName: "origin",
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
assert.equal(result.remoteName, "origin-1");
|
||||
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
git: {
|
||||
ensureRemote: () => Effect.succeed("origin-1"),
|
||||
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
|
||||
Effect.sync(() => {
|
||||
pushCalls.push({ cwd, remoteName: options?.remoteName });
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch: "feature/remote-v1",
|
||||
upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
|
||||
let pushCalls = 0;
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* SourceControlRepositoryService;
|
||||
const result = yield* service.publishRepository({
|
||||
cwd: "/workspace",
|
||||
provider: "github",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "private",
|
||||
remoteName: "origin",
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
repository: { provider: "github", ...CLONE_URLS },
|
||||
remoteName: "origin",
|
||||
remoteUrl: CLONE_URLS.sshUrl,
|
||||
branch: "main",
|
||||
status: "remote_added",
|
||||
});
|
||||
assert.strictEqual(pushCalls, 0);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
git: {
|
||||
execute: (input) =>
|
||||
input.args[0] === "rev-parse"
|
||||
? Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: "git rev-parse --verify HEAD",
|
||||
cwd: input.cwd,
|
||||
detail: "fatal: Needed a single revision",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(processOutput()),
|
||||
statusDetails: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
}),
|
||||
pushCurrentBranch: () =>
|
||||
Effect.sync(() => {
|
||||
pushCalls += 1;
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch: "main",
|
||||
upstreamBranch: "origin/main",
|
||||
setUpstream: true,
|
||||
};
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import OS from "node:os";
|
||||
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
|
||||
import {
|
||||
SourceControlRepositoryError,
|
||||
type SourceControlCloneRepositoryInput,
|
||||
type SourceControlCloneRepositoryResult,
|
||||
type SourceControlCloneProtocol,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlPublishRepositoryInput,
|
||||
type SourceControlPublishRepositoryResult,
|
||||
type SourceControlRepositoryCloneUrls,
|
||||
type SourceControlRepositoryInfo,
|
||||
type SourceControlRepositoryLookupInput,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
|
||||
|
||||
export interface SourceControlRepositoryServiceShape {
|
||||
readonly lookupRepository: (
|
||||
input: SourceControlRepositoryLookupInput,
|
||||
) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
|
||||
readonly cloneRepository: (
|
||||
input: SourceControlCloneRepositoryInput,
|
||||
) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
|
||||
readonly publishRepository: (
|
||||
input: SourceControlPublishRepositoryInput,
|
||||
) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
|
||||
}
|
||||
|
||||
export class SourceControlRepositoryService extends Context.Service<
|
||||
SourceControlRepositoryService,
|
||||
SourceControlRepositoryServiceShape
|
||||
>()("t3/source-control/SourceControlRepositoryService") {}
|
||||
|
||||
function detailFromUnknown(cause: unknown): string {
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
if ("detail" in cause && typeof cause.detail === "string" && cause.detail.length > 0) {
|
||||
return cause.detail;
|
||||
}
|
||||
if ("message" in cause && typeof cause.message === "string" && cause.message.length > 0) {
|
||||
return cause.message;
|
||||
}
|
||||
}
|
||||
|
||||
return "An unexpected source control error occurred.";
|
||||
}
|
||||
|
||||
function repositoryError(input: {
|
||||
readonly operation: string;
|
||||
readonly provider: SourceControlProviderKind;
|
||||
readonly detail: string;
|
||||
readonly cause?: unknown;
|
||||
}): SourceControlRepositoryError {
|
||||
return new SourceControlRepositoryError({
|
||||
provider: input.provider,
|
||||
operation: input.operation,
|
||||
detail: input.detail,
|
||||
...(input.cause === undefined ? {} : { cause: input.cause }),
|
||||
});
|
||||
}
|
||||
|
||||
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
|
||||
return Effect.mapError((cause: unknown) =>
|
||||
Schema.is(SourceControlRepositoryError)(cause)
|
||||
? cause
|
||||
: repositoryError({
|
||||
operation,
|
||||
provider,
|
||||
detail: detailFromUnknown(cause),
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toRepositoryInfo(
|
||||
provider: SourceControlProviderKind,
|
||||
urls: SourceControlRepositoryCloneUrls,
|
||||
): SourceControlRepositoryInfo {
|
||||
return {
|
||||
provider,
|
||||
nameWithOwner: urls.nameWithOwner,
|
||||
url: urls.url,
|
||||
sshUrl: urls.sshUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function selectRemoteUrl(
|
||||
urls: SourceControlRepositoryCloneUrls,
|
||||
protocol: SourceControlCloneProtocol | undefined,
|
||||
): string {
|
||||
switch (protocol ?? "auto") {
|
||||
case "https":
|
||||
return urls.url;
|
||||
case "ssh":
|
||||
case "auto":
|
||||
return urls.sshUrl;
|
||||
}
|
||||
}
|
||||
|
||||
function expandHomePath(input: string, path: Path.Path): string {
|
||||
if (input === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
||||
return path.join(OS.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeSourceControlRepositoryService")(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const git = yield* GitVcsDriver;
|
||||
const path = yield* Path.Path;
|
||||
const providers = yield* SourceControlProviderRegistry;
|
||||
|
||||
const ensureConcreteProvider = (input: {
|
||||
readonly operation: string;
|
||||
readonly provider: SourceControlProviderKind;
|
||||
}) => {
|
||||
if (input.provider !== "unknown") {
|
||||
return Effect.succeed(input.provider);
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
repositoryError({
|
||||
operation: input.operation,
|
||||
provider: input.provider,
|
||||
detail: "Choose a source control provider before continuing.",
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
|
||||
input: SourceControlRepositoryLookupInput,
|
||||
) {
|
||||
const providerKind = yield* ensureConcreteProvider({
|
||||
operation: "lookupRepository",
|
||||
provider: input.provider,
|
||||
});
|
||||
const provider = yield* providers.get(providerKind);
|
||||
const urls = yield* provider.getRepositoryCloneUrls({
|
||||
cwd: input.cwd ?? config.cwd,
|
||||
repository: input.repository.trim(),
|
||||
});
|
||||
return toRepositoryInfo(providerKind, urls);
|
||||
});
|
||||
|
||||
const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
|
||||
function* (destinationPath: string) {
|
||||
const trimmed = destinationPath.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return yield* Effect.fail(
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider: "unknown",
|
||||
detail: "Choose a destination path before cloning.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return path.resolve(expandHomePath(trimmed, path));
|
||||
},
|
||||
);
|
||||
|
||||
const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
|
||||
function* (destinationPath: string) {
|
||||
const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
|
||||
if (yield* fileSystem.exists(normalizedDestination).pipe(Effect.orElseSucceed(() => false))) {
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(normalizedDestination, { recursive: false })
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider: "unknown",
|
||||
detail: "Destination path already exists and is not a directory.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (entries.length > 0) {
|
||||
return yield* Effect.fail(
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider: "unknown",
|
||||
detail: "Destination path already exists and is not empty.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
|
||||
}
|
||||
|
||||
return {
|
||||
destinationPath: normalizedDestination,
|
||||
parentPath: path.dirname(normalizedDestination),
|
||||
directoryName: path.basename(normalizedDestination),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
|
||||
input: SourceControlCloneRepositoryInput,
|
||||
) {
|
||||
const preparedDestination = yield* prepareDestination(input.destinationPath);
|
||||
let repository: SourceControlRepositoryInfo | null = null;
|
||||
let remoteUrl = input.remoteUrl?.trim() ?? null;
|
||||
let provider: SourceControlProviderKind = input.provider ?? "unknown";
|
||||
|
||||
if (input.provider && input.repository) {
|
||||
repository = yield* lookupRepository({
|
||||
provider: input.provider,
|
||||
repository: input.repository,
|
||||
cwd: preparedDestination.parentPath,
|
||||
});
|
||||
remoteUrl = selectRemoteUrl(repository, input.protocol);
|
||||
provider = input.provider;
|
||||
}
|
||||
|
||||
if (!remoteUrl) {
|
||||
return yield* Effect.fail(
|
||||
repositoryError({
|
||||
operation: "cloneRepository",
|
||||
provider,
|
||||
detail: "Enter a repository path or clone URL before cloning.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation: "SourceControlRepositoryService.cloneRepository",
|
||||
cwd: preparedDestination.parentPath,
|
||||
args: ["clone", remoteUrl, preparedDestination.directoryName],
|
||||
timeoutMs: 120_000,
|
||||
maxOutputBytes: 256 * 1024,
|
||||
});
|
||||
|
||||
return {
|
||||
cwd: preparedDestination.destinationPath,
|
||||
remoteUrl,
|
||||
repository,
|
||||
};
|
||||
});
|
||||
|
||||
const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
|
||||
function* (input: SourceControlPublishRepositoryInput) {
|
||||
const providerKind = yield* ensureConcreteProvider({
|
||||
operation: "publishRepository",
|
||||
provider: input.provider,
|
||||
});
|
||||
const provider = yield* providers.get(providerKind);
|
||||
const urls = yield* provider.createRepository({
|
||||
cwd: input.cwd,
|
||||
repository: input.repository.trim(),
|
||||
visibility: input.visibility,
|
||||
});
|
||||
const remoteUrl = selectRemoteUrl(urls, input.protocol);
|
||||
const remoteName = yield* git.ensureRemote({
|
||||
cwd: input.cwd,
|
||||
preferredName: input.remoteName?.trim() || "origin",
|
||||
url: remoteUrl,
|
||||
});
|
||||
|
||||
// An empty local repo (no commits) would make `git push HEAD:...` fail
|
||||
// with an opaque "src refspec HEAD does not match any". Treat this as a
|
||||
// partial success: the remote was created and wired up, but there is
|
||||
// nothing to push yet.
|
||||
const hasCommits = yield* git
|
||||
.execute({
|
||||
operation: "SourceControlRepositoryService.publishRepository.headCheck",
|
||||
cwd: input.cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
if (!hasCommits) {
|
||||
const details = yield* git
|
||||
.statusDetails(input.cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
return {
|
||||
repository: toRepositoryInfo(providerKind, urls),
|
||||
remoteName,
|
||||
remoteUrl,
|
||||
branch: details?.branch ?? "main",
|
||||
status: "remote_added" as const,
|
||||
};
|
||||
}
|
||||
|
||||
const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
|
||||
|
||||
return {
|
||||
repository: toRepositoryInfo(providerKind, urls),
|
||||
remoteName,
|
||||
remoteUrl,
|
||||
branch: pushResult.branch,
|
||||
...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
|
||||
status: "pushed" as const,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
return SourceControlRepositoryService.of({
|
||||
lookupRepository: (input) =>
|
||||
lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
|
||||
cloneRepository: (input) =>
|
||||
cloneRepository(input).pipe(
|
||||
mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
|
||||
),
|
||||
publishRepository: (input) =>
|
||||
publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlRepositoryService, make());
|
||||
@@ -860,6 +860,7 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
|
||||
const closedEvents = (yield* getEvents).filter(
|
||||
(event): event is Extract<TerminalEvent, { type: "closed" }> => event.type === "closed",
|
||||
);
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
expect(closedEvents.map((event) => event.terminalId).sort()).toEqual(["default", "sidecar"]);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -167,6 +167,7 @@ export interface GitVcsDriverShape {
|
||||
readonly pushCurrentBranch: (
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
options?: { readonly remoteName?: string | null },
|
||||
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||
readonly readRangeContext: (
|
||||
cwd: string,
|
||||
|
||||
@@ -326,5 +326,41 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
assert.notEqual(badBranch.exitCode, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes to the requested remote instead of the primary remote", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const originRemote = yield* makeTmpDir("git-origin-remote-");
|
||||
const publishRemote = yield* makeTmpDir("git-publish-remote-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* git(cwd, ["branch", "-M", "main"]);
|
||||
yield* git(originRemote, ["init", "--bare"]);
|
||||
yield* git(publishRemote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", originRemote]);
|
||||
yield* git(cwd, ["remote", "add", "origin-1", publishRemote]);
|
||||
|
||||
const pushed = yield* driver.pushCurrentBranch(cwd, null, { remoteName: "origin-1" });
|
||||
|
||||
assert.deepInclude(pushed, {
|
||||
status: "pushed",
|
||||
branch: "main",
|
||||
upstreamBranch: "origin-1/main",
|
||||
setUpstream: true,
|
||||
});
|
||||
assert.equal(
|
||||
yield* git(publishRemote, ["log", "-1", "--pretty=%s", "main"]),
|
||||
"initial commit",
|
||||
);
|
||||
const originMain = yield* driver.execute({
|
||||
operation: "GitVcsDriver.test.originMainMissing",
|
||||
cwd: originRemote,
|
||||
args: ["show-ref", "--verify", "--quiet", "refs/heads/main"],
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
assert.notEqual(originMain.exitCode, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1445,7 +1445,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
});
|
||||
|
||||
const pushCurrentBranch: GitVcsDriverShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")(
|
||||
function* (cwd, fallbackBranch) {
|
||||
function* (cwd, fallbackBranch, options) {
|
||||
const details = yield* statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
@@ -1457,6 +1457,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
}
|
||||
|
||||
const requestedRemoteName = options?.remoteName?.trim() || null;
|
||||
if (requestedRemoteName) {
|
||||
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
|
||||
yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, [
|
||||
"push",
|
||||
"-u",
|
||||
requestedRemoteName,
|
||||
`HEAD:refs/heads/${publishBranch}`,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch,
|
||||
upstreamBranch: `${requestedRemoteName}/${publishBranch}`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}
|
||||
|
||||
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
|
||||
if (hasNoLocalDelta) {
|
||||
if (details.hasUpstream) {
|
||||
|
||||
@@ -58,6 +58,7 @@ import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentit
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
|
||||
import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import {
|
||||
BootstrapCredentialService,
|
||||
@@ -157,6 +158,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
|
||||
const sourceControlRepositories = yield* SourceControlRepositoryService;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const serverCommandId = (tag: string) =>
|
||||
@@ -797,6 +799,32 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.sourceControlLookupRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
sourceControlRepositories.lookupRepository(input),
|
||||
{
|
||||
"rpc.aggregate": "source-control",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.sourceControlCloneRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlCloneRepository,
|
||||
sourceControlRepositories.cloneRepository(input),
|
||||
{
|
||||
"rpc.aggregate": "source-control",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.sourceControlPublishRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlPublishRepository,
|
||||
sourceControlRepositories
|
||||
.publishRepository(input)
|
||||
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{
|
||||
"rpc.aggregate": "source-control",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.projectsSearchEntries]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsSearchEntries,
|
||||
|
||||
@@ -210,6 +210,7 @@ function createMockEnvironmentApi(input: {
|
||||
filesystem: {
|
||||
browse: input.browse,
|
||||
},
|
||||
sourceControl: {} as EnvironmentApi["sourceControl"],
|
||||
vcs: {} as EnvironmentApi["vcs"],
|
||||
git: {} as EnvironmentApi["git"],
|
||||
orchestration: {
|
||||
@@ -4338,8 +4339,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForCommandPaletteShortcutLabel();
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
@@ -4391,8 +4391,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForCommandPaletteShortcutLabel();
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
@@ -4465,13 +4464,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
await waitForCommandPaletteShortcutLabel();
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("Local folder", { exact: true }).click();
|
||||
|
||||
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
|
||||
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
|
||||
@@ -4518,6 +4517,126 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows clone destination controls after resolving an add project repository", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-command-palette-add-project-remote" as MessageId,
|
||||
targetText: "command palette add project remote",
|
||||
}),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
keybindings: [
|
||||
{
|
||||
command: "commandPalette.toggle",
|
||||
shortcut: {
|
||||
key: "k",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.filesystemBrowse) {
|
||||
return {
|
||||
parentPath: "~/",
|
||||
entries: [{ name: "Development", fullPath: "~/Development" }],
|
||||
};
|
||||
}
|
||||
|
||||
if (body._tag === WS_METHODS.sourceControlLookupRepository) {
|
||||
return {
|
||||
provider: "github",
|
||||
nameWithOwner: "t3-oss/t3-env",
|
||||
url: "https://github.com/t3-oss/t3-env",
|
||||
sshUrl: "[email protected]:t3-oss/t3-env.git",
|
||||
};
|
||||
}
|
||||
|
||||
if (body._tag === WS_METHODS.sourceControlCloneRepository) {
|
||||
return {
|
||||
cwd: body.destinationPath,
|
||||
remoteUrl: body.remoteUrl,
|
||||
repository: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
|
||||
const palette = page.getByTestId("command-palette");
|
||||
await openCommandPaletteFromTrigger();
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("GitHub repository", { exact: true }).click();
|
||||
|
||||
const repositoryInput = await waitForCommandPaletteInput(
|
||||
"Enter GitHub repository (owner/repo)",
|
||||
);
|
||||
await page.getByPlaceholder("Enter GitHub repository (owner/repo)").fill("t3-oss/t3-env");
|
||||
await dispatchInputKey(repositoryInput, { key: "Enter" });
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const clonePathInput = document.querySelector<HTMLInputElement>(
|
||||
'input[placeholder="Enter path (e.g. ~/projects/my-app)"]',
|
||||
);
|
||||
expect(clonePathInput?.value).toBe("~/");
|
||||
expect(document.body.textContent).toContain("Repository");
|
||||
expect(document.body.textContent).toContain("t3-oss/t3-env");
|
||||
expect(document.body.textContent).toContain("https://github.com/t3-oss/t3-env");
|
||||
expect(document.body.textContent).toContain("Select where to clone");
|
||||
expect(document.body.textContent).toContain("Development");
|
||||
expect(document.body.textContent).toContain("Clone");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await page
|
||||
.getByPlaceholder("Enter path (e.g. ~/projects/my-app)")
|
||||
.fill("~/Development/t3env");
|
||||
const clonePathInput = await waitForCommandPaletteInput(
|
||||
"Enter path (e.g. ~/projects/my-app)",
|
||||
);
|
||||
await dispatchInputKey(clonePathInput, { key: "Enter" });
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const cloneRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.sourceControlCloneRepository,
|
||||
) as { destinationPath?: string; remoteUrl?: string } | undefined;
|
||||
expect(cloneRequest).toMatchObject({
|
||||
remoteUrl: "[email protected]:t3-oss/t3-env.git",
|
||||
destinationPath: "~/Development/t3env",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens add project browse mode from the sidebar add button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -4870,6 +4989,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("Local folder", { exact: true }).click();
|
||||
await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument();
|
||||
await expect
|
||||
.element(palette.getByText("This device", { exact: true }).first())
|
||||
@@ -5085,6 +5205,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
await expect.element(palette).toBeInTheDocument();
|
||||
await palette.getByText("Add project", { exact: true }).click();
|
||||
await palette.getByText("Local folder", { exact: true }).click();
|
||||
|
||||
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
|
||||
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
|
||||
|
||||
@@ -420,7 +420,9 @@ function terminalIdListsEqual(left: readonly string[], right: readonly string[])
|
||||
if (left.length === 0) {
|
||||
return true;
|
||||
}
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
const sortedLeft = [...left].sort((a, b) => a.localeCompare(b));
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
const sortedRight = [...right].sort((a, b) => a.localeCompare(b));
|
||||
for (let index = 0; index < sortedLeft.length; index += 1) {
|
||||
if (sortedLeft[index] !== sortedRight[index]) {
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
type FilesystemBrowseResult,
|
||||
type ProjectId,
|
||||
ProviderInstanceId,
|
||||
type SourceControlProviderKind,
|
||||
type SourceControlRepositoryInfo,
|
||||
} from "@t3tools/contracts";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
@@ -17,6 +19,7 @@ import {
|
||||
CornerLeftUpIcon,
|
||||
FolderIcon,
|
||||
FolderPlusIcon,
|
||||
LinkIcon,
|
||||
MessageSquareIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
@@ -89,6 +92,7 @@ import {
|
||||
} from "./CommandPalette.logic";
|
||||
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
|
||||
import { CommandPaletteResults } from "./CommandPaletteResults";
|
||||
import { GitHubIcon, GitLabIcon } from "./Icons";
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
@@ -139,6 +143,70 @@ interface AddProjectEnvironmentOption {
|
||||
readonly isPrimary: boolean;
|
||||
}
|
||||
|
||||
type AddProjectRemoteProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
|
||||
type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
|
||||
|
||||
type AddProjectCloneFlow =
|
||||
| {
|
||||
readonly step: "repository";
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly source: AddProjectRemoteSource;
|
||||
}
|
||||
| {
|
||||
readonly step: "confirm";
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly source: AddProjectRemoteSource;
|
||||
readonly repositoryInput: string;
|
||||
readonly repository: SourceControlRepositoryInfo | null;
|
||||
readonly remoteUrl: string;
|
||||
};
|
||||
|
||||
const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = ["github", "gitlab", "url"];
|
||||
|
||||
function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
|
||||
switch (source) {
|
||||
case "github":
|
||||
return "GitHub";
|
||||
case "gitlab":
|
||||
return "GitLab";
|
||||
case "url":
|
||||
return "Git URL";
|
||||
}
|
||||
}
|
||||
|
||||
function remoteProjectSourceProvider(
|
||||
source: AddProjectRemoteSource,
|
||||
): AddProjectRemoteProviderKind | null {
|
||||
return source === "url" ? null : source;
|
||||
}
|
||||
|
||||
function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: string): ReactNode {
|
||||
switch (source) {
|
||||
case "github":
|
||||
return <GitHubIcon className={className} />;
|
||||
case "gitlab":
|
||||
return <GitLabIcon className={className} />;
|
||||
case "url":
|
||||
return <LinkIcon className={className} />;
|
||||
}
|
||||
}
|
||||
|
||||
function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null {
|
||||
if (!flow) return null;
|
||||
if (flow.step === "confirm") return null;
|
||||
if (flow.source === "url") {
|
||||
return "Enter Git clone URL";
|
||||
}
|
||||
return `Enter ${remoteProjectSourceLabel(flow.source)} repository (owner/repo)`;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
return "An error occurred.";
|
||||
}
|
||||
|
||||
export function CommandPalette({ children }: { children: ReactNode }) {
|
||||
const open = useCommandPaletteStore((store) => store.open);
|
||||
const setOpen = useCommandPaletteStore((store) => store.setOpen);
|
||||
@@ -227,6 +295,9 @@ function OpenCommandPaletteDialog() {
|
||||
null,
|
||||
);
|
||||
const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
|
||||
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
|
||||
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
|
||||
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null;
|
||||
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId);
|
||||
@@ -295,7 +366,10 @@ function OpenCommandPaletteDialog() {
|
||||
: null;
|
||||
return getEnvironmentBrowsePlatform(os);
|
||||
}, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
|
||||
const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
|
||||
const isRemoteProjectCloneFlow = addProjectCloneFlow !== null;
|
||||
const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
|
||||
const isBrowsing =
|
||||
!isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
|
||||
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
|
||||
const getAddProjectInitialQueryForEnvironment = useCallback(
|
||||
(environmentId: EnvironmentId | null): string => {
|
||||
@@ -541,6 +615,7 @@ function OpenCommandPaletteDialog() {
|
||||
}
|
||||
|
||||
function popView(): void {
|
||||
setAddProjectCloneFlow(null);
|
||||
if (viewStack.length <= 1) {
|
||||
setAddProjectEnvironmentId(null);
|
||||
}
|
||||
@@ -560,6 +635,7 @@ function OpenCommandPaletteDialog() {
|
||||
const startAddProjectBrowse = useCallback(
|
||||
(environmentId: EnvironmentId): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow(null);
|
||||
pushPaletteView({
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: [],
|
||||
@@ -569,6 +645,19 @@ function OpenCommandPaletteDialog() {
|
||||
[getAddProjectInitialQueryForEnvironment],
|
||||
);
|
||||
|
||||
const startAddProjectClone = useCallback(
|
||||
(environmentId: EnvironmentId, source: AddProjectRemoteSource): void => {
|
||||
setAddProjectEnvironmentId(environmentId);
|
||||
setAddProjectCloneFlow({ step: "repository", environmentId, source });
|
||||
pushPaletteView({
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: [],
|
||||
initialQuery: "",
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
|
||||
(option) => ({
|
||||
kind: "action",
|
||||
@@ -595,6 +684,156 @@ function OpenCommandPaletteDialog() {
|
||||
[addProjectEnvironmentItems],
|
||||
);
|
||||
|
||||
const addProjectRemoteEnvironmentGroups = useMemo<
|
||||
Record<AddProjectRemoteSource, CommandPaletteView["groups"]>
|
||||
>(() => {
|
||||
const buildGroups = (source: AddProjectRemoteSource): CommandPaletteView["groups"] => [
|
||||
{
|
||||
value: `environments:${source}`,
|
||||
label: "Environments",
|
||||
items: addProjectEnvironmentOptions.map((option) => ({
|
||||
kind: "action" as const,
|
||||
value: `action:add-project:${source}:environment:${option.environmentId}`,
|
||||
searchTerms: [
|
||||
option.label,
|
||||
option.environmentId,
|
||||
option.isPrimary ? "this device" : "",
|
||||
remoteProjectSourceLabel(source),
|
||||
],
|
||||
title: option.label,
|
||||
description: option.isPrimary ? "This device" : option.environmentId,
|
||||
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
startAddProjectClone(option.environmentId, source);
|
||||
},
|
||||
})),
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
github: buildGroups("github"),
|
||||
gitlab: buildGroups("gitlab"),
|
||||
url: buildGroups("url"),
|
||||
};
|
||||
}, [addProjectEnvironmentOptions, startAddProjectClone]);
|
||||
|
||||
const openAddProjectCloneFlow = useCallback(
|
||||
(source: AddProjectRemoteSource) => {
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
pushPaletteView({
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: addProjectRemoteEnvironmentGroups[source],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const environmentId = defaultAddProjectEnvironmentId;
|
||||
if (!environmentId) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to clone project",
|
||||
description: "No environment is available.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
startAddProjectClone(environmentId, source);
|
||||
},
|
||||
[
|
||||
addProjectEnvironmentOptions.length,
|
||||
addProjectRemoteEnvironmentGroups,
|
||||
defaultAddProjectEnvironmentId,
|
||||
startAddProjectClone,
|
||||
],
|
||||
);
|
||||
|
||||
const addProjectSourceGroups = useMemo<CommandPaletteView["groups"]>(() => {
|
||||
const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
sourceItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project:local",
|
||||
searchTerms: ["local", "folder", "directory", "browse", "environment"],
|
||||
title: "Local folder",
|
||||
description: "Browse a folder on disk",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectEnvironmentGroups,
|
||||
});
|
||||
} else {
|
||||
sourceItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project:local",
|
||||
searchTerms: ["local", "folder", "directory", "browse"],
|
||||
title: "Local folder",
|
||||
description: "Browse a folder on disk",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
const environmentId = defaultAddProjectEnvironmentId;
|
||||
if (!environmentId) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to browse projects",
|
||||
description: "No environment is available.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
startAddProjectBrowse(environmentId);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
for (const source of REMOTE_PROJECT_SOURCES) {
|
||||
const label = remoteProjectSourceLabel(source);
|
||||
const title = source === "url" ? "Git URL" : `${label} repository`;
|
||||
const description =
|
||||
source === "url" ? "Clone from a remote URL" : `Clone ${label} owner/repo`;
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
sourceItems.push({
|
||||
kind: "submenu",
|
||||
value: `action:add-project:${source}`,
|
||||
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
|
||||
title,
|
||||
description,
|
||||
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
|
||||
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
|
||||
groups: addProjectRemoteEnvironmentGroups[source],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
sourceItems.push({
|
||||
kind: "action",
|
||||
value: `action:add-project:${source}`,
|
||||
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
|
||||
title,
|
||||
description,
|
||||
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
openAddProjectCloneFlow(source);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return [{ value: "sources", label: "Sources", items: sourceItems }];
|
||||
}, [
|
||||
addProjectEnvironmentGroups,
|
||||
addProjectEnvironmentOptions.length,
|
||||
addProjectRemoteEnvironmentGroups,
|
||||
defaultAddProjectEnvironmentId,
|
||||
openAddProjectCloneFlow,
|
||||
startAddProjectBrowse,
|
||||
]);
|
||||
|
||||
const openAddProjectFlow = useCallback(() => {
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
pushPaletteView({
|
||||
@@ -674,29 +913,29 @@ function OpenCommandPaletteDialog() {
|
||||
});
|
||||
}
|
||||
|
||||
if (addProjectEnvironmentOptions.length > 1) {
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project",
|
||||
searchTerms: ["add project", "folder", "directory", "browse", "environment"],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectEnvironmentGroups,
|
||||
});
|
||||
} else {
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
value: "action:add-project",
|
||||
searchTerms: ["add project", "folder", "directory", "browse"],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
keepOpen: true,
|
||||
run: async () => {
|
||||
openAddProjectFlow();
|
||||
},
|
||||
});
|
||||
}
|
||||
actionItems.push({
|
||||
kind: "submenu",
|
||||
value: "action:add-project",
|
||||
searchTerms: [
|
||||
"add project",
|
||||
"folder",
|
||||
"directory",
|
||||
"browse",
|
||||
"clone",
|
||||
"remote",
|
||||
"repository",
|
||||
"repo",
|
||||
"git",
|
||||
"github",
|
||||
"gitlab",
|
||||
"url",
|
||||
"environment",
|
||||
],
|
||||
title: "Add project",
|
||||
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
|
||||
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
|
||||
groups: addProjectSourceGroups,
|
||||
});
|
||||
|
||||
actionItems.push({
|
||||
kind: "action",
|
||||
@@ -820,6 +1059,137 @@ function OpenCommandPaletteDialog() {
|
||||
],
|
||||
);
|
||||
|
||||
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
|
||||
return getAddProjectInitialQueryForEnvironment(environmentId);
|
||||
}
|
||||
|
||||
async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
|
||||
if (!addProjectCloneFlow) {
|
||||
return;
|
||||
}
|
||||
|
||||
const api = readEnvironmentApi(addProjectCloneFlow.environmentId);
|
||||
if (!api) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to clone project",
|
||||
description: "Environment API is not available.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (addProjectCloneFlow.step === "repository") {
|
||||
const rawRepository = query.trim();
|
||||
if (rawRepository.length === 0 || isRemoteProjectLookingUp) {
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = remoteProjectSourceProvider(addProjectCloneFlow.source);
|
||||
if (!provider) {
|
||||
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
|
||||
setAddProjectCloneFlow({
|
||||
step: "confirm",
|
||||
environmentId: addProjectCloneFlow.environmentId,
|
||||
source: addProjectCloneFlow.source,
|
||||
repositoryInput: rawRepository,
|
||||
repository: null,
|
||||
remoteUrl: rawRepository,
|
||||
});
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(destinationPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRemoteProjectLookingUp(true);
|
||||
try {
|
||||
const repository = await api.sourceControl.lookupRepository({
|
||||
provider,
|
||||
repository: rawRepository,
|
||||
});
|
||||
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
|
||||
setAddProjectCloneFlow({
|
||||
step: "confirm",
|
||||
environmentId: addProjectCloneFlow.environmentId,
|
||||
source: addProjectCloneFlow.source,
|
||||
repositoryInput: rawRepository,
|
||||
repository,
|
||||
remoteUrl: repository.sshUrl,
|
||||
});
|
||||
setHighlightedItemValue(null);
|
||||
setQuery(destinationPath);
|
||||
setBrowseGeneration((generation) => generation + 1);
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Repository lookup failed",
|
||||
description: errorMessage(error),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsRemoteProjectLookingUp(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const rawDestination = (destinationPathInput ?? query).trim();
|
||||
if (rawDestination.length === 0 || isRemoteProjectCloning) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Clone failed",
|
||||
description: "Windows-style paths are only supported on Windows.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Clone failed",
|
||||
description: "Relative paths require an active project.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const destinationPath = resolveProjectPathForDispatch(
|
||||
rawDestination,
|
||||
currentProjectCwdForBrowse,
|
||||
);
|
||||
if (destinationPath.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRemoteProjectCloning(true);
|
||||
try {
|
||||
const result = await api.sourceControl.cloneRepository({
|
||||
remoteUrl: addProjectCloneFlow.remoteUrl,
|
||||
destinationPath,
|
||||
});
|
||||
await handleAddProject(result.cwd);
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Clone failed",
|
||||
description: errorMessage(error),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsRemoteProjectCloning(false);
|
||||
}
|
||||
}
|
||||
|
||||
function browseTo(name: string): void {
|
||||
const nextQuery = appendBrowsePathSegment(query, name);
|
||||
setHighlightedItemValue(null);
|
||||
@@ -858,13 +1228,38 @@ function OpenCommandPaletteDialog() {
|
||||
browseUp,
|
||||
browseTo,
|
||||
});
|
||||
const cloneDestinationBrowseGroups = useMemo(
|
||||
() =>
|
||||
browseGroups.map((group) =>
|
||||
group.value === "directories" ? { ...group, label: "Select where to clone" } : group,
|
||||
),
|
||||
[browseGroups],
|
||||
);
|
||||
|
||||
let displayedGroups = filteredGroups;
|
||||
if (isBrowsing) {
|
||||
const remoteProjectContext = useMemo(() => {
|
||||
if (addProjectCloneFlow?.step !== "confirm") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
title: addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.repositoryInput,
|
||||
description: addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl,
|
||||
icon: remoteProjectSourceIcon(addProjectCloneFlow.source, ITEM_ICON_CLASS),
|
||||
};
|
||||
}, [addProjectCloneFlow]);
|
||||
|
||||
let displayedGroups: CommandPaletteView["groups"] = filteredGroups;
|
||||
if (addProjectCloneFlow?.step === "repository") {
|
||||
displayedGroups = [];
|
||||
} else if (addProjectCloneFlow?.step === "confirm") {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups;
|
||||
} else if (isBrowsing) {
|
||||
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
|
||||
}
|
||||
|
||||
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const inputPlaceholder =
|
||||
remoteProjectInputPlaceholder(addProjectCloneFlow) ??
|
||||
getCommandPaletteInputPlaceholder(paletteMode);
|
||||
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
|
||||
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
|
||||
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
|
||||
@@ -876,8 +1271,25 @@ function OpenCommandPaletteDialog() {
|
||||
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
|
||||
const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
|
||||
const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm";
|
||||
const submitActionLabel = isCloneDestinationStep
|
||||
? willCreateProjectPath
|
||||
? "Create & Clone"
|
||||
: "Clone"
|
||||
: willCreateProjectPath
|
||||
? "Create & Add"
|
||||
: "Add";
|
||||
const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
|
||||
const remoteProjectButtonLabel = addProjectCloneFlow
|
||||
? addProjectCloneFlow.source === "url"
|
||||
? "Continue"
|
||||
: "Lookup"
|
||||
: null;
|
||||
const isRemoteProjectPending = isRemoteProjectLookingUp || isRemoteProjectCloning;
|
||||
const canSubmitRemoteProjectFlow =
|
||||
addProjectCloneFlow?.step === "repository" &&
|
||||
query.trim().length > 0 &&
|
||||
!isRemoteProjectPending;
|
||||
const fileManagerName = getLocalFileManagerName(navigator.platform);
|
||||
const canOpenProjectFromFileManager =
|
||||
isBrowsing &&
|
||||
@@ -915,6 +1327,12 @@ function OpenCommandPaletteDialog() {
|
||||
}
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
|
||||
if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
void submitAddProjectCloneFlow();
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldSubmitBrowsePath =
|
||||
canSubmitBrowsePath &&
|
||||
event.key === "Enter" &&
|
||||
@@ -922,7 +1340,11 @@ function OpenCommandPaletteDialog() {
|
||||
|
||||
if (shouldSubmitBrowsePath) {
|
||||
event.preventDefault();
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -999,9 +1421,9 @@ function OpenCommandPaletteDialog() {
|
||||
}}
|
||||
>
|
||||
<Command
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
|
||||
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
|
||||
aria-label="Command palette"
|
||||
autoHighlight={isBrowsing ? false : "always"}
|
||||
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
|
||||
mode="none"
|
||||
onItemHighlighted={(value) => {
|
||||
setHighlightedItemValue(typeof value === "string" ? value : null);
|
||||
@@ -1011,7 +1433,15 @@ function OpenCommandPaletteDialog() {
|
||||
>
|
||||
<div className="relative">
|
||||
<CommandInput
|
||||
className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
|
||||
className={
|
||||
addProjectCloneFlow?.step === "repository"
|
||||
? "pe-32"
|
||||
: isBrowsing
|
||||
? willCreateProjectPath
|
||||
? "pe-36"
|
||||
: "pe-16"
|
||||
: undefined
|
||||
}
|
||||
placeholder={inputPlaceholder}
|
||||
wrapperClassName={
|
||||
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
|
||||
@@ -1036,7 +1466,28 @@ function OpenCommandPaletteDialog() {
|
||||
: {})}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
{isBrowsing ? (
|
||||
{addProjectCloneFlow?.step === "repository" ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
className="absolute end-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
|
||||
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
disabled={!canSubmitRemoteProjectFlow}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
void submitAddProjectCloneFlow();
|
||||
}}
|
||||
title={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
|
||||
>
|
||||
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>Enter</Kbd>
|
||||
</KbdGroup>
|
||||
</Button>
|
||||
) : isBrowsing ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
@@ -1046,7 +1497,9 @@ function OpenCommandPaletteDialog() {
|
||||
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
|
||||
)}
|
||||
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
disabled={relativePathNeedsActiveProject}
|
||||
disabled={
|
||||
relativePathNeedsActiveProject || (isCloneDestinationStep && isRemoteProjectPending)
|
||||
}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
@@ -1054,11 +1507,17 @@ function OpenCommandPaletteDialog() {
|
||||
if (relativePathNeedsActiveProject) {
|
||||
return;
|
||||
}
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
if (isCloneDestinationStep) {
|
||||
void submitAddProjectCloneFlow(resolvedAddProjectPath);
|
||||
} else {
|
||||
void handleAddProject(resolvedAddProjectPath);
|
||||
}
|
||||
}}
|
||||
title={`${submitActionLabel} (${addShortcutLabel})`}
|
||||
>
|
||||
<span>{submitActionLabel}</span>
|
||||
<span>
|
||||
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
|
||||
</span>
|
||||
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
|
||||
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
|
||||
</KbdGroup>
|
||||
@@ -1066,19 +1525,47 @@ function OpenCommandPaletteDialog() {
|
||||
) : null}
|
||||
</div>
|
||||
<CommandPanel className="max-h-[min(28rem,70vh)]">
|
||||
{remoteProjectContext ? (
|
||||
<div className="p-2 pb-0">
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Repository
|
||||
</div>
|
||||
<div className="flex min-h-8 items-center gap-2 rounded-sm px-2 py-1.5">
|
||||
{remoteProjectContext.icon}
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-foreground text-sm">
|
||||
{remoteProjectContext.title}
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">
|
||||
{remoteProjectContext.description}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<CommandPaletteResults
|
||||
groups={displayedGroups}
|
||||
highlightedItemValue={highlightedItemValue}
|
||||
isActionsOnly={isActionsOnly}
|
||||
keybindings={keybindings}
|
||||
onExecuteItem={executeItem}
|
||||
{...(relativePathNeedsActiveProject
|
||||
? { emptyStateMessage: "Relative paths require an active project." }
|
||||
: willCreateProjectPath
|
||||
? {
|
||||
emptyStateMessage: "Press Enter to create this folder and add it as a project.",
|
||||
}
|
||||
: {})}
|
||||
{...(addProjectCloneFlow?.step === "repository"
|
||||
? {
|
||||
emptyStateMessage:
|
||||
addProjectCloneFlow.source === "url"
|
||||
? "Enter a Git clone URL and press Enter to continue."
|
||||
: "Enter a repository path and press Enter to look it up.",
|
||||
}
|
||||
: addProjectCloneFlow?.step === "confirm"
|
||||
? { emptyStateMessage: "Choose a destination path and press Enter to clone." }
|
||||
: relativePathNeedsActiveProject
|
||||
? { emptyStateMessage: "Relative paths require an active project." }
|
||||
: willCreateProjectPath
|
||||
? {
|
||||
emptyStateMessage:
|
||||
"Press Enter to create this folder and add it as a project.",
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</CommandPanel>
|
||||
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
|
||||
@@ -1092,7 +1579,14 @@ function OpenCommandPaletteDialog() {
|
||||
</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Navigate</span>
|
||||
</KbdGroup>
|
||||
{!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
|
||||
{addProjectCloneFlow?.step === "repository" ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>
|
||||
{remoteProjectButtonLabel ?? "Continue"}
|
||||
</span>
|
||||
</KbdGroup>
|
||||
) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? (
|
||||
<KbdGroup className="items-center gap-1.5">
|
||||
<Kbd>Enter</Kbd>
|
||||
<span className={cn("text-muted-foreground/80")}>Select</span>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
TextWrapIcon,
|
||||
} from "lucide-react";
|
||||
@@ -172,6 +173,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const settings = useSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const previousDiffOpenRef = useRef(false);
|
||||
@@ -277,6 +279,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
threadId: activeThreadId,
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
enabled: isGitRepo,
|
||||
}),
|
||||
@@ -317,9 +320,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
useEffect(() => {
|
||||
if (diffOpen && !previousDiffOpenRef.current) {
|
||||
setDiffWordWrap(settings.diffWordWrap);
|
||||
setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace);
|
||||
}
|
||||
previousDiffOpenRef.current = diffOpen;
|
||||
}, [diffOpen, settings.diffWordWrap]);
|
||||
}, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath || !patchViewportRef.current) {
|
||||
@@ -551,6 +555,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffIgnoreWhitespace}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffIgnoreWhitespace(Boolean(pressed));
|
||||
}}
|
||||
>
|
||||
<PilcrowIcon className="size-3" />
|
||||
</Toggle>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -100,12 +100,14 @@ vi.mock("~/editorPreferences", () => ({
|
||||
vi.mock("~/lib/gitReactQuery", () => ({
|
||||
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
|
||||
gitMutationKeys: {
|
||||
publishRepository: vi.fn(() => ["publish-repository"]),
|
||||
pull: vi.fn(() => ["pull"]),
|
||||
runStackedAction: vi.fn(() => ["run-stacked-action"]),
|
||||
},
|
||||
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
|
||||
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
|
||||
invalidateGitQueries: invalidateGitQueriesSpy,
|
||||
sourceControlPublishRepositoryMutationOptions: vi.fn(() => ({ __kind: "publish-repository" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/lib/gitStatusState", () => ({
|
||||
|
||||
@@ -730,7 +730,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolveQuickAction disables push-and-pr flows when no origin remote exists", () => {
|
||||
it("resolveQuickAction publishes when no origin remote exists", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
@@ -742,10 +742,9 @@ describe("when: ref has no upstream configured", () => {
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(quick, {
|
||||
kind: "show_hint",
|
||||
label: "Push",
|
||||
hint: 'Add an "origin" remote before pushing or creating a pull request.',
|
||||
disabled: true,
|
||||
kind: "open_publish",
|
||||
label: "Publish repository",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -779,7 +778,7 @@ describe("when: ref has no upstream configured", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("buildMenuItems disables push and create PR when no origin remote exists", () => {
|
||||
it("buildMenuItems hides push and create PR when no origin remote exists", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
|
||||
false,
|
||||
@@ -794,22 +793,6 @@ describe("when: ref has no upstream configured", () => {
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
icon: "push",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "push",
|
||||
},
|
||||
{
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: true,
|
||||
icon: "pr",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "create_pr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -3,11 +3,30 @@ import type {
|
||||
GitActionProgressEvent,
|
||||
GitRunStackedActionResult,
|
||||
GitStackedAction,
|
||||
SourceControlCloneProtocol,
|
||||
SourceControlProviderKind,
|
||||
SourceControlPublishRepositoryResult,
|
||||
SourceControlRepositoryVisibility,
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Option } from "effect";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
CloudUploadIcon,
|
||||
ExternalLinkIcon,
|
||||
GitCommitIcon,
|
||||
InfoIcon,
|
||||
LockIcon,
|
||||
GlobeIcon,
|
||||
} from "lucide-react";
|
||||
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
|
||||
import { GitHubIcon, GitLabIcon } from "~/components/Icons";
|
||||
import { RadioGroup } from "~/components/ui/radio-group";
|
||||
import { Spinner } from "~/components/ui/spinner";
|
||||
import { cn } from "~/lib/utils";
|
||||
import {
|
||||
buildGitActionProgressStages,
|
||||
buildMenuItems,
|
||||
@@ -34,6 +53,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "~/components/ui/dialog";
|
||||
import { Group, GroupSeparator } from "~/components/ui/group";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
@@ -45,8 +65,10 @@ import {
|
||||
gitMutationKeys,
|
||||
gitPullMutationOptions,
|
||||
gitRunStackedActionMutationOptions,
|
||||
sourceControlPublishRepositoryMutationOptions,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
|
||||
import { useSourceControlDiscovery } from "~/lib/sourceControlDiscoveryState";
|
||||
import { newCommandId, randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
|
||||
@@ -71,6 +93,8 @@ interface PendingDefaultBranchAction {
|
||||
filePaths?: string[];
|
||||
}
|
||||
|
||||
type PublishProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
interface ActiveGitActionProgress {
|
||||
@@ -143,6 +167,7 @@ function GitQuickActionIcon({
|
||||
}) {
|
||||
const iconClassName = "size-3.5";
|
||||
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
|
||||
if (quickAction.kind === "run_action") {
|
||||
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
|
||||
@@ -184,8 +209,35 @@ export default function GitActionsControl({
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
|
||||
const [isEditingFiles, setIsEditingFiles] = useState(false);
|
||||
const [isPublishDialogOpen, setIsPublishDialogOpen] = useState(false);
|
||||
const [publishProvider, setPublishProvider] = useState<PublishProviderKind>("github");
|
||||
const [publishRepository, setPublishRepository] = useState("");
|
||||
const [publishVisibility, setPublishVisibility] =
|
||||
useState<SourceControlRepositoryVisibility>("private");
|
||||
const [publishRemoteName, setPublishRemoteName] = useState("origin");
|
||||
const [publishProtocol, setPublishProtocol] = useState<SourceControlCloneProtocol>("ssh");
|
||||
const [publishWizardStep, setPublishWizardStep] = useState(0);
|
||||
const [publishAdvancedOpen, setPublishAdvancedOpen] = useState(false);
|
||||
const [publishError, setPublishError] = useState<string | null>(null);
|
||||
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
|
||||
null,
|
||||
);
|
||||
const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false);
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
const sourceControlDiscovery = useSourceControlDiscovery();
|
||||
const publishAccountByProvider = useMemo(() => {
|
||||
const accounts: Record<PublishProviderKind, string | null> = { github: null, gitlab: null };
|
||||
for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
|
||||
if (provider.kind === "github" || provider.kind === "gitlab") {
|
||||
accounts[provider.kind] = Option.getOrNull(provider.auth.account);
|
||||
}
|
||||
}
|
||||
return accounts;
|
||||
}, [sourceControlDiscovery.data]);
|
||||
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
|
||||
? `${publishAccountByProvider[publishProvider]}/`
|
||||
: "";
|
||||
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
|
||||
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
|
||||
|
||||
@@ -297,6 +349,13 @@ export default function GitActionsControl({
|
||||
const pullMutation = useMutation(
|
||||
gitPullMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }),
|
||||
);
|
||||
const publishRepositoryMutation = useMutation(
|
||||
sourceControlPublishRepositoryMutationOptions({
|
||||
environmentId: activeEnvironmentId,
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
}),
|
||||
);
|
||||
|
||||
const isRunStackedActionRunning =
|
||||
useIsMutating({
|
||||
@@ -304,7 +363,11 @@ export default function GitActionsControl({
|
||||
}) > 0;
|
||||
const isPullRunning =
|
||||
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
|
||||
const isPublishRunning =
|
||||
useIsMutating({
|
||||
mutationKey: gitMutationKeys.publishRepository(activeEnvironmentId, gitCwd),
|
||||
}) > 0;
|
||||
const isGitActionRunning = isRunStackedActionRunning || isPullRunning || isPublishRunning;
|
||||
const isSelectingWorktreeBase =
|
||||
!activeServerThread &&
|
||||
activeDraftThread?.envMode === "worktree" &&
|
||||
@@ -371,6 +434,13 @@ export default function GitActionsControl({
|
||||
};
|
||||
}, [updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPublishDialogOpen || hasUserEditedPublishRepository) {
|
||||
return;
|
||||
}
|
||||
setPublishRepository(publishRepositoryPrefill);
|
||||
}, [isPublishDialogOpen, hasUserEditedPublishRepository, publishRepositoryPrefill]);
|
||||
|
||||
useEffect(() => {
|
||||
if (gitCwd === null) {
|
||||
return;
|
||||
@@ -717,6 +787,10 @@ export default function GitActionsControl({
|
||||
void openExistingPr();
|
||||
return;
|
||||
}
|
||||
if (quickAction.kind === "open_publish") {
|
||||
setIsPublishDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
if (quickAction.kind === "run_pull") {
|
||||
const promise = pullMutation.mutateAsync();
|
||||
void toastManager.promise<
|
||||
@@ -814,6 +888,47 @@ export default function GitActionsControl({
|
||||
[gitCwd, threadToastData],
|
||||
);
|
||||
|
||||
const canPublishRepository = isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
|
||||
const canSubmitPublishRepository = (() => {
|
||||
if (publishRepositoryMutation.isPending) return false;
|
||||
const repositoryParts = publishRepository.trim().split("/");
|
||||
const owner = repositoryParts[0]?.trim() ?? "";
|
||||
const rest = repositoryParts.slice(1);
|
||||
const name = rest.join("/").trim();
|
||||
return owner.length > 0 && name.length > 0;
|
||||
})();
|
||||
|
||||
const publishHost = publishProvider === "github" ? "github.com" : "gitlab.com";
|
||||
const publishPathPlaceholder = publishProvider === "github" ? "owner/repo" : "group/project";
|
||||
const publishProviderLabel = publishProvider === "github" ? "GitHub" : "GitLab";
|
||||
|
||||
const submitPublishRepository = () => {
|
||||
if (!canSubmitPublishRepository) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPublishError(null);
|
||||
|
||||
void publishRepositoryMutation
|
||||
.mutateAsync({
|
||||
provider: publishProvider,
|
||||
repository: publishRepository.trim(),
|
||||
visibility: publishVisibility,
|
||||
remoteName: publishRemoteName.trim() || "origin",
|
||||
protocol: publishProtocol,
|
||||
})
|
||||
.then((result) => {
|
||||
setPublishResult(result);
|
||||
setPublishWizardStep(2);
|
||||
void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
setPublishError(err instanceof Error ? err.message : "An error occurred.");
|
||||
});
|
||||
};
|
||||
|
||||
if (!gitCwd) return null;
|
||||
|
||||
return (
|
||||
@@ -928,6 +1043,17 @@ export default function GitActionsControl({
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{canPublishRepository ? (
|
||||
<MenuItem
|
||||
disabled={isGitActionRunning}
|
||||
onClick={() => {
|
||||
setIsPublishDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<CloudUploadIcon />
|
||||
Publish repository...
|
||||
</MenuItem>
|
||||
) : null}
|
||||
{gitStatusForActions?.refName === null && (
|
||||
<p className="px-2 py-1.5 text-xs text-warning">
|
||||
Detached HEAD: create and checkout a refName to enable push and pull request
|
||||
@@ -1120,6 +1246,420 @@ export default function GitActionsControl({
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={isPublishDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsPublishDialogOpen(open);
|
||||
if (!open) {
|
||||
setPublishRemoteName("origin");
|
||||
setPublishRepository("");
|
||||
setHasUserEditedPublishRepository(false);
|
||||
setPublishWizardStep(0);
|
||||
setPublishAdvancedOpen(false);
|
||||
setPublishError(null);
|
||||
setPublishResult(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Publish repository</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick where to host it, then point us at a repo to push to.
|
||||
</DialogDescription>
|
||||
<div className="mt-1 grid grid-cols-3 gap-2">
|
||||
{(["Provider", "Repository", "Summary"] as const).map((label, index) => {
|
||||
const summary =
|
||||
index === 0 && publishWizardStep > 0
|
||||
? publishProviderLabel
|
||||
: index === 1 && publishWizardStep > 1 && publishResult
|
||||
? publishResult.repository.nameWithOwner
|
||||
: null;
|
||||
const isComplete = index < publishWizardStep;
|
||||
const isDoneStep = index === 2;
|
||||
// The summary step is only reachable via a successful submit;
|
||||
// disallow user-driven navigation to or from it.
|
||||
const isClickable =
|
||||
publishWizardStep !== 2 && !isDoneStep && index <= publishWizardStep;
|
||||
return (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={isClickable ? () => setPublishWizardStep(index) : undefined}
|
||||
disabled={!isClickable}
|
||||
className={cn(
|
||||
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left transition",
|
||||
index === publishWizardStep
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25"
|
||||
: isComplete
|
||||
? "border-border bg-background"
|
||||
: "border-border bg-muted/40",
|
||||
!isClickable && "cursor-default",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
|
||||
isComplete
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: index === publishWizardStep
|
||||
? "border-primary bg-background"
|
||||
: "border-muted-foreground/35 bg-background",
|
||||
)}
|
||||
>
|
||||
{isComplete ? <CheckIcon className="size-3" /> : null}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
Step {index + 1}
|
||||
</span>
|
||||
<span className="truncate text-xs font-semibold text-foreground">
|
||||
{label}
|
||||
{summary ? `: ${summary}` : ""}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Step 1: Provider */}
|
||||
{publishWizardStep === 0 && (
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<span
|
||||
id="publish-provider-cards-label"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Provider
|
||||
</span>
|
||||
<RadioGroup
|
||||
value={publishProvider}
|
||||
onValueChange={(value) => setPublishProvider(value as PublishProviderKind)}
|
||||
aria-labelledby="publish-provider-cards-label"
|
||||
className="grid grid-cols-2 gap-2.5"
|
||||
>
|
||||
{[
|
||||
{
|
||||
value: "github" as const,
|
||||
label: "GitHub",
|
||||
description: "github.com",
|
||||
Icon: GitHubIcon,
|
||||
},
|
||||
{
|
||||
value: "gitlab" as const,
|
||||
label: "GitLab",
|
||||
description: "gitlab.com",
|
||||
Icon: GitLabIcon,
|
||||
},
|
||||
].map((option) => {
|
||||
const isSelected = publishProvider === option.value;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<option.Icon className="size-5 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{option.description}
|
||||
</span>
|
||||
</span>
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
)}
|
||||
{publishWizardStep === 1 && (
|
||||
<DialogPanel className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="publish-repository-path"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Repository
|
||||
</label>
|
||||
<div className="flex items-stretch overflow-hidden rounded-md border border-input bg-background focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-ring">
|
||||
<span className="flex shrink-0 items-center gap-1.5 border-r border-input bg-muted/50 px-2.5 font-mono text-xs text-muted-foreground">
|
||||
{publishProvider === "github" ? (
|
||||
<GitHubIcon className="size-3.5" />
|
||||
) : (
|
||||
<GitLabIcon className="size-3.5" />
|
||||
)}
|
||||
{publishHost}/
|
||||
</span>
|
||||
<input
|
||||
id="publish-repository-path"
|
||||
name="publish-repository-path"
|
||||
value={publishRepository}
|
||||
onChange={(event) => {
|
||||
setPublishRepository(event.target.value);
|
||||
setHasUserEditedPublishRepository(true);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
submitPublishRepository();
|
||||
}
|
||||
}}
|
||||
placeholder={publishPathPlaceholder}
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
className="w-full bg-transparent px-3 py-2 font-mono text-sm placeholder:text-muted-foreground/60 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<span
|
||||
id="publish-visibility-cards-label"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Visibility
|
||||
</span>
|
||||
<RadioGroup
|
||||
value={publishVisibility}
|
||||
onValueChange={(value) =>
|
||||
setPublishVisibility(value as SourceControlRepositoryVisibility)
|
||||
}
|
||||
aria-labelledby="publish-visibility-cards-label"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
className="grid grid-cols-2 gap-2.5"
|
||||
>
|
||||
{[
|
||||
{
|
||||
value: "private" as const,
|
||||
label: "Private",
|
||||
description: "Only invited people",
|
||||
Icon: LockIcon,
|
||||
},
|
||||
{
|
||||
value: "public" as const,
|
||||
label: "Public",
|
||||
description: "Anyone on the web",
|
||||
Icon: GlobeIcon,
|
||||
},
|
||||
].map((option) => {
|
||||
const isSelected = publishVisibility === option.value;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
|
||||
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
|
||||
)}
|
||||
>
|
||||
<option.Icon
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium text-foreground">
|
||||
{option.label}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{option.description}
|
||||
</span>
|
||||
</span>
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPublishAdvancedOpen((prev) => !prev)}
|
||||
aria-expanded={publishAdvancedOpen}
|
||||
className="flex items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-3.5 transition-transform",
|
||||
publishAdvancedOpen ? "" : "-rotate-90",
|
||||
)}
|
||||
/>
|
||||
Advanced
|
||||
</button>
|
||||
{publishAdvancedOpen && (
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
<label className="space-y-1.5" htmlFor="publish-remote-name">
|
||||
<span className="text-xs font-medium text-foreground">Remote</span>
|
||||
<Input
|
||||
id="publish-remote-name"
|
||||
value={publishRemoteName}
|
||||
onChange={(event) => setPublishRemoteName(event.target.value)}
|
||||
placeholder="origin"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
/>
|
||||
</label>
|
||||
<div className="space-y-1.5">
|
||||
<span
|
||||
id="publish-protocol-label"
|
||||
className="text-xs font-medium text-foreground"
|
||||
>
|
||||
Protocol
|
||||
</span>
|
||||
<RadioGroup
|
||||
value={publishProtocol}
|
||||
onValueChange={(value) =>
|
||||
setPublishProtocol(value as SourceControlCloneProtocol)
|
||||
}
|
||||
aria-labelledby="publish-protocol-label"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
className="grid grid-cols-2 gap-2"
|
||||
>
|
||||
{(["ssh", "https"] as const).map((value) => {
|
||||
const isSelected = publishProtocol === value;
|
||||
return (
|
||||
<RadioPrimitive.Root
|
||||
key={value}
|
||||
value={value}
|
||||
className={cn(
|
||||
"rounded-md border px-3 py-1.5 text-center text-sm font-medium outline-none transition",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
isSelected
|
||||
? "border-primary bg-background ring-2 ring-primary/35 text-foreground"
|
||||
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{value === "ssh" ? "SSH" : "HTTPS"}
|
||||
</RadioPrimitive.Root>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{publishRepositoryMutation.isPending && (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground"
|
||||
>
|
||||
<Spinner className="size-3.5" aria-hidden />
|
||||
Publishing repository to {publishProviderLabel}...
|
||||
</div>
|
||||
)}
|
||||
{publishError && !publishRepositoryMutation.isPending && (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
|
||||
>
|
||||
<p className="font-medium">Publish failed</p>
|
||||
<p className="mt-0.5 text-destructive/90">{publishError}</p>
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
)}
|
||||
{publishWizardStep === 2 && publishResult && (
|
||||
<DialogPanel className="space-y-4">
|
||||
<div className="flex flex-col items-center gap-2 py-1 text-center">
|
||||
<span className="grid size-8 place-items-center rounded-full bg-success/15 text-success">
|
||||
<CheckIcon className="size-4" aria-hidden />
|
||||
</span>
|
||||
<h3 className="text-sm font-semibold text-foreground">
|
||||
{publishResult.status === "pushed"
|
||||
? "Repository published"
|
||||
: "Repository created"}
|
||||
</h3>
|
||||
<p className="max-w-xs text-pretty text-xs text-muted-foreground">
|
||||
{publishResult.status === "pushed"
|
||||
? `${publishResult.branch} is now live on ${publishProviderLabel}.`
|
||||
: `Remote "${publishResult.remoteName}" is set up. Make a commit and push it to share your code.`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2">
|
||||
{publishProvider === "github" ? (
|
||||
<GitHubIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<GitLabIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
|
||||
{publishResult.repository.nameWithOwner}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => {
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
void api.shell.openExternal(publishResult.repository.url);
|
||||
}}
|
||||
>
|
||||
<ExternalLinkIcon className="size-3.5" aria-hidden />
|
||||
Open on {publishProviderLabel}
|
||||
</Button>
|
||||
</DialogPanel>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{publishWizardStep === 2 ? (
|
||||
<Button size="sm" onClick={() => setIsPublishDialogOpen(false)}>
|
||||
Done
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={publishRepositoryMutation.isPending}
|
||||
onClick={() => {
|
||||
if (publishWizardStep === 0) {
|
||||
setIsPublishDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
setPublishWizardStep((step) => Math.max(0, step - 1));
|
||||
}}
|
||||
>
|
||||
{publishWizardStep === 0 ? "Cancel" : "Back"}
|
||||
</Button>
|
||||
{publishWizardStep < 1 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setPublishWizardStep((step) => Math.min(1, step + 1))}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!canSubmitPublishRepository}
|
||||
onClick={submitPublishRepository}
|
||||
>
|
||||
{publishRepositoryMutation.isPending ? (
|
||||
<>
|
||||
<Spinner className="size-3.5" aria-hidden />
|
||||
Publishing...
|
||||
</>
|
||||
) : (
|
||||
"Publish"
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={pendingDefaultBranchAction !== null}
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -386,6 +386,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap
|
||||
? ["Diff line wrapping"]
|
||||
: []),
|
||||
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
|
||||
? ["Diff whitespace changes"]
|
||||
: []),
|
||||
...(settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar
|
||||
? ["Auto-open task panel"]
|
||||
: []),
|
||||
@@ -415,6 +418,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.confirmThreadDelete,
|
||||
settings.addProjectBaseDirectory,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.timestampFormat,
|
||||
@@ -889,6 +893,32 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Hide whitespace changes"
|
||||
description="Set whether the diff panel ignores whitespace-only edits by default."
|
||||
resetAction={
|
||||
settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace ? (
|
||||
<SettingResetButton
|
||||
label="diff whitespace changes"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.diffIgnoreWhitespace}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({ diffIgnoreWhitespace: Boolean(checked) })
|
||||
}
|
||||
aria-label="Hide whitespace changes by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Assistant output"
|
||||
description="Show token-by-token output while a response is in progress."
|
||||
|
||||
@@ -57,6 +57,8 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
|
||||
jj: JujutsuIcon,
|
||||
};
|
||||
|
||||
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
|
||||
|
||||
function optionLabel(value: Option.Option<string>): string | null {
|
||||
return Option.getOrNull(value);
|
||||
}
|
||||
@@ -157,6 +159,11 @@ function itemSummary({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (!item.executable) {
|
||||
return <span>{item.installHint}</span>;
|
||||
}
|
||||
|
||||
if (auth.status === "unauthenticated") {
|
||||
return <span>Sign in with the {item.executable} CLI to enable pull request actions.</span>;
|
||||
}
|
||||
@@ -232,8 +239,8 @@ function SourceControlSectionSkeleton({
|
||||
}) {
|
||||
return (
|
||||
<SettingsSection title={title} headerAction={headerAction}>
|
||||
{Array.from({ length: 2 }, (_, index) => (
|
||||
<div key={index} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
|
||||
{SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
|
||||
<div key={row} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -25,6 +25,11 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
|
||||
filesystem: {
|
||||
browse: rpcClient.filesystem.browse,
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: rpcClient.sourceControl.lookupRepository,
|
||||
cloneRepository: rpcClient.sourceControl.cloneRepository,
|
||||
publishRepository: rpcClient.sourceControl.publishRepository,
|
||||
},
|
||||
vcs: {
|
||||
pull: rpcClient.vcs.pull,
|
||||
refreshStatus: rpcClient.vcs.refreshStatus,
|
||||
|
||||
@@ -98,6 +98,11 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
filesystem: {
|
||||
browse: vi.fn(),
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: vi.fn(),
|
||||
cloneRepository: vi.fn(),
|
||||
publishRepository: vi.fn(),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: vi.fn(),
|
||||
},
|
||||
|
||||
@@ -101,6 +101,13 @@ const lastAppliedProjectionVersionByEnvironment = new Map<
|
||||
let activeService: EnvironmentServiceState | null = null;
|
||||
let needsProviderInvalidation = false;
|
||||
|
||||
// TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY):
|
||||
// This file still owns web's legacy thread-detail subscription cache. Mobile
|
||||
// uses createThreadDetailManager from @t3tools/client-runtime for the same
|
||||
// retain/reconnect/evict lifecycle. When touching this logic, prefer migrating
|
||||
// web to the shared manager or extracting the missing adapter layer instead of
|
||||
// adding more behavior here.
|
||||
//
|
||||
// Thread detail subscription cache policy:
|
||||
// - Active consumers keep a subscription retained via refCount.
|
||||
// - Released subscriptions stay warm for a longer idle TTL to avoid churn
|
||||
@@ -746,6 +753,11 @@ function createEnvironmentConnectionHandlers() {
|
||||
return {
|
||||
applyShellEvent,
|
||||
syncShellSnapshot: (snapshot: OrchestrationShellSnapshot, environmentId: EnvironmentId) => {
|
||||
// TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY):
|
||||
// Shell snapshots already have createShellSnapshotManager in
|
||||
// @t3tools/client-runtime. Web currently projects snapshots straight into
|
||||
// its denormalized Zustand store; future shell changes should migrate or
|
||||
// bridge to the shared manager instead of growing this handler.
|
||||
if (
|
||||
!shouldApplyProjectionSnapshot({
|
||||
current: readLastAppliedProjectionVersion(environmentId),
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
type EnvironmentId,
|
||||
type GitActionProgressEvent,
|
||||
type GitStackedAction,
|
||||
type SourceControlPublishRepositoryInput,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -36,6 +37,8 @@ export const gitMutationKeys = {
|
||||
["git", "mutation", "pull", environmentId ?? null, cwd] as const,
|
||||
preparePullRequestThread: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "prepare-pull-request-thread", environmentId ?? null, cwd] as const,
|
||||
publishRepository: (environmentId: EnvironmentId | null, cwd: string | null) =>
|
||||
["git", "mutation", "publish-repository", environmentId ?? null, cwd] as const,
|
||||
};
|
||||
|
||||
export function invalidateGitQueries(
|
||||
@@ -228,6 +231,26 @@ export function gitPullMutationOptions(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export function sourceControlPublishRepositoryMutationOptions(input: {
|
||||
environmentId: EnvironmentId | null;
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.publishRepository(input.environmentId, input.cwd),
|
||||
mutationFn: async (args: Omit<SourceControlPublishRepositoryInput, "cwd">) => {
|
||||
if (!input.cwd || !input.environmentId) {
|
||||
throw new Error("Repository publishing is unavailable.");
|
||||
}
|
||||
const api = ensureEnvironmentApi(input.environmentId);
|
||||
return api.sourceControl.publishRepository({ cwd: input.cwd, ...args });
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
|
||||
*/
|
||||
|
||||
@@ -30,6 +30,7 @@ describe("providerQueryKeys.checkpointDiff", () => {
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: false,
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
@@ -44,10 +45,32 @@ describe("providerQueryKeys.checkpointDiff", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("includes ignoreWhitespace so normal and whitespace-hidden diffs do not collide", () => {
|
||||
const baseInput = {
|
||||
environmentId,
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
cacheScope: "turn:abc",
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
ignoreWhitespace: false,
|
||||
}),
|
||||
).not.toEqual(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
ignoreWhitespace: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkpointDiffQueryOptions", () => {
|
||||
it("forwards checkpoint range to the provider API", async () => {
|
||||
it("forwards checkpoint range to the provider API by default", async () => {
|
||||
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
mockNativeApi({ getTurnDiff, getFullThreadDiff });
|
||||
@@ -57,6 +80,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
|
||||
@@ -67,6 +91,33 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
expect(getFullThreadDiff).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards whitespace-hidden checkpoint range to the provider API", async () => {
|
||||
const getTurnDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
const getFullThreadDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
mockNativeApi({ getTurnDiff, getFullThreadDiff });
|
||||
|
||||
const options = checkpointDiffQueryOptions({
|
||||
environmentId,
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
await queryClient.fetchQuery(options);
|
||||
|
||||
expect(getTurnDiff).toHaveBeenCalledWith({
|
||||
threadId,
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
expect(getFullThreadDiff).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -81,6 +132,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
cacheScope: "thread:all",
|
||||
});
|
||||
|
||||
@@ -90,6 +142,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
expect(getFullThreadDiff).toHaveBeenCalledWith({
|
||||
threadId,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
expect(getTurnDiff).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -104,6 +157,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 4,
|
||||
toTurnCount: 3,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:invalid",
|
||||
});
|
||||
|
||||
@@ -122,6 +176,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retry = options.retry;
|
||||
@@ -147,6 +202,7 @@ describe("checkpointDiffQueryOptions", () => {
|
||||
threadId,
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: false,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
const retryDelay = options.retryDelay;
|
||||
|
||||
@@ -13,6 +13,7 @@ interface CheckpointDiffQueryInput {
|
||||
threadId: ThreadId | null;
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
ignoreWhitespace: boolean;
|
||||
cacheScope?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
@@ -27,6 +28,7 @@ export const providerQueryKeys = {
|
||||
input.threadId,
|
||||
input.fromTurnCount,
|
||||
input.toTurnCount,
|
||||
input.ignoreWhitespace,
|
||||
input.cacheScope ?? null,
|
||||
] as const,
|
||||
};
|
||||
@@ -36,6 +38,7 @@ function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
|
||||
return Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput)({
|
||||
threadId: input.threadId,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace,
|
||||
}).pipe(Option.map((fields) => ({ kind: "fullThreadDiff" as const, input: fields })));
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace,
|
||||
}).pipe(Option.map((fields) => ({ kind: "turnDiff" as const, input: fields })));
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,11 @@ const rpcClientMock = {
|
||||
filesystem: {
|
||||
browse: vi.fn(),
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: vi.fn(),
|
||||
cloneRepository: vi.fn(),
|
||||
publishRepository: vi.fn(),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: vi.fn(),
|
||||
},
|
||||
@@ -566,6 +571,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
@@ -626,6 +632,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
|
||||
@@ -42,6 +42,12 @@ export interface EnvironmentState {
|
||||
projectIds: ProjectId[];
|
||||
projectById: Record<ProjectId, Project>;
|
||||
|
||||
// TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY):
|
||||
// Web still stores shell snapshots and thread details in this denormalized
|
||||
// Zustand shape. Mobile uses createShellSnapshotManager and
|
||||
// createThreadDetailManager from @t3tools/client-runtime. New shared behavior
|
||||
// belongs in those managers/reducers, with a web adapter layered on top.
|
||||
//
|
||||
// ---------------------------------------------------------------------------
|
||||
// Thread bookkeeping — written by BOTH shell stream and detail stream.
|
||||
// Both streams ensure the thread is registered here; the bookkeeping is
|
||||
@@ -1119,6 +1125,9 @@ export function syncServerShellSnapshot(
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
environmentId: EnvironmentId,
|
||||
): AppState {
|
||||
// TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY):
|
||||
// Keep web-specific projection here only until the store can consume
|
||||
// createShellSnapshotManager or a shared adapter over its reducer.
|
||||
return commitEnvironmentState(
|
||||
state,
|
||||
environmentId,
|
||||
@@ -1135,6 +1144,9 @@ export function syncServerThreadDetail(
|
||||
thread: OrchestrationThread,
|
||||
environmentId: EnvironmentId,
|
||||
): AppState {
|
||||
// TODO(CLIENT-RUNTIME MIGRATION - DO NOT EXPAND THIS WEB-ONLY COPY):
|
||||
// Keep web-specific projection here only until the store can consume
|
||||
// createThreadDetailManager or a shared adapter over its reducer.
|
||||
const environmentState = getStoredEnvironmentState(state, environmentId);
|
||||
const previousThread = getThreadFromEnvironmentState(environmentState, thread.id);
|
||||
return commitEnvironmentState(
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "vitest";
|
||||
|
||||
import { buildMenuItems, resolveQuickAction } from "./gitActions.ts";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/test",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("git action logic", () => {
|
||||
it("offers repository publishing when a clean ref has commits but no primary remote", () => {
|
||||
const quickAction = resolveQuickAction(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 2,
|
||||
}),
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
|
||||
assert.deepEqual(quickAction, {
|
||||
kind: "open_publish",
|
||||
label: "Publish repository",
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps only commit in the menu when no primary remote exists", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 2,
|
||||
}),
|
||||
false,
|
||||
false,
|
||||
);
|
||||
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: true,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -27,7 +27,7 @@ export interface GitActionMenuItem {
|
||||
export interface GitQuickAction {
|
||||
label: string;
|
||||
disabled: boolean;
|
||||
kind: "run_action" | "run_pull" | "open_pr" | "show_hint";
|
||||
kind: "run_action" | "run_pull" | "open_pr" | "open_publish" | "show_hint";
|
||||
action?: GitStackedAction;
|
||||
hint?: string;
|
||||
}
|
||||
@@ -128,15 +128,21 @@ export function buildMenuItems(
|
||||
(gitStatus.hasUpstream || canPushWithoutUpstream);
|
||||
const canOpenPr = !isBusy && hasOpenPr;
|
||||
|
||||
const commitItem: GitActionMenuItem = {
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: !canCommit,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
};
|
||||
|
||||
if (!hasPrimaryRemote) {
|
||||
return [commitItem];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: !canCommit,
|
||||
icon: "commit",
|
||||
kind: "open_dialog",
|
||||
dialogAction: "commit",
|
||||
},
|
||||
commitItem,
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
@@ -222,10 +228,9 @@ export function resolveQuickAction(
|
||||
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
|
||||
}
|
||||
return {
|
||||
label: "Push",
|
||||
disabled: true,
|
||||
kind: "show_hint",
|
||||
hint: `Add an "origin" remote before pushing or creating a ${terminology.singular}.`,
|
||||
label: "Publish repository",
|
||||
disabled: false,
|
||||
kind: "open_publish",
|
||||
};
|
||||
}
|
||||
if (!isAhead) {
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { assert, beforeEach, it } from "vitest";
|
||||
import type { SourceControlDiscoveryResult } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -12,6 +13,37 @@ const EMPTY_RESULT: SourceControlDiscoveryResult = {
|
||||
sourceControlProviders: [],
|
||||
};
|
||||
|
||||
const GITHUB_RESULT: SourceControlDiscoveryResult = {
|
||||
versionControlSystems: [
|
||||
{
|
||||
kind: "git",
|
||||
label: "Git",
|
||||
implemented: true,
|
||||
status: "available",
|
||||
version: Option.some("2.51.0"),
|
||||
installHint: "Install Git.",
|
||||
detail: Option.none(),
|
||||
},
|
||||
],
|
||||
sourceControlProviders: [
|
||||
{
|
||||
kind: "github",
|
||||
label: "GitHub",
|
||||
implemented: true,
|
||||
status: "available",
|
||||
version: Option.some("2.85.0"),
|
||||
installHint: "Install GitHub CLI.",
|
||||
detail: Option.none(),
|
||||
auth: {
|
||||
status: "authenticated",
|
||||
account: Option.some("octo"),
|
||||
host: Option.some("github.com"),
|
||||
detail: Option.none(),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function unresolvedDiscovery() {
|
||||
throw new Error("Discovery resolver was not initialized.");
|
||||
}
|
||||
@@ -105,3 +137,47 @@ it("keeps the previous snapshot when refresh fails", async () => {
|
||||
isPending: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("invalidates a discovery target back to the initial snapshot", async () => {
|
||||
const manager = createSourceControlDiscoveryManager({
|
||||
getRegistry: () => registry,
|
||||
getClient: () => ({
|
||||
discoverSourceControl: async () => GITHUB_RESULT,
|
||||
}),
|
||||
});
|
||||
|
||||
await manager.refresh({ key: "primary" });
|
||||
manager.invalidate({ key: "primary" });
|
||||
|
||||
assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), {
|
||||
data: null,
|
||||
error: null,
|
||||
isPending: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores an in-flight refresh after the target is invalidated", async () => {
|
||||
let resolveDiscovery: (result: SourceControlDiscoveryResult) => void = unresolvedDiscovery;
|
||||
const manager = createSourceControlDiscoveryManager({
|
||||
getRegistry: () => registry,
|
||||
getClient: () => ({
|
||||
discoverSourceControl: () =>
|
||||
new Promise<SourceControlDiscoveryResult>((resolve) => {
|
||||
resolveDiscovery = resolve;
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
const refresh = manager.refresh({ key: "primary" });
|
||||
manager.invalidate({ key: "primary" });
|
||||
resolveDiscovery(GITHUB_RESULT);
|
||||
|
||||
const result = await refresh;
|
||||
|
||||
assert.strictEqual(result, GITHUB_RESULT);
|
||||
assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), {
|
||||
data: null,
|
||||
error: null,
|
||||
isPending: true,
|
||||
});
|
||||
});
|
||||
@@ -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,11 +70,22 @@ 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>();
|
||||
|
||||
function getRefreshVersion(targetKey: string): number {
|
||||
return refreshVersions.get(targetKey) ?? 0;
|
||||
}
|
||||
|
||||
function bumpRefreshVersion(targetKey: string): void {
|
||||
refreshVersions.set(targetKey, getRefreshVersion(targetKey) + 1);
|
||||
}
|
||||
|
||||
/* -- Atom helpers -------------------------------------------------- */
|
||||
|
||||
@@ -135,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);
|
||||
@@ -156,28 +167,59 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove
|
||||
}
|
||||
|
||||
markPending(targetKey);
|
||||
const refreshVersion = getRefreshVersion(targetKey);
|
||||
const promise = resolvedClient.discoverSourceControl().then(
|
||||
(result) => {
|
||||
setData(targetKey, result);
|
||||
if (getRefreshVersion(targetKey) === refreshVersion) {
|
||||
setData(targetKey, result);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
(error: unknown) => {
|
||||
setError(targetKey, error);
|
||||
if (getRefreshVersion(targetKey) === refreshVersion) {
|
||||
setError(targetKey, error);
|
||||
}
|
||||
return getSnapshot(target).data;
|
||||
},
|
||||
);
|
||||
const tracked = promise.finally(() => refreshInFlight.delete(targetKey));
|
||||
let tracked: Promise<SourceControlDiscoveryResult | null>;
|
||||
tracked = promise.finally(() => {
|
||||
if (refreshInFlight.get(targetKey) === tracked) {
|
||||
refreshInFlight.delete(targetKey);
|
||||
}
|
||||
});
|
||||
refreshInFlight.set(targetKey, tracked);
|
||||
return tracked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset discovery state for one target and ignore any currently in-flight
|
||||
* refresh for that target. If no target is provided, every known target is
|
||||
* invalidated.
|
||||
*/
|
||||
function invalidate(target?: SourceControlDiscoveryTarget<TKey>): void {
|
||||
if (!target) {
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
|
||||
const targetKey = getSourceControlDiscoveryTargetKey(target);
|
||||
if (targetKey === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
bumpRefreshVersion(targetKey);
|
||||
refreshInFlight.delete(targetKey);
|
||||
setState(targetKey, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the current atom snapshot for `target`.
|
||||
*
|
||||
* 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;
|
||||
@@ -191,16 +233,18 @@ export function createSourceControlDiscoveryManager(config: SourceControlDiscove
|
||||
* Primarily used by tests and runtime teardown.
|
||||
*/
|
||||
function reset(): void {
|
||||
const keys = new Set([...knownSourceControlDiscoveryKeys, ...refreshInFlight.keys()]);
|
||||
refreshInFlight.clear();
|
||||
for (const key of knownSourceControlDiscoveryKeys) {
|
||||
for (const key of keys) {
|
||||
bumpRefreshVersion(key);
|
||||
setState(key, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE);
|
||||
}
|
||||
knownSourceControlDiscoveryKeys.clear();
|
||||
}
|
||||
|
||||
return {
|
||||
refresh,
|
||||
getSnapshot,
|
||||
invalidate,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
@@ -251,26 +251,29 @@ function listKnownSessionsFromMetadata(
|
||||
getBuffer: (target: KnownTerminalSessionTarget) => TerminalBufferState,
|
||||
filter?: Partial<KnownTerminalSessionTarget>,
|
||||
): ReadonlyArray<KnownTerminalSession> {
|
||||
return Object.values(metadata)
|
||||
.filter(({ target }) => {
|
||||
if (filter?.environmentId && target.environmentId !== filter.environmentId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.threadId && target.threadId !== filter.threadId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.terminalId && target.terminalId !== filter.terminalId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map(({ target, summary }) => ({
|
||||
target,
|
||||
state: combineSessionState(summary, getBuffer(target)),
|
||||
}))
|
||||
.sort((left, right) =>
|
||||
left.target.terminalId.localeCompare(right.target.terminalId, undefined, { numeric: true }),
|
||||
);
|
||||
return (
|
||||
Object.values(metadata)
|
||||
.filter(({ target }) => {
|
||||
if (filter?.environmentId && target.environmentId !== filter.environmentId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.threadId && target.threadId !== filter.threadId) {
|
||||
return false;
|
||||
}
|
||||
if (filter?.terminalId && target.terminalId !== filter.terminalId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map(({ target, summary }) => ({
|
||||
target,
|
||||
state: combineSessionState(summary, getBuffer(target)),
|
||||
}))
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
.sort((left, right) =>
|
||||
left.target.terminalId.localeCompare(right.target.terminalId, undefined, { numeric: true }),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export const terminalSessionStateAtom = Atom.family((target: KnownTerminalSessionTarget) =>
|
||||
@@ -299,16 +302,19 @@ export const knownTerminalSessionsAtom = Atom.family((filter: KnownTerminalSessi
|
||||
|
||||
export const runningTerminalIdsAtom = Atom.family((filter: KnownTerminalSessionListFilter) =>
|
||||
Atom.make((get) => {
|
||||
return Object.values(get(terminalSessionMetadataAtom(filter.environmentId)))
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.target.environmentId === filter.environmentId &&
|
||||
(filter.threadId === null || entry.target.threadId === filter.threadId) &&
|
||||
(filter.terminalId === null || entry.target.terminalId === filter.terminalId) &&
|
||||
entry.summary.hasRunningSubprocess,
|
||||
)
|
||||
.map((entry) => entry.target.terminalId)
|
||||
.sort();
|
||||
return (
|
||||
Object.values(get(terminalSessionMetadataAtom(filter.environmentId)))
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.target.environmentId === filter.environmentId &&
|
||||
(filter.threadId === null || entry.target.threadId === filter.threadId) &&
|
||||
(filter.terminalId === null || entry.target.terminalId === filter.terminalId) &&
|
||||
entry.summary.hasRunningSubprocess,
|
||||
)
|
||||
.map((entry) => entry.target.terminalId)
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
.sort()
|
||||
);
|
||||
}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`terminal-session:running-terminal-ids:${JSON.stringify(filter)}`),
|
||||
|
||||
@@ -344,6 +344,7 @@ export function applyThreadDetailEvent(
|
||||
thread.proposedPlans,
|
||||
Arr.filter((entry) => entry.id !== proposedPlan.id),
|
||||
Arr.append(proposedPlan),
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
Arr.sort(proposedPlanOrder),
|
||||
Arr.takeRight(limits.maxProposedPlans),
|
||||
);
|
||||
@@ -376,6 +377,7 @@ export function applyThreadDetailEvent(
|
||||
thread.checkpoints,
|
||||
Arr.filter((entry) => entry.turnId !== checkpoint.turnId),
|
||||
Arr.append(checkpoint),
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
Arr.sort(checkpointOrder),
|
||||
Arr.takeRight(limits.maxCheckpoints),
|
||||
);
|
||||
@@ -407,6 +409,7 @@ export function applyThreadDetailEvent(
|
||||
entry.checkpointTurnCount !== undefined &&
|
||||
entry.checkpointTurnCount <= event.payload.turnCount,
|
||||
),
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
Arr.sort(checkpointOrder),
|
||||
Arr.takeRight(limits.maxCheckpoints),
|
||||
);
|
||||
@@ -459,6 +462,7 @@ export function applyThreadDetailEvent(
|
||||
thread.activities,
|
||||
Arr.filter((activity) => activity.id !== event.payload.activity.id),
|
||||
Arr.append(event.payload.activity),
|
||||
// oxlint-disable-next-line unicorn/no-array-sort
|
||||
Arr.sort(activityOrder),
|
||||
Arr.takeRight(limits.maxActivities),
|
||||
);
|
||||
|
||||
@@ -71,6 +71,11 @@ export interface WsRpcClient {
|
||||
readonly filesystem: {
|
||||
readonly browse: RpcUnaryMethod<typeof WS_METHODS.filesystemBrowse>;
|
||||
};
|
||||
readonly sourceControl: {
|
||||
readonly lookupRepository: RpcUnaryMethod<typeof WS_METHODS.sourceControlLookupRepository>;
|
||||
readonly cloneRepository: RpcUnaryMethod<typeof WS_METHODS.sourceControlCloneRepository>;
|
||||
readonly publishRepository: RpcUnaryMethod<typeof WS_METHODS.sourceControlPublishRepository>;
|
||||
};
|
||||
readonly shell: {
|
||||
readonly openInEditor: (input: {
|
||||
readonly cwd: Parameters<LocalApi["shell"]["openInEditor"]>[0];
|
||||
@@ -180,6 +185,14 @@ export function createWsRpcClient(
|
||||
filesystem: {
|
||||
browse: (input) => transport.request((client) => client[WS_METHODS.filesystemBrowse](input)),
|
||||
},
|
||||
sourceControl: {
|
||||
lookupRepository: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.sourceControlLookupRepository](input)),
|
||||
cloneRepository: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.sourceControlCloneRepository](input)),
|
||||
publishRepository: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.sourceControlPublishRepository](input)),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)),
|
||||
|
||||
@@ -59,7 +59,15 @@ import type {
|
||||
import type { EnvironmentId } from "./baseSchemas.ts";
|
||||
import { EditorId } from "./editor.ts";
|
||||
import { ServerSettings, type ClientSettings, type ServerSettingsPatch } from "./settings.ts";
|
||||
import type { SourceControlDiscoveryResult } from "./sourceControl.ts";
|
||||
import type {
|
||||
SourceControlCloneRepositoryInput,
|
||||
SourceControlCloneRepositoryResult,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlPublishRepositoryInput,
|
||||
SourceControlPublishRepositoryResult,
|
||||
SourceControlRepositoryInfo,
|
||||
SourceControlRepositoryLookupInput,
|
||||
} from "./sourceControl.ts";
|
||||
|
||||
export interface ContextMenuItem<T extends string = string> {
|
||||
id: T;
|
||||
@@ -274,6 +282,17 @@ export interface EnvironmentApi {
|
||||
filesystem: {
|
||||
browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;
|
||||
};
|
||||
sourceControl: {
|
||||
lookupRepository: (
|
||||
input: SourceControlRepositoryLookupInput,
|
||||
) => Promise<SourceControlRepositoryInfo>;
|
||||
cloneRepository: (
|
||||
input: SourceControlCloneRepositoryInput,
|
||||
) => Promise<SourceControlCloneRepositoryResult>;
|
||||
publishRepository: (
|
||||
input: SourceControlPublishRepositoryInput,
|
||||
) => Promise<SourceControlPublishRepositoryResult>;
|
||||
};
|
||||
vcs: {
|
||||
listRefs: (input: VcsListRefsInput) => Promise<VcsListRefsResult>;
|
||||
createWorktree: (input: VcsCreateWorktreeInput) => Promise<VcsCreateWorktreeResult>;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ModelSelection,
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationLatestTurn,
|
||||
ProjectCreatedPayload,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
import { ProviderInstanceId } from "./providerInstance.ts";
|
||||
|
||||
const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);
|
||||
const decodeFullThreadDiffInput = Schema.decodeUnknownEffect(OrchestrationGetFullThreadDiffInput);
|
||||
const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);
|
||||
const decodeProjectCreateCommand = Schema.decodeUnknownEffect(ProjectCreateCommand);
|
||||
const decodeProjectCreatedPayload = Schema.decodeUnknownEffect(ProjectCreatedPayload);
|
||||
@@ -59,6 +61,29 @@ it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses turn diff input with whitespace ignoring enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeTurnDiffInput({
|
||||
threadId: "thread-1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
assert.strictEqual(parsed.ignoreWhitespace, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("parses full thread diff input with whitespace ignoring enabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeFullThreadDiffInput({
|
||||
threadId: "thread-1",
|
||||
toTurnCount: 2,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
assert.strictEqual(parsed.ignoreWhitespace, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects turn diff input when fromTurnCount > toTurnCount", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
|
||||
@@ -1171,7 +1171,10 @@ export const DispatchResult = Schema.Struct({
|
||||
export type DispatchResult = typeof DispatchResult.Type;
|
||||
|
||||
export const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(
|
||||
Struct.assign({ threadId: ThreadId }),
|
||||
Struct.assign({
|
||||
threadId: ThreadId,
|
||||
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
{ unsafePreserveChecks: true },
|
||||
);
|
||||
export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;
|
||||
@@ -1182,6 +1185,7 @@ export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResu
|
||||
export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
toTurnCount: NonNegativeInt,
|
||||
ignoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
export type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;
|
||||
|
||||
|
||||
@@ -82,7 +82,16 @@ import {
|
||||
ServerUpsertKeybindingResult,
|
||||
} from "./server.ts";
|
||||
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
|
||||
import { SourceControlDiscoveryResult } from "./sourceControl.ts";
|
||||
import {
|
||||
SourceControlCloneRepositoryInput,
|
||||
SourceControlCloneRepositoryResult,
|
||||
SourceControlDiscoveryResult,
|
||||
SourceControlPublishRepositoryInput,
|
||||
SourceControlPublishRepositoryResult,
|
||||
SourceControlRepositoryError,
|
||||
SourceControlRepositoryInfo,
|
||||
SourceControlRepositoryLookupInput,
|
||||
} from "./sourceControl.ts";
|
||||
import { VcsError } from "./vcs.ts";
|
||||
|
||||
export const WS_METHODS = {
|
||||
@@ -132,6 +141,11 @@ export const WS_METHODS = {
|
||||
serverUpdateSettings: "server.updateSettings",
|
||||
serverDiscoverSourceControl: "server.discoverSourceControl",
|
||||
|
||||
// Source control methods
|
||||
sourceControlLookupRepository: "sourceControl.lookupRepository",
|
||||
sourceControlCloneRepository: "sourceControl.cloneRepository",
|
||||
sourceControlPublishRepository: "sourceControl.publishRepository",
|
||||
|
||||
// Streaming subscriptions
|
||||
subscribeVcsStatus: "subscribeVcsStatus",
|
||||
subscribeTerminalEvents: "subscribeTerminalEvents",
|
||||
@@ -183,6 +197,30 @@ export const WsServerDiscoverSourceControlRpc = Rpc.make(WS_METHODS.serverDiscov
|
||||
success: SourceControlDiscoveryResult,
|
||||
});
|
||||
|
||||
export const WsSourceControlLookupRepositoryRpc = Rpc.make(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
{
|
||||
payload: SourceControlRepositoryLookupInput,
|
||||
success: SourceControlRepositoryInfo,
|
||||
error: SourceControlRepositoryError,
|
||||
},
|
||||
);
|
||||
|
||||
export const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlCloneRepository, {
|
||||
payload: SourceControlCloneRepositoryInput,
|
||||
success: SourceControlCloneRepositoryResult,
|
||||
error: SourceControlRepositoryError,
|
||||
});
|
||||
|
||||
export const WsSourceControlPublishRepositoryRpc = Rpc.make(
|
||||
WS_METHODS.sourceControlPublishRepository,
|
||||
{
|
||||
payload: SourceControlPublishRepositoryInput,
|
||||
success: SourceControlPublishRepositoryResult,
|
||||
error: SourceControlRepositoryError,
|
||||
},
|
||||
);
|
||||
|
||||
export const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, {
|
||||
payload: ProjectSearchEntriesInput,
|
||||
success: ProjectSearchEntriesResult,
|
||||
@@ -408,6 +446,9 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerGetSettingsRpc,
|
||||
WsServerUpdateSettingsRpc,
|
||||
WsServerDiscoverSourceControlRpc,
|
||||
WsSourceControlLookupRepositoryRpc,
|
||||
WsSourceControlCloneRepositoryRpc,
|
||||
WsSourceControlPublishRepositoryRpc,
|
||||
WsProjectsSearchEntriesRpc,
|
||||
WsProjectsWriteFileRpc,
|
||||
WsShellOpenInEditorRpc,
|
||||
|
||||
@@ -32,6 +32,7 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
// Model favorites. Historically keyed by provider kind, now
|
||||
// widened to `ProviderInstanceId` so users can favorite a specific model
|
||||
@@ -451,6 +452,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
autoOpenPlanSidebar: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
|
||||
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
diffWordWrap: Schema.optionalKey(Schema.Boolean),
|
||||
favorites: Schema.optionalKey(
|
||||
Schema.Array(
|
||||
|
||||
@@ -43,6 +43,66 @@ export const SourceControlRepositoryCloneUrls = Schema.Struct({
|
||||
});
|
||||
export type SourceControlRepositoryCloneUrls = typeof SourceControlRepositoryCloneUrls.Type;
|
||||
|
||||
export const SourceControlRepositoryVisibility = Schema.Literals(["private", "public"]);
|
||||
export type SourceControlRepositoryVisibility = typeof SourceControlRepositoryVisibility.Type;
|
||||
|
||||
export const SourceControlCloneProtocol = Schema.Literals(["auto", "ssh", "https"]);
|
||||
export type SourceControlCloneProtocol = typeof SourceControlCloneProtocol.Type;
|
||||
|
||||
export const SourceControlRepositoryInfo = Schema.Struct({
|
||||
provider: SourceControlProviderKind,
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
export type SourceControlRepositoryInfo = typeof SourceControlRepositoryInfo.Type;
|
||||
|
||||
export const SourceControlRepositoryLookupInput = Schema.Struct({
|
||||
provider: SourceControlProviderKind,
|
||||
repository: TrimmedNonEmptyString,
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type SourceControlRepositoryLookupInput = typeof SourceControlRepositoryLookupInput.Type;
|
||||
|
||||
export const SourceControlCloneRepositoryInput = Schema.Struct({
|
||||
provider: Schema.optional(SourceControlProviderKind),
|
||||
repository: Schema.optional(TrimmedNonEmptyString),
|
||||
remoteUrl: Schema.optional(TrimmedNonEmptyString),
|
||||
destinationPath: TrimmedNonEmptyString,
|
||||
protocol: Schema.optional(SourceControlCloneProtocol),
|
||||
});
|
||||
export type SourceControlCloneRepositoryInput = typeof SourceControlCloneRepositoryInput.Type;
|
||||
|
||||
export const SourceControlCloneRepositoryResult = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
remoteUrl: TrimmedNonEmptyString,
|
||||
repository: Schema.NullOr(SourceControlRepositoryInfo),
|
||||
});
|
||||
export type SourceControlCloneRepositoryResult = typeof SourceControlCloneRepositoryResult.Type;
|
||||
|
||||
export const SourceControlPublishRepositoryInput = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
provider: SourceControlProviderKind,
|
||||
repository: TrimmedNonEmptyString,
|
||||
visibility: SourceControlRepositoryVisibility,
|
||||
remoteName: Schema.optional(TrimmedNonEmptyString),
|
||||
protocol: Schema.optional(SourceControlCloneProtocol),
|
||||
});
|
||||
export type SourceControlPublishRepositoryInput = typeof SourceControlPublishRepositoryInput.Type;
|
||||
|
||||
export const SourceControlPublishStatus = Schema.Literals(["pushed", "remote_added"]);
|
||||
export type SourceControlPublishStatus = typeof SourceControlPublishStatus.Type;
|
||||
|
||||
export const SourceControlPublishRepositoryResult = Schema.Struct({
|
||||
repository: SourceControlRepositoryInfo,
|
||||
remoteName: TrimmedNonEmptyString,
|
||||
remoteUrl: TrimmedNonEmptyString,
|
||||
branch: TrimmedNonEmptyString,
|
||||
upstreamBranch: Schema.optional(TrimmedNonEmptyString),
|
||||
status: SourceControlPublishStatus,
|
||||
});
|
||||
export type SourceControlPublishRepositoryResult = typeof SourceControlPublishRepositoryResult.Type;
|
||||
|
||||
export const SourceControlDiscoveryStatus = Schema.Literals(["available", "missing"]);
|
||||
export type SourceControlDiscoveryStatus = typeof SourceControlDiscoveryStatus.Type;
|
||||
|
||||
@@ -63,7 +123,7 @@ export type SourceControlProviderAuth = typeof SourceControlProviderAuth.Type;
|
||||
|
||||
const SourceControlDiscoveryItemFields = {
|
||||
label: TrimmedNonEmptyString,
|
||||
executable: TrimmedNonEmptyString,
|
||||
executable: Schema.optional(TrimmedNonEmptyString),
|
||||
implemented: Schema.Boolean,
|
||||
status: SourceControlDiscoveryStatus,
|
||||
version: Schema.Option(TrimmedNonEmptyString),
|
||||
@@ -109,3 +169,17 @@ export class SourceControlProviderError extends Schema.TaggedErrorClass<SourceCo
|
||||
return `Source control provider ${this.provider} failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class SourceControlRepositoryError extends Schema.TaggedErrorClass<SourceControlRepositoryError>()(
|
||||
"SourceControlRepositoryError",
|
||||
{
|
||||
provider: SourceControlProviderKind,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Source control repository operation ${this.operation} failed for ${this.provider}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user