diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index af208a739..b79df273a 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -54,7 +54,7 @@ The project name in "What's next in …?" on the new-thread screen opens the lis A repository can already have worktrees that Threadlines did not make (git worktree add, or another app). Right after such a repository is added as a project, the new-thread screen lists them under the message box with a checkbox each, and "Add N threads" makes a thread for every ticked one, named from its branch; nothing runs until you send a message there. After that the screen shows only a count beside the recent threads ("4 worktrees"); opening it lists them with Work here, which points the thread you are about to start at that worktree, Add as threads…, and Hide for this project. The Workspace picker under the message box lists the same worktrees under Existing worktree, and the command palette has Add existing worktrees as threads…, which also brings a hidden count back. A thread in one of these is a guest: no setup script runs, the branch is not renamed, deleting the thread never offers to delete the folder, and undoing a turn only undoes that thread's own edits. Worktrees a thread already works in are left out. The computer's server needs to be on a version that has this; with an older one none of it shows. -The agent and model a new thread starts with is {place:threads.agent}. You can switch model or agent at any time from the model button in the composer, which also holds the agent's effort. Beside it sit Build or Plan (one click switches, as does Shift+Tab in the message box) and the access level; on a narrow window they show just their icons, and on phones both live in the model button's panel instead. +The agent and model a new thread starts with is {place:threads.agent}. You can switch model or agent at any time from the model button in the composer, which also holds the agent's effort. Beside it sit Build or Plan (one click switches, as does Shift+Tab in the message box; default {place:threads.mode}) and the access level (default {place:threads.access}); on a narrow window they show just their icons, and on phones both live in the model button's panel instead. While an agent works, {place:general.followUpDelivery} sets how a message goes by default (Steer now adds it to the reply in progress, Send when done holds it for the next one), and the arrow beside the send button overrides it for the current thread. Enter sends that way; Cmd+Enter (Ctrl+Enter on Windows and Linux) sends that one message the other way. @@ -74,7 +74,7 @@ When Threadlines quits, updates or crashes while an agent works on something the id: "access-levels", title: "Access levels", keywords: ["access", "permissions", "approval", "sandbox", "full access", "auto", "supervised"], - body: `Each thread runs at an access level, picked from the access button beside the model button in the composer (on phones, in the model button's panel): + body: `Each thread runs at an access level, picked from the access button beside the model button in the composer (on phones, in the model button's panel). {place:threads.access} sets the default for new threads: - Supervised: asks before commands and file changes. - Auto-accept edits: edits run without asking; other actions ask. diff --git a/apps/web/src/commands/projectCommands.tsx b/apps/web/src/commands/projectCommands.tsx index 93504cd2d..f994161d6 100644 --- a/apps/web/src/commands/projectCommands.tsx +++ b/apps/web/src/commands/projectCommands.tsx @@ -37,6 +37,7 @@ import { startNewThreadFromContext, startNewThreadInProjectFromContext, } from "../lib/chatThreadActions"; +import { readComputerConfig } from "../newThreadDefaults"; import { projectBriefLocation, useProjectBriefSupport } from "../projectBrief"; import { deriveProviderInstanceEntries } from "../providerInstances"; import { useServerProviders } from "../rpc/serverState"; @@ -215,6 +216,7 @@ export function useProjectCommands(): void { runtimeMode: openThreadRuntimeMode ?? activeDraftThread?.runtimeMode ?? + readComputerConfig(currentProject.environmentId)?.settings.newThreadRuntimeMode ?? DEFAULT_NEW_THREAD_RUNTIME_MODE, returnFocus: focusComposer, }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 42c6661a3..27dd18116 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1558,6 +1558,7 @@ export default function ChatView(props: ChatViewProps) { sendCtx.selectedModelSelection.options, ), runtimeMode, + interactionMode, }); } catch (error) { toastManager.add(failureNotice({ title: "Couldn't add the threads", error })); @@ -1571,6 +1572,7 @@ export default function ChatView(props: ChatViewProps) { draftProjectId, draftWorktreePath, environmentId, + interactionMode, isGeneralChatThread, isLocalDraftThread, pickupProjectCwd, @@ -4613,14 +4615,15 @@ export default function ChatView(props: ChatViewProps) { // for more changes, and focus moving to the prompt would close it. const handleRuntimeModeChange = useCallback( (mode: RuntimeMode, options?: { focusComposer?: boolean }) => { - if (mode === runtimeMode) return; + if (mode === runtimeMode && (!isLocalDraftThread || composerRuntimeMode === mode)) return; setComposerDraftRuntimeMode(composerDraftTarget, mode); - if (isLocalDraftThread) { + if (isLocalDraftThread && mode !== runtimeMode) { setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); } if (options?.focusComposer !== false) scheduleComposerFocus(); }, [ + composerRuntimeMode, isLocalDraftThread, runtimeMode, scheduleComposerFocus, @@ -4632,14 +4635,17 @@ export default function ChatView(props: ChatViewProps) { const handleInteractionModeChange = useCallback( (mode: ProviderInteractionMode, options?: { focusComposer?: boolean }) => { - if (mode === interactionMode) return; + if (mode === interactionMode && (!isLocalDraftThread || composerInteractionMode === mode)) { + return; + } setComposerDraftInteractionMode(composerDraftTarget, mode); - if (isLocalDraftThread) { + if (isLocalDraftThread && mode !== interactionMode) { setDraftThreadContext(composerDraftTarget, { interactionMode: mode }); } if (options?.focusComposer !== false) scheduleComposerFocus(); }, [ + composerInteractionMode, interactionMode, isLocalDraftThread, scheduleComposerFocus, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 343c5e74c..e4baa8696 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1873,7 +1873,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) options: accessLevel.options, // The row's menu returns the cursor itself once it has closed. onChange: (mode) => handleRuntimeModeChange(mode, { focusComposer: false }), - planning: interactionMode === "plan", + planning: composerProviderControls.showInteractionModeToggle && interactionMode === "plan", }); const settingsModeControl = runControlsOnRow ? null : modeControl; const settingsAccessControl = runControlsOnRow ? null : accessControl; @@ -3943,7 +3943,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) data-glass-surface="composer" className={cn( "group rounded-[13px] p-px transition-[background-color,box-shadow] duration-200", - interactionMode === "plan" && "plan-mode-frame", + composerProviderControls.showInteractionModeToggle && + interactionMode === "plan" && + "plan-mode-frame", composerProviderState.composerFrameClassName, )} onDragEnter={onComposerDragEnter} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index ed0d7959b..2fa46d9f6 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -4608,6 +4608,22 @@ describe("ThreadsSettingsPanel new thread defaults", () => { .toBeInTheDocument(); await expect.element(page.getByRole("button", { name: "Add agent" })).toBeDisabled(); }); + + it("changes and resets default mode and access level", async () => { + const updateSettings = await mountWith({}); + + await page.getByRole("combobox", { name: "Default build or plan mode" }).click(); + await page.getByRole("option", { name: /Plan/ }).click(); + await vi.waitFor(() => { + expect(updateSettings).toHaveBeenCalledWith({ newThreadInteractionMode: "plan" }); + }); + + await page.getByRole("combobox", { name: "Default access level" }).click(); + await page.getByRole("option", { name: /Full access/ }).click(); + await vi.waitFor(() => { + expect(updateSettings).toHaveBeenCalledWith({ newThreadRuntimeMode: "full-access" }); + }); + }); }); describe("Agent Instructions", () => { diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 1fd86f218..8a8848c8e 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -518,6 +518,12 @@ export function useSettingsRestore(onRestored?: () => void) { : []), ...(settings.newThreadModelSelection !== null ? ["New thread agent"] : []), ...(settings.newThreadRoomAgents.length > 0 ? ["New thread room"] : []), + ...(settings.newThreadInteractionMode !== DEFAULT_UNIFIED_SETTINGS.newThreadInteractionMode + ? ["Build or Plan"] + : []), + ...(settings.newThreadRuntimeMode !== DEFAULT_UNIFIED_SETTINGS.newThreadRuntimeMode + ? ["New thread access"] + : []), ...(settings.openLinksIn !== DEFAULT_UNIFIED_SETTINGS.openLinksIn ? ["Open links in"] : []), ...(settings.browserNewTabSize !== null ? ["Browser page size"] : []), ...(settings.browserSearchEngine !== DEFAULT_UNIFIED_SETTINGS.browserSearchEngine @@ -590,6 +596,8 @@ export function useSettingsRestore(onRestored?: () => void) { settings.wrapUpThreadsOnPullRequestSettled, settings.newThreadModelSelection, settings.newThreadRoomAgents, + settings.newThreadInteractionMode, + settings.newThreadRuntimeMode, settings.enableRooms, settings.enableAgentPages, settings.enableClaudeArtifacts, @@ -669,6 +677,8 @@ export function useSettingsRestore(onRestored?: () => void) { wrapUpThreadsOnPullRequestSettled: DEFAULT_UNIFIED_SETTINGS.wrapUpThreadsOnPullRequestSettled, newThreadModelSelection: DEFAULT_UNIFIED_SETTINGS.newThreadModelSelection, newThreadRoomAgents: DEFAULT_UNIFIED_SETTINGS.newThreadRoomAgents, + newThreadInteractionMode: DEFAULT_UNIFIED_SETTINGS.newThreadInteractionMode, + newThreadRuntimeMode: DEFAULT_UNIFIED_SETTINGS.newThreadRuntimeMode, openLinksIn: DEFAULT_UNIFIED_SETTINGS.openLinksIn, browserNewTabSize: DEFAULT_UNIFIED_SETTINGS.browserNewTabSize, browserSearchEngine: DEFAULT_UNIFIED_SETTINGS.browserSearchEngine, diff --git a/apps/web/src/components/settings/ThreadsSettings.tsx b/apps/web/src/components/settings/ThreadsSettings.tsx index e40760225..a30f775b2 100644 --- a/apps/web/src/components/settings/ThreadsSettings.tsx +++ b/apps/web/src/components/settings/ThreadsSettings.tsx @@ -6,13 +6,17 @@ import { type NewWorktreeBaseFrom, ProviderDriverKind, ProviderInstanceId, + type ProviderInteractionMode, ROOM_AGENT_ROLE_MAX_LENGTH, + RUNTIME_MODES, + type RuntimeMode, } from "@threadlines/contracts"; import { DEFAULT_UNIFIED_SETTINGS } from "@threadlines/contracts/settings"; import { AGENT_INVITES_LABELS, AGENT_THREADS_LABELS, GENERAL_CHATS_PLACEMENT_LABELS, + INTERACTION_MODE_LABELS, NEW_WORKTREE_BASE_LABELS, THREAD_ENV_MODE_LABELS, } from "@threadlines/shared/appPlaces"; @@ -27,6 +31,8 @@ import { useState } from "react"; import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; import { roomsEnabledFor } from "../../hooks/useRoomsEnabled"; +import { interactionModeConfig, interactionModeOptions } from "../../interactionModeOptions"; +import { cn } from "../../lib/utils"; import { getCustomModelOptionsByInstance, resolveAppModelSelectionState, @@ -36,6 +42,8 @@ import { import { canRunOnComputer } from "../../newThreadDefaults"; import { deriveDisplayProviderInstanceEntries } from "../../providerInstances"; import { useServerProviders } from "../../rpc/serverState"; +import { runtimeModeConfig } from "../../runtimeModeOptions"; +import { AccessOptionContent } from "../chat/ComposerRunControls"; import { ProviderModelPicker } from "../chat/ProviderModelPicker"; import { Button } from "../ui/button"; import { DraftInput } from "../ui/draft-input"; @@ -73,6 +81,8 @@ export function ThreadsSettingsPanel({ surface = "full" }: { surface?: "full" | + + @@ -325,6 +335,126 @@ export function NewThreadRoomRow() { ); } +export function NewThreadModeRow() { + const settings = useSettings(); + const { updateSettings } = useUpdateSettings(); + const mode = settings.newThreadInteractionMode; + const current = interactionModeConfig[mode]; + const CurrentIcon = current.icon; + return ( + + updateSettings({ + newThreadInteractionMode: DEFAULT_UNIFIED_SETTINGS.newThreadInteractionMode, + }) + } + /> + ) : null + } + control={ + + } + /> + ); +} + +export function NewThreadAccessRow() { + const settings = useSettings(); + const { updateSettings } = useUpdateSettings(); + const mode = settings.newThreadRuntimeMode; + const current = runtimeModeConfig[mode]; + const CurrentIcon = current.icon; + return ( + + updateSettings({ + newThreadRuntimeMode: DEFAULT_UNIFIED_SETTINGS.newThreadRuntimeMode, + }) + } + /> + ) : null + } + control={ + + } + /> + ); +} + export function DefaultThreadEnvModeRow() { const settings = useSettings(); const { updateSettings } = useUpdateSettings(); diff --git a/apps/web/src/components/settings/settingsRowRegistry.tsx b/apps/web/src/components/settings/settingsRowRegistry.tsx index 67f512b40..d854f29bc 100644 --- a/apps/web/src/components/settings/settingsRowRegistry.tsx +++ b/apps/web/src/components/settings/settingsRowRegistry.tsx @@ -69,7 +69,9 @@ import { ContinueAfterRestartRow, DefaultThreadEnvModeRow, GeneralChatsPlacementRow, + NewThreadAccessRow, NewThreadAgentRow, + NewThreadModeRow, NewThreadRoomRow, NewWorktreeBaseRow, RoomsRow, @@ -144,6 +146,8 @@ export const SETTINGS_ROWS = { // Threads "threads.agent": live(NewThreadAgentRow), "threads.room": live(NewThreadRoomRow), + "threads.mode": live(NewThreadModeRow), + "threads.access": live(NewThreadAccessRow), "threads.startIn": live(DefaultThreadEnvModeRow), "threads.worktreesFrom": live(NewWorktreeBaseRow), "threads.agentThreads": live(AgentThreadsRow), diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index e7b3976bf..eb87f4333 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -2198,6 +2198,48 @@ describe("composerDraftStore new thread defaults", () => { expect(composerDraft()?.activeProvider).toBe(CODEX_INSTANCE); expect(draftRoom()).toBeUndefined(); }); + + it("applies default access and mode, clearing stale composer overrides unless kept", () => { + const store = useComposerDraftStore.getState(); + store.setRuntimeMode(draftId, "approval-required"); + store.setInteractionMode(draftId, "plan"); + store.setDraftThreadContext(draftId, { + runtimeMode: "approval-required", + interactionMode: "plan", + }); + + // Keeping explicit picks leaves both alone. + store.applyNewThreadDefaults( + draftId, + { + modelSelection: null, + room: null, + runtimeMode: "full-access", + interactionMode: "default", + }, + { keepRuntimeMode: true, keepInteractionMode: true }, + ); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({ + runtimeMode: "approval-required", + interactionMode: "plan", + }); + expect(composerDraft()?.runtimeMode).toBe("approval-required"); + expect(composerDraft()?.interactionMode).toBe("plan"); + + // Starting over applies the computer's defaults and clears old composer picks. + store.applyNewThreadDefaults(draftId, { + modelSelection: null, + room: null, + runtimeMode: "full-access", + interactionMode: "default", + }); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({ + runtimeMode: "full-access", + interactionMode: "default", + }); + expect(composerDraft()?.runtimeMode ?? null).toBeNull(); + expect(composerDraft()?.interactionMode ?? null).toBeNull(); + }); }); describe("composerDraftStore provider-scoped option updates", () => { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 9e36d4d41..1c04392af 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -414,6 +414,8 @@ export interface NewThreadDraftDefaults { readonly modelSelection: ModelSelection | null; /** Null: no agents beside the thread's own. */ readonly room: DraftRoom | null; + readonly runtimeMode?: RuntimeMode; + readonly interactionMode?: ProviderInteractionMode; } const PersistedDraftThreadState = Schema.Struct({ @@ -731,7 +733,11 @@ interface ComposerDraftStoreState { applyNewThreadDefaults: ( threadRef: ComposerThreadTarget, defaults: NewThreadDraftDefaults | null, - options?: { readonly keepModel?: boolean }, + options?: { + readonly keepModel?: boolean; + readonly keepRuntimeMode?: boolean; + readonly keepInteractionMode?: boolean; + }, ) => void; setProviderModelOptions: ( threadRef: ComposerThreadTarget, @@ -3326,21 +3332,45 @@ const composerDraftStore = create()( }; } } + const applyRuntimeMode = + defaults !== null && + options?.keepRuntimeMode !== true && + defaults.runtimeMode !== undefined; + const applyInteractionMode = + defaults !== null && + options?.keepInteractionMode !== true && + defaults.interactionMode !== undefined; + if (applyRuntimeMode && nextDraft.runtimeMode !== null) { + nextDraft = { ...nextDraft, runtimeMode: null }; + } + if (applyInteractionMode && nextDraft.interactionMode !== null) { + nextDraft = { ...nextDraft, interactionMode: null }; + } const draftsChanged = !Equal.equals(base.modelSelectionByProvider, nextDraft.modelSelectionByProvider) || base.activeProvider !== nextDraft.activeProvider || - base.modelPicked !== nextDraft.modelPicked; + base.modelPicked !== nextDraft.modelPicked || + base.runtimeMode !== nextDraft.runtimeMode || + base.interactionMode !== nextDraft.interactionMode; - // "New thread" starts with the computer's room, or none: agents in - // a draft are setup, like its model, not work in progress. + // "New thread" starts with the computer's room, mode and access: + // draft setup follows the computer's settings unless kept. const thread = state.draftThreadsByThreadKey[threadKey]; let nextThread = thread; if (defaults !== null && thread && !isDraftThreadPromoting(thread)) { const { room: _previous, ...rest } = thread; - nextThread = - defaults.room === null || defaults.room.agents.length === 0 - ? rest - : { ...rest, room: defaults.room }; + nextThread = { + ...rest, + ...(applyRuntimeMode && defaults.runtimeMode !== undefined + ? { runtimeMode: defaults.runtimeMode } + : {}), + ...(applyInteractionMode && defaults.interactionMode !== undefined + ? { interactionMode: defaults.interactionMode } + : {}), + ...(defaults.room !== null && defaults.room.agents.length > 0 + ? { room: defaults.room } + : {}), + }; } const threadChanged = nextThread !== thread && !Equal.equals(nextThread, thread); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 0425cbb4f..2fbe0fcf2 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -1,6 +1,7 @@ import { scopedProjectKey, scopeProjectRef } from "@threadlines/client-runtime"; import { DEFAULT_NEW_THREAD_RUNTIME_MODE, + DEFAULT_PROVIDER_INTERACTION_MODE, type ScopedProjectRef, type ScopedThreadRef, type ThreadEnvMode, @@ -148,9 +149,11 @@ function useNewThreadState() { // Every other new thread starts where its computer's "Start in" says, // read here so no surface can leave the setting out. const isPlacementPinned = hasBranchOption || hasWorktreePathOption || hasEnvModeOption; - const computerSettings = isPlacementPinned - ? null - : (readComputerConfig(projectRef.environmentId)?.settings ?? null); + const computerSettings = readComputerConfig(projectRef.environmentId)?.settings ?? null; + const defaultRuntimeMode = + computerSettings?.newThreadRuntimeMode ?? DEFAULT_NEW_THREAD_RUNTIME_MODE; + const defaultInteractionMode = + computerSettings?.newThreadInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; const activeThread = currentRouteTarget?.kind === "server" ? selectThreadByRef(useStore.getState(), currentRouteTarget.threadRef) @@ -195,6 +198,9 @@ function useNewThreadState() { emptyStoredDraftThread.draftId, { threadId: emptyStoredDraftThread.threadId, + ...(computerSettings !== null + ? { runtimeMode: defaultRuntimeMode, interactionMode: defaultInteractionMode } + : {}), ...placement, }, ); @@ -238,8 +244,12 @@ function useNewThreadState() { setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentDraftId, { threadId: latestActiveDraftThread.threadId, createdAt: latestActiveDraftThread.createdAt, - runtimeMode: latestActiveDraftThread.runtimeMode, - interactionMode: latestActiveDraftThread.interactionMode, + runtimeMode: + computerSettings !== null ? defaultRuntimeMode : latestActiveDraftThread.runtimeMode, + interactionMode: + computerSettings !== null + ? defaultInteractionMode + : latestActiveDraftThread.interactionMode, ...placement, }); placeFromSettings(currentDraftId); @@ -259,7 +269,8 @@ function useNewThreadState() { worktreePath: null, envMode: "local", ...placement, - runtimeMode: DEFAULT_NEW_THREAD_RUNTIME_MODE, + runtimeMode: defaultRuntimeMode, + interactionMode: defaultInteractionMode, }); placeFromSettings(draftId); writeInitialPrompt(draftId); diff --git a/apps/web/src/leadChat.ts b/apps/web/src/leadChat.ts index 7182fbfba..5bc32b7a7 100644 --- a/apps/web/src/leadChat.ts +++ b/apps/web/src/leadChat.ts @@ -261,7 +261,7 @@ export async function createLeadChat( projectId: project.id, title: "Lead chat", modelSelection, - runtimeMode: DEFAULT_NEW_THREAD_RUNTIME_MODE, + runtimeMode: config?.settings.newThreadRuntimeMode ?? DEFAULT_NEW_THREAD_RUNTIME_MODE, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, branch: null, worktreePath: null, diff --git a/apps/web/src/newThreadDefaults.test.ts b/apps/web/src/newThreadDefaults.test.ts index 3c7bd29d6..14969721e 100644 --- a/apps/web/src/newThreadDefaults.test.ts +++ b/apps/web/src/newThreadDefaults.test.ts @@ -82,6 +82,8 @@ describe("resolveNewThreadDefaults", () => { expect(resolveNewThreadDefaults({ settings, providers })).toEqual({ modelSelection: opus, roomAgents: [{ modelSelection: astra, role: "Reviewer" }], + runtimeMode: "auto", + interactionMode: "default", }); // Codex turned off: the agent on it is left out, the Claude default stays. @@ -108,6 +110,8 @@ describe("resolveNewThreadDefaults", () => { expect(resolveNewThreadDefaults({ settings, providers: [] })).toEqual({ modelSelection: opus, roomAgents: [{ modelSelection: astra }], + runtimeMode: "auto", + interactionMode: "default", }); }); }); @@ -296,6 +300,8 @@ describe("new thread defaults on a draft", () => { serverConfig: computerConfig(studio, { newThreadModelSelection: opus, defaultThreadEnvMode: "worktree", + newThreadRuntimeMode: "full-access", + newThreadInteractionMode: "plan", }), }); store.setStickyModelSelection(astra); @@ -305,19 +311,30 @@ describe("new thread defaults on a draft", () => { // Last used on the desktop: the draft starts on Astra without the user picking it. await applyNewThreadDefaultsToDraft(draftId, desktop); const draft = () => useComposerDraftStore.getState().getComposerDraft(draftId); + const session = () => useComposerDraftStore.getState().getDraftSession(draftId); expect(draft()?.activeProvider).toBe(CODEX); + expect(session()?.runtimeMode).toBe("auto"); + expect(session()?.interactionMode).toBe("default"); store.setDraftThreadContext(draftId, { projectRef: scopeProjectRef(studio, projectId) }); await applyMovedDraftDefaults(draftId, studio); expect(draft()?.activeProvider).toBe(CLAUDE); - // The studio's Start in comes with the move too. - expect(useComposerDraftStore.getState().getDraftSession(draftId)?.envMode).toBe("worktree"); + // The studio's Start in, Access and Mode come with the move too. + expect(session()?.envMode).toBe("worktree"); + expect(session()?.runtimeMode).toBe("full-access"); + expect(session()?.interactionMode).toBe("plan"); store.setModelSelection(draftId, astra); + store.setRuntimeMode(draftId, "approval-required"); + store.setDraftThreadContext(draftId, { runtimeMode: "approval-required" }); + store.setInteractionMode(draftId, "default"); + store.setDraftThreadContext(draftId, { interactionMode: "default" }); store.setDraftThreadContext(draftId, { projectRef: scopeProjectRef(desktop, projectId) }); store.setDraftThreadContext(draftId, { projectRef: scopeProjectRef(studio, projectId) }); await applyMovedDraftDefaults(draftId, studio); expect(draft()?.activeProvider).toBe(CODEX); + expect(session()?.runtimeMode).toBe("approval-required"); + expect(session()?.interactionMode).toBe("default"); }); it("keeps the last used model for a draft written in before the computer's settings came", async () => { const store = useComposerDraftStore.getState(); @@ -337,4 +354,39 @@ describe("new thread defaults on a draft", () => { expect(draft?.activeProvider).toBe(CLAUDE); expect(draft?.modelSelectionByProvider[CLAUDE]).toEqual(opus); }); + + it("drops un-picked Full access when moving to a connecting computer and applies late defaults even after typing", async () => { + const store = useComposerDraftStore.getState(); + useSavedEnvironmentRuntimeStore.getState().patch(desktop, { + serverConfig: computerConfig(desktop, { + newThreadRuntimeMode: "full-access", + newThreadInteractionMode: "plan", + }), + }); + store.setProjectDraftThreadId(scopeProjectRef(desktop, projectId), draftId, { + threadId: ThreadId.make("thread-connecting"), + }); + await applyNewThreadDefaultsToDraft(draftId, desktop); + const session = () => useComposerDraftStore.getState().getDraftSession(draftId); + expect(session()).toMatchObject({ runtimeMode: "full-access", interactionMode: "plan" }); + + // Move to studio before studio's config arrives: Full access must not carry over. + store.setDraftThreadContext(draftId, { projectRef: scopeProjectRef(studio, projectId) }); + const moveRequest = applyMovedDraftDefaults(draftId, studio); + expect(session()).toMatchObject({ runtimeMode: "auto", interactionMode: "default" }); + + // Typing before studio's config lands must not block studio's Access/Mode defaults. + store.setPrompt(draftId, "check tests"); + useSavedEnvironmentRuntimeStore.getState().patch(studio, { + serverConfig: computerConfig(studio, { + newThreadRuntimeMode: "approval-required", + newThreadInteractionMode: "plan", + }), + }); + await moveRequest; + expect(session()).toMatchObject({ + runtimeMode: "approval-required", + interactionMode: "plan", + }); + }); }); diff --git a/apps/web/src/newThreadDefaults.ts b/apps/web/src/newThreadDefaults.ts index d22ffddaa..af9ec9c2c 100644 --- a/apps/web/src/newThreadDefaults.ts +++ b/apps/web/src/newThreadDefaults.ts @@ -8,11 +8,15 @@ */ import { DEFAULT_MODEL, + DEFAULT_NEW_THREAD_RUNTIME_MODE, + DEFAULT_PROVIDER_INTERACTION_MODE, type EnvironmentId, type ModelSelection, ProviderDriverKind, ProviderInstanceId, + type ProviderInteractionMode, type NewThreadRoomAgent, + type RuntimeMode, type ScopedProjectRef, type ServerConfig, type ServerProvider, @@ -20,6 +24,7 @@ import { type ThreadEnvMode, ThreadParticipantId, } from "@threadlines/contracts"; +import { saferRuntimeMode } from "@threadlines/shared/runtimeMode"; import { roomsEnabled } from "@threadlines/shared/serverSettings"; import { nextRoomAgentName } from "@threadlines/shared/threadParticipants"; @@ -78,6 +83,8 @@ export function canRunOnComputer( export function resolveNewThreadDefaults(config: ComputerConfig): { readonly modelSelection: ModelSelection | null; readonly roomAgents: ReadonlyArray; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; } { const { settings, providers } = config; const modelSelection = @@ -90,7 +97,12 @@ export function resolveNewThreadDefaults(config: ComputerConfig): { canRunOnComputer(providers, agent.modelSelection.instanceId), ) : []; - return { modelSelection, roomAgents }; + return { + modelSelection, + roomAgents, + runtimeMode: settings.newThreadRuntimeMode, + interactionMode: settings.newThreadInteractionMode, + }; } /** @@ -242,9 +254,12 @@ export function lastUsedSelection(): ModelSelection | null { */ function draftSetup(draftId: DraftId) { const state = useComposerDraftStore.getState(); + const session = state.getDraftSession(draftId); return { composer: state.getComposerDraft(draftId), - room: state.getDraftSession(draftId)?.room, + room: session?.room, + runtimeMode: session?.runtimeMode, + interactionMode: session?.interactionMode, }; } @@ -267,10 +282,21 @@ let lastRequest = 0; export async function applyNewThreadDefaultsToDraft( draftId: DraftId, environmentId: EnvironmentId, - options?: { readonly keepModel?: boolean }, + options?: { + readonly keepModel?: boolean; + readonly keepRuntimeMode?: boolean; + readonly keepInteractionMode?: boolean; + }, ): Promise { const request = ++lastRequest; latestRequestByDraft.set(draftId, request); + const keepModel = options?.keepModel === true; + const keepRuntimeMode = options?.keepRuntimeMode === true; + const keepInteractionMode = options?.keepInteractionMode === true; + // Access and Build/Plan follow the computer's settings without a timeout + // (like Start in): typing in the prompt must not stop late settings from + // applying the computer's access level, while an explicit pick stands. + applyModesFromSettings(draftId, environmentId, { keepRuntimeMode, keepInteractionMode }); const arrivedLate = readComputerConfig(environmentId) === null; if (arrivedLate) { // The device's last used model needs no settings: it applies now, so the @@ -298,8 +324,11 @@ export async function applyNewThreadDefaultsToDraft( // Gone, moved, being sent, or worked on while the settings were on their way. return; } - const keepModel = options?.keepModel === true; - const applyOptions = keepModel ? { keepModel: true } : undefined; + const applyOptions = { + ...(keepModel ? { keepModel: true } : {}), + keepRuntimeMode: true, + keepInteractionMode: true, + }; if (config === null) { store.applyNewThreadDefaults(draftId, null, applyOptions); @@ -321,7 +350,10 @@ export async function applyNewThreadDefaultsToDraft( } store.applyNewThreadDefaults( draftId, - { modelSelection: defaults.modelSelection, room }, + { + modelSelection: defaults.modelSelection, + room, + }, applyOptions, ); } @@ -335,11 +367,32 @@ interface PendingPlacement { readonly placementFor: (startIn: ThreadEnvMode) => NewThreadPlacement; } +/** A draft waiting for its computer's default Access and Build/Plan settings. */ +interface PendingModes { + readonly environmentId: EnvironmentId; + readonly openedRuntimeMode: RuntimeMode; + readonly openedInteractionMode: ProviderInteractionMode; + readonly keepRuntimeMode: boolean; + readonly keepInteractionMode: boolean; +} + const pendingPlacements = new Map(); +const pendingModes = new Map(); /** Set while any draft waits: one watch on the computers' settings for all. */ let stopWatchingSettings: (() => void) | null = null; -function settlePendingPlacements(): void { +function ensureWatchingSettings(): void { + if (stopWatchingSettings !== null) return; + const stops = [ + onServerConfigUpdated(settlePendingSettings), + useSavedEnvironmentRuntimeStore.subscribe(settlePendingSettings), + ]; + stopWatchingSettings = () => { + for (const stop of stops) stop(); + }; +} + +function settlePendingSettings(): void { const store = useComposerDraftStore.getState(); for (const [draftId, pending] of pendingPlacements) { const session = store.getDraftSession(draftId); @@ -365,12 +418,105 @@ function settlePendingPlacements(): void { pending.placementFor(config.settings.defaultThreadEnvMode), ); } - if (pendingPlacements.size === 0) { + for (const [draftId, pending] of pendingModes) { + const session = store.getDraftSession(draftId); + if ( + session === null || + session.environmentId !== pending.environmentId || + (session.promotedTo ?? null) !== null + ) { + pendingModes.delete(draftId); + continue; + } + const composer = store.getComposerDraft(draftId); + const keepRuntimeMode = + pending.keepRuntimeMode || + composer?.runtimeMode != null || + session.runtimeMode !== pending.openedRuntimeMode; + const keepInteractionMode = + pending.keepInteractionMode || + composer?.interactionMode != null || + session.interactionMode !== pending.openedInteractionMode; + if (keepRuntimeMode && keepInteractionMode) { + pendingModes.delete(draftId); + continue; + } + const config = readComputerConfig(pending.environmentId); + if (config === null) { + continue; + } + pendingModes.delete(draftId); + const defaults = resolveNewThreadDefaults(config); + store.applyNewThreadDefaults( + draftId, + { + modelSelection: null, + room: session.room ?? null, + runtimeMode: defaults.runtimeMode, + interactionMode: defaults.interactionMode, + }, + { + keepModel: true, + keepRuntimeMode, + keepInteractionMode, + }, + ); + } + if (pendingPlacements.size === 0 && pendingModes.size === 0) { stopWatchingSettings?.(); stopWatchingSettings = null; } } +/** + * Applies a computer's default Access and Build/Plan settings to a draft: now + * when the settings are known, else when they arrive (startup or a connecting + * computer). Typing in the prompt never blocks them; an explicit pick does. + */ +function applyModesFromSettings( + draftId: DraftId, + environmentId: EnvironmentId, + options: { readonly keepRuntimeMode: boolean; readonly keepInteractionMode: boolean }, +): void { + const store = useComposerDraftStore.getState(); + const session = store.getDraftSession(draftId); + if (session === null || (options.keepRuntimeMode && options.keepInteractionMode)) { + pendingModes.delete(draftId); + settlePendingSettings(); + return; + } + const config = readComputerConfig(environmentId); + if (config !== null) { + pendingModes.delete(draftId); + const defaults = resolveNewThreadDefaults(config); + store.applyNewThreadDefaults( + draftId, + { + modelSelection: null, + room: session.room ?? null, + runtimeMode: defaults.runtimeMode, + interactionMode: defaults.interactionMode, + }, + { + keepModel: true, + keepRuntimeMode: options.keepRuntimeMode, + keepInteractionMode: options.keepInteractionMode, + }, + ); + settlePendingSettings(); + return; + } + pendingModes.set(draftId, { + environmentId, + openedRuntimeMode: session.runtimeMode, + openedInteractionMode: session.interactionMode, + keepRuntimeMode: options.keepRuntimeMode, + keepInteractionMode: options.keepInteractionMode, + }); + ensureWatchingSettings(); + settlePendingSettings(); +} + /** * Places a draft where its computer's "Start in" says: now when the settings * are known, else when they arrive (the first new thread at startup, or a @@ -398,35 +544,55 @@ export function placeDraftFromSettings( }, placementFor, }); - if (stopWatchingSettings === null) { - const stops = [ - onServerConfigUpdated(settlePendingPlacements), - useSavedEnvironmentRuntimeStore.subscribe(settlePendingPlacements), - ]; - stopWatchingSettings = () => { - for (const stop of stops) stop(); - }; - } + ensureWatchingSettings(); } - settlePendingPlacements(); + settlePendingSettings(); } /** * A draft moved to another computer before its first message takes that * computer's room and "Start in" (the move leaves the old computer's checkout - * behind), and its model too unless the user picked the model. + * behind), and its model, mode and access too unless the user picked them. */ export function applyMovedDraftDefaults( draftId: DraftId, toEnvironmentId: EnvironmentId, ): Promise { - const picked = useComposerDraftStore.getState().getComposerDraft(draftId)?.modelPicked === true; + const store = useComposerDraftStore.getState(); + const draft = store.getComposerDraft(draftId); + const session = store.getDraftSession(draftId); + const pickedModel = draft?.modelPicked === true; + const pickedRuntimeMode = draft?.runtimeMode != null; + const pickedInteractionMode = draft?.interactionMode != null; + // Moving an un-picked draft to a computer whose settings have not arrived yet + // must not carry Full access (or an un-picked Plan default) across computers. + if (session !== null && readComputerConfig(toEnvironmentId) === null) { + const safeRuntimeMode = !pickedRuntimeMode + ? saferRuntimeMode(session.runtimeMode, DEFAULT_NEW_THREAD_RUNTIME_MODE) + : session.runtimeMode; + const safeInteractionMode = !pickedInteractionMode + ? DEFAULT_PROVIDER_INTERACTION_MODE + : session.interactionMode; + if ( + safeRuntimeMode !== session.runtimeMode || + safeInteractionMode !== session.interactionMode + ) { + store.setDraftThreadContext(draftId, { + runtimeMode: safeRuntimeMode, + interactionMode: safeInteractionMode, + }); + } + } placeDraftFromSettings(draftId, toEnvironmentId, (startIn) => ({ branch: null, worktreePath: null, envMode: startIn, })); - return applyNewThreadDefaultsToDraft(draftId, toEnvironmentId, { keepModel: picked }); + return applyNewThreadDefaultsToDraft(draftId, toEnvironmentId, { + keepModel: pickedModel, + keepRuntimeMode: pickedRuntimeMode, + keepInteractionMode: pickedInteractionMode, + }); } /** diff --git a/apps/web/src/worktreePickup.ts b/apps/web/src/worktreePickup.ts index 40a76e0e9..4778fb07a 100644 --- a/apps/web/src/worktreePickup.ts +++ b/apps/web/src/worktreePickup.ts @@ -8,6 +8,7 @@ import { type EnvironmentId, type ModelSelection, type ProjectId, + type ProviderInteractionMode, type RuntimeMode, type VcsWorktreeStatus, } from "@threadlines/contracts"; @@ -121,6 +122,7 @@ export async function addWorktreeThreads(input: { readonly worktrees: ReadonlyArray; readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; + readonly interactionMode?: ProviderInteractionMode; }): Promise { const api = ensureEnvironmentApi(input.environmentId); for (const worktree of input.worktrees) { @@ -132,7 +134,7 @@ export async function addWorktreeThreads(input: { title: threadTitleFromWorktree(worktree), modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + interactionMode: input.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE, branch: worktree.refName, worktreePath: worktree.path, worktreeOrigin: { kind: "existing" }, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 12abf78dc..7c0c32349 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -12,9 +12,13 @@ import { import { AgentInvitesMode, AgentThreadsMode, + DEFAULT_NEW_THREAD_RUNTIME_MODE, + DEFAULT_PROVIDER_INTERACTION_MODE, FollowUpDelivery, ModelSelection, + ProviderInteractionMode, RoomAgentRole, + RuntimeMode, } from "./orchestration.ts"; import { ProjectNotesMode } from "./projectContext.ts"; import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts"; @@ -1182,6 +1186,20 @@ export const ServerSettings = Schema.Struct({ newThreadRoomAgents: Schema.Array(NewThreadRoomAgent).pipe( Schema.withDecodingDefault(Effect.succeed([])), ), + /** + * The access level a new thread starts with on this computer. Agents that + * lack the level run at the next safer one they have. Never chosen: Auto. + */ + newThreadRuntimeMode: RuntimeMode.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_NEW_THREAD_RUNTIME_MODE)), + ), + /** + * Whether a new thread starts in Build (`default`) or Plan (`plan`) mode on + * this computer. Agents without Plan mode start in Build. Never chosen: Build. + */ + newThreadInteractionMode: ProviderInteractionMode.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)), + ), /** * The name the user gave this computer in Threadlines. Every device and * linked computer sees it (the descriptor's `label`); `null` keeps the name @@ -1367,6 +1385,8 @@ export const ServerSettingsPatch = Schema.Struct({ // reasoning, and the list is the whole list. newThreadModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), newThreadRoomAgents: Schema.optionalKey(Schema.Array(NewThreadRoomAgent)), + newThreadRuntimeMode: Schema.optionalKey(RuntimeMode), + newThreadInteractionMode: Schema.optionalKey(ProviderInteractionMode), computerName: Schema.optionalKey(Schema.NullOr(DeviceName)), }); export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; diff --git a/packages/shared/src/appPlaces.ts b/packages/shared/src/appPlaces.ts index b2953a6bc..fa007d818 100644 --- a/packages/shared/src/appPlaces.ts +++ b/packages/shared/src/appPlaces.ts @@ -27,6 +27,7 @@ import type { ModelSelection, NewWorktreeBaseFrom, ProjectNotesMode, + ProviderInteractionMode, PushAlertKinds, ServerSettings, ServerSettingsPatch, @@ -42,6 +43,7 @@ import { RESPONSIVE_PAGE_SIZE_ID, RESPONSIVE_PAGE_SIZE_LABEL, } from "./browserPageSizes.ts"; +import { RUNTIME_MODE_LABELS } from "./runtimeMode.ts"; import { agentInvitesChoice, agentThreadsMode, @@ -318,6 +320,12 @@ const editableAlert = (alert: keyof PushAlertKinds | "quietAtComputer") => const fetchIntervalSeconds = (settings: ServerSettings): number => Math.round(Duration.toSeconds(settings.automaticGitFetchInterval)); +/** "Mode", as its menu words each choice. */ +export const INTERACTION_MODE_LABELS: Readonly> = { + default: "Build", + plan: "Plan", +}; + /** "Start in", as its menu words each choice. */ export const THREAD_ENV_MODE_LABELS: Readonly> = { local: "Local", @@ -1527,6 +1535,39 @@ const ROWS = [ about: "Other agents new threads start with in the room, if any.", widensAgents: true, }, + { + id: "threads.mode", + kind: "row", + parent: "threads.newThreads", + title: "Build or Plan", + about: "Whether new threads start in Build or Plan. Agents without Plan start in Build.", + keywords: ["build", "plan", "planning"], + ...editableServerChoice("newThreadInteractionMode", INTERACTION_MODE_LABELS), + }, + { + id: "threads.access", + kind: "row", + parent: "threads.newThreads", + title: "Access", + about: + "The access level new threads start with. Agents without it use the next safer level they have.", + keywords: [ + "access level", + "default access", + "full access", + "auto", + "supervised", + "auto-accept edits", + "permissions", + "sandbox", + ], + value: { + kind: "choice", + read: (settings) => settings.newThreadRuntimeMode, + options: RUNTIME_MODE_LABELS, + }, + widensAgents: true, + }, { id: "threads.startIn", kind: "row", diff --git a/packages/shared/src/settingsEdits.test.ts b/packages/shared/src/settingsEdits.test.ts index ba6f97737..2212d68a7 100644 --- a/packages/shared/src/settingsEdits.test.ts +++ b/packages/shared/src/settingsEdits.test.ts @@ -99,6 +99,7 @@ describe("agents' settings changes", () => { expect(refused([])).toBe("count"); expect(refused([{ place: "settings.nowhere", value: true }])).toBe("unknown"); expect(refused([{ place: "threads.agentThreads", value: "auto" }])).toBe("user_only"); + expect(refused([{ place: "threads.access", value: "full-access" }])).toBe("user_only"); expect(refused([{ place: "general.usageAnalytics", value: true }])).toBe("not_editable"); expect( refused([