The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 09:30 UTC
feat: pin favorite projects and archive old ones (#26154)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 31, 2026 at 02:37 UTC
ffaa1dba76d86c073533055e48d7f8f015c8a7b7
68 files changed
+1367
-256
apps/mobile/src/features/home/HomeRouteScreen.tsx
+11
-6
@@ -10,7 +10,10 @@ import { useMemo, useState } from "react";
10
import { Platform, useWindowDimensions } from "react-native";
11
12
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
13
-import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";
13
+import {
14
+ pickableProjectGroups,
15
+ resolveScratchProjectScopeKey,
16
+} from "@t3tools/client-runtime/state/project-grouping";
17
18
import { NativeStackScreenOptions } from "../../native/StackHeader";
19
import { useProjects } from "../../state/entities";
@@ -138,11 +141,13 @@ export function HomeRouteScreen() {
141
);
142
const projectFilterOptions = useMemo(
143
() =>
141
- buildHomeProjectScopes({
142
- projects,
143
- environmentId: selectedEnvironmentId,
144
- projectGroupingMode: listOptions.projectGroupingMode,
145
- }).map((scope) => ({
144
+ pickableProjectGroups(
145
+ buildHomeProjectScopes({
146
+ projects,
147
+ environmentId: selectedEnvironmentId,
148
+ projectGroupingMode: listOptions.projectGroupingMode,
149
+ }),
150
+ ).map((scope) => ({
151
key: scope.key,
152
label: scope.title,
153
})),
apps/mobile/src/features/home/HomeScreen.tsx
+10
-2
@@ -9,6 +9,7 @@ import {
9
type EnvironmentProject,
10
type EnvironmentThreadShell,
11
} from "@t3tools/client-runtime/state/shell";
12
+import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
13
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
14
import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
15
import { useAtomValue } from "@effect/atom-react";
@@ -376,7 +377,11 @@ export function HomeScreen(props: HomeScreenProps) {
377
})();
378
379
const v2ProjectScopeKey = props.selectedProjectKey;
379
- const v2ScopedProjectGroup = findHomeProjectScope(projectScopes, v2ProjectScopeKey);
380
+ // An archived project's filter reads as all projects, matching the filter menu.
381
+ const v2ScopedProjectGroup = findHomeProjectScope(
382
+ pickableProjectGroups(projectScopes),
383
+ v2ProjectScopeKey,
384
+ );
385
const threadSearch = useThreadSearch(
386
searchEnvironmentIds,
387
props.searchQuery,
@@ -711,7 +716,10 @@ export function HomeScreen(props: HomeScreenProps) {
716
<ThreadListFilters
717
gutter={primaryColumn ? 8 : 0}
718
environments={props.environments}
714
- projects={projectScopes.map((scope) => ({ key: scope.key, label: scope.title }))}
719
+ projects={pickableProjectGroups(projectScopes).map((scope) => ({
720
+ key: scope.key,
721
+ label: scope.title,
722
+ }))}
723
selectedEnvironmentId={props.selectedEnvironmentId}
724
selectedProjectKey={props.selectedProjectKey}
725
onEnvironmentChange={props.onEnvironmentChange}
apps/mobile/src/features/home/homeThreadList.ts
+4
@@ -27,6 +27,8 @@ export interface HomeProjectScope {
27
readonly representative: EnvironmentProject;
28
readonly projects: ReadonlyArray<EnvironmentProject>;
29
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
30
+ readonly pinned: boolean;
31
+ readonly archived: boolean;
32
}
33
34
function getProjectSortTimestamp(
@@ -62,6 +64,8 @@ export function buildHomeProjectScopes(input: {
64
representative: group.representative,
65
projects: group.members.map((member) => member.project),
66
projectRefs: group.memberProjectRefs,
67
+ pinned: group.pinned,
68
+ archived: group.archived,
69
};
70
});
71
}
apps/mobile/src/features/keyboard/CommandPalette.tsx
+5
-1
@@ -401,7 +401,11 @@ export function CommandPalette(props: {
401
})),
402
);
403
}
404
- const projectItems: CommandPaletteItem[] = projects.map((project) => ({
404
+ const openProjects = projects.filter((project) => project.archivedAt == null);
405
+ const projectItems: CommandPaletteItem[] = [
406
+ ...openProjects.filter((project) => project.pinnedAt != null),
407
+ ...openProjects.filter((project) => project.pinnedAt == null),
408
+ ].map((project) => ({
409
key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
410
kind: "project",
411
project,
apps/mobile/src/features/projects/AddProjectScreen.tsx
+16
-1
@@ -713,6 +713,9 @@ function useCreateProject(environment: EnvironmentOption | null) {
713
const openNewTaskDraft = useOpenNewTaskDraft();
714
const navigation = useNavigation();
715
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
716
+ const updateProject = useAtomCommand(projectEnvironment.update, {
717
+ label: "project unarchive",
718
+ });
719
const projects = useProjects();
720
721
return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => {
@@ -734,7 +737,19 @@ function useCreateProject(environment: EnvironmentOption | null) {
737
path: workspaceRoot,
738
});
739
if (existing) {
737
- Dialog.alert("Project already exists", existing.title);
740
+ // Adding an archived project's folder again brings the project back.
741
+ const unarchived =
742
+ existing.archivedAt == null ||
743
+ (
744
+ await updateProject({
745
+ environmentId: existing.environmentId,
746
+ input: { projectId: existing.id, archived: false },
747
+ })
748
+ )._tag === "Success";
749
+ Dialog.alert(
750
+ "Project already exists",
751
+ unarchived ? existing.title : `${existing.title} is still archived. Try again later.`,
752
+ );
753
openNewTaskDraft(
754
{
755
environmentId: existing.environmentId,
apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
+88
-6
@@ -9,7 +9,10 @@ import {
9
isAtomCommandInterrupted,
10
squashAtomCommandFailure,
11
} from "@t3tools/client-runtime/state/runtime";
12
-import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";
12
+import {
13
+ deriveProjectGroupLabel,
14
+ type ProjectGroup,
15
+} from "@t3tools/client-runtime/state/project-grouping";
16
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
17
import { useNavigation } from "@react-navigation/native";
18
import { useRef, useState } from "react";
@@ -34,6 +37,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
37
import { SettingsScreen } from "./components/SettingsScreen";
38
import { SettingsSection } from "./components/SettingsSection";
39
import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow";
40
+import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
41
import {
42
AndroidSettingsEnvironmentFilter,
43
SettingsEnvironmentFilterHeader,
@@ -59,6 +63,7 @@ export function SettingsProjectOverviewRouteScreen() {
63
};
64
const navigation = useNavigation();
65
const {
66
+ availableTargets,
67
selectedTargets,
68
projectGroups,
69
selectedProjectKey,
@@ -95,7 +100,7 @@ export function SettingsProjectOverviewRouteScreen() {
100
<Text className="px-2 text-base text-foreground-muted">
101
Choose a project with the filter above to manage its name, checkouts and removal.
102
</Text>
98
- ) : members.length === 0 ? (
103
+ ) : !group || members.length === 0 ? (
104
<Text className="px-2 text-base text-foreground-muted">
105
This project has no checkout on the selected connected environments. Change the filter
106
above.
@@ -104,6 +109,8 @@ export function SettingsProjectOverviewRouteScreen() {
109
<ProjectOverviewContent
110
key={`${selectedProjectKey}:${members.map((member) => member.id).join(",")}`}
111
members={members}
112
+ group={group}
113
+ connectedTargets={availableTargets}
114
environments={selectedTargets}
115
hasOtherMembers={members.length < (group?.members.length ?? 0)}
116
isRemoving={isRemoving}
@@ -122,6 +129,9 @@ export function SettingsProjectOverviewRouteScreen() {
129
130
function ProjectOverviewContent(props: {
131
readonly members: readonly EnvironmentProject[];
132
+ /** Pin and archive belong to the whole project, even when the filter picks one machine. */
133
+ readonly group: ProjectGroup;
134
+ readonly connectedTargets: readonly SettingsTarget[];
135
readonly environments: readonly SettingsTarget[];
136
readonly hasOtherMembers: boolean;
137
readonly isRemoving: boolean;
@@ -137,10 +147,8 @@ function ProjectOverviewContent(props: {
147
const [draftName, setDraftName] = useState<string | null>(null);
148
const [isSaving, setIsSaving] = useState(false);
149
const threads = useThreadShells();
140
- const removableEnvironments = useEnvironmentsWithScope(
141
- props.members,
142
- AuthOrchestrationOperateScope,
143
- );
150
+ const allMembers = props.group.members.map((member) => member.project);
151
+ const removableEnvironments = useEnvironmentsWithScope(allMembers, AuthOrchestrationOperateScope);
152
const canRemoveGroup = props.members.every((member) =>
153
removableEnvironments.has(member.environmentId),
154
);
@@ -149,6 +157,52 @@ function ProjectOverviewContent(props: {
157
label: "project name update",
158
reportFailure: true,
159
});
160
+ const organizeProject = useAtomCommand(projectEnvironment.update, {
161
+ label: "project update",
162
+ reportFailure: true,
163
+ });
164
+ const [isOrganizing, setIsOrganizing] = useState(false);
165
+ const memberTargets = allMembers.map((member) =>
166
+ props.connectedTargets.find((entry) => entry.environmentId === member.environmentId),
167
+ );
168
+ const offline = memberTargets.some((target) => target === undefined);
169
+ // Older servers drop pin and archive, so their projects do not offer them.
170
+ // Offline members are checked when the write runs, so their reason can show.
171
+ const canOrganize =
172
+ allMembers.every(
173
+ (member, index) =>
174
+ memberTargets[index] === undefined || removableEnvironments.has(member.environmentId),
175
+ ) &&
176
+ memberTargets.every(
177
+ (target) =>
178
+ target === undefined ||
179
+ target.serverConfig.environment.capabilities.projectOrganization === true,
180
+ );
181
+ // One machine at a time, stopping at the first failure, as web does.
182
+ const organize = async (input: { readonly pinned?: boolean; readonly archived?: boolean }) => {
183
+ setIsOrganizing(true);
184
+ for (const member of allMembers) {
185
+ if (!readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope)) {
186
+ Dialog.alert("Failed to update project", "This connection can no longer change it.");
187
+ break;
188
+ }
189
+ const result = await organizeProject({
190
+ environmentId: member.environmentId,
191
+ input: { projectId: member.id, ...input },
192
+ });
193
+ if (result._tag === "Failure") {
194
+ if (!isAtomCommandInterrupted(result)) {
195
+ const error = squashAtomCommandFailure(result);
196
+ Dialog.alert(
197
+ `Failed to update "${member.title}"`,
198
+ error instanceof Error ? error.message : "An error occurred.",
199
+ );
200
+ }
201
+ break;
202
+ }
203
+ }
204
+ setIsOrganizing(false);
205
+ };
206
const nextName = (draftName ?? displayName).trim();
207
const canSave = !isSaving && nextName.length > 0 && nextName !== displayName;
208
@@ -295,6 +349,34 @@ function ProjectOverviewContent(props: {
349
</View>
350
</SettingsSection>
351
352
+ {canOrganize ? (
353
+ <SettingsSection title="Organize">
354
+ <SettingsSwitchRow
355
+ icon="pin"
356
+ label="Pin"
357
+ subtitle={
358
+ offline
359
+ ? "Connect every machine with this project to change this."
360
+ : "Pinned projects come first in project pickers."
361
+ }
362
+ value={props.group.pinned}
363
+ disabled={isOrganizing || offline}
364
+ onValueChange={(pinned) => void organize({ pinned })}
365
+ />
366
+ <SettingsActionRow
367
+ icon="archivebox"
368
+ label={props.group.archived ? "Unarchive project" : "Archive project"}
369
+ description={
370
+ props.group.archived
371
+ ? "Hidden from project pickers. Threads and files are kept."
372
+ : "Hides the project from project pickers. Threads and files are kept."
373
+ }
374
+ disabled={isOrganizing || offline}
375
+ onPress={() => void organize({ archived: !props.group.archived })}
376
+ />
377
+ </SettingsSection>
378
+ ) : null}
379
+
380
<SettingsSection title="Checkouts">
381
{props.members.map((member, index) => {
382
const environment = props.environments.find(
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+10
-1
@@ -666,7 +666,16 @@ function TaskForm({
666
const tasks = useEnvironmentQuery(
667
serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
668
);
669
- const projects = useProjects().filter((project) => project.environmentId === environmentId);
669
+ // Pinned first. The chosen project stays listed after it is archived.
670
+ const projects = useProjects()
671
+ .filter(
672
+ (project) =>
673
+ project.environmentId === environmentId &&
674
+ (project.archivedAt == null ||
675
+ project.id === draft.projectId ||
676
+ project.id === draft.task?.projectId),
677
+ )
678
+ .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
679
const config = useEnvironmentServerConfig(environmentId);
680
const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
681
const canOperate = useAtomValue(
apps/mobile/src/features/settings/components/SettingsEnvironmentFilterHeader.tsx
+5
-2
@@ -100,7 +100,7 @@ export function SettingsEnvironmentFilterHeader(props: {
100
},
101
...selectableProjectGroups.map((group) => ({
102
type: "action" as const,
103
- label: group.label,
103
+ label: projectMenuLabel(group),
104
state: selectedProjectKey === group.key ? ("on" as const) : undefined,
105
onPress: () => selectProject(group.key),
106
})),
@@ -160,7 +160,7 @@ export function AndroidSettingsEnvironmentFilter() {
160
},
161
...selectableProjectGroups.map((group) => ({
162
id: `project:${group.key}`,
163
- title: `Project · ${group.label}`,
163
+ title: `Project · ${projectMenuLabel(group)}`,
164
state: selectedProjectKey === group.key ? ("on" as const) : ("off" as const),
165
})),
166
]}
@@ -190,3 +190,6 @@ export function AndroidSettingsEnvironmentFilter() {
190
</Menu>
191
);
192
}
193
+
194
+const projectMenuLabel = (group: { readonly label: string; readonly archived: boolean }) =>
195
+ group.archived ? `${group.label} · Archived` : group.label;
apps/mobile/src/features/settings/scheduled-task-editor.tsx
+5
-1
@@ -37,7 +37,11 @@ export function useScheduledTaskEditor() {
37
(member) =>
38
member.project.environmentId === environmentId && member.project.id === project.id,
39
),
40
- ) ?? environmentProjects[0];
40
+ ) ??
41
+ environmentProjects.find(
42
+ (project) => project.pinnedAt != null && project.archivedAt == null,
43
+ ) ??
44
+ environmentProjects.find((project) => project.archivedAt == null);
45
return createDraft(
46
project?.id ?? null,
47
scheduledTaskDefaultModel(configs.get(environmentId) ?? null, project ?? null),
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+10
-4
@@ -18,6 +18,7 @@ import * as Dialog from "../../components/ui/Dialog";
18
import { useAtomValue } from "@effect/atom-react";
19
import * as Cause from "effect/Cause";
20
import { AsyncResult } from "effect/reactivity";
21
+import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
22
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
23
import {
24
CommonActions,
@@ -458,10 +459,15 @@ export function NewTaskDraftScreen(props: {
459
return;
460
}
461
461
- const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes, {
462
- incomingShareId: props.incomingShareId,
463
- pickerClosed: initialPickerRef.current === "open" && isFocused,
464
- });
462
+ const selection = resolveDraftProjectSelection(
463
+ selectedProjectKey,
464
+ projects,
465
+ pickableProjectGroups(projectScopes),
466
+ {
467
+ incomingShareId: props.incomingShareId,
468
+ pickerClosed: initialPickerRef.current === "open" && isFocused,
469
+ },
470
+ );
471
if (selection.kind === "preserve") {
472
initialPickerRef.current = null;
473
return;
apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+2
-1
@@ -10,6 +10,7 @@ import {
10
type StaticScreenProps,
11
} from "@react-navigation/native";
12
import { SymbolView } from "../../components/ui/AppSymbol";
13
+import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
14
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
15
import {
16
isAtomCommandInterrupted,
@@ -175,7 +176,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
176
const screenTitle = incomingShare ? "Start a task" : "Choose project";
177
const projectEmptyState = deriveProjectEmptyState(catalogState);
178
const serverConfigs = useServerConfigs();
178
- const listScopes = projectScopes.filter(
179
+ const listScopes = pickableProjectGroups(projectScopes).filter(
180
(scope) =>
181
!scope.projects.every((project) =>
182
isScratchProject(project, serverConfigs.get(project.environmentId)?.scratchWorkspaceRoot),
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+7
-3
@@ -1,7 +1,10 @@
1
import { useActiveNewTask } from "../../state/active-new-task";
2
import { ThreadUndoNotice } from "../home/ThreadUndoNotice";
3
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
4
-import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";
4
+import {
5
+ pickableProjectGroups,
6
+ resolveScratchProjectScopeKey,
7
+} from "@t3tools/client-runtime/state/project-grouping";
8
import {
9
useAppearancePreferences,
10
useAndroidFloatingTabs,
@@ -219,7 +222,7 @@ function ThreadNavigationSidebarPane(
222
}),
223
[projects, options.selectedEnvironmentId, options.projectGroupingMode],
224
);
222
- const projectFilterOptions = projectScopes.map((scope) => ({
225
+ const projectFilterOptions = pickableProjectGroups(projectScopes).map((scope) => ({
226
key: scope.key,
227
label: scope.title,
228
}));
@@ -238,8 +241,9 @@ function ThreadNavigationSidebarPane(
241
),
242
[projectScopes],
243
);
244
+ // An archived project's filter reads as all projects, matching the filter menu.
245
const selectedProjectScope =
242
- projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null;
246
+ pickableProjectGroups(projectScopes).find((scope) => scope.key === resolvedProjectKey) ?? null;
247
const threadSearch = useThreadSearch(
248
searchEnvironmentIds,
249
props.searchQuery,
apps/mobile/src/features/threads/new-task-project-selection.test.ts
+16
@@ -52,6 +52,8 @@ function makeScope(projects: ReadonlyArray<EnvironmentProject>): HomeProjectScop
52
environmentId: project.environmentId,
53
projectId: project.id,
54
})),
55
+ pinned: false,
56
+ archived: false,
57
};
58
}
59
@@ -199,6 +201,20 @@ describe("newTaskDestination", () => {
201
});
202
});
203
204
+ it("opens the picker for an archived last project, but keeps an archived current one", () => {
205
+ const archived = { ...makeProject("archived"), archivedAt: "2026-01-01T00:00:00.000Z" };
206
+ expect(
207
+ destination({
208
+ useLastProject: true,
209
+ projects: [archived],
210
+ last: { environmentId: "environment", projectId: "archived" },
211
+ }),
212
+ ).toEqual(picker);
213
+ expect(destination({ useLastProject: true, projects: [archived], current: archived })).toEqual({
214
+ draft: { requestId: "request", environmentId: "environment", projectId: "archived" },
215
+ });
216
+ });
217
+
218
it("treats an unset preference as on", () => {
219
const projects = [makeProject("first"), makeProject("current")];
220
expect(destination({ useLastProject: undefined, projects, current: projects[1] })).toEqual({
apps/mobile/src/features/threads/new-task-project-selection.ts
+3
-1
@@ -159,10 +159,12 @@ export function newTaskDestination(options: {
159
options.projects.find(
160
(project) => project.environmentId === ref.environmentId && project.id === ref.projectId,
161
);
162
+ // A remembered project that was archived since opens the picker; the current one still wins.
163
+ const last = find(options.lastProject);
164
const project =
165
options.useLastProject === false
166
? undefined
165
- : (find(options.currentProject) ?? find(options.lastProject));
167
+ : (find(options.currentProject) ?? (last?.archivedAt == null ? last : undefined));
168
return project
169
? {
170
draft: {
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -264,6 +264,7 @@ export const make = Effect.gen(function* () {
264
...(hostPlatform === "win32" ? {} : { localServerStop: true }),
265
environmentIcon: true,
266
projectCloneTracking: true,
267
+ projectOrganization: true,
268
ignoredFileListing: true,
269
triage: true,
270
npmReleaseLookup: true,
apps/server/src/orchestration-v2/ProjectCommands.test.ts
+34
@@ -23,6 +23,8 @@ const row = (overrides: Partial<ProjectRow> = {}): ProjectRow => ({
23
faviconPath: null,
24
projectIcon: null,
25
scripts: [],
26
+ pinnedAt: null,
27
+ archivedAt: null,
28
createdAt: "2026-01-01T00:00:00.000Z",
29
updatedAt: "2026-01-01T00:00:00.000Z",
30
deletedAt: null,
@@ -77,6 +79,38 @@ describe("planProjectCommand", () => {
79
);
80
});
81
82
+ it("keeps the first pin and archive time, and clears both on undo", () => {
83
+ const earlier = "2025-12-01T00:00:00.000Z";
84
+ const update = (project: ProjectRow, change: { pinned?: boolean; archived?: boolean }) =>
85
+ payloadOf(
86
+ plan(
87
+ {
88
+ type: "project.meta.update",
89
+ commandId: CommandId.make("cmd-organize"),
90
+ projectId,
91
+ ...change,
92
+ },
93
+ { project },
94
+ ),
95
+ );
96
+ assert.deepInclude(update(row(), { pinned: true, archived: true }), {
97
+ pinnedAt: "2026-01-01T00:00:00.000Z",
98
+ archivedAt: "2026-01-01T00:00:00.000Z",
99
+ });
100
+ const organized = row({ pinnedAt: earlier, archivedAt: earlier });
101
+ assert.deepInclude(update(organized, { pinned: true, archived: true }), {
102
+ pinnedAt: earlier,
103
+ archivedAt: earlier,
104
+ });
105
+ assert.deepInclude(update(organized, { pinned: false, archived: false }), {
106
+ pinnedAt: null,
107
+ archivedAt: null,
108
+ });
109
+ const untouched = update(organized, {});
110
+ assert.notProperty(untouched, "pinnedAt");
111
+ assert.notProperty(untouched, "archivedAt");
112
+ });
113
+
114
it("rejects a workspace root held by another active project", () => {
115
const owner = row({
116
projectId: ProjectId.make("project-existing"),
apps/server/src/orchestration-v2/ProjectCommands.ts
+9
@@ -37,6 +37,8 @@ export interface ProjectMetaUpdateCommand {
37
readonly faviconPath?: string | null;
38
readonly projectIcon?: ProjectIconOverride | null;
39
readonly scripts?: ReadonlyArray<ProjectScript>;
40
+ readonly pinned?: boolean;
41
+ readonly archived?: boolean;
42
}
43
44
export interface ProjectDeleteCommand {
@@ -208,6 +210,13 @@ export function planProjectCommand(input: {
210
...(command.faviconPath === undefined ? {} : { faviconPath: command.faviconPath }),
211
...(command.projectIcon === undefined ? {} : { projectIcon: command.projectIcon }),
212
...(command.scripts === undefined ? {} : { scripts: command.scripts }),
213
+ // Repeating a pin or archive keeps the original time.
214
+ ...(command.pinned === undefined
215
+ ? {}
216
+ : { pinnedAt: command.pinned ? (project.pinnedAt ?? occurredAt) : null }),
217
+ ...(command.archived === undefined
218
+ ? {}
219
+ : { archivedAt: command.archived ? (project.archivedAt ?? occurredAt) : null }),
220
updatedAt: occurredAt,
221
},
222
});
apps/server/src/orchestration-v2/ProjectStore.test.ts
+45
@@ -51,5 +51,50 @@ it.layer(ProjectStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemor
51
);
52
}),
53
);
54
+
55
+ it.effect("keeps pin and archive times across later updates", () =>
56
+ Effect.gen(function* () {
57
+ const projects = yield* ProjectStore.ProjectStoreV2;
58
+ const projectId = ProjectId.make("project-organized");
59
+ const at = "2026-03-24T00:00:00.000Z";
60
+ const event = { aggregateKind: "project", aggregateId: projectId, occurredAt: at } as const;
61
+ const meta = { commandId: null, causationEventId: null, correlationId: null, metadata: {} };
62
+ yield* projects.apply({
63
+ ...event,
64
+ ...meta,
65
+ sequence: 1,
66
+ eventId: EventId.make("event-organized-created"),
67
+ type: "project.created",
68
+ payload: {
69
+ projectId,
70
+ title: "Organized",
71
+ workspaceRoot: "/tmp/project-organized",
72
+ defaultModelSelection: null,
73
+ scripts: [],
74
+ createdAt: at,
75
+ updatedAt: at,
76
+ },
77
+ });
78
+ yield* projects.apply({
79
+ ...event,
80
+ ...meta,
81
+ sequence: 2,
82
+ eventId: EventId.make("event-organized-pinned"),
83
+ type: "project.meta-updated",
84
+ payload: { projectId, pinnedAt: at, archivedAt: at, updatedAt: at },
85
+ });
86
+ yield* projects.apply({
87
+ ...event,
88
+ ...meta,
89
+ sequence: 3,
90
+ eventId: EventId.make("event-organized-renamed"),
91
+ type: "project.meta-updated",
92
+ payload: { projectId, title: "Renamed", updatedAt: at },
93
+ });
94
+ const project = Option.getOrNull(yield* projects.get(projectId));
95
+ assert.strictEqual(project?.pinnedAt, at);
96
+ assert.strictEqual(project?.archivedAt, at);
97
+ }),
98
+ );
99
},
100
);
apps/server/src/orchestration-v2/ProjectStore.ts
+16
@@ -39,6 +39,8 @@ export const ProjectRow = Schema.Struct({
39
faviconPath: Schema.NullOr(Schema.String),
40
projectIcon: Schema.NullOr(StoredProjectIcon),
41
scripts: Schema.Array(ProjectScript),
42
+ pinnedAt: Schema.NullOr(IsoDateTime),
43
+ archivedAt: Schema.NullOr(IsoDateTime),
44
createdAt: IsoDateTime,
45
updatedAt: IsoDateTime,
46
deletedAt: Schema.NullOr(IsoDateTime),
@@ -65,6 +67,8 @@ function toShell(row: ProjectRow): OrchestrationProjectShell {
67
faviconPath: row.faviconPath,
68
projectIcon: row.projectIcon,
69
scripts: row.scripts,
70
+ pinnedAt: row.pinnedAt,
71
+ archivedAt: row.archivedAt,
72
createdAt: row.createdAt,
73
updatedAt: row.updatedAt,
74
};
@@ -120,6 +124,8 @@ export const make = Effect.gen(function* () {
124
favicon_path AS "faviconPath",
125
project_icon_json AS "projectIcon",
126
scripts_json AS "scripts",
127
+ pinned_at AS "pinnedAt",
128
+ archived_at AS "archivedAt",
129
created_at AS "createdAt",
130
updated_at AS "updatedAt",
131
deleted_at AS "deletedAt"
@@ -150,6 +156,8 @@ export const make = Effect.gen(function* () {
156
favicon_path,
157
project_icon_json,
158
scripts_json,
159
+ pinned_at,
160
+ archived_at,
161
created_at,
162
updated_at,
163
deleted_at
@@ -164,6 +172,8 @@ export const make = Effect.gen(function* () {
172
${encoded.faviconPath},
173
${encoded.projectIcon},
174
${encoded.scripts},
175
+ ${encoded.pinnedAt},
176
+ ${encoded.archivedAt},
177
${encoded.createdAt},
178
${encoded.updatedAt},
179
${encoded.deletedAt}
@@ -178,6 +188,8 @@ export const make = Effect.gen(function* () {
188
favicon_path = excluded.favicon_path,
189
project_icon_json = excluded.project_icon_json,
190
scripts_json = excluded.scripts_json,
191
+ pinned_at = excluded.pinned_at,
192
+ archived_at = excluded.archived_at,
193
created_at = excluded.created_at,
194
updated_at = excluded.updated_at,
195
deleted_at = excluded.deleted_at
@@ -226,6 +238,8 @@ export const make = Effect.gen(function* () {
238
faviconPath: payload.faviconPath ?? null,
239
projectIcon: payload.projectIcon ?? null,
240
scripts: payload.scripts,
241
+ pinnedAt: null,
242
+ archivedAt: null,
243
createdAt: payload.createdAt,
244
updatedAt: payload.updatedAt,
245
deletedAt: null,
@@ -256,6 +270,8 @@ export const make = Effect.gen(function* () {
270
...(payload.faviconPath === undefined ? {} : { faviconPath: payload.faviconPath }),
271
...(payload.projectIcon === undefined ? {} : { projectIcon: payload.projectIcon }),
272
...(payload.scripts === undefined ? {} : { scripts: payload.scripts }),
273
+ ...(payload.pinnedAt === undefined ? {} : { pinnedAt: payload.pinnedAt }),
274
+ ...(payload.archivedAt === undefined ? {} : { archivedAt: payload.archivedAt }),
275
updatedAt: payload.updatedAt,
276
}).pipe(mapError("apply"));
277
},
apps/server/src/orchestration-v2/RuntimePolicy.test.ts
+2
@@ -96,6 +96,8 @@ const layerTest = RuntimePolicy.layerFromProjectStore.pipe(
96
faviconPath: null,
97
projectIcon: null,
98
scripts: [],
99
+ pinnedAt: null,
100
+ archivedAt: null,
101
createdAt: "2026-06-21T00:00:00.000Z",
102
updatedAt: "2026-06-21T00:00:00.000Z",
103
deletedAt: null,
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+4
@@ -82,6 +82,8 @@ const project = {
82
defaultModelSelection: modelSelection,
83
defaultThreadEnvMode: null,
84
scripts: [],
85
+ pinnedAt: null,
86
+ archivedAt: null,
87
createdAt: "2026-06-20T00:00:00.000Z",
88
updatedAt: "2026-06-20T00:00:00.000Z",
89
deletedAt: null,
@@ -247,6 +249,8 @@ function makeHarness(options: HarnessOptions = {}) {
249
faviconPath: null,
250
projectIcon: null,
251
scripts: project.scripts,
252
+ pinnedAt: null,
253
+ archivedAt: null,
254
createdAt: project.createdAt,
255
updatedAt: project.updatedAt,
256
deletedAt: project.deletedAt,
apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
+2
@@ -82,6 +82,8 @@ function makeHarness(
82
faviconPath: null,
83
projectIcon: null,
84
scripts: [],
85
+ pinnedAt: null,
86
+ archivedAt: null,
87
createdAt: "2026-06-20T00:00:00.000Z",
88
updatedAt: "2026-06-20T00:00:00.000Z",
89
deletedAt: null,
apps/server/src/persistence/Migrations.ts
+2
@@ -78,6 +78,7 @@ import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
78
import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts";
79
import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts";
80
import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
81
+import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
82
83
const migrationEntries = [
84
[1, "OrchestrationEvents", Migration0001],
@@ -156,6 +157,7 @@ const migrationEntries = [
157
[73, "ActiveTurnItemIndexes", Migration0073],
158
[74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074],
159
[75, "SubagentDeliveryState", Migration0075],
160
+ [76, "ProjectionProjectsPinArchive", Migration0076],
161
] as const;
162
163
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/076_ProjectionProjectsPinArchive.ts
new
+9
@@ -0,0 +1,9 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/sql/SqlClient";
3
+
4
+// Null means unpinned and not archived.
5
+export default Effect.gen(function* () {
6
+ const sql = yield* SqlClient.SqlClient;
7
+ yield* sql`ALTER TABLE projection_projects ADD COLUMN pinned_at TEXT`;
8
+ yield* sql`ALTER TABLE projection_projects ADD COLUMN archived_at TEXT`;
9
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -55,6 +55,7 @@ describe("V2 preview upgrade", () => {
55
[73, "ActiveTurnItemIndexes"],
56
[74, "ExcludeAttachmentPlaceholdersFromSearch"],
57
[75, "SubagentDeliveryState"],
58
+ [76, "ProjectionProjectsPinArchive"],
59
]);
60
assert.deepStrictEqual(yield* runMigrations(), []);
61
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -153,6 +154,7 @@ describe("V2 preview upgrade", () => {
154
[73, "ActiveTurnItemIndexes"],
155
[74, "ExcludeAttachmentPlaceholdersFromSearch"],
156
[75, "SubagentDeliveryState"],
157
+ [76, "ProjectionProjectsPinArchive"],
158
]);
159
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
160
);
apps/server/src/project/ProjectMutation.ts
+2
@@ -42,6 +42,8 @@ export const projectMutationOperation = Effect.fn("projectMutationOperation")(fu
42
? {}
43
: { defaultThreadEnvMode: mutation.defaultThreadEnvMode }),
44
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
45
+ ...(mutation.pinned === undefined ? {} : { pinned: mutation.pinned }),
46
+ ...(mutation.archived === undefined ? {} : { archived: mutation.archived }),
47
});
48
49
case "project.delete":
apps/server/src/project/ProjectService.ts
+4
@@ -179,6 +179,8 @@ export const make = Effect.gen(function* () {
179
autoPull: row.autoPull,
180
projectIcon: row.projectIcon,
181
scripts: row.scripts,
182
+ pinnedAt: row.pinnedAt,
183
+ archivedAt: row.archivedAt,
184
createdAt: row.createdAt,
185
updatedAt: row.updatedAt,
186
deletedAt: row.deletedAt,
@@ -386,6 +388,8 @@ export const make = Effect.gen(function* () {
388
? {}
389
: { defaultThreadEnvMode: input.defaultThreadEnvMode }),
390
...(input.scripts === undefined ? {} : { scripts: input.scripts }),
391
+ ...(input.pinned === undefined ? {} : { pinned: input.pinned }),
392
+ ...(input.archived === undefined ? {} : { archived: input.archived }),
393
});
394
if (workspaceRoot !== previousRoot) {
395
yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]);
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 5129,
3
"codexAdditionalContextBytes": 6859,
4
- "mcpToolListJsonBytes": 46007
4
+ "mcpToolListJsonBytes": 46109
5
}
apps/web/src/components/CommandPalette.logic.test.ts
+23
@@ -3,6 +3,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
3
import type { Thread } from "../types";
4
import { makeThreadFixture } from "../test-fixtures";
5
import {
6
+ newThreadNoProjectIndex,
7
buildNestedSearchItems,
8
resolveCommandPaletteProject,
9
buildThreadActionItems,
@@ -938,3 +939,25 @@ it("resolves project metadata and browse roots within the active environment", (
939
expect(resolveCommandPaletteProject(projects, null, sharedId)).toBeUndefined();
940
expect(resolveCommandPaletteProject(projects, EnvironmentId.make("local"), null)).toBeUndefined();
941
});
942
+
943
+describe("newThreadNoProjectIndex", () => {
944
+ const entry = (pinned = false, isPreferred = false, isScratch = false) => ({
945
+ pinned,
946
+ isPreferred,
947
+ isScratch,
948
+ });
949
+
950
+ it("goes after the pinned projects and the first unpinned one", () => {
951
+ expect(newThreadNoProjectIndex([entry(true), entry(true), entry(false, true), entry()])).toBe(
952
+ 3,
953
+ );
954
+ expect(newThreadNoProjectIndex([entry(false, true), entry(), entry(false, false, true)])).toBe(
955
+ 1,
956
+ );
957
+ });
958
+
959
+ it("keeps a pinned or current scratch project in its own place", () => {
960
+ expect(newThreadNoProjectIndex([entry(false, true, true), entry()])).toBe(0);
961
+ expect(newThreadNoProjectIndex([entry(true), entry(true, false, true), entry()])).toBe(1);
962
+ });
963
+});
apps/web/src/components/CommandPalette.logic.ts
+52
-17
@@ -208,6 +208,14 @@ export interface CommandPaletteActionItem extends CommandPaletteItem {
208
readonly kind: "action";
209
readonly keepOpen?: boolean;
210
readonly run: () => Promise<void>;
211
+ /** A pin toggle on the row, also reached with the pin shortcut while the row is highlighted. */
212
+ readonly pin?: CommandPaletteItemPin;
213
+}
214
+
215
+export interface CommandPaletteItemPin {
216
+ readonly name: string;
217
+ readonly pinned: boolean;
218
+ readonly toggle: () => void;
219
}
220
221
export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
@@ -364,24 +372,29 @@ export function buildProjectActionItems(input: {
372
searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
373
renderDescription?: (project: CommandPaletteProject) => ReactNode;
374
shortcutCommand?: KeybindingCommand;
375
+ pin?: (project: CommandPaletteProject) => CommandPaletteItemPin | null;
376
}): CommandPaletteActionItem[] {
368
- return input.projects.map((project) => ({
369
- kind: "action",
370
- value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
371
- searchTerms: [
372
- project.displayName,
373
- project.title,
374
- project.workspaceRoot,
375
- ...(input.searchTerms?.(project) ?? []),
376
- ],
377
- title: project.displayName,
378
- description: input.renderDescription?.(project) ?? project.workspaceRoot,
379
- icon: input.icon(project),
380
- ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
381
- run: async () => {
382
- await input.runProject(project);
383
- },
384
- }));
377
+ return input.projects.map((project) => {
378
+ const pin = input.pin?.(project) ?? null;
379
+ return {
380
+ kind: "action",
381
+ value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
382
+ searchTerms: [
383
+ project.displayName,
384
+ project.title,
385
+ project.workspaceRoot,
386
+ ...(input.searchTerms?.(project) ?? []),
387
+ ],
388
+ title: project.displayName,
389
+ description: input.renderDescription?.(project) ?? project.workspaceRoot,
390
+ icon: input.icon(project),
391
+ ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
392
+ ...(pin ? { pin } : {}),
393
+ run: async () => {
394
+ await input.runProject(project);
395
+ },
396
+ };
397
+ });
398
}
399
400
export type BuildThreadActionItemsThread = Pick<
@@ -869,3 +882,25 @@ export function resolveCommandPaletteProject<TProject>(
882
) {
883
return environmentId && projectId ? projects.get(`${environmentId}:${projectId}`) : undefined;
884
}
885
+
886
+/**
887
+ * Where "No project" goes among the new-thread picker's real projects: at the
888
+ * scratch project's own place when it is pinned or current, else after the
889
+ * pinned projects and the first unpinned one.
890
+ */
891
+export function newThreadNoProjectIndex(
892
+ entries: ReadonlyArray<{
893
+ readonly isScratch: boolean;
894
+ readonly pinned: boolean;
895
+ readonly isPreferred: boolean;
896
+ }>,
897
+): number {
898
+ const projects = entries.filter((entry) => !entry.isScratch);
899
+ const scratchAt = entries.findIndex((entry) => entry.isScratch);
900
+ const scratch = entries[scratchAt];
901
+ if (scratch && (scratch.pinned || scratch.isPreferred)) {
902
+ return entries.slice(0, scratchAt).filter((entry) => !entry.isScratch).length;
903
+ }
904
+ const pinnedCount = projects.filter((entry) => entry.pinned).length;
905
+ return Math.min(pinnedCount + 1, projects.length);
906
+}
apps/web/src/components/CommandPalette.tsx
+140
-39
@@ -68,6 +68,8 @@ import {
68
RotateCcwIcon,
69
SettingsIcon,
70
MonitorIcon,
71
+ PinIcon,
72
+ PinOffIcon,
73
SquarePenIcon,
74
TextSearchIcon,
75
UserPlusIcon,
@@ -111,11 +113,14 @@ import { threadEnvironment } from "../state/threads";
113
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
114
import { sourceControlEnvironment } from "../state/sourceControl";
115
import { useAtomCommand } from "../state/use-atom-command";
116
+import { useOrchestrationCommand } from "../state/use-orchestration-command";
117
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
118
import { useScratchProject } from "../hooks/useScratchProject";
119
import { useStartTriage } from "../hooks/useStartTriage";
120
import { pickTriageEnvironment } from "../lib/triageTarget";
121
import { useNewProject } from "../hooks/useNewProject";
122
+import { useOrderWhileOpen } from "../hooks/useOrderWhileOpen";
123
+import { reportProjectFailure, useProjectPin } from "../hooks/useProjectGroupUpdate";
124
import {
125
useEnvironmentProviders,
126
useEnvironments,
@@ -167,6 +172,7 @@ import {
172
buildLinkedThreadActionItems,
173
buildCommandPaletteRows,
174
enumerateCommandPaletteItems,
175
+ newThreadNoProjectIndex,
176
findHighlightedCommandPaletteItem,
177
type CommandPaletteActionItem,
178
type CommandPaletteOpenIntent,
@@ -236,6 +242,7 @@ import { suggestAppAccessForRemote } from "./sourceControlAppAccessToast";
242
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
243
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
244
import type { ChatComposerHandle } from "./chat/ChatComposer";
245
+import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
246
import { buildSidebarProjectPickerEntries } from "../sidebarProjectGrouping";
247
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
248
import { readPullRequestListPreferences } from "~/components/pullRequest/pullRequestListPreferences";
@@ -270,6 +277,8 @@ function openIntentView(intent: CommandPaletteOpenIntent | null): CommandPalette
277
}
278
}
279
280
+const NEW_THREAD_NO_PROJECT_VALUE = "new-thread-in:no-project";
281
+
282
export function CommandPalette({ children }: { children: ReactNode }) {
283
useCommandPaletteMount();
284
const state = useCommandPaletteStore();
@@ -408,6 +417,9 @@ function OpenCommandPaletteDialog(props: {
417
const createProject = useAtomCommand(projectEnvironment.create, {
418
reportFailure: false,
419
});
420
+ const updateProject = useOrchestrationCommand(projectEnvironment.update, {
421
+ label: "project unarchive",
422
+ });
423
const { scratchEnvironmentId, scratchWorkspaceRootFor, startScratchThread } = useScratchProject();
424
const startTriage = useStartTriage();
425
const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {
@@ -500,7 +512,7 @@ function OpenCommandPaletteDialog(props: {
512
handleNewThread,
513
});
514
const projectPickerEntries = buildSidebarProjectPickerEntries({
503
- groups: projectGroups,
515
+ groups: pickableProjectGroups(projectGroups),
516
preferredProjectRef: contextualProjectRef,
517
});
518
const pickerProjects = projectPickerEntries.map(({ group, targetProject }) => ({
@@ -513,6 +525,21 @@ function OpenCommandPaletteDialog(props: {
525
group,
526
]),
527
);
528
+ const { canPinProjectGroup, toggleProjectGroupPin } = useProjectPin();
529
+ // A row's target record can change when another machine's copy loads, so the kept
530
+ // order follows the project group instead.
531
+ const rowOrderKey = (prefix: string) => (item: CommandPaletteActionItem) =>
532
+ projectGroupByTargetKey.get(item.value.slice(prefix.length + 1))?.projectKey ?? item.value;
533
+ const projectPin = (project: CommandPaletteProject) => {
534
+ const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
535
+ return group && canPinProjectGroup(group)
536
+ ? {
537
+ name: group.displayName,
538
+ pinned: group.pinned,
539
+ toggle: () => toggleProjectGroupPin(group),
540
+ }
541
+ : null;
542
+ };
543
544
const addProjectEnvironmentOptions = (() => {
545
const options = environments
@@ -755,21 +782,28 @@ function OpenCommandPaletteDialog(props: {
782
await handleNewThread(scopeProjectRef(project.environmentId, project.id));
783
};
784
758
- const projectSearchItems = buildProjectSearchItems({
759
- projects: pickerProjects,
760
- projectGroupByTargetKey,
761
- locationByEnvironmentId: projectEnvironmentLocationById,
762
- runProject: openProjectFromSearch,
763
- });
785
+ // Pinning from a row keeps rows in place while the palette is open.
786
+ const projectSearchItems = useOrderWhileOpen(
787
+ buildProjectSearchItems({
788
+ projects: pickerProjects,
789
+ projectGroupByTargetKey,
790
+ locationByEnvironmentId: projectEnvironmentLocationById,
791
+ runProject: openProjectFromSearch,
792
+ pin: projectPin,
793
+ }),
794
+ rowOrderKey("project"),
795
+ true,
796
+ );
797
765
- const projectThreadItems = (() => {
766
- const isScratch = (project: CommandPaletteProject) =>
767
- isScratchProject(project, scratchWorkspaceRootFor(project.environmentId));
768
- const projectItems = enumerateCommandPaletteItems(
769
- buildNewThreadInProjectItems({
798
+ const openingOrderThreadItems = useOrderWhileOpen(
799
+ (() => {
800
+ const isScratch = (project: CommandPaletteProject) =>
801
+ isScratchProject(project, scratchWorkspaceRootFor(project.environmentId));
802
+ const projectItems = buildNewThreadInProjectItems({
803
projects: pickerProjects.filter((project) => !isScratch(project)),
804
projectGroupByTargetKey,
805
locationByEnvironmentId: projectEnvironmentLocationById,
806
+ pin: projectPin,
807
runProject: async (project) => {
808
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
809
const contextualRefBelongsToGroup =
@@ -785,25 +819,45 @@ function OpenCommandPaletteDialog(props: {
819
: scopeProjectRef(project.environmentId, project.id),
820
);
821
},
788
- }),
789
- );
790
- if (scratchTargetEnvironmentId === null) return projectItems;
822
+ });
823
+ if (scratchTargetEnvironmentId === null) return projectItems;
824
792
- const noProjectIndex = pickerProjects[0] !== undefined && isScratch(pickerProjects[0]) ? 0 : 1;
793
- return [
794
- ...projectItems.slice(0, noProjectIndex),
795
- {
796
- kind: "action" as const,
797
- value: "new-thread-in:no-project",
798
- searchTerms: ["no project", "without project", "none"],
799
- title: "No project",
800
- icon: <MessageSquareDashedIcon className={ITEM_ICON_CLASS} />,
801
- shortcutCommand: "chat.newWithoutProject" as const,
802
- run: () => startScratchThread(scratchTargetEnvironmentId),
803
- },
804
- ...projectItems.slice(noProjectIndex),
805
- ];
806
- })();
825
+ const noProjectIndex = newThreadNoProjectIndex(
826
+ projectPickerEntries.map(({ group, targetProject, isPreferred }) => ({
827
+ isScratch: isScratchProject(
828
+ targetProject,
829
+ scratchWorkspaceRootFor(targetProject.environmentId),
830
+ ),
831
+ pinned: group.pinned,
832
+ isPreferred,
833
+ })),
834
+ );
835
+ return [
836
+ ...projectItems.slice(0, noProjectIndex),
837
+ {
838
+ kind: "action" as const,
839
+ value: NEW_THREAD_NO_PROJECT_VALUE,
840
+ searchTerms: ["no project", "without project", "none"],
841
+ title: "No project",
842
+ icon: <MessageSquareDashedIcon className={ITEM_ICON_CLASS} />,
843
+ shortcutCommand: "chat.newWithoutProject" as const,
844
+ run: () => startScratchThread(scratchTargetEnvironmentId),
845
+ },
846
+ ...projectItems.slice(noProjectIndex),
847
+ ];
848
+ })(),
849
+ rowOrderKey("new-thread-in"),
850
+ true,
851
+ );
852
+ // Jump shortcuts follow the rows as shown, so a pin cannot move a number to another row.
853
+ const projectJumpItems = new Map(
854
+ enumerateCommandPaletteItems(
855
+ openingOrderThreadItems.filter((item) => item.value !== NEW_THREAD_NO_PROJECT_VALUE),
856
+ ).map((item) => [item.value, item] as const),
857
+ );
858
+ const projectThreadItems = openingOrderThreadItems.map(
859
+ (item) => projectJumpItems.get(item.value) ?? item,
860
+ );
861
862
const {
863
threadItems: allThreadItems,
@@ -1420,7 +1474,7 @@ function OpenCommandPaletteDialog(props: {
1474
});
1475
}
1476
1423
- actionItems.push({
1477
+ const addProjectAction: CommandPaletteActionItem = {
1478
kind: "action",
1479
value: "action:add-project",
1480
searchTerms: [
@@ -1448,7 +1502,8 @@ function OpenCommandPaletteDialog(props: {
1502
run: async () => {
1503
openAddProjectFlow();
1504
},
1451
- });
1505
+ };
1506
+ actionItems.push(addProjectAction);
1507
1508
if (wslAddProjectEnvironmentOption) {
1509
actionItems.push({
@@ -1536,14 +1591,33 @@ function OpenCommandPaletteDialog(props: {
1591
},
1592
});
1593
1539
- const contextualProjectGroup =
1594
+ // Every group, so an archived project's thread still opens its own settings.
1595
+ const currentProjectGroup =
1596
(contextualProjectRef
1541
- ? projectGroupByTargetKey.get(
1542
- `${contextualProjectRef.environmentId}:${contextualProjectRef.projectId}`,
1597
+ ? projectGroups.find((group) =>
1598
+ group.memberProjectRefs.some(
1599
+ (ref) =>
1600
+ ref.environmentId === contextualProjectRef.environmentId &&
1601
+ ref.projectId === contextualProjectRef.projectId,
1602
+ ),
1603
)
1544
- : null) ??
1545
- projectGroups[0] ??
1546
- null;
1604
+ : null) ?? null;
1605
+ if (currentProjectGroup && canPinProjectGroup(currentProjectGroup)) {
1606
+ actionItems.push({
1607
+ kind: "action",
1608
+ value: "action:project-pin",
1609
+ searchTerms: ["pin", "unpin", "project", "favorite"],
1610
+ title: currentProjectGroup.pinned ? "Unpin project" : "Pin project",
1611
+ description: currentProjectGroup.displayName,
1612
+ icon: currentProjectGroup.pinned ? (
1613
+ <PinOffIcon className={ITEM_ICON_CLASS} />
1614
+ ) : (
1615
+ <PinIcon className={ITEM_ICON_CLASS} />
1616
+ ),
1617
+ run: async () => toggleProjectGroupPin(currentProjectGroup),
1618
+ });
1619
+ }
1620
+ const contextualProjectGroup = currentProjectGroup ?? projectGroups[0] ?? null;
1621
if (contextualProjectGroup) {
1622
actionItems.push({
1623
kind: "action",
@@ -1608,7 +1682,14 @@ function OpenCommandPaletteDialog(props: {
1682
: currentView?.groups[0]?.value === ADD_PROJECT_ENTRY_GROUP
1683
? addProjectEntryGroups()
1684
: currentView?.groups[0]?.value === NEW_THREAD_IN_GROUP
1611
- ? [{ value: NEW_THREAD_IN_GROUP, label: "Projects", items: projectThreadItems }]
1685
+ ? [
1686
+ {
1687
+ value: NEW_THREAD_IN_GROUP,
1688
+ label: "Projects",
1689
+ // Every project archived and no "No project" home leaves only adding one.
1690
+ items: projectThreadItems.length > 0 ? projectThreadItems : [addProjectAction],
1691
+ },
1692
+ ]
1693
: currentView?.groups[0]?.value === "themes"
1694
? changeThemeItem.groups
1695
: currentView?.groups[0]?.value === "appearance"
@@ -1700,6 +1781,13 @@ function OpenCommandPaletteDialog(props: {
1781
cwd,
1782
);
1783
if (existing) {
1784
+ // Adding an archived project's folder again brings the project back.
1785
+ if (existing.archivedAt != null) {
1786
+ void updateProject({
1787
+ environmentId: existing.environmentId,
1788
+ input: { projectId: existing.id, archived: false },
1789
+ }).then((result) => reportProjectFailure("Failed to unarchive project", result));
1790
+ }
1791
const latestThread = getLatestThreadForProject(
1792
threads.filter((thread) => thread.environmentId === existing.environmentId),
1793
existing.id,
@@ -2302,6 +2390,19 @@ function OpenCommandPaletteDialog(props: {
2390
platform: navigator.platform,
2391
context: { modelPickerOpen: false, editableFocus: true },
2392
});
2393
+ if (command === "thread.pin") {
2394
+ const highlightedItem = findHighlightedCommandPaletteItem(
2395
+ displayedGroups,
2396
+ highlightedItemValue ??
2397
+ (autoHighlightsFirstRow ? (resultRows.itemValues[0] ?? null) : null),
2398
+ );
2399
+ if (highlightedItem?.kind === "action" && highlightedItem.pin) {
2400
+ event.preventDefault();
2401
+ event.stopPropagation();
2402
+ highlightedItem.pin.toggle();
2403
+ return;
2404
+ }
2405
+ }
2406
// Global new-thread handlers ignore shortcuts while the palette is open.
2407
const isJump = threadJumpIndexFromCommand(command ?? "") !== null;
2408
const isNewThread =
apps/web/src/components/CommandPaletteProjectItems.tsx
+4
@@ -5,6 +5,7 @@ import type { Project } from "../types";
5
import {
6
buildCommandPaletteProjectMetadata,
7
buildProjectActionItems,
8
+ type CommandPaletteItemPin,
9
type CommandPaletteProject,
10
ITEM_ICON_CLASS,
11
} from "./CommandPalette.logic";
@@ -29,6 +30,7 @@ interface ProjectItemsInput {
30
readonly projectGroupByTargetKey: ReadonlyMap<string, SidebarProjectSnapshot>;
31
readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, CommandPaletteProjectLocation>;
32
readonly runProject: (project: CommandPaletteProject) => Promise<void>;
33
+ readonly pin?: (project: CommandPaletteProject) => CommandPaletteItemPin | null;
34
}
35
36
function projectFaviconIcon(project: Project) {
@@ -66,6 +68,7 @@ export function buildProjectSearchItems(input: ProjectItemsInput) {
68
},
69
icon: projectFaviconIcon,
70
runProject: input.runProject,
71
+ ...(input.pin ? { pin: input.pin } : {}),
72
});
73
}
74
@@ -90,6 +93,7 @@ export function buildNewThreadInProjectItems(input: ProjectItemsInput) {
93
),
94
icon: projectFaviconIcon,
95
runProject: input.runProject,
96
+ ...(input.pin ? { pin: input.pin } : {}),
97
});
98
}
99
apps/web/src/components/CommandPaletteResults.tsx
+9
@@ -22,6 +22,7 @@ import {
22
CommandShortcut,
23
} from "./ui/command";
24
import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
25
+import { ProjectPinButton } from "./ProjectPinButton";
26
import { SearchMatchHintLine, ThreadSearchMatchExcerpt } from "./ThreadSearchMatch";
27
28
interface CommandPaletteResultsProps {
@@ -268,6 +269,14 @@ function CommandPaletteResultRow(props: {
269
</span>
270
)}
271
{props.item.titleTrailingContent}
272
+ {props.item.kind === "action" && props.item.pin ? (
273
+ <ProjectPinButton
274
+ name={props.item.pin.name}
275
+ pinned={props.item.pin.pinned}
276
+ onToggle={props.item.pin.toggle}
277
+ shortcutLabel={shortcutLabelForCommand(props.keybindings, "thread.pin")}
278
+ />
279
+ ) : null}
280
{props.item.timestamp ? (
281
<span className="min-w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground/70">
282
{props.item.timestamp}
apps/web/src/components/ProjectPinButton.tsx
new
+67
@@ -0,0 +1,67 @@
1
+import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
2
+import { PinIcon, PinOffIcon } from "lucide-react";
3
+import type { KeyboardEvent } from "react";
4
+
5
+import { resolveShortcutCommand } from "../keybindings";
6
+
7
+import { cn } from "~/lib/utils";
8
+import { Button } from "./ui/button";
9
+
10
+/** The thread pin shortcut, which pins the highlighted row in a project list. */
11
+export function isProjectPinShortcut(
12
+ event: KeyboardEvent,
13
+ keybindings: ResolvedKeybindingsConfig,
14
+): boolean {
15
+ return (
16
+ resolveShortcutCommand(event.nativeEvent, keybindings, {
17
+ platform: navigator.platform,
18
+ context: { modelPickerOpen: false, editableFocus: true },
19
+ }) === "thread.pin"
20
+ );
21
+}
22
+
23
+/**
24
+ * Pin toggle for a project row in a menu or list. A pinned project always shows its pin;
25
+ * an unpinned one shows it only on the highlighted row. Keyboard users get a shortcut
26
+ * from the list that hosts it, so the button stays out of the tab order.
27
+ */
28
+export function ProjectPinButton(props: {
29
+ readonly name: string;
30
+ readonly pinned: boolean;
31
+ readonly onToggle: () => void;
32
+ readonly shortcutLabel?: string | null;
33
+}) {
34
+ const action = `${props.pinned ? "Unpin" : "Pin"} ${props.name}`;
35
+ return (
36
+ <span
37
+ className={cn(
38
+ "group/pin ml-auto flex",
39
+ !props.pinned && "opacity-0 in-data-highlighted:opacity-100 pointer-coarse:opacity-100",
40
+ )}
41
+ >
42
+ <Button
43
+ size="icon-xs"
44
+ variant="ghost-muted"
45
+ tabIndex={-1}
46
+ aria-hidden="true"
47
+ title={props.shortcutLabel ? `${action} (${props.shortcutLabel})` : action}
48
+ onPointerDown={(event) => event.stopPropagation()}
49
+ onMouseDown={(event) => event.preventDefault()}
50
+ onClick={(event) => {
51
+ event.preventDefault();
52
+ event.stopPropagation();
53
+ props.onToggle();
54
+ }}
55
+ >
56
+ {props.pinned ? (
57
+ <>
58
+ <PinIcon className="size-3.5 group-hover/pin:hidden" />
59
+ <PinOffIcon className="hidden size-3.5 group-hover/pin:block" />
60
+ </>
61
+ ) : (
62
+ <PinIcon className="size-3.5" />
63
+ )}
64
+ </Button>
65
+ </span>
66
+ );
67
+}
apps/web/src/components/Sidebar.logic.test.ts
+26
-3
@@ -6,6 +6,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
6
import * as Cause from "effect/Cause";
7
import { AsyncResult } from "effect/reactivity";
8
import {
9
+ shouldCreateNewThreadInCurrentProject,
10
archiveSelectedThreadEntries,
11
deleteSelectedThreadEntries,
12
getFallbackThreadIdAfterDelete,
@@ -1630,6 +1631,12 @@ describe("groupSidebarThreadsByProject", () => {
1631
projectKey: "fleet",
1632
memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: fleet }],
1633
},
1634
+ {
1635
+ projectKey: "notes",
1636
+ memberProjectRefs: [
1637
+ { environmentId: localEnvironmentId, projectId: ProjectId.make("notes") },
1638
+ ],
1639
+ },
1640
];
1641
1642
const threads = [
@@ -1637,17 +1644,23 @@ describe("groupSidebarThreadsByProject", () => {
1644
thread("orphan", localEnvironmentId, ProjectId.make("deleted")),
1645
thread("b", remoteEnvironmentId, t3codeRemote),
1646
];
1640
- const summarize = (keepEmpty: boolean) =>
1647
+ const summarize = (keepEmpty: (group: (typeof groups)[number]) => boolean) =>
1648
groupSidebarThreadsByProject(groups, threads, keepEmpty).map((folder) => ({
1649
projectKey: folder.group.projectKey,
1650
threads: folder.threads.map((entry) => entry.id),
1651
}));
1652
1646
- expect(summarize(true)).toEqual([
1653
+ expect(summarize(() => true)).toEqual([
1654
+ { projectKey: "t3code", threads: ["a", "b"] },
1655
+ { projectKey: "fleet", threads: [] },
1656
+ { projectKey: "notes", threads: [] },
1657
+ ]);
1658
+ expect(summarize(() => false)).toEqual([{ projectKey: "t3code", threads: ["a", "b"] }]);
1659
+ // A pinned project keeps its empty folder while other empty projects drop out.
1660
+ expect(summarize((group) => group.projectKey === "fleet")).toEqual([
1661
{ projectKey: "t3code", threads: ["a", "b"] },
1662
{ projectKey: "fleet", threads: [] },
1663
]);
1650
- expect(summarize(false)).toEqual([{ projectKey: "t3code", threads: ["a", "b"] }]);
1664
});
1665
});
1666
@@ -1687,3 +1700,13 @@ describe("resolveSidebarFolderDot", () => {
1700
expect(resolveSidebarFolderDot([unread, limited])).toBe("attention");
1701
});
1702
});
1703
+
1704
+describe("shouldCreateNewThreadInCurrentProject", () => {
1705
+ it("opens the picker when several projects are open, or only archived ones exist", () => {
1706
+ expect(shouldCreateNewThreadInCurrentProject(false, 2, 3)).toBe(false);
1707
+ expect(shouldCreateNewThreadInCurrentProject(false, 0, 2)).toBe(false);
1708
+ expect(shouldCreateNewThreadInCurrentProject(false, 1, 3)).toBe(true);
1709
+ expect(shouldCreateNewThreadInCurrentProject(false, 0, 0)).toBe(true);
1710
+ expect(shouldCreateNewThreadInCurrentProject(true, 2, 2)).toBe(true);
1711
+ });
1712
+});
apps/web/src/components/Sidebar.logic.ts
+6
-4
@@ -782,11 +782,13 @@ export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
782
return nodeClosest(parent, "a[href]") !== null;
783
}
784
785
+/** The "New thread in" picker opens unless there is one open project or none; then the current context decides. */
786
export function shouldCreateNewThreadInCurrentProject(
787
shiftKey: boolean,
788
+ openProjectGroupCount: number,
789
projectGroupCount: number,
790
): boolean {
789
- return shiftKey || projectGroupCount <= 1;
791
+ return shiftKey || openProjectGroupCount === 1 || projectGroupCount === 0;
792
}
793
794
export function orderItemsByPreferredIds<TItem, TId>(input: {
@@ -973,7 +975,7 @@ export function sidebarFolderExpansionKeys(group: {
975
976
/**
977
* Boring sidebar folders. Folders follow `groups` order and threads keep their
976
- * input order. A project with no threads gets a folder only with `keepEmpty`.
978
+ * input order. A project with no threads gets a folder only when `keepEmpty` says so.
979
* A thread whose project is in no group has no folder and is left out.
980
*/
981
export function groupSidebarThreadsByProject<
@@ -987,7 +989,7 @@ export function groupSidebarThreadsByProject<
989
>(
990
groups: readonly TGroup[],
991
threads: readonly TThread[],
990
- keepEmpty: boolean,
992
+ keepEmpty: (group: TGroup) => boolean,
993
): Array<{ group: TGroup; threads: TThread[] }> {
994
const folders = groups.map((group) => ({ group, threads: [] as TThread[] }));
995
const folderByProject = new Map<string, (typeof folders)[number]>();
@@ -999,7 +1001,7 @@ export function groupSidebarThreadsByProject<
1001
for (const thread of threads) {
1002
folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread);
1003
}
1002
- return keepEmpty ? folders : folders.filter((folder) => folder.threads.length > 0);
1004
+ return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group));
1005
}
1006
1007
export type SidebarV2TopStatusKind =
apps/web/src/components/Sidebar.tsx
+97
-24
@@ -103,7 +103,10 @@ import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../termina
103
import { isMacPlatform } from "~/lib/utils";
104
import { readLocalApi } from "../localApi";
105
import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
106
-import { selectProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
106
+import {
107
+ pickableProjectGroups,
108
+ selectProjectGroupingSettings,
109
+} from "@t3tools/client-runtime/state/project-grouping";
110
import {
111
projectGroupsSpanEnvironments,
112
resolveSidebarProjectScopeKeys,
@@ -121,6 +124,8 @@ import {
124
useThreadActions,
125
} from "../hooks/useThreadActions";
126
import { useHandleNewThread } from "../hooks/useHandleNewThread";
127
+import { useOrderWhileOpen } from "../hooks/useOrderWhileOpen";
128
+import { useProjectPin } from "../hooks/useProjectGroupUpdate";
129
import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups";
130
import { useTerminalFocus } from "../hooks/useTerminalFocus";
131
import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
@@ -230,6 +235,7 @@ import { stackedThreadToast, toastManager } from "./ui/toast";
235
import { copyThreadReference } from "../lib/copyThreadReference";
236
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
237
import { Button } from "./ui/button";
238
+import { isProjectPinShortcut, ProjectPinButton } from "./ProjectPinButton";
239
import {
240
Combobox,
241
ComboboxEmpty,
@@ -408,8 +414,8 @@ function useSidebarThreads(input: {
414
readonly routeRowThreadKey: string | null;
415
// Set in boring mode: the project groups to fold active threads into, in order.
416
readonly folderGroups: readonly SidebarProjectSnapshot[] | null;
411
- // Keeps folders with no active threads, so a project the user filtered to can start one.
412
- readonly keepEmptyFolders: boolean;
417
+ // Keeps folders with no active threads, so a project the user filtered to or pinned can start one.
418
+ readonly keepEmptyFolders: (group: SidebarProjectSnapshot) => boolean;
419
}) {
420
const {
421
projectScopeKey,
@@ -811,7 +817,10 @@ function useSidebarLookups() {
817
);
818
const projectScopeItems = [
819
{ value: "all", label: "All projects" },
814
- ...projectGroups.map((project) => ({ value: project.projectKey, label: project.displayName })),
820
+ ...pickableProjectGroups(projectGroups).map((project) => ({
821
+ value: project.projectKey,
822
+ label: project.displayName,
823
+ })),
824
];
825
return {
826
projects,
@@ -886,7 +895,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
895
projectByKey,
896
projectDisplayNameByKey,
897
projectGroupByScopeKey,
889
- projectScopeItems,
898
+ projectScopeItems: lookupProjectScopeItems,
899
} = useSidebarLookups();
900
const delegatedUnderParent = useDelegatedUnderParent();
901
const router = useRouter();
@@ -1054,13 +1063,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1063
};
1064
// A scope whose project is gone reads as all projects once every snapshot has
1065
// loaded. The stored keys are left alone, so the scope returns with its project.
1066
+ // An archived project's scope reads as all projects, matching the menu.
1067
+ const scopeGroups = pickableProjectGroups(projectGroups);
1068
+ const archivedProjectKeys = new Set(
1069
+ projectGroups.filter((project) => project.archived).map((project) => project.projectKey),
1070
+ );
1071
const chosenProjectScopeKeys = resolveSidebarProjectScopeKeys({
1072
groups: projectGroups,
1073
keys: persistedProjectScopeKeys,
1074
settings: projectGroupingSettings,
1075
canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
1062
- });
1063
- const chosenProjectGroups = projectGroups.filter((project) =>
1076
+ }).filter((key) => !archivedProjectKeys.has(key));
1077
+ const chosenProjectGroups = scopeGroups.filter((project) =>
1078
chosenProjectScopeKeys.includes(project.projectKey),
1079
);
1080
const chosenScopeProjectKeys =
@@ -1134,6 +1148,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1148
}
1149
return environmentLabelById.get(thread.environmentId) ?? null;
1150
};
1151
+ // Pinning from a row keeps rows in place while the menu is open.
1152
+ const projectScopeItems = useOrderWhileOpen(
1153
+ lookupProjectScopeItems,
1154
+ (item) => item.value,
1155
+ projectScopeMenuState.open,
1156
+ );
1157
const selectedProjectScopeItem =
1158
projectScopeKeys.length > 1
1159
? null
@@ -1194,6 +1214,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1214
});
1215
},
1216
);
1217
+ const {
1218
+ canPinProjectGroup: canPinProject,
1219
+ setProjectGroupPinned,
1220
+ toggleProjectGroupPin,
1221
+ } = useProjectPin();
1222
const handleProjectSettings = useStableCallback(
1223
(
1224
event: ReactMouseEvent<HTMLElement> | ReactKeyboardEvent<HTMLInputElement>,
@@ -1220,6 +1245,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1245
[
1246
{ id: "new-thread", label: "New thread" },
1247
{ id: "copy-path", label: "Copy path" },
1248
+ ...(canPinProject(group)
1249
+ ? [
1250
+ group.pinned
1251
+ ? { id: "unpin", label: "Unpin project", icon: "pin-off" }
1252
+ : { id: "pin", label: "Pin project", icon: "pin" },
1253
+ ]
1254
+ : []),
1255
{ id: "project-settings", label: "Project settings", icon: "settings" },
1256
],
1257
position,
@@ -1233,6 +1265,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1265
case "copy-path":
1266
copyPathToClipboard(group.workspaceRoot, { path: group.workspaceRoot });
1267
return;
1268
+ case "pin":
1269
+ case "unpin":
1270
+ setProjectGroupPinned(group, clicked.value === "pin");
1271
+ return;
1272
case "project-settings":
1273
openProjectSettings(group);
1274
return;
@@ -1288,10 +1324,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1324
routeRowThreadKey,
1325
folderGroups: boringSidebarEnabled
1326
? scopedProjectGroups.length === 0
1291
- ? projectGroups
1327
+ ? // An archived project keeps a folder for its active threads, below the rest.
1328
+ [...scopeGroups, ...projectGroups.filter((project) => project.archived)]
1329
: scopedProjectGroups
1330
: null,
1294
- keepEmptyFolders: scopedProjectGroups.length > 0,
1331
+ keepEmptyFolders: (group) =>
1332
+ scopedProjectGroups.length > 0 || (group.pinned && !group.archived),
1333
});
1334
1335
// Ranked across environments as the palette ranks them, so one
@@ -1862,7 +1900,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1900
const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
1901
return { kind: "thread", key, section };
1902
});
1865
- // Boring mode keeps a project the user filtered to, so it can start a thread.
1903
+ // Boring mode keeps a pinned open project or one the user filtered to, so it can start a thread.
1904
if (
1905
!hasProjectFolders &&
1906
pinnedThreads.length +
@@ -2552,12 +2590,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2590
AuthOrchestrationOperateScope,
2591
),
2592
branch: thread.branch ?? null,
2555
- projectFilter: threadProjectGroup
2556
- ? {
2557
- label: threadProjectGroup.displayName,
2558
- isActive: projectScopeKeys.includes(threadProjectGroup.projectKey),
2559
- }
2560
- : null,
2593
+ // An archived project is not a filter choice.
2594
+ projectFilter:
2595
+ threadProjectGroup && !threadProjectGroup.archived
2596
+ ? {
2597
+ label: threadProjectGroup.displayName,
2598
+ isActive: projectScopeKeys.includes(threadProjectGroup.projectKey),
2599
+ }
2600
+ : null,
2601
isPinned,
2602
isSettled,
2603
autoSettleEnabled: thread.autoSettleDisabledAt == null,
@@ -2875,14 +2915,21 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2915
const handleNewThreadClick = (event?: ReactMouseEvent) => {
2916
if (
2917
boringSidebarEnabled ||
2878
- shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)
2918
+ shouldCreateNewThreadInCurrentProject(
2919
+ event?.shiftKey ?? false,
2920
+ scopeGroups.length,
2921
+ projectGroups.length,
2922
+ )
2923
) {
2924
if (isMobile) setOpenMobile(false);
2925
+ // With no current or open project, such as when every project is archived, pick one.
2926
void startNewThreadFromContext({
2927
activeDraftThread: newThreadContext.activeDraftThread,
2928
activeThread: newThreadContext.activeThread ?? undefined,
2929
defaultProjectRef: newThreadContext.defaultProjectRef,
2930
handleNewThread,
2931
+ }).then((started) => {
2932
+ if (!started) openCommandPalette({ open: "new-thread-in" });
2933
});
2934
return;
2935
}
@@ -2892,7 +2939,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2939
2940
const newThreadShortcutLabel =
2941
shortcutLabelForCommand(keybindings, "chat.new") ??
2895
- (projectGroups.length <= 1 ? shortcutLabelForCommand(keybindings, "chat.newLocal") : undefined);
2942
+ (shouldCreateNewThreadInCurrentProject(false, scopeGroups.length, projectGroups.length)
2943
+ ? shortcutLabelForCommand(keybindings, "chat.newLocal")
2944
+ : undefined);
2945
const newThreadInProjectShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal");
2946
return (
2947
<>
@@ -2984,15 +3033,24 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3033
if (
3034
event.defaultPrevented ||
3035
event.nativeEvent.isComposing ||
2987
- event.keyCode === 229 ||
2988
- event.ctrlKey ||
2989
- event.altKey ||
2990
- event.metaKey
3036
+ event.keyCode === 229
3037
) {
3038
return;
3039
}
3040
const scopeKey = highlightedProjectScopeKeyRef.current;
3041
const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null;
3042
+ // The thread pin shortcut pins the highlighted project here.
3043
+ if (
3044
+ project &&
3045
+ canPinProject(project) &&
3046
+ isProjectPinShortcut(event, keybindings)
3047
+ ) {
3048
+ event.preventDefault();
3049
+ event.stopPropagation();
3050
+ toggleProjectGroupPin(project);
3051
+ return;
3052
+ }
3053
+ if (event.ctrlKey || event.altKey || event.metaKey) return;
3054
if (event.shiftKey && event.key === "Enter") {
3055
if (!project) return;
3056
event.preventDefault();
@@ -3048,6 +3106,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3106
machineByEnvironmentId={environmentMachineById}
3107
/>
3108
) : null}
3109
+ {project && canPinProject(project) ? (
3110
+ <ProjectPinButton
3111
+ name={project.displayName}
3112
+ pinned={project.pinned}
3113
+ shortcutLabel={shortcutLabelForCommand(keybindings, "thread.pin")}
3114
+ onToggle={() => toggleProjectGroupPin(project)}
3115
+ />
3116
+ ) : null}
3117
{project ? (
3118
<Button
3119
size="icon-xs"
@@ -3055,7 +3121,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3121
tabIndex={-1}
3122
aria-hidden="true"
3123
title={`Project settings for ${project.displayName}`}
3058
- className="ml-auto"
3124
+ className={canPinProject(project) ? undefined : "ml-auto"}
3125
onPointerDown={(event) => event.stopPropagation()}
3126
onClick={(event) => {
3127
void handleProjectSettings(event, project);
@@ -3076,7 +3142,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
3142
newThreadDisabled={projects.length === 0}
3143
newThreadShortcutLabel={newThreadShortcutLabel}
3144
newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel}
3079
- showNewThreadInProjectHint={!boringSidebarEnabled && projectGroups.length > 1}
3145
+ showNewThreadInProjectHint={
3146
+ !boringSidebarEnabled &&
3147
+ !shouldCreateNewThreadInCurrentProject(
3148
+ false,
3149
+ scopeGroups.length,
3150
+ projectGroups.length,
3151
+ )
3152
+ }
3153
searchInputRef={threadSearchInputRef}
3154
searchQuery={threadSearchQuery}
3155
onSearchQueryChange={(value) => {
apps/web/src/components/chat/DraftHeroHeadline.tsx
+37
-5
@@ -11,12 +11,15 @@ import { openCommandPalette } from "~/commandPaletteBus";
11
import { shortcutLabelForCommand } from "~/keybindings";
12
import { primaryServerKeybindingsAtom } from "~/state/server";
13
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
14
+import { useOrderWhileOpen } from "~/hooks/useOrderWhileOpen";
15
+import { useProjectPin } from "~/hooks/useProjectGroupUpdate";
16
import { useScratchProject } from "~/hooks/useScratchProject";
17
import { isTriagePrompt } from "~/hooks/useStartTriage";
18
import { useClientSettings } from "~/hooks/useSettings";
19
import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";
20
import {
21
deriveLogicalProjectKeyFromSettings,
22
+ pickableProjectGroups,
23
selectProjectGroupingSettings,
24
} from "@t3tools/client-runtime/state/project-grouping";
25
import {
@@ -32,6 +35,7 @@ import {
35
} from "~/state/environments";
36
import { ProjectEnvironmentBadge } from "../ProjectEnvironmentBadge";
37
import { ProjectFavicon } from "../ProjectFavicon";
38
+import { isProjectPinShortcut, ProjectPinButton } from "../ProjectPinButton";
39
import { sortLogicalProjectsForSidebar } from "../Sidebar.logic";
40
import {
41
Combobox,
@@ -94,6 +98,8 @@ export function DraftHeroHeadline({
98
const [pickerOpen, setPickerOpen] = useState(false);
99
const [pickerQuery, setPickerQuery] = useState("");
100
const pickerFilter = useComboboxFilter();
101
+ const highlightedPickerValueRef = useRef<string | null>(null);
102
+ const { canPinProjectGroup, toggleProjectGroupPin } = useProjectPin();
103
104
const environmentLabelById = new Map(
105
environments.map((environment) => [environment.environmentId, environment.label] as const),
@@ -119,7 +125,7 @@ export function DraftHeroHeadline({
125
),
126
);
127
const projectPickerEntries = buildSidebarProjectPickerEntries({
122
- groups: projectGroups,
128
+ groups: pickableProjectGroups(projectGroups),
129
preferredProjectRef: activeProjectRef,
130
});
131
const projectEntryByKey = new Map(
@@ -156,10 +162,15 @@ export function DraftHeroHeadline({
162
activeProject !== null &&
163
isScratchProject(activeProject, scratchWorkspaceRootFor(activeProject.environmentId));
164
159
- const pickerItems: readonly PickerItem[] = [
160
- ...menuEntries.map(({ group }) => ({ value: group.projectKey, label: group.displayName })),
161
- { value: ADD_PROJECT_VALUE, label: "Add project" },
162
- ];
165
+ // Pinning from a row keeps rows in place while the picker is open.
166
+ const pickerItems: readonly PickerItem[] = useOrderWhileOpen(
167
+ [
168
+ ...menuEntries.map(({ group }) => ({ value: group.projectKey, label: group.displayName })),
169
+ { value: ADD_PROJECT_VALUE, label: "Add project" },
170
+ ],
171
+ (item) => item.value,
172
+ pickerOpen,
173
+ );
174
const pickerSearch = pickerQuery.trim();
175
const filteredPickerItems =
176
pickerSearch.length === 0
@@ -258,6 +269,9 @@ export function DraftHeroHeadline({
269
itemToStringLabel={(item) => item.label}
270
isItemEqualToValue={(a, b) => a.value === b.value}
271
open={pickerOpen}
272
+ onItemHighlighted={(item) => {
273
+ highlightedPickerValueRef.current = item?.value ?? null;
274
+ }}
275
onOpenChange={(open) => {
276
setPickerOpen(open);
277
setPickerQuery("");
@@ -302,6 +316,16 @@ export function DraftHeroHeadline({
316
placeholder="Search projects..."
317
value={pickerQuery}
318
onChange={(event) => setPickerQuery(event.target.value)}
319
+ onKeyDown={(event) => {
320
+ const highlighted = highlightedPickerValueRef.current;
321
+ const group = highlighted ? projectEntryByKey.get(highlighted)?.group : undefined;
322
+ if (!group || !canPinProjectGroup(group) || !isProjectPinShortcut(event, keybindings)) {
323
+ return;
324
+ }
325
+ event.preventDefault();
326
+ event.stopPropagation();
327
+ toggleProjectGroupPin(group);
328
+ }}
329
/>
330
<ComboboxEmpty>No matching projects.</ComboboxEmpty>
331
<ComboboxList>
@@ -327,6 +351,14 @@ export function DraftHeroHeadline({
351
machineByEnvironmentId={environmentMachineById}
352
/>
353
) : null}
354
+ {entry && canPinProjectGroup(entry.group) ? (
355
+ <ProjectPinButton
356
+ name={entry.group.displayName}
357
+ pinned={entry.group.pinned}
358
+ shortcutLabel={shortcutLabelForCommand(keybindings, "thread.pin")}
359
+ onToggle={() => toggleProjectGroupPin(entry.group)}
360
+ />
361
+ ) : null}
362
</ComboboxItem>
363
);
364
}}
apps/web/src/components/chat/useThreadLifecycle.tsx
+8
-1
@@ -623,7 +623,14 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
623
if (settleAndAdvance(activeThreadRef)) return;
624
void settleThread(activeThreadRef).then(toastThreadActionFailure("Failed to settle thread"));
625
},
626
- "thread.pin": () => {
626
+ "thread.pin": ({ event }) => {
627
+ // An open project list pins its highlighted project with this key instead.
628
+ if (
629
+ event.target instanceof Element &&
630
+ event.target.closest('[role="combobox"][aria-expanded="true"]') !== null
631
+ ) {
632
+ return false;
633
+ }
634
if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
635
if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return;
636
void (
apps/web/src/components/desktop/DesktopAppActivationCoordinator.tsx
+20
-1
@@ -14,10 +14,15 @@ import { usePrimaryEnvironment } from "../../state/environments";
14
import { projectEnvironment } from "../../state/projects";
15
import { useEnvironmentShellHasSnapshot } from "../../state/shell";
16
import { useAtomCommand } from "../../state/use-atom-command";
17
+import { useOrchestrationCommand } from "../../state/use-orchestration-command";
18
+import { reportProjectFailure } from "../../hooks/useProjectGroupUpdate";
19
20
export function DesktopAppActivationCoordinator() {
21
const primaryEnvironment = usePrimaryEnvironment();
22
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
23
+ const updateProject = useOrchestrationCommand(projectEnvironment.update, {
24
+ label: "project unarchive",
25
+ });
26
const openThread = useNewThreadHandler();
27
const queueRef = useRef(Promise.resolve());
28
const activation = window.desktopBridge?.appActivation;
@@ -70,7 +75,21 @@ export function DesktopAppActivationCoordinator() {
75
waitForProject: async (projectRef) => {
76
await waitForProject(projectRef);
77
},
73
- openThread: (projectRef) => openThread(projectRef),
78
+ openThread: (projectRef) => {
79
+ const project = readProjects().find(
80
+ (candidate) =>
81
+ candidate.environmentId === projectRef.environmentId &&
82
+ candidate.id === projectRef.projectId,
83
+ );
84
+ // Opening an archived project's folder again brings the project back.
85
+ if (project?.archivedAt != null) {
86
+ void updateProject({
87
+ environmentId: projectRef.environmentId,
88
+ input: { projectId: projectRef.projectId, archived: false },
89
+ }).then((result) => reportProjectFailure("Failed to unarchive project", result));
90
+ }
91
+ return openThread(projectRef);
92
+ },
93
}),
94
);
95
apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx
+22
-1
@@ -70,12 +70,18 @@ vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
70
vi.mock(import("~/state/environments"), async (original) => ({
71
...(await original()),
72
useEnvironments: (() => ({ environments })) as never,
73
+ readEnvironment: ((id: EnvironmentId) =>
74
+ environments.find((environment) => environment.environmentId === id) ?? null) as never,
75
usePrimaryEnvironmentId: () => primaryId,
76
}));
77
vi.mock(import("~/state/entities"), async (original) => ({
78
...(await original()),
79
useProjects: (() => state.projects) as never,
80
useThreadShells: () => [],
81
+ useServerConfigs: (() =>
82
+ new Map(
83
+ environments.map((environment) => [environment.environmentId, environment.serverConfig]),
84
+ )) as never,
85
waitForProjectRemoval: async () => true,
86
}));
87
vi.mock(import("~/state/projects"), async (original) => {
@@ -145,7 +151,7 @@ const environments = [primaryId, remoteId].map((environmentId) => ({
151
serverConfig: {
152
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
153
settings: DEFAULT_SERVER_SETTINGS,
148
- environment: { platform: { machine: "server" } },
154
+ environment: { platform: { machine: "server" }, capabilities: { projectOrganization: true } },
155
},
156
}));
157
const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({
@@ -326,6 +332,21 @@ async function expectProjectAccessDeniedToast(title: string) {
332
expect(state.toast).toHaveBeenCalledOnce();
333
}
334
335
+describe("project organization", () => {
336
+ it("archives the checkout on every machine while one machine is picked", async () => {
337
+ setup();
338
+ await using _screen = await mountPanel({ machine: primaryId });
339
+ await userEvent.click(page.getByRole("button", { name: "Archive" }));
340
+ await vi.waitFor(() => expect(state.update).toHaveBeenCalledTimes(2));
341
+ expect(
342
+ state.update.mock.calls.map(([request]) => [request.environmentId, request.input.archived]),
343
+ ).toEqual([
344
+ [primaryId, true],
345
+ [remoteId, true],
346
+ ]);
347
+ });
348
+});
349
+
350
describe("project settings permissions", () => {
351
it("disables shared edits when any member lacks project access", async () => {
352
setup();
apps/web/src/components/settings/ProjectSettingsPanel.tsx
+75
-95
@@ -1,20 +1,18 @@
1
import { useComposerMenuState } from "../chat/useComposerMenuState";
2
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
3
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
4
-import { useEnvironmentsWithScope, readEnvironmentScope } from "../../state/session";
5
-import {
6
- isAtomCommandInterrupted,
7
- mapAtomCommandResult,
8
- settlePromise,
9
- squashAtomCommandFailure,
10
- type AtomCommandResult,
11
-} from "@t3tools/client-runtime/state/runtime";
4
+import { useEnvironmentsWithScope } from "../../state/session";
5
+import { mapAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
6
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
7
import { planProjectRemoval } from "@t3tools/client-runtime/state/projects";
14
-import { AsyncResult } from "effect/reactivity";
15
-import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";
8
+import { type EnvironmentId } from "@t3tools/contracts";
9
+import {
10
+ checkProjectAccess,
11
+ reportProjectFailure,
12
+ useProjectGroupUpdate,
13
+ type ProjectGroupUpdate,
14
+} from "../../hooks/useProjectGroupUpdate";
15
import { Navigate, useLocation, useNavigate } from "@tanstack/react-router";
17
-import * as Cause from "effect/Cause";
16
import { InfoIcon, Trash2Icon } from "lucide-react";
17
import { lazy, Suspense, useRef, useState, type ReactNode } from "react";
18
@@ -32,7 +30,8 @@ import { ProjectFavicon } from "../ProjectFavicon";
30
import { Alert, AlertDescription } from "../ui/alert";
31
import { Button } from "../ui/button";
32
import { Input } from "../ui/input";
35
-import { stackedThreadToast, toastManager } from "../ui/toast";
33
+import { Switch } from "../ui/switch";
34
+import { toastManager } from "../ui/toast";
35
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
36
import {
37
SettingResetButton,
@@ -169,22 +168,20 @@ export function ProjectSettingsPanel({
168
<ProjectDetail
169
key={`${selected.projectKey}:${environmentId ?? "all"}:${checkoutKey ?? "all"}`}
170
group={scopedGroup}
171
+ allMembers={selected.memberProjects}
172
hasOtherMembers={members.length < selected.memberProjects.length}
173
/>
174
);
175
}
176
177
-type ProjectIdentityUpdate = Partial<{
178
- title: string;
179
- faviconPath: string | null;
180
- projectIcon: ProjectIconOverride | null;
181
-}>;
182
-
177
function ProjectDetail({
178
group,
179
+ allMembers,
180
hasOtherMembers,
181
}: {
182
group: SidebarProjectSnapshot;
183
+ /** Pin and archive belong to the whole project, even when one machine is picked. */
184
+ allMembers: ReadonlyArray<SidebarProjectGroupMember>;
185
hasOtherMembers: boolean;
186
}) {
187
const navigate = useNavigate({ from: "/settings" });
@@ -193,7 +190,7 @@ function ProjectDetail({
190
const environmentById = new Map(
191
environments.map((environment) => [environment.environmentId, environment]),
192
);
196
- const editableIds = useEnvironmentsWithScope(group.memberProjects, AuthOrchestrationOperateScope);
193
+ const editableIds = useEnvironmentsWithScope(allMembers, AuthOrchestrationOperateScope);
194
const canEditGroup = group.memberProjects.every((member) =>
195
editableIds.has(member.environmentId),
196
);
@@ -202,9 +199,6 @@ function ProjectDetail({
199
(member) => environmentById.get(member.environmentId)?.serverConfig != null,
200
) ?? group.memberProjects[0]!;
201
const threads = useThreadShells();
205
- const updateProject = useOrchestrationCommand(projectEnvironment.update, {
206
- reportFailure: false,
207
- });
202
const deleteProject = useOrchestrationCommand(projectEnvironment.delete, {
203
reportFailure: false,
204
});
@@ -222,79 +216,19 @@ function ProjectDetail({
216
? window.desktopBridge?.pickProjectFavicon
217
: undefined;
218
225
- const reportFailure = (title: string, result: AtomCommandResult<void, unknown>) => {
226
- if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
227
- const error = squashAtomCommandFailure(result);
228
- toastManager.add(
229
- stackedThreadToast({
230
- type: "error",
231
- title,
232
- description: error instanceof Error ? error.message : "An error occurred.",
233
- }),
234
- );
235
- };
236
-
237
- const checkProjectAccess = (
238
- members: ReadonlyArray<SidebarProjectGroupMember>,
219
+ const { updateProjectGroup, canOrganizeProjectGroup } = useProjectGroupUpdate();
220
+ const updateAllMembers = (
221
+ input: ProjectGroupUpdate | ((member: SidebarProjectGroupMember) => ProjectGroupUpdate),
222
failureTitle: string,
240
- ) => {
241
- const denied = members.find(
242
- (member) => !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
243
- );
244
- if (!denied) return null;
245
- const result = AsyncResult.failure<void, Error>(
246
- Cause.fail(
247
- new Error(
248
- `This connection cannot change projects in ${denied.environmentLabel ?? "this environment"}.`,
249
- ),
250
- ),
251
- );
252
- reportFailure(failureTitle, result);
253
- return result;
254
- };
255
-
256
- const updateAllMembers = async (
257
- input: ProjectIdentityUpdate | ((member: SidebarProjectGroupMember) => ProjectIdentityUpdate),
258
- failureTitle: string,
259
- ): Promise<AtomCommandResult<void, unknown>> => {
260
- const denied = checkProjectAccess(group.memberProjects, failureTitle);
261
- if (denied) return denied;
262
- const unavailable = group.memberProjects.find((member) => {
263
- const environment = environmentById.get(member.environmentId);
264
- return environment?.connection.phase !== "connected" || !environment.serverConfig;
265
- });
266
- if (unavailable) {
267
- const error = new Error(
268
- `Connect ${unavailable.environmentLabel ?? "the selected environment"} and try again.`,
269
- );
270
- const result: AtomCommandResult<void, unknown> = AsyncResult.failure(Cause.fail(error));
271
- reportFailure(failureTitle, result);
272
- return result;
273
- }
274
- for (const member of group.memberProjects) {
275
- const revoked = checkProjectAccess([member], failureTitle);
276
- if (revoked) return revoked;
277
- const result = mapAtomCommandResult(
278
- await updateProject({
279
- environmentId: member.environmentId,
280
- input: {
281
- projectId: member.id,
282
- ...(typeof input === "function" ? input(member) : input),
283
- },
284
- }),
285
- () => undefined,
286
- );
287
- if (result._tag === "Failure") {
288
- reportFailure(
289
- group.memberProjects.length > 1
290
- ? `${failureTitle} on ${member.environmentLabel ?? "the current environment"}`
291
- : failureTitle,
292
- result,
293
- );
294
- return result;
295
- }
296
- }
297
- return AsyncResult.success(undefined);
223
+ ) => updateProjectGroup(group.memberProjects, input, failureTitle);
224
+ const canOrganize =
225
+ allMembers.every((member) => editableIds.has(member.environmentId)) &&
226
+ canOrganizeProjectGroup(allMembers);
227
+ const [isOrganizing, setIsOrganizing] = useState(false);
228
+ const organize = async (input: ProjectGroupUpdate, failureTitle: string) => {
229
+ setIsOrganizing(true);
230
+ await updateProjectGroup(allMembers, input, failureTitle);
231
+ setIsOrganizing(false);
232
};
233
234
const renameGroup = async (nextTitle: string, wasEdited: boolean) => {
@@ -369,7 +303,7 @@ function ProjectDetail({
303
() => undefined,
304
);
305
if (result._tag === "Failure") {
372
- reportFailure(`Failed to remove "${member.title}"`, result);
306
+ reportProjectFailure(`Failed to remove "${member.title}"`, result);
307
return;
308
}
309
const projectRef = scopeProjectRef(member.environmentId, member.id);
@@ -581,6 +515,52 @@ function ProjectDetail({
515
</div>
516
}
517
/>
518
+ {canOrganize ? (
519
+ <>
520
+ <SettingsRow
521
+ title="Pin"
522
+ description="Pinned projects come first in project pickers."
523
+ control={
524
+ <Switch
525
+ checked={group.pinned}
526
+ disabled={isOrganizing}
527
+ onCheckedChange={(checked) =>
528
+ void organize(
529
+ { pinned: Boolean(checked) },
530
+ checked ? "Failed to pin project" : "Failed to unpin project",
531
+ )
532
+ }
533
+ aria-label="Pin project"
534
+ />
535
+ }
536
+ />
537
+ <SettingsRow
538
+ title="Archive"
539
+ description={
540
+ group.archived
541
+ ? "Hidden from project pickers. Threads and files are kept."
542
+ : "Hides the project from project pickers. Threads and files are kept."
543
+ }
544
+ control={
545
+ <Button
546
+ size="sm"
547
+ variant="outline"
548
+ disabled={isOrganizing}
549
+ onClick={() =>
550
+ void organize(
551
+ { archived: !group.archived },
552
+ group.archived
553
+ ? "Failed to unarchive project"
554
+ : "Failed to archive project",
555
+ )
556
+ }
557
+ >
558
+ {group.archived ? "Unarchive" : "Archive"}
559
+ </Button>
560
+ }
561
+ />
562
+ </>
563
+ ) : null}
564
</SettingsSection>
565
<ProjectDefaultsSettings category="project" />
566
<ProjectActionsSettings />
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+22
-7
@@ -79,6 +79,7 @@ import {
79
WEBHOOK_SIGNATURE_DEFAULTS,
80
webhookDraftErrors,
81
webhookDeliveryLabel,
82
+ defaultScheduledTaskProjectId,
83
matchesScheduledTaskScope,
84
scheduleFromDraft,
85
scheduledTaskDefaultModel,
@@ -1176,11 +1177,11 @@ function ScheduledTaskEditorForm({
1177
connected ? serverEnvironment.scheduledTasksLive({ environmentId, input: {} }) : null,
1178
);
1179
const allProjects = useProjects();
1179
- const projects = allProjects.filter(
1180
- (project) =>
1181
- project.environmentId === environmentId &&
1182
- matchesScheduledTaskScope(scope, environmentId, project.id),
1183
- );
1180
+ const projectsOn = (id: EnvironmentId) =>
1181
+ allProjects.filter(
1182
+ (project) => project.environmentId === id && matchesScheduledTaskScope(scope, id, project.id),
1183
+ );
1184
+ const scopedProjects = projectsOn(environmentId);
1185
const settings = useEnvironmentSettings(environmentId);
1186
const providers =
1187
useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
@@ -1191,8 +1192,22 @@ function ScheduledTaskEditorForm({
1192
label: "scheduled task upsert",
1193
});
1194
const [draft, setDraft] = useState<DraftState>(() =>
1194
- task ? taskToDraft(task) : { ...EMPTY_DRAFT, projectId: projects[0]?.id ?? "" },
1195
+ task
1196
+ ? taskToDraft(task)
1197
+ : {
1198
+ ...EMPTY_DRAFT,
1199
+ projectId: defaultScheduledTaskProjectId(scopedProjects, scope),
1200
+ },
1201
);
1202
+ // Pinned first. The chosen project stays listed after it is archived.
1203
+ const projects = scopedProjects
1204
+ .filter(
1205
+ (project) =>
1206
+ project.archivedAt == null ||
1207
+ project.id === draft.projectId ||
1208
+ project.id === task?.projectId,
1209
+ )
1210
+ .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
1211
const submissionPending = useRef(false);
1212
const editingTaskMissing =
1213
draft.editingId !== null &&
@@ -1357,7 +1372,7 @@ function ScheduledTaskEditorForm({
1372
setEnvironmentId(next.environmentId);
1373
setDraft((current) => ({
1374
...current,
1360
- projectId: "",
1375
+ projectId: defaultScheduledTaskProjectId(projectsOn(next.environmentId), scope),
1376
modelKey: "",
1377
baseModelSelection: null,
1378
baseRef: "main",
apps/web/src/components/settings/SettingsScopeNotice.tsx
+1
@@ -84,6 +84,7 @@ export function SettingsScopeNotice({
84
? groups.map((group) => ({
85
label: group.displayName,
86
secondary: [
87
+ ...(group.archived ? ["Archived"] : []),
88
...(groups.some(
89
(other) =>
90
other.projectKey !== group.projectKey && other.displayName === group.displayName,
apps/web/src/components/settings/SettingsScopeSentence.tsx
+9
-8
@@ -324,17 +324,18 @@ function ProjectScopeMenu({ value, groups, environments, onChange }: SettingsSco
324
other.group.projectKey !== group.projectKey &&
325
other.group.displayName === group.displayName,
326
);
327
+ const location =
328
+ sameName.length === 0
329
+ ? environments.length > 1
330
+ ? group.workspaceRoot
331
+ : ""
332
+ : sameName.some((other) => other.machines === machines)
333
+ ? `${machines} · ${group.workspaceRoot}`
334
+ : machines;
335
return {
336
value: group.projectKey,
337
label: group.displayName,
330
- secondary:
331
- sameName.length === 0
332
- ? environments.length > 1
333
- ? group.workspaceRoot
334
- : ""
335
- : sameName.some((other) => other.machines === machines)
336
- ? `${machines} · ${group.workspaceRoot}`
337
- : machines,
338
+ secondary: group.archived ? ["Archived", location].filter(Boolean).join(" · ") : location,
339
icon: <ProjectFavicon project={group} className="size-3.5 shrink-0" />,
340
};
341
})}
apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
+19
@@ -18,6 +18,7 @@ import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope"
18
import { deriveProviderInstanceEntries } from "../../providerInstances";
19
import {
20
scheduledTaskDefaultModel,
21
+ defaultScheduledTaskProjectId,
22
matchesScheduledTaskScope,
23
scheduleFromDraft,
24
taskToDraft,
@@ -70,6 +71,8 @@ function group(
71
allRemoteMembersAreDesktopLocal: false,
72
allRemoteMembersAreWsl: false,
73
remoteEnvironmentLabels: [],
74
+ pinned: false,
75
+ archived: false,
76
};
77
}
78
@@ -101,6 +104,22 @@ describe("scheduled task settings scope", () => {
104
).toEqual(expected);
105
});
106
107
+ it("defaults a new task to a pinned open project, and to an archived one only when scoped to it", () => {
108
+ const at = "2026-01-01T00:00:00.000Z";
109
+ const project = (id: string, pinnedAt: string | null, archivedAt: string | null) => ({
110
+ id: ProjectId.make(id),
111
+ pinnedAt,
112
+ archivedAt,
113
+ });
114
+ const all = resolveSettingsScope({}, groups, environments);
115
+ const scoped = resolveSettingsScope({ project: "t3code" }, groups, environments);
116
+ expect(
117
+ defaultScheduledTaskProjectId([project("a", null, null), project("b", at, null)], all),
118
+ ).toBe("b");
119
+ expect(defaultScheduledTaskProjectId([project("x", null, at)], all)).toBe("");
120
+ expect(defaultScheduledTaskProjectId([project("x", null, at)], scoped)).toBe("x");
121
+ });
122
+
123
it("keeps tasks with removed projects manageable at environment scope", () => {
124
const removedProject = ProjectId.make("removed");
125
expect(
apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+22
@@ -285,3 +285,25 @@ export function scheduledTaskDefaultModel(
285
const fallback = models.find(({ model }) => model.isDefault) ?? models[0];
286
return fallback ? { instanceId: fallback.instanceId, model: fallback.model.slug } : null;
287
}
288
+
289
+/**
290
+ * A new task's project: a pinned open project, then any open one. An archived
291
+ * project only when Settings is scoped to it, so that scope can still save.
292
+ */
293
+export function defaultScheduledTaskProjectId<
294
+ TProject extends {
295
+ readonly id: ProjectId;
296
+ readonly pinnedAt?: string | null | undefined;
297
+ readonly archivedAt?: string | null | undefined;
298
+ },
299
+>(scopedProjects: ReadonlyArray<TProject>, scope: ResolvedSettingsScope): ProjectId | "" {
300
+ const open = scopedProjects.filter((project) => project.archivedAt == null);
301
+ const scopedToProject = scope.kind === "project" || scope.kind === "checkout";
302
+ return (
303
+ (
304
+ open.find((project) => project.pinnedAt != null) ??
305
+ open[0] ??
306
+ (scopedToProject ? scopedProjects[0] : undefined)
307
+ )?.id ?? ""
308
+ );
309
+}
apps/web/src/components/settings/scopedSettings.test.ts
+2
@@ -91,6 +91,8 @@ const group: SidebarProjectSnapshot = {
91
allRemoteMembersAreDesktopLocal: false,
92
allRemoteMembersAreWsl: false,
93
remoteEnvironmentLabels: [server.label, laptop.label],
94
+ pinned: false,
95
+ archived: false,
96
};
97
const project = resolveSettingsScope({ project: group.projectKey }, [group], environments);
98
const checkout = resolveSettingsScope(
apps/web/src/components/settings/settingsScope.test.ts
+2
@@ -54,6 +54,8 @@ function group(
54
allRemoteMembersAreDesktopLocal: false,
55
allRemoteMembersAreWsl: false,
56
remoteEnvironmentLabels: [],
57
+ pinned: false,
58
+ archived: false,
59
};
60
}
61
apps/web/src/environmentGrouping.test.ts
+27
-1
@@ -1,7 +1,10 @@
1
import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
2
import { describe, expect, it } from "vite-plus/test";
3
4
-import { deriveLogicalProjectKeyFromSettings } from "@t3tools/client-runtime/state/project-grouping";
4
+import {
5
+ deriveLogicalProjectKeyFromSettings,
6
+ pickableProjectGroups,
7
+} from "@t3tools/client-runtime/state/project-grouping";
8
import {
9
buildSidebarProjectPickerEntries,
10
buildSidebarProjectSnapshots,
@@ -275,4 +278,27 @@ describe("environment grouping", () => {
278
id: fallbackPrimary.id,
279
});
280
});
281
+
282
+ it("puts the preferred project after pinned projects", () => {
283
+ const project = (title: string, pinnedAt: string | null = null) =>
284
+ makeProject({
285
+ id: ProjectId.make(title),
286
+ title,
287
+ workspaceRoot: `/tmp/${title}`,
288
+ repositoryIdentity: null,
289
+ pinnedAt,
290
+ });
291
+ const current = project("current");
292
+ const groups = buildSidebarProjectSnapshots({
293
+ projects: [project("other"), project("pinned", "2026-01-01T00:00:00.000Z"), current],
294
+ settings: defaultGroupingSettings,
295
+ primaryEnvironmentId,
296
+ resolveEnvironmentLabel: () => null,
297
+ });
298
+ const entries = buildSidebarProjectPickerEntries({
299
+ groups: pickableProjectGroups(groups),
300
+ preferredProjectRef: { environmentId: current.environmentId, projectId: current.id },
301
+ });
302
+ expect(entries.map((entry) => entry.group.displayName)).toEqual(["pinned", "current", "other"]);
303
+ });
304
});
apps/web/src/hooks/useHandleNewThread.ts
+1
-1
@@ -428,7 +428,7 @@ export function resolveDefaultProjectRef(
428
projectOrder: readonly string[],
429
): ScopedProjectRef | null {
430
const [defaultProject] = orderItemsByPreferredIds({
431
- items: projects,
431
+ items: projects.filter((project) => project.archivedAt == null),
432
preferredIds: projectOrder,
433
getId: getProjectOrderKey,
434
getPreferenceIds: (project) => [
apps/web/src/hooks/useOrderWhileOpen.test.ts
new
+21
@@ -0,0 +1,21 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { keepOrder, withArrivedKeys } from "./useOrderWhileOpen";
4
+
5
+describe("keepOrder", () => {
6
+ it("keeps the opening order and puts new items after it", () => {
7
+ const key = (item: string) => item;
8
+ // "c" was pinned and moved to the top; "d" arrived after the list opened; "b" is gone.
9
+ expect(keepOrder(["c", "d", "a"], ["a", "b", "c"], key)).toEqual(["a", "c", "d"]);
10
+ expect(keepOrder(["c", "a"], null, key)).toEqual(["c", "a"]);
11
+ });
12
+
13
+ it("holds rows that arrived after opening in their first place", () => {
14
+ // "b" and "c" load from another machine after the list opened with nothing in it.
15
+ const order = withArrivedKeys(null, ["b", "c"]);
16
+ expect(order).toEqual(["b", "c"]);
17
+ // Pinning "c" moves it first in the source list; the shown order stays.
18
+ expect(keepOrder(["c", "b"], order, (item) => item)).toEqual(["b", "c"]);
19
+ expect(withArrivedKeys(order, ["b", "c"])).toBe(order);
20
+ });
21
+});
apps/web/src/hooks/useOrderWhileOpen.ts
new
+46
@@ -0,0 +1,46 @@
1
+import { useState } from "react";
2
+
3
+/** Sorts `items` into `order` by key. Items missing from `order` follow, in their own order. */
4
+export function keepOrder<T>(
5
+ items: ReadonlyArray<T>,
6
+ order: ReadonlyArray<string> | null,
7
+ key: (item: T) => string,
8
+): T[] {
9
+ if (order === null) return [...items];
10
+ const rank = new Map(order.map((itemKey, index) => [itemKey, index]));
11
+ return items
12
+ .map((item, index) => ({ item, rank: rank.get(key(item)) ?? order.length + index }))
13
+ .toSorted((a, b) => a.rank - b.rank)
14
+ .map(({ item }) => item);
15
+}
16
+
17
+/** `order` with keys it has not seen added at the end, or `order` itself when nothing is new. */
18
+export function withArrivedKeys(
19
+ order: ReadonlyArray<string> | null,
20
+ keys: ReadonlyArray<string>,
21
+): ReadonlyArray<string> | null {
22
+ const known = new Set(order);
23
+ const arrived = keys.filter((itemKey) => !known.has(itemKey));
24
+ return arrived.length === 0 ? order : [...(order ?? []), ...arrived];
25
+}
26
+
27
+/**
28
+ * Keeps the order a list had when it opened, so a row that a pin moves does not slide out
29
+ * from under the pointer or the keyboard highlight. Rows that load later join at the end and
30
+ * then hold their place too. The new order shows on the next open.
31
+ */
32
+export function useOrderWhileOpen<T>(
33
+ items: ReadonlyArray<T>,
34
+ key: (item: T) => string,
35
+ open: boolean,
36
+): T[] {
37
+ const [order, setOrder] = useState<ReadonlyArray<string> | null>(null);
38
+ if (!open) {
39
+ if (order !== null) setOrder(null);
40
+ return [...items];
41
+ }
42
+ const ordered = keepOrder(items, order, key);
43
+ const nextOrder = withArrivedKeys(order, ordered.map(key));
44
+ if (nextOrder !== order) setOrder(nextOrder);
45
+ return ordered;
46
+}
apps/web/src/hooks/useProjectGroupUpdate.ts
new
+160
@@ -0,0 +1,160 @@
1
+import { AuthOrchestrationOperateScope, type ProjectIconOverride } from "@t3tools/contracts";
2
+import {
3
+ isAtomCommandInterrupted,
4
+ mapAtomCommandResult,
5
+ squashAtomCommandFailure,
6
+ type AtomCommandResult,
7
+} from "@t3tools/client-runtime/state/runtime";
8
+import { AsyncResult } from "effect/reactivity";
9
+import * as Cause from "effect/Cause";
10
+
11
+import { stackedThreadToast, toastManager } from "../components/ui/toast";
12
+import type { SidebarProjectGroupMember } from "../sidebarProjectGrouping";
13
+import { useProjects, useServerConfigs } from "../state/entities";
14
+import { readEnvironment } from "../state/environments";
15
+import { projectEnvironment } from "../state/projects";
16
+import { readEnvironmentScope, useEnvironmentsWithScope } from "../state/session";
17
+import { useOrchestrationCommand } from "../state/use-orchestration-command";
18
+
19
+export type ProjectGroupUpdate = Partial<{
20
+ title: string;
21
+ faviconPath: string | null;
22
+ projectIcon: ProjectIconOverride | null;
23
+ pinned: boolean;
24
+ archived: boolean;
25
+}>;
26
+
27
+type ProjectGroupMember = Pick<
28
+ SidebarProjectGroupMember,
29
+ "environmentId" | "id" | "environmentLabel"
30
+>;
31
+
32
+/**
33
+ * Writes one update to each checkout of a project, one machine at a time, and
34
+ * reports the first failure as a toast. Every machine must be connected first.
35
+ */
36
+export function useProjectGroupUpdate() {
37
+ const serverConfigs = useServerConfigs();
38
+ const updateProject = useOrchestrationCommand(projectEnvironment.update, {
39
+ reportFailure: false,
40
+ });
41
+
42
+ const updateProjectGroup = async <TMember extends ProjectGroupMember>(
43
+ members: ReadonlyArray<TMember>,
44
+ input: ProjectGroupUpdate | ((member: TMember) => ProjectGroupUpdate),
45
+ failureTitle: string,
46
+ ): Promise<AtomCommandResult<void, unknown>> => {
47
+ const denied = checkProjectAccess(members, failureTitle);
48
+ if (denied) return denied;
49
+ const unavailable = members.find((member) => {
50
+ const environment = readEnvironment(member.environmentId);
51
+ return environment?.connection.phase !== "connected" || !environment.serverConfig;
52
+ });
53
+ if (unavailable) {
54
+ return failWith(
55
+ failureTitle,
56
+ `Connect ${unavailable.environmentLabel ?? "the selected environment"} and try again.`,
57
+ );
58
+ }
59
+ for (const member of members) {
60
+ // Access can be revoked between writes.
61
+ const revoked = checkProjectAccess([member], failureTitle);
62
+ if (revoked) return revoked;
63
+ const result = mapAtomCommandResult(
64
+ await updateProject({
65
+ environmentId: member.environmentId,
66
+ input: {
67
+ projectId: member.id,
68
+ ...(typeof input === "function" ? input(member) : input),
69
+ },
70
+ }),
71
+ () => undefined,
72
+ );
73
+ if (result._tag === "Failure") {
74
+ reportProjectFailure(
75
+ members.length > 1
76
+ ? `${failureTitle} on ${member.environmentLabel ?? "the current environment"}`
77
+ : failureTitle,
78
+ result,
79
+ );
80
+ return result;
81
+ }
82
+ }
83
+ return AsyncResult.success(undefined);
84
+ };
85
+
86
+ /** Older servers drop pin and archive, so their projects do not offer them. */
87
+ const canOrganizeProjectGroup = (members: ReadonlyArray<ProjectGroupMember>) =>
88
+ members.every(
89
+ (member) =>
90
+ serverConfigs.get(member.environmentId)?.environment.capabilities.projectOrganization ===
91
+ true,
92
+ );
93
+
94
+ return { updateProjectGroup, canOrganizeProjectGroup };
95
+}
96
+
97
+/** Pin state for a project group, shared by every list that can pin or unpin a project. */
98
+export function useProjectPin() {
99
+ const { updateProjectGroup, canOrganizeProjectGroup } = useProjectGroupUpdate();
100
+ const environments = [...new Set(useProjects().map((project) => project.environmentId))].map(
101
+ (environmentId) => ({ environmentId }),
102
+ );
103
+ const operableEnvironmentIds = useEnvironmentsWithScope(
104
+ environments,
105
+ AuthOrchestrationOperateScope,
106
+ );
107
+ type PinnableGroup = {
108
+ readonly memberProjects: ReadonlyArray<ProjectGroupMember>;
109
+ readonly pinned: boolean;
110
+ };
111
+ const canPinProjectGroup = (group: PinnableGroup) =>
112
+ canOrganizeProjectGroup(group.memberProjects) &&
113
+ group.memberProjects.every((member) => operableEnvironmentIds.has(member.environmentId));
114
+ const setProjectGroupPinned = (group: PinnableGroup, pinned: boolean) => {
115
+ void updateProjectGroup(
116
+ group.memberProjects,
117
+ { pinned },
118
+ pinned ? "Failed to pin project" : "Failed to unpin project",
119
+ );
120
+ };
121
+ return {
122
+ canPinProjectGroup,
123
+ setProjectGroupPinned,
124
+ toggleProjectGroupPin: (group: PinnableGroup) => setProjectGroupPinned(group, !group.pinned),
125
+ };
126
+}
127
+
128
+/** Reports the first member this connection cannot change, and returns that failure. */
129
+export function checkProjectAccess(
130
+ members: ReadonlyArray<ProjectGroupMember>,
131
+ failureTitle: string,
132
+): AtomCommandResult<void, unknown> | null {
133
+ const denied = members.find(
134
+ (member) => !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
135
+ );
136
+ return denied
137
+ ? failWith(
138
+ failureTitle,
139
+ `This connection cannot change projects in ${denied.environmentLabel ?? "this environment"}.`,
140
+ )
141
+ : null;
142
+}
143
+
144
+export function reportProjectFailure(title: string, result: AtomCommandResult<unknown, unknown>) {
145
+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
146
+ const error = squashAtomCommandFailure(result);
147
+ toastManager.add(
148
+ stackedThreadToast({
149
+ type: "error",
150
+ title,
151
+ description: error instanceof Error ? error.message : "An error occurred.",
152
+ }),
153
+ );
154
+}
155
+
156
+function failWith(title: string, message: string): AtomCommandResult<void, unknown> {
157
+ const result = AsyncResult.failure<void, Error>(Cause.fail(new Error(message)));
158
+ reportProjectFailure(title, result);
159
+ return result;
160
+}
apps/web/src/routes/_chat.index.tsx
+5
-1
@@ -45,7 +45,11 @@ function IndexDraftLanding() {
45
const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });
46
47
const mostRecentProject =
48
- sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null;
48
+ sortScopedProjectsForSidebar(
49
+ projects.filter((project) => project.archivedAt == null),
50
+ threads,
51
+ "updated_at",
52
+ )[0] ?? null;
53
const attempt = startState.retryRequest;
54
55
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts a draft thread in the most recent project and navigates to it while still on the index
apps/web/src/shortcuts/chatRouteCommands.ts
+19
-4
@@ -7,6 +7,7 @@ import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
7
import { useComposerDraftStore } from "../composerDraftStore";
8
import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";
9
import { isAppModalPage } from "../components/sidebar/mainAppLocation";
10
+import { shouldCreateNewThreadInCurrentProject } from "../components/Sidebar.logic";
11
import { createNewThreadHandler, resolveDefaultProjectRef } from "../hooks/useHandleNewThread";
12
import { createScratchProjectActions } from "../hooks/useScratchProject";
13
import { getClientSettings } from "../hooks/useSettings";
@@ -76,13 +77,15 @@ export function installChatRouteCommands(router: AnyRouter): () => void {
77
handleNewThread,
78
};
79
};
79
- const readProjectGroupCount = () =>
80
+ // Grouped like the sidebar, so the shortcut and the New thread button agree.
81
+ const readProjectGroups = () =>
82
buildSidebarProjectSnapshots({
83
projects: readProjects(),
84
+ groupScratchProjects: true,
85
settings: selectProjectGroupingSettings(getClientSettings()),
86
primaryEnvironmentId: appAtomRegistry.get(primaryEnvironmentIdAtom),
87
resolveEnvironmentLabel: () => null,
85
- }).length;
88
+ });
89
const canOperatePreview = (environmentId: EnvironmentId) =>
90
readEnvironmentScope(environmentId, AuthPreviewOperateScope);
91
@@ -93,7 +96,10 @@ export function installChatRouteCommands(router: AnyRouter): () => void {
96
97
const startNewLocal: CommandHandler = (event) => {
98
claim(event);
96
- void startNewThreadFromContext(readThreadContext());
99
+ // With no current or open project, such as when every project is archived, pick one.
100
+ void startNewThreadFromContext(readThreadContext()).then((started) => {
101
+ if (!started) openCommandPalette({ open: "new-thread-in" });
102
+ });
103
};
104
105
const previewCommand =
@@ -120,7 +126,16 @@ export function installChatRouteCommands(router: AnyRouter): () => void {
126
// The boring sidebar's folders already show the context, so it starts in
127
// the current project like the legacy sidebar did.
128
const { boringSidebarEnabled, legacySidebarEnabled } = getClientSettings();
123
- if (!boringSidebarEnabled && !legacySidebarEnabled && readProjectGroupCount() > 1) {
129
+ const groups = readProjectGroups();
130
+ if (
131
+ !boringSidebarEnabled &&
132
+ !legacySidebarEnabled &&
133
+ !shouldCreateNewThreadInCurrentProject(
134
+ false,
135
+ groups.filter((group) => !group.archived).length,
136
+ groups.length,
137
+ )
138
+ ) {
139
claim(event);
140
openCommandPalette({ open: "new-thread-in" });
141
return;
apps/web/src/sidebarProjectGrouping.ts
+10
-8
@@ -24,6 +24,8 @@ export interface SidebarProjectSnapshot extends Project {
24
memberProjects: readonly SidebarProjectGroupMember[];
25
memberProjectRefs: readonly ScopedProjectRef[];
26
remoteEnvironmentLabels: readonly string[];
27
+ pinned: boolean;
28
+ archived: boolean;
29
}
30
31
export function projectGroupsSpanEnvironments(
@@ -177,6 +179,8 @@ export function buildSidebarProjectSnapshots(input: {
179
memberProjects: members,
180
memberProjectRefs: group.memberProjectRefs,
181
remoteEnvironmentLabels,
182
+ pinned: group.pinned,
183
+ archived: group.archived,
184
};
185
});
186
}
@@ -214,12 +218,10 @@ export function buildSidebarProjectPickerEntries(input: {
218
219
return [{ group, targetProject, isPreferred }];
220
});
217
- const preferredIndex = entries.findIndex((entry) => entry.isPreferred);
218
- if (preferredIndex <= 0) return entries;
219
-
220
- return [
221
- entries[preferredIndex]!,
222
- ...entries.slice(0, preferredIndex),
223
- ...entries.slice(preferredIndex + 1),
224
- ];
221
+ // The preferred project leads the unpinned ones; pinned projects stay first.
222
+ const preferred = entries.find((entry) => entry.isPreferred);
223
+ if (!preferred || preferred.group.pinned) return entries;
224
+ const rest = entries.filter((entry) => entry !== preferred);
225
+ const pinnedCount = rest.filter((entry) => entry.group.pinned).length;
226
+ return [...rest.slice(0, pinnedCount), preferred, ...rest.slice(pinnedCount)];
227
}
apps/web/src/state/environments.ts
+8
@@ -69,6 +69,14 @@ export function readPrimaryEnvironmentId(): EnvironmentId | null {
69
return appAtomRegistry.get(primaryEnvironmentIdAtom);
70
}
71
72
+/** The environment's state now, for handlers that should not re-render on every change. */
73
+export function readEnvironment(environmentId: EnvironmentId): EnvironmentPresentation | null {
74
+ const presentation = appAtomRegistry
75
+ .get(environmentPresentations.presentationsAtom)
76
+ .get(environmentId);
77
+ return presentation ? projectEnvironmentPresentation(environmentId, presentation) : null;
78
+}
79
+
80
export function useEnvironment(
81
environmentId: EnvironmentId | null,
82
): EnvironmentPresentation | null {
docs/user/project-settings.md
+16
@@ -46,6 +46,22 @@ Settings that are environment-wide stay read-only while a project is selected. W
46
targets disagree, a control shows **Mixed** until you choose one value. Appearance, keyboard,
47
and other phone-only settings ignore the filter.
48
49
+## Pin and archive projects
50
+
51
+Pinned projects come first in the project pickers: the project picker on a new thread, the
52
+new-thread list, the command palette, the sidebar project filter, and mobile. In the boring sidebar, pinned projects get the top
53
+folders, even with no active threads. Pin or unpin a project from its row in any of those lists,
54
+or press the thread pin shortcut (`mod+shift+p` by default) on the highlighted row. **Pin
55
+project** in the command palette and **Settings → Projects** work too. A list keeps its order
56
+while it is open, so a new pin moves up the next time you open it.
57
+
58
+Archive a project you are done with in **Settings → Projects**. It leaves the project pickers.
59
+Its threads, settings, and files stay as they are, and archived projects still show in the
60
+Settings project list, marked **Archived**. Choose one there and select **Unarchive** to bring it
61
+back. On mobile, both are in **Settings → Projects → Organize**.
62
+
63
+A project on several machines must have every machine connected to pin or archive it.
64
+
65
## Worktree branch names
66
67
In **Settings → Worktrees → Worktree branch naming**, choose a static prefix,
docs/user/thread-sidebar.md
+7
-6
@@ -148,12 +148,13 @@ cannot drag or move threads within it. Your saved order returns when you turn it
148
### Group threads by project (beta)
149
150
Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active
151
-threads in a folder for each project. A project with no active threads has no folder until you
152
-pick it in the project filter. Click a folder to open or close it. A closed folder shows how
153
-many threads it holds, and a dot when one of them needs you. Use the pen button on a folder, or
154
-right-click it, to start a thread in that project. Pinned threads stay above the folders, and
155
-Snoozed and Settled stay below them. In this mode you cannot drag threads, and the Working section
156
-is off. Each device keeps its own choice.
151
+threads in a folder for each project. Pinned projects come first. A project with no active
152
+threads has no folder unless it is pinned or you pick it in the project filter. An archived
153
+project's folder comes last and shows only while it has active threads. Click a folder to open or
154
+close it. A closed folder shows how many threads it holds, and a dot when one of them
155
+needs you. Use the pen button on a folder, or right-click it, to start a thread in that project.
156
+Pinned threads stay above the folders, and Snoozed and Settled stay below them. In this mode you
157
+cannot drag threads, and the Working section is off. Each device keeps its own choice.
158
159
## Settle finished work
160
evals/mcp-tool-use/cases/projects.ndjson
new
+1
@@ -0,0 +1 @@
1
+{"id": "archive-project-not-delete", "area": "projects", "kind": "guard", "pattern": "archive a project by deleting it", "experience": "Projects gained an archive flag. Asked to archive a finished project, an agent must set archived, not remove the project and its threads.", "rule": "t3_project_update archived: Threads and files are kept.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-app", "title": "app", "workspaceRoot": "/home/dev/code/app", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-old-site", "title": "old-site", "workspaceRoot": "/home/dev/code/old-site", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-03-01T00:00:00.000Z", "updatedAt": "2026-04-02T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}}}, "prompt": "I'm done with the old-site project. Archive it in T3 Code so it stops showing up in my project pickers.", "expect": {"calls": [{"tool": "t3_project_update", "args": {"projectId": "project-old-site", "archived": true}}], "callsMustNot": [{"tool": "t3_project_delete"}, {"tool": "t3_project_update", "args": {"projectId": "project-app"}}]}, "maxSteps": 6}
packages/client-runtime/src/operations/commands.ts
+4
@@ -60,6 +60,8 @@ export interface UpdateProjectInput extends CommandMetadata {
60
readonly faviconPath?: string | null;
61
readonly defaultThreadEnvMode?: ThreadEnvMode | null;
62
readonly scripts?: ReadonlyArray<ProjectScript>;
63
+ readonly pinned?: boolean;
64
+ readonly archived?: boolean;
65
}
66
67
export interface DeleteProjectInput extends CommandMetadata {
@@ -375,6 +377,8 @@ export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(func
377
? {}
378
: { defaultThreadEnvMode: input.defaultThreadEnvMode }),
379
...(input.scripts === undefined ? {} : { scripts: input.scripts }),
380
+ ...(input.pinned === undefined ? {} : { pinned: input.pinned }),
381
+ ...(input.archived === undefined ? {} : { archived: input.archived }),
382
});
383
});
384
packages/client-runtime/src/state/projectGrouping.test.ts
+26
@@ -6,6 +6,7 @@ import { chooseLoadBalancedEnvironment } from "../load-balancing.ts";
6
import {
7
buildProjectGroups,
8
deriveLogicalProjectKeyFromSettings,
9
+ pickableProjectGroups,
10
derivePhysicalProjectKey,
11
resolveScratchProjectScopeKey,
12
sortProjectsByGroupOrder,
@@ -379,6 +380,31 @@ describe("buildProjectGroups", () => {
380
});
381
});
382
383
+describe("project pins and archives", () => {
384
+ const at = "2026-07-02T00:00:00.000Z";
385
+ const remote = EnvironmentId.make("remote");
386
+ const group = (...projects: EnvironmentProject[]) =>
387
+ buildProjectGroups({ projects, settings: settings("repository") })[0]!;
388
+
389
+ it("keeps a project visible while its machines disagree", () => {
390
+ const local = makeProject("local", "/work/t3code");
391
+ const other = makeProject("remote", "/work/t3code", { environmentId: remote });
392
+ const partial = group({ ...local, pinnedAt: at, archivedAt: at }, other);
393
+ expect(partial).toMatchObject({ pinned: true, archived: false });
394
+ expect(group({ ...local, archivedAt: at }, { ...other, archivedAt: at }).archived).toBe(true);
395
+ });
396
+
397
+ it("offers pinned projects first and leaves archived ones out", () => {
398
+ const pickable = pickableProjectGroups([
399
+ { key: "a", pinned: false, archived: false },
400
+ { key: "b", pinned: true, archived: true },
401
+ { key: "c", pinned: true, archived: false },
402
+ { key: "d", pinned: false, archived: true },
403
+ ]);
404
+ expect(pickable.map((entry) => entry.key)).toEqual(["c", "a"]);
405
+ });
406
+});
407
+
408
describe("sortProjectsByGroupOrder", () => {
409
const remote = EnvironmentId.make("remote");
410
const ref = (projectId: string, env = environmentId) => ({
packages/client-runtime/src/state/projectGrouping.ts
+13
@@ -242,6 +242,17 @@ export interface ProjectGroup<TProject extends EnvironmentProject = EnvironmentP
242
readonly representative: TProject;
243
readonly members: ReadonlyArray<ProjectGroupMember<TProject>>;
244
readonly memberProjectRefs: ReadonlyArray<ScopedProjectRef>;
245
+ /** Clients write every member together. When members still disagree, the project stays visible. */
246
+ readonly pinned: boolean;
247
+ readonly archived: boolean;
248
+}
249
+
250
+/** The groups a project picker offers: archived groups left out, pinned ones first. */
251
+export function pickableProjectGroups<
252
+ TGroup extends { readonly pinned: boolean; readonly archived: boolean },
253
+>(groups: ReadonlyArray<TGroup>): TGroup[] {
254
+ const open = groups.filter((group) => !group.archived);
255
+ return [...open.filter((group) => group.pinned), ...open.filter((group) => !group.pinned)];
256
}
257
258
function projectFreshnessTime(project: EnvironmentProject): number {
@@ -363,6 +374,8 @@ export function buildProjectGroups<TProject extends EnvironmentProject>(input: {
374
representative,
375
members,
376
memberProjectRefs: projectRefsByLogicalKey.get(key) ?? [],
377
+ pinned: members.some((member) => member.project.pinnedAt != null),
378
+ archived: members.every((member) => member.project.archivedAt != null),
379
};
380
});
381
}
packages/contracts/src/applicationEvent.ts
+2
@@ -60,6 +60,8 @@ export const ApplicationProjectMetaUpdatedPayload = Schema.Struct({
60
faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
61
projectIcon: Schema.optional(Schema.NullOr(StoredProjectIcon)),
62
scripts: Schema.optional(Schema.Array(ProjectScript)),
63
+ pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
64
+ archivedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
65
updatedAt: IsoDateTime,
66
});
67
export type ApplicationProjectMetaUpdatedPayload = typeof ApplicationProjectMetaUpdatedPayload.Type;
packages/contracts/src/environment.ts
+2
@@ -135,6 +135,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
135
/** Only explicit false skips Live Activity seeding; older servers may still publish. */
136
agentActivityPublishing: Schema.optionalKey(Schema.Boolean),
137
projectCloneTracking: Schema.optionalKey(Schema.Boolean),
138
+ /** Server keeps `pinned` and `archived` from project.update. Older servers drop them. */
139
+ projectOrganization: Schema.optionalKey(Schema.Boolean),
140
/** Server answers projects.listIgnoredFiles. */
141
ignoredFileListing: Schema.optionalKey(Schema.Boolean),
142
environmentIcon: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/orchestrationProject.ts
+3
@@ -17,6 +17,9 @@ export const OrchestrationProjectShell = Schema.Struct({
17
faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
18
projectIcon: Schema.optional(Schema.NullOr(ReceivedProjectIcon)),
19
scripts: Schema.Array(ProjectScript),
20
+ // Pinned projects lead project pickers; archived ones leave them. Optional so older servers decode.
21
+ pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
22
+ archivedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
23
createdAt: IsoDateTime,
24
updatedAt: IsoDateTime,
25
});
packages/contracts/src/project.ts
+8
@@ -161,6 +161,8 @@ export const Project = Schema.Struct({
161
// Opt-in because background sync performs network I/O and may move the checkout.
162
autoPull: Schema.optional(Schema.Boolean),
163
scripts: Schema.Array(ProjectScript),
164
+ pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
165
+ archivedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
166
createdAt: IsoDateTime,
167
updatedAt: IsoDateTime,
168
deletedAt: Schema.NullOr(IsoDateTime),
@@ -191,6 +193,12 @@ export const ProjectUpdatePayload = Schema.Struct({
193
faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
194
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
195
scripts: Schema.optional(Schema.Array(ProjectScript)),
196
+ pinned: Schema.optional(Schema.Boolean),
197
+ archived: Schema.optional(
198
+ Schema.Boolean.annotate({
199
+ description: "Threads and files are kept.",
200
+ }),
201
+ ),
202
});
203
export type ProjectUpdatePayload = typeof ProjectUpdatePayload.Type;
204