Share project edit form; add per-project default model (#2015)

* feat(chat): migrate history list to @tanstack/react-virtual with deterministic mobile history loading

- Replace virtua with @tanstack/react-virtual for chat history on all
  surfaces: bottom anchoring (anchorTo: end), key-stable prepend
  preservation, and native iOS touch/momentum deferral live in the core
- Patch virtual-core to clamp the render range to real scroll bounds
  during transient adjustments (OpenCode upstream parity)
- Rows render in normal flow inside a translated wrapper so sticky user
  headers keep working; measurement snapshots cached per session
- Pre-write container height in scrollToFn so the browser cannot clamp
  anchor corrections to the stale height; hold the prepend anchor for up
  to 180 frames on mobile while fresh rows settle (cancelled by user
  input; desktop relies on core anchoring alone)
- Adaptive row-size estimate from per-session measured averages; disable
  reveal fade-in for virtualized history rows
- Mobile loads older history only through an explicit localized top
  button: no scroll-position trigger and no post-mount background
  prepend, so every insert happens from a resting state; a quiet-window
  hold defers any stray prepend commit while a touch gesture is active
- Desktop/VS Code keep the seamless scroll-up trigger and progressive
  background prepend

* Share project edit form between settings and sidebar dialog

Extract ProjectIdentityFields and useProjectIdentityForm so the projects
settings page and sidebar Edit dialog share the same layout and behavior.
Rename the project menu action from Rename to Edit, and add per-project
default model selection for new chats with persistence and draft-session
resolution ahead of global defaults.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Unify project edit UI with shared ProjectIdentityEditor shell

Wrap header, fields, and inline Save changes button in one editor
component used identically by settings projects page and sidebar
dialog. Remove dialog-specific footer, title, and padding so both
surfaces render the same layout.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Include Actions and Worktree sections in project Edit dialog

Extract ProjectSettingsPanel with the full settings=projects content
(identity, actions, worktree) and render it from both the settings page
and sidebar Edit dialog. Keep the dialog open after identity save so
users can configure actions and worktrees without reopening.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Narrow project Edit dialog to modal-appropriate width

Use max-w-2xl instead of max-w-4xl so the popup does not inherit the
full settings page width.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Unify project settings subsections and auto-save all fields

- Add shared ProjectSettingsSubsection with consistent titles and dividers
- Auto-save identity, actions, and worktree setup commands (debounced)
- Remove Save changes and Save Actions buttons
- Split worktree into Worktree and Existing worktrees subsections
- Align controls to shared max width across all subsections

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Harden project settings auto-save error handling

- Only update worktree setup snapshot after successful save; toast on failure
- Toast when actions auto-save is blocked by validation for >1s

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Show toast when project identity auto-save fails

Wrap onSave in try/catch and surface settings.projects.page.toast.saveFailed
so rejected parent callbacks are not silently swallowed.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Fix clearing project default model from settings

Send null instead of undefined when no default model is selected so
updateProjectMeta enters the defaultModel branch and deletes the field.
Apply consistently in prepareSaveData, ProjectsPage, and SessionSidebar.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

---------

Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>
This commit is contained in:
Serhii Dziupin
2026-07-09 13:54:05 +03:00
committed by GitHub
co-authored by Serhii Dziupin Bohdan Triapitsyn Cursor Agent
parent 57ebaedada
commit a1aae30e66
36 changed files with 1362 additions and 1271 deletions
@@ -37,11 +37,17 @@ import {
PROJECT_ACTION_ICONS,
PROJECT_ACTIONS_UPDATED_EVENT,
} from '@/lib/projectActions';
import {
PROJECT_SETTINGS_CONTROL_WIDTH,
ProjectSettingsSubsection,
} from '@/components/sections/projects/ProjectSettingsSubsection';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
type EditableProjectAction = OpenChamberProjectAction;
const AUTO_SAVE_DELAY_MS = 450;
const createActionId = (): string => {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
@@ -68,9 +74,10 @@ export const ProjectActionsSection: React.FC<ProjectActionsSectionProps> = ({ pr
const [actions, setActions] = React.useState<EditableProjectAction[]>([]);
const [isLoading, setIsLoading] = React.useState(false);
const [isSaving, setIsSaving] = React.useState(false);
const [initialSnapshot, setInitialSnapshot] = React.useState<string | null>(null);
const [expandedActions, setExpandedActions] = React.useState<Record<string, boolean>>({});
const isSavingRef = React.useRef(false);
const validationToastShownRef = React.useRef<string | null>(null);
React.useEffect(() => {
if (!isDesktopShellApp) {
@@ -133,6 +140,69 @@ export const ProjectActionsSection: React.FC<ProjectActionsSectionProps> = ({ pr
return initialSnapshot !== JSON.stringify({ actions });
}, [actions, initialSnapshot]);
const persistActions = React.useCallback(async (nextActions: EditableProjectAction[]) => {
const ok = await saveProjectActionsState(projectRef, {
actions: nextActions,
primaryActionId: null,
});
if (!ok) {
toast.error(t('settings.projects.actions.toast.saveFailed'));
return false;
}
setInitialSnapshot(JSON.stringify({ actions: nextActions }));
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent(PROJECT_ACTIONS_UPDATED_EVENT, {
detail: { projectId: projectRef.id },
}));
}
return true;
}, [projectRef, t]);
React.useEffect(() => {
if (!hasChanges || isLoading || validationError || isSavingRef.current) {
return;
}
const timer = window.setTimeout(() => {
if (isSavingRef.current) {
return;
}
isSavingRef.current = true;
void (async () => {
try {
await persistActions(actions);
} finally {
isSavingRef.current = false;
}
})();
}, AUTO_SAVE_DELAY_MS);
return () => {
window.clearTimeout(timer);
};
}, [actions, hasChanges, isLoading, persistActions, validationError]);
React.useEffect(() => {
if (!hasChanges || !validationError || isLoading) {
if (!validationError) {
validationToastShownRef.current = null;
}
return;
}
const timer = window.setTimeout(() => {
if (validationToastShownRef.current === validationError) {
return;
}
validationToastShownRef.current = validationError;
toast.error(validationError);
}, 1000);
return () => {
window.clearTimeout(timer);
};
}, [hasChanges, isLoading, validationError]);
const handleAddAction = React.useCallback(() => {
const nextAction = createEmptyAction();
setActions((prev) => [...prev, nextAction]);
@@ -155,275 +225,224 @@ export const ProjectActionsSection: React.FC<ProjectActionsSectionProps> = ({ pr
setActions((prev) => prev.map((entry) => (entry.id === id ? updater(entry) : entry)));
}, []);
const handleSave = React.useCallback(async () => {
if (validationError) {
toast.error(validationError);
return;
}
setIsSaving(true);
try {
const ok = await saveProjectActionsState(projectRef, {
actions,
primaryActionId: null,
});
if (!ok) {
toast.error(t('settings.projects.actions.toast.saveFailed'));
return;
}
setInitialSnapshot(JSON.stringify({ actions }));
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent(PROJECT_ACTIONS_UPDATED_EVENT, {
detail: { projectId: projectRef.id },
}));
}
toast.success(t('settings.projects.actions.toast.saved'));
} catch {
toast.error(t('settings.projects.actions.toast.saveFailed'));
} finally {
setIsSaving(false);
}
}, [actions, projectRef, t, validationError]);
const canSave = !isSaving && !isLoading && hasChanges && !validationError;
return (
<div className="mb-8">
<div className="mb-1 flex items-start justify-between gap-2">
<div>
<h3 className="typography-ui-header font-medium text-foreground">{t('settings.projects.actions.title')}</h3>
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.description')}</p>
</div>
<ProjectSettingsSubsection
title={t('settings.projects.actions.title')}
description={t('settings.projects.actions.description')}
settingsItem="projects.actions"
headerAction={(
<Button type="button" variant="outline" size="xs" className="!font-normal" onClick={handleAddAction}>
<Icon name="add" className="h-3.5 w-3.5" />
{t('settings.projects.actions.actions.add')}
</Button>
</div>
<section className="pb-2 pt-0 space-y-2">
{isLoading ? (
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.loading')}</p>
) : actions.length === 0 ? (
<div className="py-2">
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.empty')}</p>
</div>
) : (
<div className="space-y-0 max-w-[30rem]">
{actions.map((action) => {
const selectedIconKey = (action.icon as keyof typeof PROJECT_ACTION_ICON_MAP) || 'play';
const selectedIconName = PROJECT_ACTION_ICON_MAP[selectedIconKey] || 'play';
const isOpen = expandedActions[action.id] ?? false;
const title = action.name.trim() || t('settings.projects.actions.state.untitled');
return (
<Collapsible
key={action.id}
open={isOpen}
onOpenChange={(open) => {
setExpandedActions((prev) => ({
...prev,
[action.id]: open,
}));
}}
className={cn(
'py-1.5'
)}
>
<div className="flex items-start gap-2">
<CollapsibleTrigger className="group flex-1 justify-start gap-2 rounded-md px-0 pr-1 py-1 hover:bg-[var(--interactive-hover)] focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]">
{isOpen ? (
<Icon name="arrow-down-s" className="h-4 w-4 text-muted-foreground" />
) : (
<Icon name="arrow-right-s" className="h-4 w-4 text-muted-foreground" />
)}
<Icon name={selectedIconName} className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="typography-ui-label text-foreground truncate">{title}</span>
</div>
</div>
</CollapsibleTrigger>
<Button
type="button"
variant="ghost"
size="xs"
className="!font-normal h-7 w-7 px-0 text-muted-foreground hover:text-[var(--status-error)]"
onClick={() => handleRemoveAction(action.id)}
>
<Icon name="delete-bin" className="h-3.5 w-3.5" />
</Button>
</div>
<CollapsibleContent className="pt-1.5">
<div className="space-y-2 pb-6 pl-3 pr-3">
<div className="flex items-center gap-2 py-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]"
aria-label={t('settings.projects.actions.field.selectIconAria')}
>
<Icon name={selectedIconName} className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56 p-2">
<div className="grid grid-cols-6 gap-1">
{PROJECT_ACTION_ICONS.map((entry) => {
const iconName = entry.Icon;
const selected = (action.icon || 'play') === entry.key;
return (
<button
key={entry.key}
type="button"
onClick={() => updateAction(action.id, (current) => ({ ...current, icon: entry.key }))}
className={cn(
'inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]',
selected && 'border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]'
)}
aria-label={t('settings.projects.actions.field.iconAria', { icon: entry.label })}
>
<Icon name={iconName} className="h-4 w-4" />
</button>
);
})}
</div>
</DropdownMenuContent>
</DropdownMenu>
<Input
value={action.name}
onChange={(event) => updateAction(action.id, (current) => ({ ...current, name: event.target.value }))}
placeholder={t('settings.projects.actions.field.actionNamePlaceholder')}
className="h-7 max-w-[14rem]"
/>
</div>
<div className="py-1">
<p className="typography-meta mb-0.5 text-muted-foreground">{t('settings.projects.actions.field.command')}</p>
<Textarea
value={action.command}
onChange={(event) => updateAction(action.id, (current) => ({ ...current, command: event.target.value }))}
placeholder={t('settings.projects.actions.field.commandPlaceholder')}
className="min-h-[88px] max-w-[30rem] font-mono text-xs"
/>
</div>
<div className="py-1">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<span className="typography-ui-label text-foreground">{t('settings.projects.actions.field.autoOpenUrl')}</span>
<div
className="group flex cursor-pointer items-center gap-2"
role="button"
tabIndex={0}
aria-pressed={action.autoOpenUrl === true}
onClick={() => updateAction(action.id, (current) => ({
...current,
...(current.autoOpenUrl === true ? { autoOpenUrl: undefined } : { autoOpenUrl: true }),
}))}
onKeyDown={(event) => {
if (event.key === ' ' || event.key === 'Enter') {
event.preventDefault();
updateAction(action.id, (current) => ({
...current,
...(current.autoOpenUrl === true ? { autoOpenUrl: undefined } : { autoOpenUrl: true }),
}));
}
}}
>
<Checkbox
checked={action.autoOpenUrl === true}
onChange={(checked) => updateAction(action.id, (current) => ({
...current,
...(checked ? { autoOpenUrl: true } : { autoOpenUrl: undefined }),
}))}
ariaLabel={t('settings.projects.actions.field.autoOpenUrlForAria', { title })}
/>
<span className="typography-ui-label font-normal text-foreground/80">{t('settings.projects.actions.field.autoOpenUrlDescription')}</span>
</div>
</div>
{action.autoOpenUrl === true ? (
<div className="mt-1">
<div className="flex items-center gap-2">
<Input
value={action.openUrl || ''}
onChange={(event) => updateAction(action.id, (current) => ({
...current,
openUrl: event.target.value,
}))}
placeholder={t('settings.projects.actions.field.overrideUrlPlaceholder')}
className="h-7 w-full max-w-[24rem]"
/>
<Tooltip>
<TooltipTrigger asChild>
<Icon name="information" className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{t('settings.projects.actions.field.overrideUrlTooltip')}
</TooltipContent>
</Tooltip>
</div>
{isDesktopShellApp ? (
<div className="mt-2">
<p className="typography-meta mb-0.5 text-muted-foreground">{t('settings.projects.actions.field.desktopSshForward')}</p>
{desktopForwardOptions.length > 0 ? (
<Select
value={
action.desktopOpenSshForward && desktopForwardOptions.some((entry) => entry.id === action.desktopOpenSshForward)
? action.desktopOpenSshForward
: '__none__'
}
onValueChange={(value) => {
updateAction(action.id, (current) => ({
...current,
...(value === '__none__' ? { desktopOpenSshForward: undefined } : { desktopOpenSshForward: value }),
}));
}}
>
<SelectTrigger className="h-7 w-full max-w-[30rem]">
<SelectValue placeholder={t('settings.projects.actions.field.useOutputManualUrl')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">{t('settings.projects.actions.field.useOutputManualUrl')}</SelectItem>
{desktopForwardOptions.map((entry) => (
<SelectItem key={entry.id} value={entry.id}>{entry.label}</SelectItem>
))}
</SelectContent>
</Select>
) : (
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.noDesktopSshForwards')}</p>
)}
</div>
) : null}
</div>
) : null}
</div>
)}
contentClassName="space-y-0"
>
{isLoading ? (
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.loading')}</p>
) : actions.length === 0 ? (
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.empty')}</p>
) : (
<div className={cn('space-y-0', PROJECT_SETTINGS_CONTROL_WIDTH)}>
{actions.map((action) => {
const selectedIconKey = (action.icon as keyof typeof PROJECT_ACTION_ICON_MAP) || 'play';
const selectedIconName = PROJECT_ACTION_ICON_MAP[selectedIconKey] || 'play';
const isOpen = expandedActions[action.id] ?? false;
const title = action.name.trim() || t('settings.projects.actions.state.untitled');
return (
<Collapsible
key={action.id}
open={isOpen}
onOpenChange={(open) => {
setExpandedActions((prev) => ({
...prev,
[action.id]: open,
}));
}}
className="py-1.5"
>
<div className="flex items-start gap-2">
<CollapsibleTrigger className="group flex-1 justify-start gap-2 rounded-md px-0 pr-1 py-1 hover:bg-[var(--interactive-hover)] focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]">
{isOpen ? (
<Icon name="arrow-down-s" className="h-4 w-4 text-muted-foreground" />
) : (
<Icon name="arrow-right-s" className="h-4 w-4 text-muted-foreground" />
)}
<Icon name={selectedIconName} className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<span className="typography-ui-label text-foreground truncate">{title}</span>
</div>
</CollapsibleContent>
</Collapsible>
);
})}
</div>
)}
</CollapsibleTrigger>
<div className="pt-3">
{validationError ? (
<p className="typography-meta mb-2 text-[var(--status-warning)]">{validationError}</p>
) : null}
<Button
type="button"
size="xs"
className="!font-normal"
onClick={handleSave}
disabled={!canSave}
>
{isSaving ? t('settings.common.actions.saving') : t('settings.projects.actions.actions.save')}
</Button>
<Button
type="button"
variant="ghost"
size="xs"
className="!font-normal h-7 w-7 px-0 text-muted-foreground hover:text-[var(--status-error)]"
onClick={() => handleRemoveAction(action.id)}
>
<Icon name="delete-bin" className="h-3.5 w-3.5" />
</Button>
</div>
<CollapsibleContent className="pt-1.5">
<div className="space-y-2 pb-4 pl-3 pr-1">
<div className="flex items-center gap-2 py-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]"
aria-label={t('settings.projects.actions.field.selectIconAria')}
>
<Icon name={selectedIconName} className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56 p-2">
<div className="grid grid-cols-6 gap-1">
{PROJECT_ACTION_ICONS.map((entry) => {
const iconName = entry.Icon;
const selected = (action.icon || 'play') === entry.key;
return (
<button
key={entry.key}
type="button"
onClick={() => updateAction(action.id, (current) => ({ ...current, icon: entry.key }))}
className={cn(
'inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]',
selected && 'border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]'
)}
aria-label={t('settings.projects.actions.field.iconAria', { icon: entry.label })}
>
<Icon name={iconName} className="h-4 w-4" />
</button>
);
})}
</div>
</DropdownMenuContent>
</DropdownMenu>
<Input
value={action.name}
onChange={(event) => updateAction(action.id, (current) => ({ ...current, name: event.target.value }))}
placeholder={t('settings.projects.actions.field.actionNamePlaceholder')}
className="h-7 flex-1 min-w-0"
/>
</div>
<div className="py-1">
<p className="typography-meta mb-0.5 text-muted-foreground">{t('settings.projects.actions.field.command')}</p>
<Textarea
value={action.command}
onChange={(event) => updateAction(action.id, (current) => ({ ...current, command: event.target.value }))}
placeholder={t('settings.projects.actions.field.commandPlaceholder')}
className="min-h-[88px] w-full font-mono text-xs"
/>
</div>
<div className="py-1">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<span className="typography-ui-label text-foreground">{t('settings.projects.actions.field.autoOpenUrl')}</span>
<div
className="group flex cursor-pointer items-center gap-2"
role="button"
tabIndex={0}
aria-pressed={action.autoOpenUrl === true}
onClick={() => updateAction(action.id, (current) => ({
...current,
...(current.autoOpenUrl === true ? { autoOpenUrl: undefined } : { autoOpenUrl: true }),
}))}
onKeyDown={(event) => {
if (event.key === ' ' || event.key === 'Enter') {
event.preventDefault();
updateAction(action.id, (current) => ({
...current,
...(current.autoOpenUrl === true ? { autoOpenUrl: undefined } : { autoOpenUrl: true }),
}));
}
}}
>
<Checkbox
checked={action.autoOpenUrl === true}
onChange={(checked) => updateAction(action.id, (current) => ({
...current,
...(checked ? { autoOpenUrl: true } : { autoOpenUrl: undefined }),
}))}
ariaLabel={t('settings.projects.actions.field.autoOpenUrlForAria', { title })}
/>
<span className="typography-ui-label font-normal text-foreground/80">{t('settings.projects.actions.field.autoOpenUrlDescription')}</span>
</div>
</div>
{action.autoOpenUrl === true ? (
<div className="mt-1">
<div className="flex items-center gap-2">
<Input
value={action.openUrl || ''}
onChange={(event) => updateAction(action.id, (current) => ({
...current,
openUrl: event.target.value,
}))}
placeholder={t('settings.projects.actions.field.overrideUrlPlaceholder')}
className="h-7 w-full max-w-[24rem]"
/>
<Tooltip>
<TooltipTrigger asChild>
<Icon name="information" className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{t('settings.projects.actions.field.overrideUrlTooltip')}
</TooltipContent>
</Tooltip>
</div>
{isDesktopShellApp ? (
<div className="mt-2">
<p className="typography-meta mb-0.5 text-muted-foreground">{t('settings.projects.actions.field.desktopSshForward')}</p>
{desktopForwardOptions.length > 0 ? (
<Select
value={
action.desktopOpenSshForward && desktopForwardOptions.some((entry) => entry.id === action.desktopOpenSshForward)
? action.desktopOpenSshForward
: '__none__'
}
onValueChange={(value) => {
updateAction(action.id, (current) => ({
...current,
...(value === '__none__' ? { desktopOpenSshForward: undefined } : { desktopOpenSshForward: value }),
}));
}}
>
<SelectTrigger className="h-7 w-full">
<SelectValue placeholder={t('settings.projects.actions.field.useOutputManualUrl')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">{t('settings.projects.actions.field.useOutputManualUrl')}</SelectItem>
{desktopForwardOptions.map((entry) => (
<SelectItem key={entry.id} value={entry.id}>{entry.label}</SelectItem>
))}
</SelectContent>
</Select>
) : (
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.noDesktopSshForwards')}</p>
)}
</div>
) : null}
</div>
) : null}
</div>
</div>
</CollapsibleContent>
</Collapsible>
);
})}
</div>
</section>
</div>
)}
{validationError && actions.length > 0 ? (
<p className="typography-meta text-[var(--status-warning)]">{validationError}</p>
) : null}
</ProjectSettingsSubsection>
);
};
@@ -0,0 +1,286 @@
import React from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/icon/Icon';
import { ModelSelector } from '@/components/sections/agents/ModelSelector';
import { PROJECT_COLORS, PROJECT_ICONS, PROJECT_COLOR_MAP as COLOR_MAP, ProjectIconImage } from '@/lib/projectMeta';
import { useThemeSystem } from '@/contexts/useThemeSystem';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
import {
PROJECT_SETTINGS_CONTROL_WIDTH,
ProjectSettingsSubsection,
} from '@/components/sections/projects/ProjectSettingsSubsection';
import type { useProjectIdentityForm } from './useProjectIdentityForm';
type ProjectIdentityFormState = ReturnType<typeof useProjectIdentityForm>;
type ProjectIdentityFieldsProps = {
form: ProjectIdentityFormState;
};
export const ProjectIdentityFields: React.FC<ProjectIdentityFieldsProps> = ({ form }) => {
const { t } = useI18n();
const { currentTheme } = useThemeSystem();
const {
name,
setName,
icon,
setIcon,
color,
setColor,
iconBackground,
setIconBackground,
parsedDefaultModel,
handleDefaultModelChange,
isUploadingIcon,
isRemovingCustomIcon,
isDiscoveringIcon,
pendingRemoveImageIcon,
setPendingRemoveImageIcon,
pendingUploadIconPreviewUrl,
setPreviewImageFailed,
hasPendingUploadImageIcon,
hasCustomIcon,
effectiveHasImageIcon,
hasRemovableImageIcon,
showImagePreview,
fileInputRef,
handleUploadIcon,
handleRemoveImageIcon,
handleDiscoverIcon,
currentIconImage,
project,
} = form;
if (!project) {
return null;
}
const currentColorVar = color ? (COLOR_MAP[color] ?? null) : null;
return (
<>
<ProjectSettingsSubsection
title={t('settings.projects.page.field.projectName')}
settingsItem="projects.name"
>
<Input
value={name}
onChange={(event) => setName(event.target.value)}
placeholder={t('settings.projects.page.field.projectNamePlaceholder')}
className={cn('h-7', PROJECT_SETTINGS_CONTROL_WIDTH)}
/>
</ProjectSettingsSubsection>
<ProjectSettingsSubsection
title={t('settings.projects.page.field.defaultModel')}
description={t('settings.projects.page.field.defaultModelDescription')}
settingsItem="projects.default-model"
>
<ModelSelector
providerId={parsedDefaultModel.providerId}
modelId={parsedDefaultModel.modelId}
onChange={handleDefaultModelChange}
className={PROJECT_SETTINGS_CONTROL_WIDTH}
/>
</ProjectSettingsSubsection>
<ProjectSettingsSubsection
title={t('settings.projects.page.field.accentColor')}
settingsItem="projects.accent-color"
>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setColor(null)}
className={cn(
'h-7 w-7 rounded-md border transition-colors flex items-center justify-center',
color === null
? 'border-2 border-foreground bg-[var(--primary-base)]/10'
: 'border-border/40 hover:border-border hover:bg-[var(--surface-muted)]',
)}
title={t('settings.projects.page.field.none')}
>
<Icon name="close" className="h-4 w-4 text-muted-foreground" />
</button>
{PROJECT_COLORS.map((entry) => (
<button
key={entry.key}
type="button"
onClick={() => setColor(entry.key)}
className={cn(
'h-7 w-7 rounded-md border transition-colors',
color === entry.key
? 'border-2 border-foreground ring-1 ring-[var(--primary-base)]/40'
: 'border-transparent hover:border-border/70',
)}
style={{ backgroundColor: entry.cssVar }}
title={entry.label}
/>
))}
</div>
</ProjectSettingsSubsection>
<ProjectSettingsSubsection
title={t('settings.projects.page.field.projectIcon')}
settingsItem="projects.icon"
>
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg"
className="hidden"
onChange={(event) => {
const file = event.target.files?.[0] ?? null;
void handleUploadIcon(file);
event.currentTarget.value = '';
}}
/>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setIcon(null)}
className={cn(
'h-7 w-7 rounded-md border transition-colors flex items-center justify-center',
icon === null
? 'border-2 border-foreground bg-[var(--primary-base)]/10'
: 'border-border/40 hover:border-border hover:bg-[var(--surface-muted)]',
)}
title={t('settings.projects.page.field.none')}
>
<Icon name="close" className="h-4 w-4 text-muted-foreground" />
</button>
{PROJECT_ICONS.map((entry) => {
const iconName = entry.Icon;
return (
<button
key={entry.key}
type="button"
onClick={() => setIcon(entry.key)}
className={cn(
'h-7 w-7 rounded-md border transition-colors flex items-center justify-center',
icon === entry.key
? 'border-2 border-foreground bg-[var(--primary-base)]/10'
: 'border-transparent hover:border-border hover:bg-[var(--surface-muted)]',
)}
title={entry.label}
>
<Icon
name={iconName}
className="w-4 h-4"
style={currentColorVar && icon === entry.key ? { color: currentColorVar } : undefined}
/>
</button>
);
})}
</div>
{effectiveHasImageIcon && showImagePreview && (
<div className="flex items-center gap-2 pt-1">
<span className="typography-meta text-muted-foreground">{t('settings.projects.page.field.preview')}</span>
<span className="inline-flex h-7 w-7 items-center justify-center rounded-md border border-border/60 bg-[var(--surface-elevated)] p-1">
<span
className="inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]"
style={iconBackground ? { backgroundColor: iconBackground } : undefined}
>
{hasPendingUploadImageIcon && pendingUploadIconPreviewUrl ? (
<img
src={pendingUploadIconPreviewUrl}
alt=""
className="h-full w-full object-contain"
draggable={false}
onError={() => setPreviewImageFailed(true)}
/>
) : (
<ProjectIconImage
project={{ ...project, iconImage: currentIconImage ?? project.iconImage }}
options={{
themeVariant: currentTheme.metadata.variant,
iconColor: currentTheme.colors.surface.foreground,
}}
className="h-full w-full object-contain"
onError={() => setPreviewImageFailed(true)}
/>
)}
</span>
</span>
</div>
)}
{effectiveHasImageIcon && (
<div className="flex flex-wrap items-center gap-2">
<input
type="color"
value={iconBackground ?? '#000000'}
onChange={(event) => setIconBackground(event.target.value)}
className="h-7 w-9 cursor-pointer rounded border border-border bg-transparent p-1"
aria-label={t('settings.projects.page.field.projectIconBackgroundAria')}
/>
<Input
value={iconBackground ?? ''}
onChange={(event) => setIconBackground(event.target.value)}
placeholder="#000000"
className="h-7 w-[8rem]"
/>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => setIconBackground(null)}
className="h-7 w-7 p-0"
aria-label={t('settings.projects.page.field.clearIconBackgroundAria')}
title={t('settings.projects.page.field.clearBackground')}
disabled={!iconBackground}
>
<Icon name="close" className="h-3.5 w-3.5" />
</Button>
</div>
)}
<div className="flex flex-wrap items-center gap-2">
{!hasCustomIcon && (
<>
<Button
size="xs"
className="h-6 !font-normal"
onClick={() => fileInputRef.current?.click()}
disabled={isUploadingIcon}
>
{isUploadingIcon ? t('settings.projects.page.actions.uploading') : t('settings.projects.page.actions.uploadIcon')}
</Button>
<Button
size="xs"
className="h-6 !font-normal"
variant="outline"
onClick={() => void handleDiscoverIcon()}
disabled={isDiscoveringIcon}
>
{isDiscoveringIcon ? t('settings.projects.page.actions.discovering') : t('settings.projects.page.actions.discoverFavicon')}
</Button>
</>
)}
{hasRemovableImageIcon && (
<Button
size="xs"
className="!font-normal"
variant="outline"
onClick={() => void handleRemoveImageIcon()}
disabled={isRemovingCustomIcon}
>
{isRemovingCustomIcon ? t('settings.projects.page.actions.removing') : t('settings.projects.page.actions.removeProjectIcon')}
</Button>
)}
{pendingRemoveImageIcon && (
<Button
size="xs"
className="!font-normal"
variant="outline"
onClick={() => setPendingRemoveImageIcon(false)}
disabled={isRemovingCustomIcon}
>
{t('settings.projects.page.actions.undoRemove')}
</Button>
)}
</div>
</ProjectSettingsSubsection>
</>
);
};
@@ -0,0 +1,60 @@
import React from 'react';
import { WorktreeSectionContent } from '@/components/sections/openchamber/WorktreeSectionContent';
import { ProjectActionsSection } from '@/components/sections/projects/ProjectActionsSection';
import { ProjectIdentityFields } from '@/components/sections/projects/ProjectIdentityFields';
import {
useProjectIdentityForm,
type ProjectIdentitySaveData,
} from '@/components/sections/projects/useProjectIdentityForm';
import { useProjectIdentityAutoSave } from '@/components/sections/projects/useProjectIdentityAutoSave';
import type { ProjectEntry } from '@/lib/api/types';
import { useI18n } from '@/lib/i18n';
type ProjectSettingsPanelProps = {
project: ProjectEntry | null;
onIdentitySave: (data: ProjectIdentitySaveData) => void | Promise<void>;
};
export const ProjectSettingsPanel: React.FC<ProjectSettingsPanelProps> = ({
project,
onIdentitySave,
}) => {
const { t } = useI18n();
const form = useProjectIdentityForm(project);
const projectRef = React.useMemo(() => {
if (!project) {
return null;
}
return { id: project.id, path: project.path };
}, [project]);
const handleIdentitySave = React.useCallback(async (data: ProjectIdentitySaveData) => {
await onIdentitySave(data);
}, [onIdentitySave]);
useProjectIdentityAutoSave(form, handleIdentitySave);
if (!project || !projectRef) {
return null;
}
const headerLabel = project.label ?? t('settings.projects.page.title.default');
return (
<div className="space-y-0">
<div className="mb-5 px-1">
<h2 className="typography-ui-header font-semibold text-foreground truncate">
{headerLabel}
</h2>
<p className="typography-meta text-muted-foreground truncate" title={project.path}>
{project.path}
</p>
</div>
<ProjectIdentityFields form={form} />
<ProjectActionsSection projectRef={projectRef} />
<WorktreeSectionContent projectRef={projectRef} />
</div>
);
};
@@ -0,0 +1,47 @@
import React from 'react';
import { cn } from '@/lib/utils';
export const PROJECT_SETTINGS_CONTROL_WIDTH = 'w-full max-w-[30rem]';
type ProjectSettingsSubsectionProps = {
title: string;
description?: string;
settingsItem?: string;
titleAccessory?: React.ReactNode;
headerAction?: React.ReactNode;
children: React.ReactNode;
className?: string;
contentClassName?: string;
};
export const ProjectSettingsSubsection: React.FC<ProjectSettingsSubsectionProps> = ({
title,
description,
settingsItem,
titleAccessory,
headerAction,
children,
className,
contentClassName,
}) => {
return (
<section
data-settings-item={settingsItem}
className={cn('border-b border-border/50 py-5 first:pt-0 last:border-b-0', className)}
>
<div className="mb-3 flex items-start justify-between gap-3 px-1">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h3 className="typography-ui-header font-medium text-foreground">{title}</h3>
{titleAccessory}
</div>
{description ? (
<p className="mt-0.5 typography-meta text-muted-foreground">{description}</p>
) : null}
</div>
{headerAction ? <div className="shrink-0">{headerAction}</div> : null}
</div>
<div className={cn('space-y-2 px-2', contentClassName)}>{children}</div>
</section>
);
};
@@ -1,28 +1,17 @@
import React from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { toast } from '@/components/ui';
import { cn } from '@/lib/utils';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useUIStore } from '@/stores/useUIStore';
import { PROJECT_COLORS, PROJECT_ICONS, PROJECT_COLOR_MAP as COLOR_MAP, ProjectIconImage } from '@/lib/projectMeta';
import { WorktreeSectionContent } from '@/components/sections/openchamber/WorktreeSectionContent';
import { ProjectActionsSection } from '@/components/sections/projects/ProjectActionsSection';
import { Icon } from "@/components/icon/Icon";
import { useThemeSystem } from '@/contexts/useThemeSystem';
import { ProjectSettingsPanel } from '@/components/sections/projects/ProjectSettingsPanel';
import type { ProjectIdentitySaveData } from '@/components/sections/projects/useProjectIdentityForm';
import { useI18n } from '@/lib/i18n';
export const ProjectsPage: React.FC = () => {
const { t } = useI18n();
const projects = useProjectsStore((state) => state.projects);
const updateProjectMeta = useProjectsStore((state) => state.updateProjectMeta);
const uploadProjectIcon = useProjectsStore((state) => state.uploadProjectIcon);
const removeProjectIcon = useProjectsStore((state) => state.removeProjectIcon);
const discoverProjectIcon = useProjectsStore((state) => state.discoverProjectIcon);
const selectedId = useUIStore((state) => state.settingsProjectsSelectedId);
const setSelectedId = useUIStore((state) => state.setSettingsProjectsSelectedId);
const { currentTheme } = useThemeSystem();
const selectedProject = React.useMemo(() => {
if (!selectedId) return null;
@@ -40,194 +29,16 @@ export const ProjectsPage: React.FC = () => {
setSelectedId(projects[0].id);
}, [projects, selectedId, setSelectedId]);
const [name, setName] = React.useState('');
const [icon, setIcon] = React.useState<string | null>(null);
const [color, setColor] = React.useState<string | null>(null);
const [iconBackground, setIconBackground] = React.useState<string | null>(null);
const [isUploadingIcon, setIsUploadingIcon] = React.useState(false);
const [isRemovingCustomIcon, setIsRemovingCustomIcon] = React.useState(false);
const [isDiscoveringIcon, setIsDiscoveringIcon] = React.useState(false);
const [pendingRemoveImageIcon, setPendingRemoveImageIcon] = React.useState(false);
const [pendingUploadIconFile, setPendingUploadIconFile] = React.useState<File | null>(null);
const [pendingUploadIconPreviewUrl, setPendingUploadIconPreviewUrl] = React.useState<string | null>(null);
const [previewImageFailed, setPreviewImageFailed] = React.useState(false);
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const clearPendingUploadIcon = React.useCallback(() => {
setPendingUploadIconFile(null);
setPendingUploadIconPreviewUrl((previousUrl) => {
if (previousUrl) {
URL.revokeObjectURL(previousUrl);
}
return null;
});
}, []);
const selectedProjectRef = React.useMemo(() => {
if (!selectedProject) {
return null;
}
return { id: selectedProject.id, path: selectedProject.path };
}, [selectedProject]);
React.useEffect(() => {
if (!selectedProject) {
setName('');
setIcon(null);
setColor(null);
setIconBackground(null);
return;
}
setName(selectedProject.label ?? '');
setIcon(selectedProject.icon ?? null);
setColor(selectedProject.color ?? null);
setIconBackground(selectedProject.iconBackground ?? null);
setPendingRemoveImageIcon(false);
clearPendingUploadIcon();
setPreviewImageFailed(false);
}, [selectedProject, clearPendingUploadIcon]);
React.useEffect(() => {
return () => {
clearPendingUploadIcon();
};
}, [clearPendingUploadIcon]);
const hasChanges = Boolean(selectedProject) && (
name.trim() !== (selectedProject?.label ?? '').trim()
|| icon !== (selectedProject?.icon ?? null)
|| color !== (selectedProject?.color ?? null)
|| iconBackground !== (selectedProject?.iconBackground ?? null)
|| pendingRemoveImageIcon
|| Boolean(pendingUploadIconFile)
);
const handleSave = React.useCallback(async () => {
const handleIdentitySave = React.useCallback(async (data: ProjectIdentitySaveData) => {
if (!selectedProject) return;
if (pendingUploadIconFile) {
setIsUploadingIcon(true);
const uploadResult = await uploadProjectIcon(selectedProject.id, pendingUploadIconFile);
setIsUploadingIcon(false);
if (!uploadResult.ok) {
toast.error(uploadResult.error || t('settings.projects.page.toast.uploadIconFailed'));
return;
}
toast.success(t('settings.projects.page.toast.iconUpdated'));
clearPendingUploadIcon();
setPendingRemoveImageIcon(false);
}
const willRemoveImageIcon = pendingRemoveImageIcon && Boolean(selectedProject.iconImage);
if (willRemoveImageIcon) {
setIsRemovingCustomIcon(true);
const removeResult = await removeProjectIcon(selectedProject.id);
setIsRemovingCustomIcon(false);
if (!removeResult.ok) {
toast.error(removeResult.error || t('settings.projects.page.toast.removeIconFailed'));
return;
}
toast.success(t('settings.projects.page.toast.iconRemoved'));
setPendingRemoveImageIcon(false);
setIconBackground(null);
}
updateProjectMeta(selectedProject.id, {
label: name.trim(),
icon,
color,
iconBackground: willRemoveImageIcon ? null : iconBackground,
label: data.label,
icon: data.icon,
color: data.color,
iconBackground: data.iconBackground,
defaultModel: data.defaultModel ?? null,
});
}, [
color,
icon,
iconBackground,
name,
pendingUploadIconFile,
pendingRemoveImageIcon,
clearPendingUploadIcon,
uploadProjectIcon,
removeProjectIcon,
selectedProject,
t,
updateProjectMeta,
]);
const currentColorVar = color ? (COLOR_MAP[color] ?? null) : null;
const hasStoredImageIcon = Boolean(selectedProject?.iconImage);
const hasPendingUploadImageIcon = Boolean(pendingUploadIconFile && pendingUploadIconPreviewUrl);
const hasCustomIcon = selectedProject?.iconImage?.source === 'custom';
const effectiveHasImageIcon = (hasStoredImageIcon && !pendingRemoveImageIcon) || hasPendingUploadImageIcon;
const hasRemovableImageIcon = effectiveHasImageIcon;
const showStoredImagePreview = Boolean(selectedProject && hasStoredImageIcon && !pendingRemoveImageIcon);
const showImagePreview = !previewImageFailed && (hasPendingUploadImageIcon || showStoredImagePreview);
const handleUploadIcon = React.useCallback((file: File | null) => {
if (!selectedProject || !file || isUploadingIcon) {
return;
}
setPendingRemoveImageIcon(false);
setPreviewImageFailed(false);
setPendingUploadIconFile(file);
setPendingUploadIconPreviewUrl((previousUrl) => {
if (previousUrl) {
URL.revokeObjectURL(previousUrl);
}
return URL.createObjectURL(file);
});
}, [isUploadingIcon, selectedProject]);
const handleRemoveImageIcon = React.useCallback(() => {
if (!selectedProject || !hasRemovableImageIcon || isRemovingCustomIcon) {
return;
}
if (hasPendingUploadImageIcon) {
clearPendingUploadIcon();
}
if (hasStoredImageIcon) {
setPendingRemoveImageIcon(true);
} else {
setPendingRemoveImageIcon(false);
}
setPreviewImageFailed(false);
}, [
clearPendingUploadIcon,
hasPendingUploadImageIcon,
hasRemovableImageIcon,
hasStoredImageIcon,
isRemovingCustomIcon,
selectedProject,
]);
const handleDiscoverIcon = React.useCallback(async () => {
if (!selectedProject || isDiscoveringIcon) {
return;
}
clearPendingUploadIcon();
setPendingRemoveImageIcon(false);
setPreviewImageFailed(false);
setIsDiscoveringIcon(true);
void discoverProjectIcon(selectedProject.id)
.then((result) => {
if (!result.ok) {
toast.error(result.error || t('settings.projects.page.toast.discoverIconFailed'));
return;
}
if (result.skipped) {
toast.success(t('settings.projects.page.toast.customIconAlreadySet'));
return;
}
toast.success(t('settings.projects.page.toast.iconDiscovered'));
})
.finally(() => {
setIsDiscoveringIcon(false);
});
}, [clearPendingUploadIcon, discoverProjectIcon, isDiscoveringIcon, selectedProject, t]);
}, [selectedProject, updateProjectMeta]);
if (!selectedProject) {
return (
@@ -238,268 +49,11 @@ export const ProjectsPage: React.FC = () => {
</ScrollableOverlay>
);
}
return (
<ScrollableOverlay outerClassName="h-full" className="w-full bg-background">
<div className="mx-auto w-full max-w-4xl p-3 sm:p-6 sm:pt-8">
{/* Top Header & Actions */}
<div className="mb-4 flex items-center justify-between gap-4">
<div className="min-w-0">
<h2 className="typography-ui-header font-semibold text-foreground truncate">
{selectedProject.label ?? t('settings.projects.page.title.default')}
</h2>
<p className="typography-meta text-muted-foreground truncate" title={selectedProject.path}>
{selectedProject.path}
</p>
</div>
</div>
{/* Identity Controls */}
<div className="mb-8">
<section className="px-2 pb-2 pt-0 space-y-0.5">
{/* Name */}
<div data-settings-item="projects.name" className="py-1.5">
<div className="flex min-w-0 flex-col">
<span className="typography-ui-label text-foreground">{t('settings.projects.page.field.projectName')}</span>
</div>
<div className="mt-1.5 flex min-w-0 items-center gap-2">
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t('settings.projects.page.field.projectNamePlaceholder')}
className="h-7 min-w-0 w-full sm:max-w-[19rem]"
/>
</div>
</div>
{/* Color */}
<div data-settings-item="projects.accent-color" className="py-1.5">
<div className="flex min-w-0 flex-col">
<span className="typography-ui-label text-foreground">{t('settings.projects.page.field.accentColor')}</span>
</div>
<div className="mt-1.5 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setColor(null)}
className={cn(
'h-7 w-7 rounded-md border transition-colors flex items-center justify-center',
color === null
? 'border-2 border-foreground bg-[var(--primary-base)]/10'
: 'border-border/40 hover:border-border hover:bg-[var(--surface-muted)]'
)}
title={t('settings.projects.page.field.none')}
>
<Icon name="close" className="h-4 w-4 text-muted-foreground" />
</button>
{PROJECT_COLORS.map((c) => (
<button
key={c.key}
type="button"
onClick={() => setColor(c.key)}
className={cn(
'h-7 w-7 rounded-md border transition-colors',
color === c.key
? 'border-2 border-foreground ring-1 ring-[var(--primary-base)]/40'
: 'border-transparent hover:border-border/70'
)}
style={{ backgroundColor: c.cssVar }}
title={c.label}
/>
))}
</div>
</div>
{/* Icon */}
<div data-settings-item="projects.icon" className="py-1.5">
<div className="flex min-w-0 flex-col">
<span className="typography-ui-label text-foreground">{t('settings.projects.page.field.projectIcon')}</span>
</div>
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg"
className="hidden"
onChange={(event) => {
const file = event.target.files?.[0] ?? null;
void handleUploadIcon(file);
event.currentTarget.value = '';
}}
/>
<div className="mt-1.5 flex max-w-[22rem] flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setIcon(null)}
className={cn(
'h-7 w-7 rounded-md border transition-colors flex items-center justify-center',
icon === null
? 'border-2 border-foreground bg-[var(--primary-base)]/10'
: 'border-border/40 hover:border-border hover:bg-[var(--surface-muted)]'
)}
title={t('settings.projects.page.field.none')}
>
<Icon name="close" className="h-4 w-4 text-muted-foreground" />
</button>
{PROJECT_ICONS.map((i) => {
const iconName = i.Icon;
return (
<button
key={i.key}
type="button"
onClick={() => setIcon(i.key)}
className={cn(
'h-7 w-7 rounded-md border transition-colors flex items-center justify-center',
icon === i.key
? 'border-2 border-foreground bg-[var(--primary-base)]/10'
: 'border-transparent hover:border-border hover:bg-[var(--surface-muted)]'
)}
title={i.label}
>
<Icon name={iconName} className="w-4 h-4" style={currentColorVar && icon === i.key ? { color: currentColorVar } : undefined} />
</button>
);
})}
</div>
{effectiveHasImageIcon && showImagePreview && (
<div className="mt-2 flex items-center gap-2">
<span className="typography-meta text-muted-foreground">{t('settings.projects.page.field.preview')}</span>
<span className="inline-flex h-7 w-7 items-center justify-center rounded-md border border-border/60 bg-[var(--surface-elevated)] p-1">
<span
className="inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]"
style={iconBackground ? { backgroundColor: iconBackground } : undefined}
>
{hasPendingUploadImageIcon && pendingUploadIconPreviewUrl ? (
<img
src={pendingUploadIconPreviewUrl}
alt=""
className="h-full w-full object-contain"
draggable={false}
onError={() => setPreviewImageFailed(true)}
/>
) : selectedProject ? (
<ProjectIconImage
project={selectedProject}
options={{
themeVariant: currentTheme.metadata.variant,
iconColor: currentTheme.colors.surface.foreground,
}}
className="h-full w-full object-contain"
onError={() => setPreviewImageFailed(true)}
/>
) : null}
</span>
</span>
</div>
)}
{effectiveHasImageIcon && (
<div className="mt-2 flex flex-wrap items-center gap-2">
<input
type="color"
value={iconBackground ?? '#000000'}
onChange={(event) => setIconBackground(event.target.value)}
className="h-7 w-9 cursor-pointer rounded border border-border bg-transparent p-1"
aria-label={t('settings.projects.page.field.projectIconBackgroundAria')}
/>
<Input
value={iconBackground ?? ''}
onChange={(event) => setIconBackground(event.target.value)}
placeholder="#000000"
className="h-7 w-[8rem]"
/>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => setIconBackground(null)}
className="h-7 w-7 p-0"
aria-label={t('settings.projects.page.field.clearIconBackgroundAria')}
title={t('settings.projects.page.field.clearBackground')}
disabled={!iconBackground}
>
<Icon name="close" className="h-3.5 w-3.5" />
</Button>
</div>
)}
<div className="mt-2 flex flex-wrap items-center gap-2">
{!hasCustomIcon && (
<>
<Button
size="xs"
className="h-6 !font-normal"
onClick={() => fileInputRef.current?.click()}
disabled={isUploadingIcon}
>
{isUploadingIcon ? t('settings.projects.page.actions.uploading') : t('settings.projects.page.actions.uploadIcon')}
</Button>
<Button
size="xs"
className="h-6 !font-normal"
variant="outline"
onClick={() => void handleDiscoverIcon()}
disabled={isDiscoveringIcon}
>
{isDiscoveringIcon ? t('settings.projects.page.actions.discovering') : t('settings.projects.page.actions.discoverFavicon')}
</Button>
</>
)}
{hasRemovableImageIcon && (
<Button
size="xs"
className="!font-normal"
variant="outline"
onClick={() => void handleRemoveImageIcon()}
disabled={isRemovingCustomIcon}
>
{isRemovingCustomIcon ? t('settings.projects.page.actions.removing') : t('settings.projects.page.actions.removeProjectIcon')}
</Button>
)}
{pendingRemoveImageIcon && (
<Button
size="xs"
className="!font-normal"
variant="outline"
onClick={() => setPendingRemoveImageIcon(false)}
disabled={isRemovingCustomIcon}
>
{t('settings.projects.page.actions.undoRemove')}
</Button>
)}
</div>
</div>
</section>
<div className="mt-0.5 px-2 py-1">
<Button
onClick={handleSave}
disabled={!hasChanges || name.trim().length === 0 || isUploadingIcon || isRemovingCustomIcon}
size="xs"
className="!font-normal"
>
{t('settings.common.actions.saveChanges')}
</Button>
</div>
</div>
{/* Worktree Group */}
<div data-settings-item="projects.worktree" className="mb-8">
<section className="px-2 pb-2 pt-0">
{selectedProjectRef && <ProjectActionsSection projectRef={selectedProjectRef} />}
</section>
</div>
{/* Worktree Group */}
<div className="mb-8">
<div className="mb-1 px-1">
<h3 className="typography-ui-header font-medium text-foreground">
{t('settings.projects.page.section.worktree')}
</h3>
</div>
<section className="px-2 pb-2 pt-0">
{selectedProjectRef && <WorktreeSectionContent projectRef={selectedProjectRef} />}
</section>
</div>
<ProjectSettingsPanel project={selectedProject} onIdentitySave={handleIdentitySave} />
</div>
</ScrollableOverlay>
);
@@ -0,0 +1,76 @@
import React from 'react';
import { toast } from '@/components/ui';
import { useI18n } from '@/lib/i18n';
import type { ProjectIdentitySaveData } from './useProjectIdentityForm';
import type { useProjectIdentityForm } from './useProjectIdentityForm';
type ProjectIdentityFormState = ReturnType<typeof useProjectIdentityForm>;
const AUTO_SAVE_DELAY_MS = 450;
export const useProjectIdentityAutoSave = (
form: ProjectIdentityFormState,
onSave: (data: ProjectIdentitySaveData) => void | Promise<void>,
) => {
const { t } = useI18n();
const {
hasChanges,
name,
icon,
color,
iconBackground,
defaultModel,
pendingRemoveImageIcon,
pendingUploadIconFile,
isUploadingIcon,
isRemovingCustomIcon,
prepareSaveData,
} = form;
const isSavingRef = React.useRef(false);
React.useEffect(() => {
if (!hasChanges || !name.trim() || isUploadingIcon || isRemovingCustomIcon || isSavingRef.current) {
return;
}
const timer = window.setTimeout(() => {
if (isSavingRef.current) {
return;
}
isSavingRef.current = true;
void (async () => {
try {
const data = await prepareSaveData({ silent: true });
if (data) {
try {
await onSave(data);
} catch {
toast.error(t('settings.projects.page.toast.saveFailed'));
}
}
} finally {
isSavingRef.current = false;
}
})();
}, AUTO_SAVE_DELAY_MS);
return () => {
window.clearTimeout(timer);
};
}, [
color,
defaultModel,
hasChanges,
icon,
iconBackground,
isRemovingCustomIcon,
isUploadingIcon,
name,
onSave,
pendingRemoveImageIcon,
pendingUploadIconFile,
prepareSaveData,
t,
]);
};
@@ -0,0 +1,293 @@
import React from 'react';
import { toast } from '@/components/ui';
import { parseModelIdentifier } from '@/lib/modelIdentifier';
import { useI18n } from '@/lib/i18n';
import type { ProjectEntry } from '@/lib/api/types';
import { useProjectsStore } from '@/stores/useProjectsStore';
const HEX_COLOR_PATTERN = /^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/;
export const normalizeProjectIconBackground = (value: string | null | undefined): string | null => {
if (!value) {
return null;
}
const trimmed = value.trim();
if (!trimmed) {
return null;
}
return HEX_COLOR_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
};
export type ProjectIdentitySaveData = {
label: string;
icon: string | null;
color: string | null;
iconBackground: string | null;
defaultModel: string | null;
};
type EditableProject = Pick<
ProjectEntry,
'id' | 'label' | 'icon' | 'color' | 'iconBackground' | 'defaultModel' | 'iconImage' | 'path'
>;
export const useProjectIdentityForm = (project: EditableProject | null) => {
const { t } = useI18n();
const uploadProjectIcon = useProjectsStore((state) => state.uploadProjectIcon);
const removeProjectIcon = useProjectsStore((state) => state.removeProjectIcon);
const discoverProjectIcon = useProjectsStore((state) => state.discoverProjectIcon);
const currentIconImage = useProjectsStore((state) =>
project ? state.projects.find((entry) => entry.id === project.id)?.iconImage ?? null : null,
);
const [name, setName] = React.useState('');
const [icon, setIcon] = React.useState<string | null>(null);
const [color, setColor] = React.useState<string | null>(null);
const [iconBackground, setIconBackground] = React.useState<string | null>(null);
const [defaultModel, setDefaultModel] = React.useState<string | undefined>(undefined);
const [isUploadingIcon, setIsUploadingIcon] = React.useState(false);
const [isRemovingCustomIcon, setIsRemovingCustomIcon] = React.useState(false);
const [isDiscoveringIcon, setIsDiscoveringIcon] = React.useState(false);
const [pendingRemoveImageIcon, setPendingRemoveImageIcon] = React.useState(false);
const [pendingUploadIconFile, setPendingUploadIconFile] = React.useState<File | null>(null);
const [pendingUploadIconPreviewUrl, setPendingUploadIconPreviewUrl] = React.useState<string | null>(null);
const [previewImageFailed, setPreviewImageFailed] = React.useState(false);
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const clearPendingUploadIcon = React.useCallback(() => {
setPendingUploadIconFile(null);
setPendingUploadIconPreviewUrl((previousUrl) => {
if (previousUrl) {
URL.revokeObjectURL(previousUrl);
}
return null;
});
}, []);
const projectId = project?.id ?? null;
React.useEffect(() => {
if (!project) {
setName('');
setIcon(null);
setColor(null);
setIconBackground(null);
setDefaultModel(undefined);
return;
}
setName(project.label ?? '');
setIcon(project.icon ?? null);
setColor(project.color ?? null);
setIconBackground(project.iconBackground ?? null);
setDefaultModel(project.defaultModel);
setPendingRemoveImageIcon(false);
clearPendingUploadIcon();
setPreviewImageFailed(false);
}, [project, clearPendingUploadIcon]);
React.useEffect(() => {
return () => {
clearPendingUploadIcon();
};
}, [clearPendingUploadIcon]);
const parsedDefaultModel = React.useMemo(() => {
const parsed = parseModelIdentifier(defaultModel);
return parsed ?? { providerId: '', modelId: '' };
}, [defaultModel]);
const hasStoredImageIcon = Boolean(project?.iconImage);
const hasPendingUploadImageIcon = Boolean(pendingUploadIconFile && pendingUploadIconPreviewUrl);
const hasCustomIcon = project?.iconImage?.source === 'custom';
const effectiveHasImageIcon = (hasStoredImageIcon && !pendingRemoveImageIcon) || hasPendingUploadImageIcon;
const hasRemovableImageIcon = effectiveHasImageIcon;
const showStoredImagePreview = Boolean(project && hasStoredImageIcon && !pendingRemoveImageIcon);
const showImagePreview = !previewImageFailed && (hasPendingUploadImageIcon || showStoredImagePreview);
const hasChanges = Boolean(project) && (
name.trim() !== (project?.label ?? '').trim()
|| icon !== (project?.icon ?? null)
|| color !== (project?.color ?? null)
|| iconBackground !== (project?.iconBackground ?? null)
|| (defaultModel ?? undefined) !== (project?.defaultModel ?? undefined)
|| pendingRemoveImageIcon
|| Boolean(pendingUploadIconFile)
);
const handleDefaultModelChange = React.useCallback((providerId: string, modelId: string) => {
setDefaultModel(providerId && modelId ? `${providerId}/${modelId}` : undefined);
}, []);
const handleUploadIcon = React.useCallback((file: File | null) => {
if (!project || !file || isUploadingIcon) {
return;
}
setPendingRemoveImageIcon(false);
setPreviewImageFailed(false);
setPendingUploadIconFile(file);
setPendingUploadIconPreviewUrl((previousUrl) => {
if (previousUrl) {
URL.revokeObjectURL(previousUrl);
}
return URL.createObjectURL(file);
});
}, [isUploadingIcon, project]);
const handleRemoveImageIcon = React.useCallback(() => {
if (!project || !hasRemovableImageIcon || isRemovingCustomIcon) {
return;
}
if (hasPendingUploadImageIcon) {
clearPendingUploadIcon();
}
if (hasStoredImageIcon) {
setPendingRemoveImageIcon(true);
} else {
setPendingRemoveImageIcon(false);
}
setPreviewImageFailed(false);
}, [
clearPendingUploadIcon,
hasPendingUploadImageIcon,
hasRemovableImageIcon,
hasStoredImageIcon,
isRemovingCustomIcon,
project,
]);
const handleDiscoverIcon = React.useCallback(async () => {
if (!project || isDiscoveringIcon) {
return;
}
clearPendingUploadIcon();
setPendingRemoveImageIcon(false);
setPreviewImageFailed(false);
setIsDiscoveringIcon(true);
try {
const result = await discoverProjectIcon(project.id);
if (!result.ok) {
toast.error(result.error || t('settings.projects.page.toast.discoverIconFailed'));
return;
}
if (result.skipped) {
toast.success(t('settings.projects.page.toast.customIconAlreadySet'));
return;
}
toast.success(t('settings.projects.page.toast.iconDiscovered'));
} finally {
setIsDiscoveringIcon(false);
}
}, [clearPendingUploadIcon, discoverProjectIcon, isDiscoveringIcon, project, t]);
const prepareSaveData = React.useCallback(async (options?: { silent?: boolean }): Promise<ProjectIdentitySaveData | null> => {
const silent = options?.silent === true;
if (!project) {
return null;
}
const trimmed = name.trim();
if (!trimmed) {
return null;
}
if (pendingUploadIconFile) {
setIsUploadingIcon(true);
const uploadResult = await uploadProjectIcon(project.id, pendingUploadIconFile);
setIsUploadingIcon(false);
if (!uploadResult.ok) {
toast.error(uploadResult.error || t('settings.projects.page.toast.uploadIconFailed'));
return null;
}
if (!silent) {
toast.success(t('settings.projects.page.toast.iconUpdated'));
}
clearPendingUploadIcon();
setPendingRemoveImageIcon(false);
}
const willRemoveImageIcon = pendingRemoveImageIcon && Boolean(project.iconImage);
if (willRemoveImageIcon) {
setIsRemovingCustomIcon(true);
const removeResult = await removeProjectIcon(project.id);
setIsRemovingCustomIcon(false);
if (!removeResult.ok) {
toast.error(removeResult.error || t('settings.projects.page.toast.removeIconFailed'));
return null;
}
if (!silent) {
toast.success(t('settings.projects.page.toast.iconRemoved'));
}
setPendingRemoveImageIcon(false);
setIconBackground(null);
}
return {
label: trimmed,
icon,
color,
iconBackground: normalizeProjectIconBackground(willRemoveImageIcon ? null : iconBackground),
defaultModel: defaultModel ?? null,
};
}, [
clearPendingUploadIcon,
color,
defaultModel,
icon,
iconBackground,
name,
pendingRemoveImageIcon,
pendingUploadIconFile,
project,
removeProjectIcon,
t,
uploadProjectIcon,
]);
React.useEffect(() => {
setPreviewImageFailed(false);
}, [projectId, currentIconImage?.updatedAt]);
return {
name,
setName,
icon,
setIcon,
color,
setColor,
iconBackground,
setIconBackground,
defaultModel,
parsedDefaultModel,
handleDefaultModelChange,
isUploadingIcon,
isRemovingCustomIcon,
isDiscoveringIcon,
pendingRemoveImageIcon,
setPendingRemoveImageIcon,
pendingUploadIconFile,
pendingUploadIconPreviewUrl,
previewImageFailed,
setPreviewImageFailed,
hasStoredImageIcon,
hasPendingUploadImageIcon,
hasCustomIcon,
effectiveHasImageIcon,
hasRemovableImageIcon,
showStoredImagePreview,
showImagePreview,
fileInputRef,
clearPendingUploadIcon,
handleUploadIcon,
handleRemoveImageIcon,
handleDiscoverIcon,
hasChanges,
prepareSaveData,
currentIconImage,
project,
};
};