Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 71 additions & 17 deletions apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
ComposerToolbarRow,
} from "../../components/ComposerToolbar";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { ControlPillMenu } from "../../components/ControlPill";
import { MaterialScreenContent } from "../../components/MaterialScreenContent";
import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
Expand Down Expand Up @@ -122,16 +123,28 @@ import { resolveDraftProjectSelection } from "./new-task-project-selection";
import {
resolveNewTaskBranchLabel,
resolveNewTaskWorkspaceLabel,
type NewTaskWorkspaceChoice,
} from "./new-task-context-presentation";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
import { appAtomRegistry } from "../../state/atom-registry";
import { serverEnvironment } from "../../state/server";
import { fileRoutePathSegments } from "../files/filePath";

const WORKSPACE_CHOICES = [
{ id: "local", title: "Current checkout" },
{ id: "worktree", title: "New worktree" },
{ id: "sandbox", title: "New sandbox", subtitle: "New worktree in a Docker container" },
] as const satisfies ReadonlyArray<{
readonly id: NewTaskWorkspaceChoice;
readonly title: string;
readonly subtitle?: string;
}>;

function NewTaskWorkspaceIcon(props: {
readonly workspaceMode: "local" | "worktree";
readonly worktreePath: string | null;
readonly sandbox: boolean;
readonly size: number;
}) {
if (props.workspaceMode === "local" && props.worktreePath === null) {
Expand Down Expand Up @@ -164,7 +177,7 @@ function NewTaskWorkspaceIcon(props: {
}
>
<SymbolView
name="arrow.triangle.branch"
name={props.sandbox ? "cube" : "arrow.triangle.branch"}
size={Math.round((9 * props.size) / 16)}
tintColorClassName="accent-icon-muted"
type="monochrome"
Expand Down Expand Up @@ -996,7 +1009,10 @@ export function NewTaskDraftScreen(props: {
const workspaceLabel = resolveNewTaskWorkspaceLabel({
workspaceMode: flow.workspaceMode,
worktreePath: flow.selectedWorktreePath,
sandbox: flow.sandbox,
});
const workspaceChoice: NewTaskWorkspaceChoice =
flow.workspaceMode === "local" ? "local" : flow.sandbox ? "sandbox" : "worktree";
const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;

async function handlePickMedia(): Promise<void> {
Expand Down Expand Up @@ -1549,24 +1565,62 @@ export function NewTaskDraftScreen(props: {
</View>
);

const workspaceControlDisabled = isComposerInteractionLocked || voiceInput.isBusy;
// Two workspaces toggle on tap. A server that offers sandboxes adds a third,
// so the control opens a menu instead.
const offersWorkspaceMenu = flow.canUseSandbox && !workspaceControlDisabled;
const workspaceControl = (
<ComposerInlineControl
accessibilityHint={
offersWorkspaceMenu
? "Chooses where the task runs"
: `Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`
}
accessibilityLabel={workspaceLabel}
disabled={workspaceControlDisabled}
renderIcon={(size) => (
<NewTaskWorkspaceIcon
workspaceMode={flow.workspaceMode}
worktreePath={flow.selectedWorktreePath}
sandbox={flow.sandbox}
size={size}
/>
)}
label={workspaceLabel}
maxWidth={flow.workspaceMode === "local" ? 220 : 148}
onPress={
offersWorkspaceMenu
? undefined
: () => flow.setWorkspaceChoice(flow.workspaceMode === "local" ? "worktree" : "local")
}
showChevron={offersWorkspaceMenu}
/>
);

const workspaceControls = (
<View className="flex-row items-center gap-1 px-2">
<ComposerInlineControl
accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
accessibilityLabel={workspaceLabel}
disabled={isComposerInteractionLocked || voiceInput.isBusy}
renderIcon={(size) => (
<NewTaskWorkspaceIcon
workspaceMode={flow.workspaceMode}
worktreePath={flow.selectedWorktreePath}
size={size}
/>
)}
label={workspaceLabel}
maxWidth={flow.workspaceMode === "local" ? 220 : 148}
onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
showChevron={false}
/>
{offersWorkspaceMenu ? (
<ControlPillMenu
accessibilityLabel={workspaceLabel}
actions={WORKSPACE_CHOICES.map((choice) => ({
...choice,
...(choice.id === "local" && flow.workspaceMode === "local"
? { title: workspaceLabel }
: {}),
state: choice.id === workspaceChoice ? ("on" as const) : ("off" as const),
}))}
onPressAction={({ nativeEvent }) => {
const choice = WORKSPACE_CHOICES.find(
(candidate) => candidate.id === nativeEvent.event,
);
if (choice) flow.setWorkspaceChoice(choice.id);
}}
>
{workspaceControl}
</ControlPillMenu>
) : (
workspaceControl
)}

<ComposerInlineControl
accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-wo
import { vcsEnvironment } from "../../../state/vcs";
import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
import { ThreadSandboxCard } from "./ThreadSandboxCard";

const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);

Expand Down Expand Up @@ -355,6 +356,7 @@ export function GitOverviewSheet(props: GitOverviewSheetProps) {
) : null}

{currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
<ThreadSandboxCard environmentId={environmentId} worktreePath={currentWorktreePath} />
</ScrollView>
);

Expand Down
132 changes: 132 additions & 0 deletions apps/mobile/src/features/threads/git/ThreadSandboxCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { findSandboxForWorktree } from "@t3tools/client-runtime/state/vcs";
import type { EnvironmentId, SandboxStatus } from "@t3tools/contracts";
import { useState } from "react";
import { Alert, Platform, View } from "react-native";

import { AppText as Text } from "../../../components/AppText";
import { showConfirmDialog } from "../../../components/ConfirmDialogHost";
import { cn } from "../../../lib/cn";
import { useEnvironmentServerConfig } from "../../../state/entities";
import { useEnvironmentQuery } from "../../../state/query";
import { useAtomCommand } from "../../../state/use-atom-command";
import { vcsEnvironment } from "../../../state/vcs";
import { SheetListRow } from "./gitSheetComponents";

const STATUS_LABEL: Record<SandboxStatus, string> = {
starting: "Starting",
running: "Running",
stopped: "Stopped",
error: "Error",
};

function confirmRemove(onConfirm: () => void) {
const title = "Remove sandbox?";
const message = "Later work in this worktree then runs on the host.";
if (Platform.OS === "ios") {
Alert.alert(title, message, [
{ text: "Cancel", style: "cancel" },
{ text: "Remove", style: "destructive", onPress: onConfirm },
]);
return;
}
showConfirmDialog({ title, message, confirmText: "Remove", destructive: true, onConfirm });
}

/**
* Status, forwarded ports, and stop/remove actions for a thread whose worktree
* runs in a Docker sandbox. Renders nothing for other threads, and only
* subscribes to the sandbox list when the server can run sandboxes.
*/
export function ThreadSandboxCard(props: {
readonly environmentId: EnvironmentId;
readonly worktreePath: string | null;
}) {
const serverConfig = useEnvironmentServerConfig(props.environmentId);
const sandboxes = useEnvironmentQuery(
serverConfig?.sandboxes === true && props.worktreePath !== null
? vcsEnvironment.sandboxes({ environmentId: props.environmentId, input: {} })
: null,
);
const sandbox = findSandboxForWorktree(sandboxes.data?.sandboxes, props.worktreePath);
const stopSandbox = useAtomCommand(vcsEnvironment.stopSandbox, { reportFailure: false });
const removeSandbox = useAtomCommand(vcsEnvironment.removeSandbox, { reportFailure: false });
const [busy, setBusy] = useState(false);

if (!sandbox) return null;
const canStop = sandbox.status === "running" || sandbox.status === "starting";
const { worktreePath } = sandbox;
const run = async (failureTitle: string, command: typeof stopSandbox) => {
setBusy(true);
try {
const result = await command({ environmentId: props.environmentId, input: { worktreePath } });
if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
const cause = squashAtomCommandFailure(result);
Alert.alert(failureTitle, cause instanceof Error ? cause.message : undefined);
} finally {
setBusy(false);
}
};

return (
<View className="overflow-hidden bg-card android:rounded-[20px] ios:rounded-[18px] ios:border ios:border-border">
<View className="gap-0.5 px-4 py-3">
<Text className="text-foreground-muted text-2xs font-t3-bold tracking-[0.9px] uppercase">
Sandbox
</Text>
<Text
selectable
className={cn(
"text-sm font-medium",
sandbox.status === "error" ? "text-danger-foreground" : "text-foreground",
)}
numberOfLines={1}
>
{STATUS_LABEL[sandbox.status]} · {sandbox.containerName}
</Text>
{sandbox.status === "error" && sandbox.error ? (
<Text selectable className="text-xs text-danger-foreground">
{sandbox.error}
</Text>
) : null}
{sandbox.ports.map((port) => (
<Text
key={`${port.containerPort}:${port.hostPort}`}
selectable
className="text-xs text-foreground-muted"
style={{ fontVariant: ["tabular-nums"] }}
>
:{port.containerPort} → 127.0.0.1:{port.hostPort}
</Text>
))}
</View>
<View className="ios:px-3">
{canStop ? (
<>
{Platform.OS !== "android" ? <View className="h-px bg-border" /> : null}
<SheetListRow
icon="stop.fill"
title="Stop sandbox"
subtitle="Starts again on the next command"
disabled={busy}
onPress={() => void run("Could not stop sandbox", stopSandbox)}
/>
</>
) : null}
{Platform.OS !== "android" ? (
<View className={canStop ? "ml-12 h-px bg-border" : "h-px bg-border"} />
) : null}
<SheetListRow
icon="trash"
title="Remove sandbox"
subtitle="Later work runs on the host"
disabled={busy}
onPress={() => confirmRemove(() => void run("Could not remove sandbox", removeSandbox))}
/>
</View>
</View>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,53 @@ import {
resolveNewTaskBranchWorktreePath,
resolveNewTaskBranchLabel,
resolveNewTaskLocalWorkspaceSelection,
resolveNewTaskSandbox,
resolveNewTaskWorkspaceLabel,
} from "./new-task-context-presentation";

describe("resolveNewTaskSandbox", () => {
it("keeps a sandbox choice only for new worktrees", () => {
const serverConfig = { sandboxes: true };
expect(
resolveNewTaskSandbox({ workspaceMode: "worktree", draftSandbox: true, serverConfig }),
).toBe(true);
expect(
resolveNewTaskSandbox({ workspaceMode: "local", draftSandbox: true, serverConfig }),
).toBe(false);
});

it("drops the choice on a server without sandboxes", () => {
expect(
resolveNewTaskSandbox({ workspaceMode: "worktree", draftSandbox: true, serverConfig: {} }),
).toBe(false);
});

it("keeps the choice while the server config is unknown", () => {
expect(
resolveNewTaskSandbox({ workspaceMode: "worktree", draftSandbox: true, serverConfig: null }),
).toBe(true);
});
});

describe("resolveNewTaskWorkspaceLabel", () => {
it("names a sandboxed worktree", () => {
expect(
resolveNewTaskWorkspaceLabel({
workspaceMode: "worktree",
worktreePath: null,
sandbox: true,
}),
).toBe("New sandbox");
expect(
resolveNewTaskWorkspaceLabel({
workspaceMode: "worktree",
worktreePath: null,
sandbox: false,
}),
).toBe("New worktree");
});
});

describe("resolveNewTaskLocalWorkspaceSelection", () => {
it("waits for refs instead of carrying a worktree base into Current checkout", () => {
expect(
Expand Down
25 changes: 23 additions & 2 deletions apps/mobile/src/features/threads/new-task-context-presentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,33 @@ import { sanitizeNewRefName } from "@t3tools/shared/git";

type WorkspaceMode = "local" | "worktree";

/** The workspace picker's options. A sandbox is a new worktree that runs in Docker. */
export type NewTaskWorkspaceChoice = "local" | "worktree" | "sandbox";

/**
* Whether a new task starts in a sandbox. The draft keeps the user's choice;
* a server that does not offer sandboxes drops it, and an unknown config
* (offline or still loading) keeps it so editing a queued task cannot lose it.
*/
export function resolveNewTaskSandbox(input: {
readonly workspaceMode: WorkspaceMode;
readonly draftSandbox: boolean | undefined;
readonly serverConfig: { readonly sandboxes?: boolean } | null;
}): boolean {
return (
input.workspaceMode === "worktree" &&
input.draftSandbox === true &&
(input.serverConfig === null || input.serverConfig.sandboxes === true)
);
}

export function resolveNewTaskWorkspaceLabel(input: {
readonly workspaceMode: WorkspaceMode;
readonly worktreePath: string | null;
}): "Current checkout" | "Current worktree" | "New worktree" {
readonly sandbox: boolean;
}): "Current checkout" | "Current worktree" | "New worktree" | "New sandbox" {
if (input.workspaceMode === "worktree") {
return "New worktree";
return input.sandbox ? "New sandbox" : "New worktree";
}
return input.worktreePath ? "Current worktree" : "Current checkout";
}
Expand Down
Loading
Loading