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
@@ -1,436 +1,33 @@
import React from 'react'; import React from 'react';
import { import { Dialog, DialogContent } from '@/components/ui/dialog';
Dialog, import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
DialogContent, import { ProjectSettingsPanel } from '@/components/sections/projects/ProjectSettingsPanel';
DialogFooter, import type { ProjectIdentitySaveData } from '@/components/sections/projects/useProjectIdentityForm';
DialogHeader, import type { ProjectEntry } from '@/lib/api/types';
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { toast } from '@/components/ui';
import { cn } from '@/lib/utils';
import { PROJECT_ICONS, PROJECT_COLORS, PROJECT_COLOR_MAP, ProjectIconImage } from '@/lib/projectMeta';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useThemeSystem } from '@/contexts/useThemeSystem';
import { useI18n } from '@/lib/i18n';
import { Icon } from "@/components/icon/Icon";
interface ProjectEditDialogProps { interface ProjectEditDialogProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
projectId: string; project: ProjectEntry | null;
projectName: string; onSave: (data: ProjectIdentitySaveData) => void | Promise<void>;
projectPath: string;
initialIcon?: string | null;
initialColor?: string | null;
initialIconBackground?: string | null;
onSave: (data: { label: string; icon: string | null; color: string | null; iconBackground: string | null }) => void;
} }
const HEX_COLOR_PATTERN = /^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/;
const normalizeIconBackground = (value: string | null): string | null => {
if (!value) {
return null;
}
const trimmed = value.trim();
if (!trimmed) {
return null;
}
return HEX_COLOR_PATTERN.test(trimmed) ? trimmed.toLowerCase() : null;
};
export const ProjectEditDialog: React.FC<ProjectEditDialogProps> = ({ export const ProjectEditDialog: React.FC<ProjectEditDialogProps> = ({
open, open,
onOpenChange, onOpenChange,
projectId, project,
projectName,
projectPath,
initialIcon = null,
initialColor = null,
initialIconBackground = null,
onSave, onSave,
}) => { }) => {
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) => state.projects.find((project) => project.id === projectId)?.iconImage ?? null);
const { currentTheme } = useThemeSystem();
const [name, setName] = React.useState(projectName);
const [icon, setIcon] = React.useState<string | null>(initialIcon);
const [color, setColor] = React.useState<string | null>(initialColor);
const [iconBackground, setIconBackground] = React.useState<string | null>(normalizeIconBackground(initialIconBackground));
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;
});
}, []);
React.useEffect(() => {
if (open) {
setName(projectName);
setIcon(initialIcon);
setColor(initialColor);
setIconBackground(normalizeIconBackground(initialIconBackground));
setPendingRemoveImageIcon(false);
clearPendingUploadIcon();
setPreviewImageFailed(false);
}
}, [open, projectName, initialIcon, initialColor, initialIconBackground, clearPendingUploadIcon]);
React.useEffect(() => {
return () => {
clearPendingUploadIcon();
};
}, [clearPendingUploadIcon]);
const handleSave = async () => {
const trimmed = name.trim();
if (!trimmed) return;
if (pendingUploadIconFile) {
setIsUploadingIcon(true);
const uploadResult = await uploadProjectIcon(projectId, pendingUploadIconFile);
setIsUploadingIcon(false);
if (!uploadResult.ok) {
toast.error(uploadResult.error || t('projectEditDialog.toast.failedToUploadIcon'));
return;
}
toast.success(t('projectEditDialog.toast.iconUpdated'));
clearPendingUploadIcon();
setPendingRemoveImageIcon(false);
}
const willRemoveImageIcon = pendingRemoveImageIcon && hasStoredImageIcon;
if (willRemoveImageIcon) {
setIsRemovingCustomIcon(true);
const result = await removeProjectIcon(projectId);
setIsRemovingCustomIcon(false);
if (!result.ok) {
toast.error(result.error || t('projectEditDialog.toast.failedToRemoveIcon'));
return;
}
toast.success(t('projectEditDialog.toast.iconRemoved'));
setPendingRemoveImageIcon(false);
setIconBackground(null);
}
onSave({
label: trimmed,
icon,
color,
iconBackground: normalizeIconBackground(willRemoveImageIcon ? null : iconBackground),
});
onOpenChange(false);
};
const currentColorVar = color ? (PROJECT_COLOR_MAP[color] ?? null) : null;
const hasStoredImageIcon = Boolean(currentIconImage);
const hasPendingUploadImageIcon = Boolean(pendingUploadIconFile && pendingUploadIconPreviewUrl);
const hasCustomIcon = currentIconImage?.source === 'custom';
const effectiveHasImageIcon = (hasStoredImageIcon && !pendingRemoveImageIcon) || hasPendingUploadImageIcon;
const hasRemovableImageIcon = effectiveHasImageIcon;
const showStoredImagePreview = hasStoredImageIcon && !pendingRemoveImageIcon;
const showImagePreview = !previewImageFailed && (hasPendingUploadImageIcon || showStoredImagePreview);
React.useEffect(() => {
setPreviewImageFailed(false);
}, [projectId, currentIconImage?.updatedAt]);
const handleUploadIcon = React.useCallback((file: File | null) => {
if (!projectId || !file || isUploadingIcon) {
return;
}
setPendingRemoveImageIcon(false);
setPreviewImageFailed(false);
setPendingUploadIconFile(file);
setPendingUploadIconPreviewUrl((previousUrl) => {
if (previousUrl) {
URL.revokeObjectURL(previousUrl);
}
return URL.createObjectURL(file);
});
}, [isUploadingIcon, projectId]);
const handleRemoveImageIcon = React.useCallback(() => {
if (!projectId || !hasRemovableImageIcon || isRemovingCustomIcon) {
return;
}
if (hasPendingUploadImageIcon) {
clearPendingUploadIcon();
}
if (hasStoredImageIcon) {
setPendingRemoveImageIcon(true);
} else {
setPendingRemoveImageIcon(false);
}
setPreviewImageFailed(false);
}, [
clearPendingUploadIcon,
hasPendingUploadImageIcon,
hasRemovableImageIcon,
hasStoredImageIcon,
isRemovingCustomIcon,
projectId,
]);
const handleDiscoverIcon = React.useCallback(async () => {
if (!projectId || isDiscoveringIcon) {
return;
}
clearPendingUploadIcon();
setPendingRemoveImageIcon(false);
setPreviewImageFailed(false);
setIsDiscoveringIcon(true);
void discoverProjectIcon(projectId)
.then((result) => {
if (!result.ok) {
toast.error(result.error || t('projectEditDialog.toast.failedToDiscoverIcon'));
return;
}
if (result.skipped) {
toast.success(t('projectEditDialog.toast.customIconAlreadySet'));
return;
}
toast.success(t('projectEditDialog.toast.iconDiscovered'));
})
.finally(() => {
setIsDiscoveringIcon(false);
});
}, [clearPendingUploadIcon, discoverProjectIcon, isDiscoveringIcon, projectId, t]);
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md"> <DialogContent className="w-full max-w-2xl gap-0 overflow-hidden p-0">
<DialogHeader className="min-w-0"> <ScrollableOverlay outerClassName="max-h-[min(90vh,48rem)]" className="w-full bg-background">
<DialogTitle>{t('projectEditDialog.title')}</DialogTitle> <div className="w-full p-3 sm:p-6 sm:pt-8">
</DialogHeader> {open && project ? (
<ProjectSettingsPanel project={project} onIdentitySave={onSave} />
<div className="min-w-0 space-y-5 py-1"> ) : null}
{/* Name */}
<div className="min-w-0 space-y-1.5">
<label className="typography-ui-label font-medium text-foreground">
{t('projectEditDialog.field.name')}
</label>
<Input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t('projectEditDialog.field.namePlaceholder')}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleSave();
}
}}
autoFocus
/>
<p className="typography-meta text-muted-foreground truncate" title={projectPath}>
{projectPath}
</p>
</div> </div>
</ScrollableOverlay>
{/* Color */}
<div className="min-w-0 space-y-2">
<label className="typography-ui-label font-medium text-foreground">
{t('projectEditDialog.field.color')}
</label>
<div className="flex gap-2 flex-wrap">
{/* No color option */}
<button
type="button"
onClick={() => setColor(null)}
className={cn(
'w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center',
color === null
? 'border-foreground scale-110'
: 'border-border hover:border-border/80'
)}
title={t('projectEditDialog.option.none')}
>
<span className="w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full" />
</button>
{PROJECT_COLORS.map((c) => (
<button
key={c.key}
type="button"
onClick={() => setColor(c.key)}
className={cn(
'w-8 h-8 rounded-lg border-2 transition-all',
color === c.key
? 'border-foreground scale-110'
: 'border-transparent hover:border-border'
)}
style={{ backgroundColor: c.cssVar }}
title={c.label}
/>
))}
</div>
</div>
{/* Icon */}
<div className="min-w-0 space-y-2">
<label className="typography-ui-label font-medium text-foreground">
{t('projectEditDialog.field.icon')}
</label>
<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 gap-2 flex-wrap">
{/* No icon option */}
<button
type="button"
onClick={() => setIcon(null)}
className={cn(
'w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center',
icon === null
? 'border-foreground scale-110 bg-[var(--surface-elevated)]'
: 'border-border hover:border-border/80'
)}
title={t('projectEditDialog.option.none')}
>
<span className="w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full" />
</button>
{PROJECT_ICONS.map((i) => {
const iconName = i.Icon;
return (
<button
key={i.key}
type="button"
onClick={() => setIcon(i.key)}
className={cn(
'w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center',
icon === i.key
? 'border-foreground scale-110 bg-[var(--surface-elevated)]'
: 'border-border hover:border-border/80'
)}
title={i.label}
>
<Icon name={iconName}
className="w-4 h-4"
style={currentColorVar ? { color: currentColorVar } : undefined}
/>
</button>
);
})}
</div>
{effectiveHasImageIcon && showImagePreview && (
<div className="flex items-center gap-2 pt-1">
<span className="typography-meta text-muted-foreground">{t('projectEditDialog.field.preview')}</span>
<span className="inline-flex h-8 w-8 items-center justify-center rounded-lg 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={{ id: projectId, iconImage: currentIconImage }}
options={{
themeVariant: currentTheme.metadata.variant,
iconColor: currentTheme.colors.surface.foreground,
}}
className="h-full w-full object-contain"
onError={() => setPreviewImageFailed(true)}
/>
)}
</span>
</span>
</div>
)}
<div className="flex flex-wrap items-center gap-2 pt-1">
{!hasCustomIcon && (
<>
<Button size="sm" variant="outline" onClick={() => fileInputRef.current?.click()} disabled={isUploadingIcon}>
{isUploadingIcon ? t('projectEditDialog.actions.uploading') : t('projectEditDialog.actions.uploadIcon')}
</Button>
<Button size="sm" variant="outline" onClick={() => void handleDiscoverIcon()} disabled={isDiscoveringIcon}>
{isDiscoveringIcon ? t('projectEditDialog.actions.discovering') : t('projectEditDialog.actions.discoverFavicon')}
</Button>
</>
)}
{hasRemovableImageIcon && (
<Button size="sm" variant="outline" onClick={() => void handleRemoveImageIcon()} disabled={isRemovingCustomIcon}>
{isRemovingCustomIcon ? t('projectEditDialog.actions.removing') : t('projectEditDialog.actions.removeProjectIcon')}
</Button>
)}
{pendingRemoveImageIcon && (
<Button size="sm" variant="outline" onClick={() => setPendingRemoveImageIcon(false)} disabled={isRemovingCustomIcon}>
{t('projectEditDialog.actions.undoRemove')}
</Button>
)}
</div>
</div>
{effectiveHasImageIcon && (
<div className="min-w-0 space-y-2">
<label className="typography-ui-label font-medium text-foreground">
{t('projectEditDialog.field.iconBackground')}
</label>
<div className="flex flex-wrap items-center gap-2">
<input
type="color"
value={iconBackground ?? '#000000'}
onChange={(event) => setIconBackground(event.target.value)}
className="h-8 w-10 cursor-pointer rounded border border-border bg-transparent p-1"
aria-label={t('projectEditDialog.field.iconBackgroundAria')}
/>
<Input
value={iconBackground ?? ''}
onChange={(event) => setIconBackground(event.target.value)}
placeholder="#000000"
className="h-8 w-[8.5rem]"
/>
<Button size="sm" variant="outline" onClick={() => setIconBackground(null)}>
{t('projectEditDialog.actions.clear')}
</Button>
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => onOpenChange(false)}>
{t('projectEditDialog.actions.cancel')}
</Button>
<Button onClick={handleSave} disabled={!name.trim() || isUploadingIcon || isRemovingCustomIcon}>
{t('projectEditDialog.actions.save')}
</Button>
</DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox'; import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { toast } from '@/components/ui';
import { Icon } from "@/components/icon/Icon"; import { Icon } from "@/components/icon/Icon";
import type { Session } from '@opencode-ai/sdk/v2'; import type { Session } from '@opencode-ai/sdk/v2';
import { useProjectsStore } from '@/stores/useProjectsStore'; import { useProjectsStore } from '@/stores/useProjectsStore';
@@ -22,12 +23,18 @@ import { listProjectWorktrees } from '@/lib/worktrees/worktreeManager';
import { sessionEvents } from '@/lib/sessionEvents'; import { sessionEvents } from '@/lib/sessionEvents';
import type { WorktreeMetadata } from '@/types/worktree'; import type { WorktreeMetadata } from '@/types/worktree';
import { formatPathForDisplay, cn } from '@/lib/utils'; import { formatPathForDisplay, cn } from '@/lib/utils';
import {
PROJECT_SETTINGS_CONTROL_WIDTH,
ProjectSettingsSubsection,
} from '@/components/sections/projects/ProjectSettingsSubsection';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
export interface WorktreeSectionContentProps { export interface WorktreeSectionContentProps {
projectRef?: { id: string; path: string } | null; projectRef?: { id: string; path: string } | null;
} }
const SETUP_COMMANDS_SAVE_DELAY_MS = 450;
export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({ projectRef: projectRefProp = null }) => { export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({ projectRef: projectRefProp = null }) => {
const { t } = useI18n(); const { t } = useI18n();
const { isMobile, isTablet } = useDeviceInfo(); const { isMobile, isTablet } = useDeviceInfo();
@@ -37,15 +44,17 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
const projectPath = projectRefProp?.path ?? activeProject?.path ?? null; const projectPath = projectRefProp?.path ?? activeProject?.path ?? null;
const getWorktreeMetadata = useSessionUIStore((s) => s.getWorktreeMetadata); const getWorktreeMetadata = useSessionUIStore((s) => s.getWorktreeMetadata);
const sessions = useSessions(); const sessions = useSessions();
const homeDirectory = useDirectoryStore((state) => state.homeDirectory); const homeDirectory = useDirectoryStore((state) => state.homeDirectory);
const [setupCommands, setSetupCommands] = React.useState<string[]>([]); const [setupCommands, setSetupCommands] = React.useState<string[]>([]);
const [waitForSetupCommands, setWaitForSetupCommands] = React.useState(false); const [waitForSetupCommands, setWaitForSetupCommands] = React.useState(false);
const [isLoadingCommands, setIsLoadingCommands] = React.useState(false); const [isLoadingCommands, setIsLoadingCommands] = React.useState(false);
const [commandsSnapshot, setCommandsSnapshot] = React.useState<string | null>(null);
const [isGitRepoLocal, setIsGitRepoLocal] = React.useState<boolean | null>(null); const [isGitRepoLocal, setIsGitRepoLocal] = React.useState<boolean | null>(null);
const [availableWorktrees, setAvailableWorktrees] = React.useState<WorktreeMetadata[]>([]); const [availableWorktrees, setAvailableWorktrees] = React.useState<WorktreeMetadata[]>([]);
const [isLoadingWorktrees, setIsLoadingWorktrees] = React.useState(false); const [isLoadingWorktrees, setIsLoadingWorktrees] = React.useState(false);
const isSavingCommandsRef = React.useRef(false);
const projectRef = React.useMemo(() => { const projectRef = React.useMemo(() => {
if (projectRefProp?.id && projectRefProp?.path) { if (projectRefProp?.id && projectRefProp?.path) {
@@ -68,7 +77,6 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
} }
}, [projectRef, isGitRepoLocal]); }, [projectRef, isGitRepoLocal]);
// Load repo info
React.useEffect(() => { React.useEffect(() => {
if (!projectPath) return; if (!projectPath) return;
@@ -90,7 +98,6 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
}; };
}, [projectPath]); }, [projectPath]);
// Load existing worktrees
React.useEffect(() => { React.useEffect(() => {
if (!projectRef) { if (!projectRef) {
setAvailableWorktrees([]); setAvailableWorktrees([]);
@@ -127,7 +134,6 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
}; };
}, [projectRef, isGitRepoLocal]); }, [projectRef, isGitRepoLocal]);
// Load setup commands
React.useEffect(() => { React.useEffect(() => {
if (!projectRef) return; if (!projectRef) return;
@@ -141,12 +147,15 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
getWorktreeSetupWaitEnabled(projectRef), getWorktreeSetupWaitEnabled(projectRef),
]); ]);
if (!cancelled) { if (!cancelled) {
setSetupCommands(commands.length > 0 ? commands : ['']); const nextCommands = commands.length > 0 ? commands : [''];
setSetupCommands(nextCommands);
setCommandsSnapshot(JSON.stringify(nextCommands));
setWaitForSetupCommands(waitForSetup); setWaitForSetupCommands(waitForSetup);
} }
} catch { } catch {
if (!cancelled) { if (!cancelled) {
setSetupCommands(['']); setSetupCommands(['']);
setCommandsSnapshot(JSON.stringify(['']));
setWaitForSetupCommands(false); setWaitForSetupCommands(false);
} }
} finally { } finally {
@@ -161,6 +170,56 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
}; };
}, [projectRef]); }, [projectRef]);
const persistSetupCommands = React.useCallback(async (commands: string[]): Promise<boolean> => {
if (!projectRef) {
return false;
}
const filtered = commands.filter((cmd) => cmd.trim().length > 0);
try {
const ok = await saveWorktreeSetupCommands(projectRef, filtered);
if (!ok) {
toast.error(t('settings.openchamber.worktrees.setup.toast.saveFailed'));
return false;
}
setCommandsSnapshot(JSON.stringify(commands));
return true;
} catch {
toast.error(t('settings.openchamber.worktrees.setup.toast.saveFailed'));
return false;
}
}, [projectRef, t]);
const commandsHaveChanges = React.useMemo(() => {
if (commandsSnapshot === null) {
return false;
}
return commandsSnapshot !== JSON.stringify(setupCommands);
}, [commandsSnapshot, setupCommands]);
React.useEffect(() => {
if (!commandsHaveChanges || isLoadingCommands || isSavingCommandsRef.current) {
return;
}
const timer = window.setTimeout(() => {
if (isSavingCommandsRef.current) {
return;
}
isSavingCommandsRef.current = true;
void (async () => {
try {
await persistSetupCommands(setupCommands);
} finally {
isSavingCommandsRef.current = false;
}
})();
}, SETUP_COMMANDS_SAVE_DELAY_MS);
return () => {
window.clearTimeout(timer);
};
}, [commandsHaveChanges, isLoadingCommands, persistSetupCommands, setupCommands]);
const handleSetupCommandChange = React.useCallback((index: number, value: string) => { const handleSetupCommandChange = React.useCallback((index: number, value: string) => {
setSetupCommands((prev) => { setSetupCommands((prev) => {
const next = [...prev]; const next = [...prev];
@@ -173,25 +232,26 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
setSetupCommands((prev) => [...prev, '']); setSetupCommands((prev) => [...prev, '']);
}, []); }, []);
const persistSetupCommands = React.useCallback(async (commands: string[]) => {
if (!projectRef) return;
const filtered = commands.filter((cmd) => cmd.trim().length > 0);
await saveWorktreeSetupCommands(projectRef, filtered);
}, [projectRef]);
const handleRemoveCommand = React.useCallback((index: number) => { const handleRemoveCommand = React.useCallback((index: number) => {
setSetupCommands((prev) => { setSetupCommands((prev) => {
const next = prev.filter((_, i) => i !== index); const next = prev.filter((_, i) => i !== index);
// Keep at least 1 row in UI, but persist empty config when all removed.
void persistSetupCommands(next);
return next.length > 0 ? next : ['']; return next.length > 0 ? next : [''];
}); });
}, [persistSetupCommands]); }, []);
// Save setup commands on blur
const handleCommandBlur = React.useCallback(() => { const handleCommandBlur = React.useCallback(() => {
void persistSetupCommands(setupCommands); if (!commandsHaveChanges || isSavingCommandsRef.current) {
}, [persistSetupCommands, setupCommands]); return;
}
isSavingCommandsRef.current = true;
void (async () => {
try {
await persistSetupCommands(setupCommands);
} finally {
isSavingCommandsRef.current = false;
}
})();
}, [commandsHaveChanges, persistSetupCommands, setupCommands]);
const handleWaitForSetupCommandsChange = React.useCallback((enabled: boolean) => { const handleWaitForSetupCommandsChange = React.useCallback((enabled: boolean) => {
setWaitForSetupCommands(enabled); setWaitForSetupCommands(enabled);
@@ -200,22 +260,16 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
} }
}, [projectRef]); }, [projectRef]);
// Delete worktree handler
const handleDeleteWorktree = React.useCallback((worktree: WorktreeMetadata) => { const handleDeleteWorktree = React.useCallback((worktree: WorktreeMetadata) => {
const normalize = (value: string): string => value.replace(/\\/g, '/').replace(/\/+$/, ''); const normalize = (value: string): string => value.replace(/\\/g, '/').replace(/\/+$/, '');
const normalizedWorktreePath = normalize(worktree.path); const normalizedWorktreePath = normalize(worktree.path);
// Find sessions linked to this worktree by:
// 1. Worktree metadata path match
// 2. Session directory match
const directSessions = sessions.filter((session) => { const directSessions = sessions.filter((session) => {
// Check worktree metadata
const metadata = getWorktreeMetadata(session.id); const metadata = getWorktreeMetadata(session.id);
if (metadata?.path && normalize(metadata.path) === normalizedWorktreePath) { if (metadata?.path && normalize(metadata.path) === normalizedWorktreePath) {
return true; return true;
} }
// Check session directory
const sessionDir = (session as { directory?: string }).directory; const sessionDir = (session as { directory?: string }).directory;
if (sessionDir) { if (sessionDir) {
const normalizedSessionDir = normalize(sessionDir); const normalizedSessionDir = normalize(sessionDir);
@@ -227,12 +281,8 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
return false; return false;
}); });
// Build a set of session IDs that are directly linked
const directSessionIds = new Set(directSessions.map((s) => s.id)); const directSessionIds = new Set(directSessions.map((s) => s.id));
// Search subsessions across all directories, not just the current sync
// context, so subagent sessions created in other worktrees/project roots
// are still included in the delete list.
const allKnownSessions = [ const allKnownSessions = [
...useGlobalSessionsStore.getState().activeSessions, ...useGlobalSessionsStore.getState().activeSessions,
...useGlobalSessionsStore.getState().archivedSessions, ...useGlobalSessionsStore.getState().archivedSessions,
@@ -252,7 +302,6 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
const allSubsessions = findSubsessions(directSessionIds); const allSubsessions = findSubsessions(directSessionIds);
// Dedupe sessions (in case same session matched both ways)
const seenIds = new Set<string>(); const seenIds = new Set<string>();
const allSessions = [...directSessions, ...allSubsessions].filter((session) => { const allSessions = [...directSessions, ...allSubsessions].filter((session) => {
if (seenIds.has(session.id)) { if (seenIds.has(session.id)) {
@@ -269,7 +318,6 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
}); });
}, [sessions, getWorktreeMetadata]); }, [sessions, getWorktreeMetadata]);
// Refresh worktrees when sessions change (after deletion)
const sessionsKey = React.useMemo(() => sessions.map(s => s.id).join(','), [sessions]); const sessionsKey = React.useMemo(() => sessions.map(s => s.id).join(','), [sessions]);
React.useEffect(() => { React.useEffect(() => {
if (isGitRepoLocal && projectPath) { if (isGitRepoLocal && projectPath) {
@@ -277,48 +325,69 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
} }
}, [sessionsKey, isGitRepoLocal, projectPath, refreshWorktrees]); }, [sessionsKey, isGitRepoLocal, projectPath, refreshWorktrees]);
const setupTooltip = (
<Tooltip>
<TooltipTrigger asChild>
<Icon name="information" className="h-3.5 w-3.5 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{t('settings.openchamber.worktrees.setup.tooltipPrefix')}
{' '}
<code className="font-mono text-xs bg-sidebar-accent/50 px-1 rounded">$ROOT_PROJECT_PATH</code>
{' '}
{t('settings.openchamber.worktrees.setup.tooltipSuffix')}
</TooltipContent>
</Tooltip>
);
const listTooltip = (
<Tooltip>
<TooltipTrigger asChild>
<Icon name="information" className="h-3.5 w-3.5 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{t('settings.openchamber.worktrees.list.tooltip')}
</TooltipContent>
</Tooltip>
);
if (!projectPath) { if (!projectPath) {
return ( return (
<p className="typography-meta text-muted-foreground"> <ProjectSettingsSubsection
{t('settings.openchamber.worktrees.state.selectProject')} title={t('settings.projects.page.section.worktree')}
</p> settingsItem="projects.worktree"
>
<p className="typography-meta text-muted-foreground">
{t('settings.openchamber.worktrees.state.selectProject')}
</p>
</ProjectSettingsSubsection>
); );
} }
if (isGitRepoLocal === false) { if (isGitRepoLocal === false) {
return ( return (
<p className="typography-meta text-muted-foreground"> <ProjectSettingsSubsection
{t('settings.openchamber.worktrees.state.gitOnly')} title={t('settings.projects.page.section.worktree')}
</p> settingsItem="projects.worktree"
>
<p className="typography-meta text-muted-foreground">
{t('settings.openchamber.worktrees.state.gitOnly')}
</p>
</ProjectSettingsSubsection>
); );
} }
return ( return (
<div className="max-w-[44rem] space-y-5"> <>
{/* Setup commands */} <ProjectSettingsSubsection
<div className="space-y-2"> title={t('settings.projects.page.section.worktree')}
<div className="mb-1 px-1"> settingsItem="projects.worktree"
<div className="flex items-center gap-2"> titleAccessory={setupTooltip}
<h3 className="typography-ui-header font-normal text-foreground">{t('settings.openchamber.worktrees.setup.title')}</h3> >
<Tooltip>
<TooltipTrigger asChild>
<Icon name="information" className="h-3.5 w-3.5 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{t('settings.openchamber.worktrees.setup.tooltipPrefix')}
{' '}
<code className="font-mono text-xs bg-sidebar-accent/50 px-1 rounded">$ROOT_PROJECT_PATH</code>
{' '}
{t('settings.openchamber.worktrees.setup.tooltipSuffix')}
</TooltipContent>
</Tooltip>
</div>
</div>
{isLoadingCommands ? ( {isLoadingCommands ? (
<p className="typography-meta text-muted-foreground px-1">{t('settings.openchamber.worktrees.setup.loading')}</p> <p className="typography-meta text-muted-foreground">{t('settings.openchamber.worktrees.setup.loading')}</p>
) : ( ) : (
<div className="space-y-2 px-1"> <div className={cn('space-y-2', PROJECT_SETTINGS_CONTROL_WIDTH)}>
{setupCommands.map((command, index) => ( {setupCommands.map((command, index) => (
<div key={index} className="flex w-full gap-2"> <div key={index} className="flex w-full gap-2">
<Input <Input
@@ -326,16 +395,14 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
onChange={(e) => handleSetupCommandChange(index, e.target.value)} onChange={(e) => handleSetupCommandChange(index, e.target.value)}
onBlur={handleCommandBlur} onBlur={handleCommandBlur}
placeholder={t('settings.openchamber.worktrees.setup.commandPlaceholder')} placeholder={t('settings.openchamber.worktrees.setup.commandPlaceholder')}
className="h-7 w-[30rem] max-w-full font-mono text-xs" className="h-7 min-w-0 flex-1 font-mono text-xs"
/> />
<button <button
type="button" type="button"
onClick={() => { onClick={() => handleRemoveCommand(index)}
handleRemoveCommand(index); className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
}} aria-label={t('settings.openchamber.worktrees.setup.removeCommandAria')}
className="flex-shrink-0 flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50" >
aria-label={t('settings.openchamber.worktrees.setup.removeCommandAria')}
>
<Icon name="close" className="h-4 w-4" /> <Icon name="close" className="h-4 w-4" />
</button> </button>
</div> </div>
@@ -352,7 +419,7 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
</Button> </Button>
<label <label
data-settings-item="projects.worktree.setup.wait" data-settings-item="projects.worktree.setup.wait"
className="flex cursor-pointer items-center gap-2 py-1.5" className="flex cursor-pointer items-center gap-2 py-1"
> >
<Checkbox <Checkbox
checked={waitForSetupCommands} checked={waitForSetupCommands}
@@ -368,58 +435,46 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
</label> </label>
</div> </div>
)} )}
</div> </ProjectSettingsSubsection>
{/* Existing worktrees */}
<div className="space-y-2 border-t border-border/40 pt-4">
<div className="mb-1 px-1">
<div className="flex items-center gap-2">
<h3 className="typography-ui-header font-normal text-foreground">{t('settings.openchamber.worktrees.list.title')}</h3>
<Tooltip>
<TooltipTrigger asChild>
<Icon name="information" className="h-3.5 w-3.5 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{t('settings.openchamber.worktrees.list.tooltip')}
</TooltipContent>
</Tooltip>
</div>
</div>
<ProjectSettingsSubsection
title={t('settings.openchamber.worktrees.list.title')}
titleAccessory={listTooltip}
>
{isLoadingWorktrees ? ( {isLoadingWorktrees ? (
<p className="typography-meta text-muted-foreground px-1">{t('settings.openchamber.worktrees.list.loading')}</p> <p className="typography-meta text-muted-foreground">{t('settings.openchamber.worktrees.list.loading')}</p>
) : availableWorktrees.length === 0 ? ( ) : availableWorktrees.length === 0 ? (
<p className="typography-meta text-muted-foreground/70 px-1"> <p className="typography-meta text-muted-foreground/70">
{t('settings.openchamber.worktrees.list.empty')} {t('settings.openchamber.worktrees.list.empty')}
</p> </p>
) : ( ) : (
<div className="space-y-1 px-1 max-w-[32.5rem]"> <div className={cn('space-y-1', PROJECT_SETTINGS_CONTROL_WIDTH)}>
{availableWorktrees.map((worktree) => ( {availableWorktrees.map((worktree) => (
<div <div
key={worktree.path} key={worktree.path}
className="group flex w-full items-center gap-2 py-1.5" className="group flex w-full items-center gap-2 py-1.5"
> >
<div className="flex-1 min-w-0"> <div className="min-w-0 flex-1">
<div className="flex items-center gap-2 min-w-0"> <div className="flex min-w-0 items-center gap-2">
<p className="typography-meta text-foreground truncate min-w-0"> <p className="typography-meta min-w-0 truncate text-foreground">
{worktree.label || worktree.branch || t('settings.openchamber.worktrees.list.detachedHead')} {worktree.label || worktree.branch || t('settings.openchamber.worktrees.list.detachedHead')}
</p> </p>
<span className="typography-micro text-muted-foreground/60 px-1.5 py-[1px] rounded bg-sidebar-accent/40 flex-shrink-0 self-center leading-none"> <span className="typography-micro flex-shrink-0 self-center rounded bg-sidebar-accent/40 px-1.5 py-[1px] leading-none text-muted-foreground/60">
OpenCode OpenCode
</span> </span>
</div> </div>
<p className="typography-micro text-muted-foreground/60 truncate"> <p className="typography-micro truncate text-muted-foreground/60">
{formatPathForDisplay(worktree.path, homeDirectory)} {formatPathForDisplay(worktree.path, homeDirectory)}
</p> </p>
</div> </div>
<button <button
type="button" type="button"
onClick={() => handleDeleteWorktree(worktree)} onClick={() => handleDeleteWorktree(worktree)}
className={cn( className={cn(
"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 transition-opacity focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50", 'flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground/50 transition-opacity hover:bg-destructive/10 hover:text-destructive focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50',
alwaysShowActions ? "opacity-100" : "opacity-0 group-hover:opacity-100" alwaysShowActions ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
)} )}
aria-label={t('settings.openchamber.worktrees.list.deleteWorktreeAria', { name: worktree.branch || worktree.label || worktree.path })} aria-label={t('settings.openchamber.worktrees.list.deleteWorktreeAria', { name: worktree.branch || worktree.label || worktree.path })}
> >
<Icon name="delete-bin" className="h-4 w-4" /> <Icon name="delete-bin" className="h-4 w-4" />
</button> </button>
@@ -427,7 +482,7 @@ export const WorktreeSectionContent: React.FC<WorktreeSectionContentProps> = ({
))} ))}
</div> </div>
)} )}
</div> </ProjectSettingsSubsection>
</div> </>
); );
}; };
@@ -37,11 +37,17 @@ import {
PROJECT_ACTION_ICONS, PROJECT_ACTION_ICONS,
PROJECT_ACTIONS_UPDATED_EVENT, PROJECT_ACTIONS_UPDATED_EVENT,
} from '@/lib/projectActions'; } from '@/lib/projectActions';
import {
PROJECT_SETTINGS_CONTROL_WIDTH,
ProjectSettingsSubsection,
} from '@/components/sections/projects/ProjectSettingsSubsection';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
type EditableProjectAction = OpenChamberProjectAction; type EditableProjectAction = OpenChamberProjectAction;
const AUTO_SAVE_DELAY_MS = 450;
const createActionId = (): string => { const createActionId = (): string => {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID(); return crypto.randomUUID();
@@ -68,9 +74,10 @@ export const ProjectActionsSection: React.FC<ProjectActionsSectionProps> = ({ pr
const [actions, setActions] = React.useState<EditableProjectAction[]>([]); const [actions, setActions] = React.useState<EditableProjectAction[]>([]);
const [isLoading, setIsLoading] = React.useState(false); const [isLoading, setIsLoading] = React.useState(false);
const [isSaving, setIsSaving] = React.useState(false);
const [initialSnapshot, setInitialSnapshot] = React.useState<string | null>(null); const [initialSnapshot, setInitialSnapshot] = React.useState<string | null>(null);
const [expandedActions, setExpandedActions] = React.useState<Record<string, boolean>>({}); const [expandedActions, setExpandedActions] = React.useState<Record<string, boolean>>({});
const isSavingRef = React.useRef(false);
const validationToastShownRef = React.useRef<string | null>(null);
React.useEffect(() => { React.useEffect(() => {
if (!isDesktopShellApp) { if (!isDesktopShellApp) {
@@ -133,6 +140,69 @@ export const ProjectActionsSection: React.FC<ProjectActionsSectionProps> = ({ pr
return initialSnapshot !== JSON.stringify({ actions }); return initialSnapshot !== JSON.stringify({ actions });
}, [actions, initialSnapshot]); }, [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 handleAddAction = React.useCallback(() => {
const nextAction = createEmptyAction(); const nextAction = createEmptyAction();
setActions((prev) => [...prev, nextAction]); 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))); 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 ( return (
<div className="mb-8"> <ProjectSettingsSubsection
<div className="mb-1 flex items-start justify-between gap-2"> title={t('settings.projects.actions.title')}
<div> description={t('settings.projects.actions.description')}
<h3 className="typography-ui-header font-medium text-foreground">{t('settings.projects.actions.title')}</h3> settingsItem="projects.actions"
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.description')}</p> headerAction={(
</div>
<Button type="button" variant="outline" size="xs" className="!font-normal" onClick={handleAddAction}> <Button type="button" variant="outline" size="xs" className="!font-normal" onClick={handleAddAction}>
<Icon name="add" className="h-3.5 w-3.5" /> <Icon name="add" className="h-3.5 w-3.5" />
{t('settings.projects.actions.actions.add')} {t('settings.projects.actions.actions.add')}
</Button> </Button>
</div> )}
contentClassName="space-y-0"
<section className="pb-2 pt-0 space-y-2"> >
{isLoading ? ( {isLoading ? (
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.loading')}</p> <p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.loading')}</p>
) : actions.length === 0 ? ( ) : actions.length === 0 ? (
<div className="py-2"> <p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.empty')}</p>
<p className="typography-meta text-muted-foreground">{t('settings.projects.actions.state.empty')}</p> ) : (
</div> <div className={cn('space-y-0', PROJECT_SETTINGS_CONTROL_WIDTH)}>
) : ( {actions.map((action) => {
<div className="space-y-0 max-w-[30rem]"> const selectedIconKey = (action.icon as keyof typeof PROJECT_ACTION_ICON_MAP) || 'play';
{actions.map((action) => { const selectedIconName = PROJECT_ACTION_ICON_MAP[selectedIconKey] || 'play';
const selectedIconKey = (action.icon as keyof typeof PROJECT_ACTION_ICON_MAP) || 'play'; const isOpen = expandedActions[action.id] ?? false;
const selectedIconName = PROJECT_ACTION_ICON_MAP[selectedIconKey] || 'play'; const title = action.name.trim() || t('settings.projects.actions.state.untitled');
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>
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> </div>
</CollapsibleContent> </CollapsibleTrigger>
</Collapsible>
);
})}
</div>
)}
<div className="pt-3"> <Button
{validationError ? ( type="button"
<p className="typography-meta mb-2 text-[var(--status-warning)]">{validationError}</p> variant="ghost"
) : null} size="xs"
<Button className="!font-normal h-7 w-7 px-0 text-muted-foreground hover:text-[var(--status-error)]"
type="button" onClick={() => handleRemoveAction(action.id)}
size="xs" >
className="!font-normal" <Icon name="delete-bin" className="h-3.5 w-3.5" />
onClick={handleSave} </Button>
disabled={!canSave} </div>
>
{isSaving ? t('settings.common.actions.saving') : t('settings.projects.actions.actions.save')} <CollapsibleContent className="pt-1.5">
</Button> <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> </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 React from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay'; import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { toast } from '@/components/ui';
import { cn } from '@/lib/utils';
import { useProjectsStore } from '@/stores/useProjectsStore'; import { useProjectsStore } from '@/stores/useProjectsStore';
import { useUIStore } from '@/stores/useUIStore'; import { useUIStore } from '@/stores/useUIStore';
import { PROJECT_COLORS, PROJECT_ICONS, PROJECT_COLOR_MAP as COLOR_MAP, ProjectIconImage } from '@/lib/projectMeta'; import { ProjectSettingsPanel } from '@/components/sections/projects/ProjectSettingsPanel';
import { WorktreeSectionContent } from '@/components/sections/openchamber/WorktreeSectionContent'; import type { ProjectIdentitySaveData } from '@/components/sections/projects/useProjectIdentityForm';
import { ProjectActionsSection } from '@/components/sections/projects/ProjectActionsSection';
import { Icon } from "@/components/icon/Icon";
import { useThemeSystem } from '@/contexts/useThemeSystem';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
export const ProjectsPage: React.FC = () => { export const ProjectsPage: React.FC = () => {
const { t } = useI18n(); const { t } = useI18n();
const projects = useProjectsStore((state) => state.projects); const projects = useProjectsStore((state) => state.projects);
const updateProjectMeta = useProjectsStore((state) => state.updateProjectMeta); 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 selectedId = useUIStore((state) => state.settingsProjectsSelectedId);
const setSelectedId = useUIStore((state) => state.setSettingsProjectsSelectedId); const setSelectedId = useUIStore((state) => state.setSettingsProjectsSelectedId);
const { currentTheme } = useThemeSystem();
const selectedProject = React.useMemo(() => { const selectedProject = React.useMemo(() => {
if (!selectedId) return null; if (!selectedId) return null;
@@ -40,194 +29,16 @@ export const ProjectsPage: React.FC = () => {
setSelectedId(projects[0].id); setSelectedId(projects[0].id);
}, [projects, selectedId, setSelectedId]); }, [projects, selectedId, setSelectedId]);
const [name, setName] = React.useState(''); const handleIdentitySave = React.useCallback(async (data: ProjectIdentitySaveData) => {
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 () => {
if (!selectedProject) return; 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, { updateProjectMeta(selectedProject.id, {
label: name.trim(), label: data.label,
icon, icon: data.icon,
color, color: data.color,
iconBackground: willRemoveImageIcon ? null : iconBackground, iconBackground: data.iconBackground,
defaultModel: data.defaultModel ?? null,
}); });
}, [ }, [selectedProject, updateProjectMeta]);
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]);
if (!selectedProject) { if (!selectedProject) {
return ( return (
@@ -238,268 +49,11 @@ export const ProjectsPage: React.FC = () => {
</ScrollableOverlay> </ScrollableOverlay>
); );
} }
return ( return (
<ScrollableOverlay outerClassName="h-full" className="w-full bg-background"> <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"> <div className="mx-auto w-full max-w-4xl p-3 sm:p-6 sm:pt-8">
<ProjectSettingsPanel project={selectedProject} onIdentitySave={handleIdentitySave} />
{/* 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>
</div> </div>
</ScrollableOverlay> </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,
};
};
@@ -605,12 +605,23 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
[projects, editingProjectDialogId], [projects, editingProjectDialogId],
); );
const handleSaveProjectEdit = React.useCallback((data: { label: string; icon: string | null; color: string | null; iconBackground: string | null }) => { const handleSaveProjectEdit = React.useCallback((data: {
label: string;
icon: string | null;
color: string | null;
iconBackground: string | null;
defaultModel: string | null;
}) => {
if (!editingProjectDialogId) { if (!editingProjectDialogId) {
return; return;
} }
updateProjectMeta(editingProjectDialogId, data); updateProjectMeta(editingProjectDialogId, {
setEditingProjectDialogId(null); label: data.label,
icon: data.icon,
color: data.color,
iconBackground: data.iconBackground,
defaultModel: data.defaultModel ?? null,
});
}, [editingProjectDialogId, updateProjectMeta]); }, [editingProjectDialogId, updateProjectMeta]);
const openNewWorktreeDialog = React.useCallback(() => { const openNewWorktreeDialog = React.useCallback(() => {
@@ -1675,23 +1686,16 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
runtimeType={updateStore.runtimeType} runtimeType={updateStore.runtimeType}
/> />
{editingProject ? ( <ProjectEditDialog
<ProjectEditDialog open={Boolean(editingProject)}
open={Boolean(editingProject)} onOpenChange={(open) => {
onOpenChange={(open) => { if (!open) {
if (!open) { setEditingProjectDialogId(null);
setEditingProjectDialogId(null); }
} }}
}} project={editingProject}
projectId={editingProject.id} onSave={handleSaveProjectEdit}
projectName={editingProject.label || formatDirectoryName(editingProject.path, homeDirectory)} />
projectPath={editingProject.path}
initialIcon={editingProject.icon}
initialColor={editingProject.color}
initialIconBackground={editingProject.iconBackground}
onSave={handleSaveProjectEdit}
/>
) : null}
<NewWorktreeDialog <NewWorktreeDialog
open={newWorktreeDialogOpen} open={newWorktreeDialogOpen}
@@ -110,7 +110,7 @@ export const SortableProjectItem: React.FC<SortableProjectItemProps> = ({
)} )}
<Item onClick={onRenameStart}> <Item onClick={onRenameStart}>
<Icon name="pencil-ai" className="mr-1.5 h-4 w-4" /> <Icon name="pencil-ai" className="mr-1.5 h-4 w-4" />
{t('sessions.sidebar.session.menu.rename')} {t('sessions.sidebar.project.actions.edit')}
</Item> </Item>
<Item onClick={onClose} className="text-destructive focus:text-destructive"> <Item onClick={onClose} className="text-destructive focus:text-destructive">
<Icon name="close" className="mr-1.5 h-4 w-4" /> <Icon name="close" className="mr-1.5 h-4 w-4" />
+1
View File
@@ -612,6 +612,7 @@ export interface ProjectEntry {
} | null; } | null;
iconBackground?: string | null; iconBackground?: string | null;
color?: string | null; color?: string | null;
defaultModel?: string;
addedAt?: number; addedAt?: number;
lastOpenedAt?: number; lastOpenedAt?: number;
sidebarCollapsed?: boolean; sidebarCollapsed?: boolean;
@@ -1013,6 +1013,8 @@ export const settingsDict = {
'settings.projects.page.section.worktree': 'Worktree', 'settings.projects.page.section.worktree': 'Worktree',
'settings.projects.page.field.projectName': 'Project Name', 'settings.projects.page.field.projectName': 'Project Name',
'settings.projects.page.field.projectNamePlaceholder': 'Project name', 'settings.projects.page.field.projectNamePlaceholder': 'Project name',
'settings.projects.page.field.defaultModel': 'Default model for new chats',
'settings.projects.page.field.defaultModelDescription': 'Used when starting a new chat in this project. Falls back to global defaults when unset.',
'settings.projects.page.field.accentColor': 'Accent Color', 'settings.projects.page.field.accentColor': 'Accent Color',
'settings.projects.page.field.projectIcon': 'Project Icon', 'settings.projects.page.field.projectIcon': 'Project Icon',
'settings.projects.page.field.projectIconBackgroundAria': 'Project icon background color', 'settings.projects.page.field.projectIconBackgroundAria': 'Project icon background color',
@@ -1034,6 +1036,7 @@ export const settingsDict = {
'settings.projects.page.toast.discoverIconFailed': 'Failed to discover project icon', 'settings.projects.page.toast.discoverIconFailed': 'Failed to discover project icon',
'settings.projects.page.toast.customIconAlreadySet': 'Custom icon already set for this project', 'settings.projects.page.toast.customIconAlreadySet': 'Custom icon already set for this project',
'settings.projects.page.toast.iconDiscovered': 'Project icon discovered', 'settings.projects.page.toast.iconDiscovered': 'Project icon discovered',
'settings.projects.page.toast.saveFailed': 'Failed to save project settings',
'settings.usage.sidebar.title': 'Usage', 'settings.usage.sidebar.title': 'Usage',
'settings.usage.sidebar.total': 'Total {count}', 'settings.usage.sidebar.total': 'Total {count}',
'settings.usage.sidebar.actions.toggleAutoRefreshAria': 'Toggle auto refresh', 'settings.usage.sidebar.actions.toggleAutoRefreshAria': 'Toggle auto refresh',
@@ -1171,6 +1174,7 @@ export const settingsDict = {
'settings.openchamber.worktrees.setup.addCommand': 'Add command', 'settings.openchamber.worktrees.setup.addCommand': 'Add command',
'settings.openchamber.worktrees.setup.waitForCommands': 'Wait for setup commands before creating or sending a session', 'settings.openchamber.worktrees.setup.waitForCommands': 'Wait for setup commands before creating or sending a session',
'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Wait for Worktree setup commands before creating or sending a session', 'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Wait for Worktree setup commands before creating or sending a session',
'settings.openchamber.worktrees.setup.toast.saveFailed': 'Failed to save worktree setup commands',
'settings.openchamber.worktrees.list.title': 'Existing worktrees', 'settings.openchamber.worktrees.list.title': 'Existing worktrees',
'settings.openchamber.worktrees.list.tooltip': 'Worktrees live outside the repo (OpenCode-managed). Deleting a worktree also removes linked sessions.', 'settings.openchamber.worktrees.list.tooltip': 'Worktrees live outside the repo (OpenCode-managed). Deleting a worktree also removes linked sessions.',
'settings.openchamber.worktrees.list.loading': 'Loading worktrees...', 'settings.openchamber.worktrees.list.loading': 'Loading worktrees...',
+1
View File
@@ -428,6 +428,7 @@ export const dict = {
'sessions.sidebar.project.actions.newWorktreeEllipsis': 'New worktree...', 'sessions.sidebar.project.actions.newWorktreeEllipsis': 'New worktree...',
'sessions.sidebar.project.actions.projectMenu': 'Project menu', 'sessions.sidebar.project.actions.projectMenu': 'Project menu',
'sessions.sidebar.project.actions.newSession': 'New session', 'sessions.sidebar.project.actions.newSession': 'New session',
'sessions.sidebar.project.actions.edit': 'Edit',
'sessions.sidebar.project.actions.closeProject': 'Close project', 'sessions.sidebar.project.actions.closeProject': 'Close project',
'sessions.sidebar.project.actions.newDraftSession': 'New draft session', 'sessions.sidebar.project.actions.newDraftSession': 'New draft session',
'sessions.sidebar.session.menu.rename': 'Rename', 'sessions.sidebar.session.menu.rename': 'Rename',
@@ -980,6 +980,8 @@ export const settingsDict = {
"settings.projects.page.section.worktree": "Worktree", "settings.projects.page.section.worktree": "Worktree",
"settings.projects.page.field.projectName": "Nombre del proyecto", "settings.projects.page.field.projectName": "Nombre del proyecto",
"settings.projects.page.field.projectNamePlaceholder": "Nombre del proyecto", "settings.projects.page.field.projectNamePlaceholder": "Nombre del proyecto",
"settings.projects.page.field.defaultModel": "Modelo predeterminado para chats nuevos",
"settings.projects.page.field.defaultModelDescription": "Se usa al iniciar un chat nuevo en este proyecto. Si no se define, se usan los valores globales.",
"settings.projects.page.field.accentColor": "Color de énfasis", "settings.projects.page.field.accentColor": "Color de énfasis",
"settings.projects.page.field.projectIcon": "Icono del proyecto", "settings.projects.page.field.projectIcon": "Icono del proyecto",
"settings.projects.page.field.projectIconBackgroundAria": "Color de fondo del icono del proyecto", "settings.projects.page.field.projectIconBackgroundAria": "Color de fondo del icono del proyecto",
@@ -1001,6 +1003,7 @@ export const settingsDict = {
"settings.projects.page.toast.discoverIconFailed": "No se pudo descubrir el icono del proyecto", "settings.projects.page.toast.discoverIconFailed": "No se pudo descubrir el icono del proyecto",
"settings.projects.page.toast.customIconAlreadySet": "Icono personalizado ya establecido para este proyecto", "settings.projects.page.toast.customIconAlreadySet": "Icono personalizado ya establecido para este proyecto",
"settings.projects.page.toast.iconDiscovered": "Icono del proyecto descubierto", "settings.projects.page.toast.iconDiscovered": "Icono del proyecto descubierto",
"settings.projects.page.toast.saveFailed": "Error al guardar la configuración del proyecto",
"settings.usage.sidebar.title": "Uso", "settings.usage.sidebar.title": "Uso",
"settings.usage.sidebar.total": "Total {count}", "settings.usage.sidebar.total": "Total {count}",
"settings.usage.sidebar.actions.toggleAutoRefreshAria": "Alternar refresco automático", "settings.usage.sidebar.actions.toggleAutoRefreshAria": "Alternar refresco automático",
@@ -1138,6 +1141,7 @@ export const settingsDict = {
"settings.openchamber.worktrees.setup.addCommand": "Añadir comando", "settings.openchamber.worktrees.setup.addCommand": "Añadir comando",
"settings.openchamber.worktrees.setup.waitForCommands": "Esperar a que terminen los comandos de configuración antes de crear o enviar una sesión", "settings.openchamber.worktrees.setup.waitForCommands": "Esperar a que terminen los comandos de configuración antes de crear o enviar una sesión",
"settings.openchamber.worktrees.setup.waitForCommandsAria": "Esperar los comandos de configuración de Worktree antes de crear o enviar una sesión", "settings.openchamber.worktrees.setup.waitForCommandsAria": "Esperar los comandos de configuración de Worktree antes de crear o enviar una sesión",
"settings.openchamber.worktrees.setup.toast.saveFailed": "Error al guardar los comandos de configuración del worktree",
"settings.openchamber.worktrees.list.title": "Worktrees existentes", "settings.openchamber.worktrees.list.title": "Worktrees existentes",
"settings.openchamber.worktrees.list.tooltip": "Los worktrees existen fuera del repositorio (gestionados por OpenCode). Eliminar un worktree también elimina las sesiones vinculadas.", "settings.openchamber.worktrees.list.tooltip": "Los worktrees existen fuera del repositorio (gestionados por OpenCode). Eliminar un worktree también elimina las sesiones vinculadas.",
"settings.openchamber.worktrees.list.loading": "Cargando worktrees...", "settings.openchamber.worktrees.list.loading": "Cargando worktrees...",
+1
View File
@@ -430,6 +430,7 @@ export const dict: Record<I18nKey, string> = {
"sessions.sidebar.project.actions.projectMenu": "Menú del proyecto", "sessions.sidebar.project.actions.projectMenu": "Menú del proyecto",
"sessions.sidebar.project.actions.newSession": "Nueva sesión", "sessions.sidebar.project.actions.newSession": "Nueva sesión",
"sessions.sidebar.project.actions.closeProject": "Cerrar proyecto", "sessions.sidebar.project.actions.closeProject": "Cerrar proyecto",
"sessions.sidebar.project.actions.edit": "Editar",
"sessions.sidebar.project.actions.newDraftSession": "Nueva sesión de borrador", "sessions.sidebar.project.actions.newDraftSession": "Nueva sesión de borrador",
"sessions.sidebar.session.menu.rename": "Cambiar nombre", "sessions.sidebar.session.menu.rename": "Cambiar nombre",
"sessions.sidebar.session.rename.save": "Guardar nombre de sesión", "sessions.sidebar.session.rename.save": "Guardar nombre de sesión",
@@ -932,6 +932,8 @@ export const settingsDict = {
'settings.projects.page.section.worktree': 'Worktree', 'settings.projects.page.section.worktree': 'Worktree',
'settings.projects.page.field.projectName': 'Nom du projet', 'settings.projects.page.field.projectName': 'Nom du projet',
'settings.projects.page.field.projectNamePlaceholder': 'Nom du projet', 'settings.projects.page.field.projectNamePlaceholder': 'Nom du projet',
'settings.projects.page.field.defaultModel': 'Modèle par défaut pour les nouveaux chats',
'settings.projects.page.field.defaultModelDescription': 'Utilisé lors du démarrage d\'un nouveau chat dans ce projet. Revient aux valeurs globales si non défini.',
'settings.projects.page.field.accentColor': 'Couleur d\'accentuation', 'settings.projects.page.field.accentColor': 'Couleur d\'accentuation',
'settings.projects.page.field.projectIcon': 'Icône du projet', 'settings.projects.page.field.projectIcon': 'Icône du projet',
'settings.projects.page.field.projectIconBackgroundAria': 'Couleur d’arrière-plan de l’icône du projet', 'settings.projects.page.field.projectIconBackgroundAria': 'Couleur d’arrière-plan de l’icône du projet',
@@ -953,6 +955,7 @@ export const settingsDict = {
'settings.projects.page.toast.discoverIconFailed': 'Échec de la découverte de l\'icône du projet', 'settings.projects.page.toast.discoverIconFailed': 'Échec de la découverte de l\'icône du projet',
'settings.projects.page.toast.customIconAlreadySet': 'Icône personnalisée déjà définie pour ce projet', 'settings.projects.page.toast.customIconAlreadySet': 'Icône personnalisée déjà définie pour ce projet',
'settings.projects.page.toast.iconDiscovered': 'Icône de projet découverte', 'settings.projects.page.toast.iconDiscovered': 'Icône de projet découverte',
'settings.projects.page.toast.saveFailed': 'Échec de l\'enregistrement des paramètres du projet',
'settings.usage.sidebar.title': 'Usage', 'settings.usage.sidebar.title': 'Usage',
'settings.usage.sidebar.total': 'Total {count}', 'settings.usage.sidebar.total': 'Total {count}',
'settings.usage.sidebar.actions.toggleAutoRefreshAria': 'Activer l\'actualisation automatique', 'settings.usage.sidebar.actions.toggleAutoRefreshAria': 'Activer l\'actualisation automatique',
@@ -1090,6 +1093,7 @@ export const settingsDict = {
'settings.openchamber.worktrees.setup.addCommand': 'Ajouter une commande', 'settings.openchamber.worktrees.setup.addCommand': 'Ajouter une commande',
'settings.openchamber.worktrees.setup.waitForCommands': 'Attendre la fin des commandes de configuration avant de créer ou d\'envoyer une session', 'settings.openchamber.worktrees.setup.waitForCommands': 'Attendre la fin des commandes de configuration avant de créer ou d\'envoyer une session',
'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Attendre les commandes de configuration Worktree avant de créer ou d\'envoyer une session', 'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Attendre les commandes de configuration Worktree avant de créer ou d\'envoyer une session',
'settings.openchamber.worktrees.setup.toast.saveFailed': 'Échec de l\'enregistrement des commandes de configuration Worktree',
'settings.openchamber.worktrees.list.title': 'Worktrees existants', 'settings.openchamber.worktrees.list.title': 'Worktrees existants',
'settings.openchamber.worktrees.list.tooltip': 'Les worktrees vivent en dehors du dépôt (gérés par OpenCode). La suppression d\'un worktree supprime également les sessions liées.', 'settings.openchamber.worktrees.list.tooltip': 'Les worktrees vivent en dehors du dépôt (gérés par OpenCode). La suppression d\'un worktree supprime également les sessions liées.',
'settings.openchamber.worktrees.list.loading': 'Chargement des worktrees...', 'settings.openchamber.worktrees.list.loading': 'Chargement des worktrees...',
+1
View File
@@ -278,6 +278,7 @@ export const dict = {
'sessions.sidebar.project.actions.projectMenu': 'Menu Projet', 'sessions.sidebar.project.actions.projectMenu': 'Menu Projet',
'sessions.sidebar.project.actions.newSession': 'Nouvelle session', 'sessions.sidebar.project.actions.newSession': 'Nouvelle session',
'sessions.sidebar.project.actions.closeProject': 'Fermer le projet', 'sessions.sidebar.project.actions.closeProject': 'Fermer le projet',
'sessions.sidebar.project.actions.edit': 'Modifier',
'sessions.sidebar.project.actions.newDraftSession': 'Nouveau brouillon de session', 'sessions.sidebar.project.actions.newDraftSession': 'Nouveau brouillon de session',
'sessions.sidebar.session.menu.rename': 'Rebaptiser', 'sessions.sidebar.session.menu.rename': 'Rebaptiser',
'sessions.sidebar.session.rename.save': 'Enregistrer le nom de la session', 'sessions.sidebar.session.rename.save': 'Enregistrer le nom de la session',
@@ -1013,6 +1013,8 @@ export const settingsDict = {
'settings.projects.page.section.worktree': 'ワークツリー', 'settings.projects.page.section.worktree': 'ワークツリー',
'settings.projects.page.field.projectName': 'プロジェクト名', 'settings.projects.page.field.projectName': 'プロジェクト名',
'settings.projects.page.field.projectNamePlaceholder': 'プロジェクト名', 'settings.projects.page.field.projectNamePlaceholder': 'プロジェクト名',
'settings.projects.page.field.defaultModel': '新規チャットのデフォルトモデル',
'settings.projects.page.field.defaultModelDescription': 'このプロジェクトで新しいチャットを開始するときに使用されます。未設定の場合はグローバル既定値にフォールバックします。',
'settings.projects.page.field.accentColor': 'アクセントカラー', 'settings.projects.page.field.accentColor': 'アクセントカラー',
'settings.projects.page.field.projectIcon': 'プロジェクトアイコン', 'settings.projects.page.field.projectIcon': 'プロジェクトアイコン',
'settings.projects.page.field.projectIconBackgroundAria': 'プロジェクトアイコンの背景色', 'settings.projects.page.field.projectIconBackgroundAria': 'プロジェクトアイコンの背景色',
@@ -1034,6 +1036,7 @@ export const settingsDict = {
'settings.projects.page.toast.discoverIconFailed': 'プロジェクトアイコンの検出に失敗しました', 'settings.projects.page.toast.discoverIconFailed': 'プロジェクトアイコンの検出に失敗しました',
'settings.projects.page.toast.customIconAlreadySet': 'このプロジェクトには既にカスタムアイコンが設定されています', 'settings.projects.page.toast.customIconAlreadySet': 'このプロジェクトには既にカスタムアイコンが設定されています',
'settings.projects.page.toast.iconDiscovered': 'プロジェクトアイコンを検出しました', 'settings.projects.page.toast.iconDiscovered': 'プロジェクトアイコンを検出しました',
'settings.projects.page.toast.saveFailed': 'プロジェクト設定の保存に失敗しました',
'settings.usage.sidebar.title': '使用量', 'settings.usage.sidebar.title': '使用量',
'settings.usage.sidebar.total': '合計 {count}', 'settings.usage.sidebar.total': '合計 {count}',
'settings.usage.sidebar.actions.toggleAutoRefreshAria': '自動更新の切替', 'settings.usage.sidebar.actions.toggleAutoRefreshAria': '自動更新の切替',
@@ -1171,6 +1174,7 @@ export const settingsDict = {
'settings.openchamber.worktrees.setup.addCommand': 'コマンドを追加', 'settings.openchamber.worktrees.setup.addCommand': 'コマンドを追加',
'settings.openchamber.worktrees.setup.waitForCommands': 'セットアップコマンドの完了を待ってからセッションを作成または送信する', 'settings.openchamber.worktrees.setup.waitForCommands': 'セットアップコマンドの完了を待ってからセッションを作成または送信する',
'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Worktree セットアップコマンドの完了を待ってからセッションを作成または送信する', 'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Worktree セットアップコマンドの完了を待ってからセッションを作成または送信する',
'settings.openchamber.worktrees.setup.toast.saveFailed': 'ワークツリー設定コマンドの保存に失敗しました',
'settings.openchamber.worktrees.list.title': '既存の Worktree', 'settings.openchamber.worktrees.list.title': '既存の Worktree',
'settings.openchamber.worktrees.list.tooltip': 'Worktree はリポジトリの外にあり(OpenCode 管理)、削除するとリンクされた Session も削除されます。', 'settings.openchamber.worktrees.list.tooltip': 'Worktree はリポジトリの外にあり(OpenCode 管理)、削除するとリンクされた Session も削除されます。',
'settings.openchamber.worktrees.list.loading': 'Worktree を読み込み中...', 'settings.openchamber.worktrees.list.loading': 'Worktree を読み込み中...',
+1
View File
@@ -430,6 +430,7 @@ export const dict: Record<I18nKey, string> = {
'sessions.sidebar.project.actions.projectMenu': 'プロジェクトメニュー', 'sessions.sidebar.project.actions.projectMenu': 'プロジェクトメニュー',
'sessions.sidebar.project.actions.newSession': '新しいセッション', 'sessions.sidebar.project.actions.newSession': '新しいセッション',
'sessions.sidebar.project.actions.closeProject': 'プロジェクトを閉じる', 'sessions.sidebar.project.actions.closeProject': 'プロジェクトを閉じる',
'sessions.sidebar.project.actions.edit': '編集',
'sessions.sidebar.project.actions.newDraftSession': '新しい下書きセッション', 'sessions.sidebar.project.actions.newDraftSession': '新しい下書きセッション',
'sessions.sidebar.session.menu.rename': '名前の変更', 'sessions.sidebar.session.menu.rename': '名前の変更',
'sessions.sidebar.session.rename.save': 'セッション名を保存', 'sessions.sidebar.session.rename.save': 'セッション名を保存',
@@ -980,6 +980,8 @@ export const settingsDict = {
'settings.projects.page.section.worktree': 'Worktree', 'settings.projects.page.section.worktree': 'Worktree',
'settings.projects.page.field.projectName': '프로젝트 이름', 'settings.projects.page.field.projectName': '프로젝트 이름',
'settings.projects.page.field.projectNamePlaceholder': '프로젝트 이름', 'settings.projects.page.field.projectNamePlaceholder': '프로젝트 이름',
'settings.projects.page.field.defaultModel': '새 채팅의 기본 모델',
'settings.projects.page.field.defaultModelDescription': '이 프로젝트에서 새 채팅을 시작할 때 사용됩니다. 설정하지 않으면 전역 기본값으로 대체됩니다.',
'settings.projects.page.field.accentColor': '강조 색상', 'settings.projects.page.field.accentColor': '강조 색상',
'settings.projects.page.field.projectIcon': '프로젝트 아이콘', 'settings.projects.page.field.projectIcon': '프로젝트 아이콘',
'settings.projects.page.field.projectIconBackgroundAria': '프로젝트 아이콘 배경색', 'settings.projects.page.field.projectIconBackgroundAria': '프로젝트 아이콘 배경색',
@@ -1001,6 +1003,7 @@ export const settingsDict = {
'settings.projects.page.toast.discoverIconFailed': '프로젝트 아이콘을 찾지 못했습니다', 'settings.projects.page.toast.discoverIconFailed': '프로젝트 아이콘을 찾지 못했습니다',
'settings.projects.page.toast.customIconAlreadySet': '이 프로젝트에는 이미 사용자 정의 아이콘이 설정되어 있습니다', 'settings.projects.page.toast.customIconAlreadySet': '이 프로젝트에는 이미 사용자 정의 아이콘이 설정되어 있습니다',
'settings.projects.page.toast.iconDiscovered': '프로젝트 아이콘을 찾았습니다', 'settings.projects.page.toast.iconDiscovered': '프로젝트 아이콘을 찾았습니다',
'settings.projects.page.toast.saveFailed': '프로젝트 설정 저장에 실패했습니다',
'settings.usage.sidebar.title': '사용량', 'settings.usage.sidebar.title': '사용량',
'settings.usage.sidebar.total': '총 {count}개', 'settings.usage.sidebar.total': '총 {count}개',
'settings.usage.sidebar.actions.toggleAutoRefreshAria': '자동 새로고침 토글', 'settings.usage.sidebar.actions.toggleAutoRefreshAria': '자동 새로고침 토글',
@@ -1138,6 +1141,7 @@ export const settingsDict = {
'settings.openchamber.worktrees.setup.addCommand': '명령어 추가', 'settings.openchamber.worktrees.setup.addCommand': '명령어 추가',
'settings.openchamber.worktrees.setup.waitForCommands': '세션을 만들거나 보내기 전에 설정 명령이 끝날 때까지 기다리기', 'settings.openchamber.worktrees.setup.waitForCommands': '세션을 만들거나 보내기 전에 설정 명령이 끝날 때까지 기다리기',
'settings.openchamber.worktrees.setup.waitForCommandsAria': '세션을 만들거나 보내기 전에 Worktree 설정 명령이 끝날 때까지 기다리기', 'settings.openchamber.worktrees.setup.waitForCommandsAria': '세션을 만들거나 보내기 전에 Worktree 설정 명령이 끝날 때까지 기다리기',
'settings.openchamber.worktrees.setup.toast.saveFailed': 'Worktree 설정 명령 저장에 실패했습니다',
'settings.openchamber.worktrees.list.title': '기존 worktree', 'settings.openchamber.worktrees.list.title': '기존 worktree',
'settings.openchamber.worktrees.list.tooltip': 'Worktree는 repo 외부에 있습니다(OpenCode 관리). worktree를 삭제하면 연결된 세션도 제거됩니다.', 'settings.openchamber.worktrees.list.tooltip': 'Worktree는 repo 외부에 있습니다(OpenCode 관리). worktree를 삭제하면 연결된 세션도 제거됩니다.',
'settings.openchamber.worktrees.list.loading': 'worktree 로딩 중...', 'settings.openchamber.worktrees.list.loading': 'worktree 로딩 중...',
+1
View File
@@ -430,6 +430,7 @@ export const dict: Record<I18nKey, string> = {
'sessions.sidebar.project.actions.projectMenu': '프로젝트 메뉴', 'sessions.sidebar.project.actions.projectMenu': '프로젝트 메뉴',
'sessions.sidebar.project.actions.newSession': '새 세션', 'sessions.sidebar.project.actions.newSession': '새 세션',
'sessions.sidebar.project.actions.closeProject': '프로젝트 닫기', 'sessions.sidebar.project.actions.closeProject': '프로젝트 닫기',
'sessions.sidebar.project.actions.edit': '편집',
'sessions.sidebar.project.actions.newDraftSession': '새 드래프트 세션', 'sessions.sidebar.project.actions.newDraftSession': '새 드래프트 세션',
'sessions.sidebar.session.menu.rename': '이름 변경', 'sessions.sidebar.session.menu.rename': '이름 변경',
'sessions.sidebar.session.rename.save': '세션 이름 저장', 'sessions.sidebar.session.rename.save': '세션 이름 저장',
@@ -1093,6 +1093,7 @@ export const settingsDict = {
'settings.openchamber.worktrees.setup.title': 'Polecenia konfiguracji', 'settings.openchamber.worktrees.setup.title': 'Polecenia konfiguracji',
'settings.openchamber.worktrees.setup.waitForCommands': 'Czekaj na zakończenie poleceń konfiguracji przed utworzeniem lub wysłaniem sesji', 'settings.openchamber.worktrees.setup.waitForCommands': 'Czekaj na zakończenie poleceń konfiguracji przed utworzeniem lub wysłaniem sesji',
'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Czekaj na polecenia konfiguracji Worktree przed utworzeniem lub wysłaniem sesji', 'settings.openchamber.worktrees.setup.waitForCommandsAria': 'Czekaj na polecenia konfiguracji Worktree przed utworzeniem lub wysłaniem sesji',
'settings.openchamber.worktrees.setup.toast.saveFailed': 'Nie udało się zapisać poleceń konfiguracji Worktree',
'settings.openchamber.worktrees.setup.tooltipPrefix': 'Uruchamiaj automatycznie w nowym katalogu worktree po jego utworzeniu. Użyj', 'settings.openchamber.worktrees.setup.tooltipPrefix': 'Uruchamiaj automatycznie w nowym katalogu worktree po jego utworzeniu. Użyj',
'settings.openchamber.worktrees.setup.tooltipSuffix': 'dla katalogu głównego projektu.', 'settings.openchamber.worktrees.setup.tooltipSuffix': 'dla katalogu głównego projektu.',
'settings.openchamber.worktrees.state.gitOnly': 'Ustawienia worktree są dostępne tylko dla repozytoriów Git.', 'settings.openchamber.worktrees.state.gitOnly': 'Ustawienia worktree są dostępne tylko dla repozytoriów Git.',
@@ -1214,11 +1215,14 @@ export const settingsDict = {
'settings.projects.page.field.projectIconBackgroundAria': 'Kolor tła ikony projektu', 'settings.projects.page.field.projectIconBackgroundAria': 'Kolor tła ikony projektu',
'settings.projects.page.field.projectName': 'Nazwa projektu', 'settings.projects.page.field.projectName': 'Nazwa projektu',
'settings.projects.page.field.projectNamePlaceholder': 'Nazwa projektu', 'settings.projects.page.field.projectNamePlaceholder': 'Nazwa projektu',
'settings.projects.page.field.defaultModel': 'Domyślny model dla nowych czatów',
'settings.projects.page.field.defaultModelDescription': 'Używany przy rozpoczynaniu nowego czatu w tym projekcie. Gdy nie ustawiono, stosowane są globalne domyślne wartości.',
'settings.projects.page.section.worktree': 'Worktree', 'settings.projects.page.section.worktree': 'Worktree',
'settings.projects.page.title.default': 'Project Settings', 'settings.projects.page.title.default': 'Project Settings',
'settings.projects.page.toast.customIconAlreadySet': 'Dla tego projektu ustawiono już własną ikonę', 'settings.projects.page.toast.customIconAlreadySet': 'Dla tego projektu ustawiono już własną ikonę',
'settings.projects.page.toast.discoverIconFailed': 'Nie udało się wykryć ikony projektu', 'settings.projects.page.toast.discoverIconFailed': 'Nie udało się wykryć ikony projektu',
'settings.projects.page.toast.iconDiscovered': 'Wykryto ikonę projektu', 'settings.projects.page.toast.iconDiscovered': 'Wykryto ikonę projektu',
'settings.projects.page.toast.saveFailed': 'Nie udało się zapisać ustawień projektu',
'settings.projects.page.toast.iconRemoved': 'Ikona projektu została usunięta', 'settings.projects.page.toast.iconRemoved': 'Ikona projektu została usunięta',
'settings.projects.page.toast.iconUpdated': 'Ikona projektu została zaktualizowana', 'settings.projects.page.toast.iconUpdated': 'Ikona projektu została zaktualizowana',
'settings.projects.page.toast.removeIconFailed': 'Nie udało się usunąć ikony projektu', 'settings.projects.page.toast.removeIconFailed': 'Nie udało się usunąć ikony projektu',
+1
View File
@@ -239,6 +239,7 @@ export const dict: Record<I18nKey, string> = {
'sessions.sidebar.project.actions.projectMenu': 'Menu projektu', 'sessions.sidebar.project.actions.projectMenu': 'Menu projektu',
'sessions.sidebar.project.actions.newSession': 'Nowa sesja', 'sessions.sidebar.project.actions.newSession': 'Nowa sesja',
'sessions.sidebar.project.actions.closeProject': 'Zamknij projekt', 'sessions.sidebar.project.actions.closeProject': 'Zamknij projekt',
'sessions.sidebar.project.actions.edit': 'Edytuj',
'sessions.sidebar.project.actions.newDraftSession': 'Nowa sesja robocza', 'sessions.sidebar.project.actions.newDraftSession': 'Nowa sesja robocza',
'sessions.sidebar.session.menu.rename': 'Zmień nazwę', 'sessions.sidebar.session.menu.rename': 'Zmień nazwę',
'sessions.sidebar.session.rename.save': 'Zapisz nazwę sesji', 'sessions.sidebar.session.rename.save': 'Zapisz nazwę sesji',
@@ -980,6 +980,8 @@ export const settingsDict = {
"settings.projects.page.section.worktree": "Worktree", "settings.projects.page.section.worktree": "Worktree",
"settings.projects.page.field.projectName": "Nome do projeto", "settings.projects.page.field.projectName": "Nome do projeto",
"settings.projects.page.field.projectNamePlaceholder": "Nome do projeto", "settings.projects.page.field.projectNamePlaceholder": "Nome do projeto",
"settings.projects.page.field.defaultModel": "Modelo padrão para novos chats",
"settings.projects.page.field.defaultModelDescription": "Usado ao iniciar um novo chat neste projeto. Se não definido, usa os padrões globais.",
"settings.projects.page.field.accentColor": "Cor de destaque", "settings.projects.page.field.accentColor": "Cor de destaque",
"settings.projects.page.field.projectIcon": "Ícone do projeto", "settings.projects.page.field.projectIcon": "Ícone do projeto",
"settings.projects.page.field.projectIconBackgroundAria": "Cor de fundo do ícone do projeto", "settings.projects.page.field.projectIconBackgroundAria": "Cor de fundo do ícone do projeto",
@@ -1001,6 +1003,7 @@ export const settingsDict = {
"settings.projects.page.toast.discoverIconFailed": "Não foi possível descobrir o ícone do projeto", "settings.projects.page.toast.discoverIconFailed": "Não foi possível descobrir o ícone do projeto",
"settings.projects.page.toast.customIconAlreadySet": "Ícone personalizado já definido para este projeto", "settings.projects.page.toast.customIconAlreadySet": "Ícone personalizado já definido para este projeto",
"settings.projects.page.toast.iconDiscovered": "Ícone do projeto descoberto", "settings.projects.page.toast.iconDiscovered": "Ícone do projeto descoberto",
"settings.projects.page.toast.saveFailed": "Falha ao salvar as configurações do projeto",
"settings.usage.sidebar.title": "Uso", "settings.usage.sidebar.title": "Uso",
"settings.usage.sidebar.total": "Total {count}", "settings.usage.sidebar.total": "Total {count}",
"settings.usage.sidebar.actions.toggleAutoRefreshAria": "Alternar atualização automática", "settings.usage.sidebar.actions.toggleAutoRefreshAria": "Alternar atualização automática",
@@ -1138,6 +1141,7 @@ export const settingsDict = {
"settings.openchamber.worktrees.setup.addCommand": "Adicionar comando", "settings.openchamber.worktrees.setup.addCommand": "Adicionar comando",
"settings.openchamber.worktrees.setup.waitForCommands": "Aguardar os comandos de configuração antes de criar ou enviar uma sessão", "settings.openchamber.worktrees.setup.waitForCommands": "Aguardar os comandos de configuração antes de criar ou enviar uma sessão",
"settings.openchamber.worktrees.setup.waitForCommandsAria": "Aguardar os comandos de configuração do Worktree antes de criar ou enviar uma sessão", "settings.openchamber.worktrees.setup.waitForCommandsAria": "Aguardar os comandos de configuração do Worktree antes de criar ou enviar uma sessão",
"settings.openchamber.worktrees.setup.toast.saveFailed": "Falha ao salvar os comandos de configuração do Worktree",
"settings.openchamber.worktrees.list.title": "Worktrees existentes", "settings.openchamber.worktrees.list.title": "Worktrees existentes",
"settings.openchamber.worktrees.list.tooltip": "Os worktrees existem fuera do repositório (gerenciados por OpenCode). Excluir um worktree também remove sessões vinculadas.", "settings.openchamber.worktrees.list.tooltip": "Os worktrees existem fuera do repositório (gerenciados por OpenCode). Excluir um worktree também remove sessões vinculadas.",
"settings.openchamber.worktrees.list.loading": "Carregando worktrees...", "settings.openchamber.worktrees.list.loading": "Carregando worktrees...",
@@ -430,6 +430,7 @@ export const dict: Record<I18nKey, string> = {
"sessions.sidebar.project.actions.projectMenu": "Menu do projeto", "sessions.sidebar.project.actions.projectMenu": "Menu do projeto",
"sessions.sidebar.project.actions.newSession": "Nova sessão", "sessions.sidebar.project.actions.newSession": "Nova sessão",
"sessions.sidebar.project.actions.closeProject": "Fechar projeto", "sessions.sidebar.project.actions.closeProject": "Fechar projeto",
"sessions.sidebar.project.actions.edit": "Editar",
"sessions.sidebar.project.actions.newDraftSession": "Nova sessão de rascunho", "sessions.sidebar.project.actions.newDraftSession": "Nova sessão de rascunho",
"sessions.sidebar.session.menu.rename": "Renomear", "sessions.sidebar.session.menu.rename": "Renomear",
"sessions.sidebar.session.rename.save": "Salvar nome da sessão", "sessions.sidebar.session.rename.save": "Salvar nome da sessão",
@@ -980,6 +980,8 @@ export const settingsDict = {
"settings.projects.page.section.worktree": "Worktree", "settings.projects.page.section.worktree": "Worktree",
"settings.projects.page.field.projectName": "Назва проєкту", "settings.projects.page.field.projectName": "Назва проєкту",
"settings.projects.page.field.projectNamePlaceholder": "Назва проєкту", "settings.projects.page.field.projectNamePlaceholder": "Назва проєкту",
"settings.projects.page.field.defaultModel": "Модель за замовчуванням для нових чатів",
"settings.projects.page.field.defaultModelDescription": "Використовується під час початку нового чату в цьому проєкті. Якщо не задано, застосовуються глобальні значення.",
"settings.projects.page.field.accentColor": "Колір акценту", "settings.projects.page.field.accentColor": "Колір акценту",
"settings.projects.page.field.projectIcon": "Значок проєкту", "settings.projects.page.field.projectIcon": "Значок проєкту",
"settings.projects.page.field.projectIconBackgroundAria": "Колір тла значка проєкту", "settings.projects.page.field.projectIconBackgroundAria": "Колір тла значка проєкту",
@@ -1001,6 +1003,7 @@ export const settingsDict = {
"settings.projects.page.toast.discoverIconFailed": "Не вдалося знайти значок проєкту", "settings.projects.page.toast.discoverIconFailed": "Не вдалося знайти значок проєкту",
"settings.projects.page.toast.customIconAlreadySet": "Спеціальна піктограма вже встановлена для цього проєкту", "settings.projects.page.toast.customIconAlreadySet": "Спеціальна піктограма вже встановлена для цього проєкту",
"settings.projects.page.toast.iconDiscovered": "Виявлено значок проєкту", "settings.projects.page.toast.iconDiscovered": "Виявлено значок проєкту",
"settings.projects.page.toast.saveFailed": "Не вдалося зберегти налаштування проєкту",
"settings.usage.sidebar.title": "Використання", "settings.usage.sidebar.title": "Використання",
"settings.usage.sidebar.total": "Усього {count}", "settings.usage.sidebar.total": "Усього {count}",
"settings.usage.sidebar.actions.toggleAutoRefreshAria": "Увімкнути автоматичне оновлення", "settings.usage.sidebar.actions.toggleAutoRefreshAria": "Увімкнути автоматичне оновлення",
@@ -1138,6 +1141,7 @@ export const settingsDict = {
"settings.openchamber.worktrees.setup.addCommand": "Додати команду", "settings.openchamber.worktrees.setup.addCommand": "Додати команду",
"settings.openchamber.worktrees.setup.waitForCommands": "Чекати завершення команд налаштування перед створенням або надсиланням сесії", "settings.openchamber.worktrees.setup.waitForCommands": "Чекати завершення команд налаштування перед створенням або надсиланням сесії",
"settings.openchamber.worktrees.setup.waitForCommandsAria": "Чекати завершення команд налаштування Worktree перед створенням або надсиланням сесії", "settings.openchamber.worktrees.setup.waitForCommandsAria": "Чекати завершення команд налаштування Worktree перед створенням або надсиланням сесії",
"settings.openchamber.worktrees.setup.toast.saveFailed": "Не вдалося зберегти команди налаштування Worktree",
"settings.openchamber.worktrees.list.title": "Наявні worktree", "settings.openchamber.worktrees.list.title": "Наявні worktree",
"settings.openchamber.worktrees.list.tooltip": "Worktree розташовані поза репозиторієм і керуються OpenCode. Видалення worktree також видаляє пов’язані сесії.", "settings.openchamber.worktrees.list.tooltip": "Worktree розташовані поза репозиторієм і керуються OpenCode. Видалення worktree також видаляє пов’язані сесії.",
"settings.openchamber.worktrees.list.loading": "Завантаження worktree...", "settings.openchamber.worktrees.list.loading": "Завантаження worktree...",
+1
View File
@@ -430,6 +430,7 @@ export const dict: Record<I18nKey, string> = {
"sessions.sidebar.project.actions.projectMenu": "Меню проєкту", "sessions.sidebar.project.actions.projectMenu": "Меню проєкту",
"sessions.sidebar.project.actions.newSession": "Нова сесія", "sessions.sidebar.project.actions.newSession": "Нова сесія",
"sessions.sidebar.project.actions.closeProject": "Закрити проєкт", "sessions.sidebar.project.actions.closeProject": "Закрити проєкт",
"sessions.sidebar.project.actions.edit": "Редагувати",
"sessions.sidebar.project.actions.newDraftSession": "Нова чернетка сесії", "sessions.sidebar.project.actions.newDraftSession": "Нова чернетка сесії",
"sessions.sidebar.session.menu.rename": "Перейменувати", "sessions.sidebar.session.menu.rename": "Перейменувати",
"sessions.sidebar.session.rename.save": "Зберегти назву сесії", "sessions.sidebar.session.rename.save": "Зберегти назву сесії",
@@ -980,6 +980,8 @@ export const settingsDict = {
'settings.projects.page.section.worktree': '工作树', 'settings.projects.page.section.worktree': '工作树',
'settings.projects.page.field.projectName': '项目名称', 'settings.projects.page.field.projectName': '项目名称',
'settings.projects.page.field.projectNamePlaceholder': '项目名称', 'settings.projects.page.field.projectNamePlaceholder': '项目名称',
'settings.projects.page.field.defaultModel': '新聊天的默认模型',
'settings.projects.page.field.defaultModelDescription': '在此项目中开始新聊天时使用。未设置时回退到全局默认值。',
'settings.projects.page.field.accentColor': '强调色', 'settings.projects.page.field.accentColor': '强调色',
'settings.projects.page.field.projectIcon': '项目图标', 'settings.projects.page.field.projectIcon': '项目图标',
'settings.projects.page.field.projectIconBackgroundAria': '项目图标背景颜色', 'settings.projects.page.field.projectIconBackgroundAria': '项目图标背景颜色',
@@ -1001,6 +1003,7 @@ export const settingsDict = {
'settings.projects.page.toast.discoverIconFailed': '发现项目图标失败', 'settings.projects.page.toast.discoverIconFailed': '发现项目图标失败',
'settings.projects.page.toast.customIconAlreadySet': '该项目已设置自定义图标', 'settings.projects.page.toast.customIconAlreadySet': '该项目已设置自定义图标',
'settings.projects.page.toast.iconDiscovered': '项目图标已发现', 'settings.projects.page.toast.iconDiscovered': '项目图标已发现',
'settings.projects.page.toast.saveFailed': '保存项目设置失败',
'settings.usage.sidebar.title': '用量', 'settings.usage.sidebar.title': '用量',
'settings.usage.sidebar.total': '总计 {count}', 'settings.usage.sidebar.total': '总计 {count}',
'settings.usage.sidebar.actions.toggleAutoRefreshAria': '切换自动刷新', 'settings.usage.sidebar.actions.toggleAutoRefreshAria': '切换自动刷新',
@@ -1138,6 +1141,7 @@ export const settingsDict = {
'settings.openchamber.worktrees.setup.addCommand': '添加命令', 'settings.openchamber.worktrees.setup.addCommand': '添加命令',
'settings.openchamber.worktrees.setup.waitForCommands': '创建或发送会话前等待初始化命令完成', 'settings.openchamber.worktrees.setup.waitForCommands': '创建或发送会话前等待初始化命令完成',
'settings.openchamber.worktrees.setup.waitForCommandsAria': '创建或发送会话前等待 Worktree 初始化命令完成', 'settings.openchamber.worktrees.setup.waitForCommandsAria': '创建或发送会话前等待 Worktree 初始化命令完成',
'settings.openchamber.worktrees.setup.toast.saveFailed': '保存 Worktree 初始化命令失败',
'settings.openchamber.worktrees.list.title': '现有工作树', 'settings.openchamber.worktrees.list.title': '现有工作树',
'settings.openchamber.worktrees.list.tooltip': '工作树位于仓库外部(由 OpenCode 管理)。删除工作树也会删除关联会话。', 'settings.openchamber.worktrees.list.tooltip': '工作树位于仓库外部(由 OpenCode 管理)。删除工作树也会删除关联会话。',
'settings.openchamber.worktrees.list.loading': '正在加载工作树...', 'settings.openchamber.worktrees.list.loading': '正在加载工作树...',
@@ -430,6 +430,7 @@ export const dict: Record<I18nKey, string> = {
'sessions.sidebar.project.actions.projectMenu': '项目菜单', 'sessions.sidebar.project.actions.projectMenu': '项目菜单',
'sessions.sidebar.project.actions.newSession': '新建会话', 'sessions.sidebar.project.actions.newSession': '新建会话',
'sessions.sidebar.project.actions.closeProject': '关闭项目', 'sessions.sidebar.project.actions.closeProject': '关闭项目',
'sessions.sidebar.project.actions.edit': '编辑',
'sessions.sidebar.project.actions.newDraftSession': '新建草稿会话', 'sessions.sidebar.project.actions.newDraftSession': '新建草稿会话',
'sessions.sidebar.session.menu.rename': '重命名', 'sessions.sidebar.session.menu.rename': '重命名',
'sessions.sidebar.session.rename.save': '保存会话名称', 'sessions.sidebar.session.rename.save': '保存会话名称',
@@ -897,6 +897,8 @@
'settings.projects.page.section.worktree': 'Worktree', 'settings.projects.page.section.worktree': 'Worktree',
'settings.projects.page.field.projectName': '專案名稱', 'settings.projects.page.field.projectName': '專案名稱',
'settings.projects.page.field.projectNamePlaceholder': '專案名稱', 'settings.projects.page.field.projectNamePlaceholder': '專案名稱',
'settings.projects.page.field.defaultModel': '新聊天的預設模型',
'settings.projects.page.field.defaultModelDescription': '在此專案中開始新聊天時使用。若未設定,則回退至全域預設值。',
'settings.projects.page.field.accentColor': '強調色', 'settings.projects.page.field.accentColor': '強調色',
'settings.projects.page.field.projectIcon': '專案圖示', 'settings.projects.page.field.projectIcon': '專案圖示',
'settings.projects.page.field.projectIconBackgroundAria': '專案圖示背景顏色', 'settings.projects.page.field.projectIconBackgroundAria': '專案圖示背景顏色',
@@ -918,6 +920,7 @@
'settings.projects.page.toast.discoverIconFailed': '發現專案圖示失敗', 'settings.projects.page.toast.discoverIconFailed': '發現專案圖示失敗',
'settings.projects.page.toast.customIconAlreadySet': '該專案已設定自訂圖示', 'settings.projects.page.toast.customIconAlreadySet': '該專案已設定自訂圖示',
'settings.projects.page.toast.iconDiscovered': '專案圖示已發現', 'settings.projects.page.toast.iconDiscovered': '專案圖示已發現',
'settings.projects.page.toast.saveFailed': '儲存專案設定失敗',
'settings.usage.sidebar.title': '用量', 'settings.usage.sidebar.title': '用量',
'settings.usage.sidebar.total': '總計 {count}', 'settings.usage.sidebar.total': '總計 {count}',
'settings.usage.sidebar.actions.toggleAutoRefreshAria': '切換自動重新整理', 'settings.usage.sidebar.actions.toggleAutoRefreshAria': '切換自動重新整理',
@@ -1054,6 +1057,7 @@
'settings.openchamber.worktrees.setup.addCommand': '新增命令', 'settings.openchamber.worktrees.setup.addCommand': '新增命令',
'settings.openchamber.worktrees.setup.waitForCommands': '建立或傳送工作階段前等待設定命令完成', 'settings.openchamber.worktrees.setup.waitForCommands': '建立或傳送工作階段前等待設定命令完成',
'settings.openchamber.worktrees.setup.waitForCommandsAria': '建立或傳送工作階段前等待 Worktree 設定命令完成', 'settings.openchamber.worktrees.setup.waitForCommandsAria': '建立或傳送工作階段前等待 Worktree 設定命令完成',
'settings.openchamber.worktrees.setup.toast.saveFailed': '儲存 Worktree 設定命令失敗',
'settings.openchamber.worktrees.list.title': '現有 worktree', 'settings.openchamber.worktrees.list.title': '現有 worktree',
'settings.openchamber.worktrees.list.tooltip': 'Worktree 位於儲存庫外部(由 OpenCode 管理)。刪除 worktree 也會刪除關聯工作階段。', 'settings.openchamber.worktrees.list.tooltip': 'Worktree 位於儲存庫外部(由 OpenCode 管理)。刪除 worktree 也會刪除關聯工作階段。',
'settings.openchamber.worktrees.list.loading': '正在載入 worktree...', 'settings.openchamber.worktrees.list.loading': '正在載入 worktree...',
@@ -443,6 +443,7 @@ export const dict: Record<I18nKey, string> = {
'sessions.sidebar.project.actions.projectMenu': '專案選單', 'sessions.sidebar.project.actions.projectMenu': '專案選單',
'sessions.sidebar.project.actions.newSession': '新增會話', 'sessions.sidebar.project.actions.newSession': '新增會話',
'sessions.sidebar.project.actions.closeProject': '關閉專案', 'sessions.sidebar.project.actions.closeProject': '關閉專案',
'sessions.sidebar.project.actions.edit': '編輯',
'sessions.sidebar.project.actions.newDraftSession': '新增草稿會話', 'sessions.sidebar.project.actions.newDraftSession': '新增草稿會話',
'sessions.sidebar.session.menu.rename': '重新命名', 'sessions.sidebar.session.menu.rename': '重新命名',
'sessions.sidebar.session.rename.save': '儲存會話名稱', 'sessions.sidebar.session.rename.save': '儲存會話名稱',
+12 -7
View File
@@ -281,7 +281,7 @@ type DefaultAgentModelSelection = {
// fresh draft (applyDefaultModelAgentSelection), so the two paths stay identical. // fresh draft (applyDefaultModelAgentSelection), so the two paths stay identical.
// //
// Agent: settings.defaultAgent → opencode default_agent → build → first primary → first // Agent: settings.defaultAgent → opencode default_agent → build → first primary → first
// Model: settings.defaultModel → resolved agent's pinned model+variant → opencode config.model // Model: project.defaultModel → settings.defaultModel → resolved agent's pinned model+variant → opencode config.model
// → opencode/big-pickle → first // → opencode/big-pickle → first
// //
// The opencode default_agent / default model (config fields on the OpenCode server) are honored // The opencode default_agent / default model (config fields on the OpenCode server) are honored
@@ -292,6 +292,7 @@ type DefaultAgentModelSelection = {
const resolveDefaultAgentModelSelection = ({ const resolveDefaultAgentModelSelection = ({
agents, agents,
providers, providers,
projectDefaultModel,
settingsDefaultAgent, settingsDefaultAgent,
settingsDefaultModel, settingsDefaultModel,
settingsDefaultVariant, settingsDefaultVariant,
@@ -300,6 +301,7 @@ const resolveDefaultAgentModelSelection = ({
}: { }: {
agents: Agent[]; agents: Agent[];
providers: ProviderWithModelList[]; providers: ProviderWithModelList[];
projectDefaultModel?: string;
settingsDefaultAgent?: string; settingsDefaultAgent?: string;
settingsDefaultModel?: string; settingsDefaultModel?: string;
settingsDefaultVariant?: string; settingsDefaultVariant?: string;
@@ -348,12 +350,14 @@ const resolveDefaultAgentModelSelection = ({
let modelId: string | undefined; let modelId: string | undefined;
let variant: string | undefined; let variant: string | undefined;
if (settingsDefaultModel) { const effectiveDefaultModel = projectDefaultModel || settingsDefaultModel;
const parsed = parseModelString(settingsDefaultModel);
if (effectiveDefaultModel) {
const parsed = parseModelString(effectiveDefaultModel);
if (parsed && hasProviderModel(providers, parsed.providerId, parsed.modelId)) { if (parsed && hasProviderModel(providers, parsed.providerId, parsed.modelId)) {
providerId = parsed.providerId; providerId = parsed.providerId;
modelId = parsed.modelId; modelId = parsed.modelId;
variant = resolveVariant(providerId, modelId, settingsDefaultVariant); variant = resolveVariant(providerId, modelId, projectDefaultModel ? undefined : settingsDefaultVariant);
} }
} }
@@ -1048,7 +1052,7 @@ interface ConfigStore {
cycleCurrentVariant: () => void; cycleCurrentVariant: () => void;
getCurrentModelVariants: () => string[]; getCurrentModelVariants: () => string[];
setAgent: (agentName: string | undefined) => void; setAgent: (agentName: string | undefined) => void;
applyDefaultModelAgentSelection: () => void; applyDefaultModelAgentSelection: (options?: { projectDefaultModel?: string }) => void;
applyOpenCodeConfigDefaults: (directory?: string | null, source?: string, config?: Config) => void; applyOpenCodeConfigDefaults: (directory?: string | null, source?: string, config?: Config) => void;
setSelectedProvider: (providerId: string) => void; setSelectedProvider: (providerId: string) => void;
setSettingsDefaultModel: (model: string | undefined) => void; setSettingsDefaultModel: (model: string | undefined) => void;
@@ -2497,10 +2501,10 @@ export const useConfigStore = create<ConfigStore>()(
// Re-applies the same priority cascade used at app startup (see loadAgents): // Re-applies the same priority cascade used at app startup (see loadAgents):
// agent: settings.defaultAgent → build → first primary → first agent // agent: settings.defaultAgent → build → first primary → first agent
// model: settings.defaultModel → agent's preferred model → opencode/big-pickle → first // model: project.defaultModel → settings.defaultModel → agent's preferred model → opencode/big-pickle → first
// Used when entering a fresh draft session so model/agent reset to defaults // Used when entering a fresh draft session so model/agent reset to defaults
// instead of sticking to the previously open session's selection. // instead of sticking to the previously open session's selection.
applyDefaultModelAgentSelection: () => { applyDefaultModelAgentSelection: (options) => {
const { const {
agents, agents,
providers, providers,
@@ -2523,6 +2527,7 @@ export const useConfigStore = create<ConfigStore>()(
} = resolveDefaultAgentModelSelection({ } = resolveDefaultAgentModelSelection({
agents, agents,
providers, providers,
projectDefaultModel: options?.projectDefaultModel,
settingsDefaultAgent, settingsDefaultAgent,
settingsDefaultModel, settingsDefaultModel,
settingsDefaultVariant, settingsDefaultVariant,
+42 -2
View File
@@ -52,7 +52,13 @@ interface ProjectsStore {
setActiveProject: (id: string) => void; setActiveProject: (id: string) => void;
setActiveProjectIdOnly: (id: string) => void; setActiveProjectIdOnly: (id: string) => void;
renameProject: (id: string, label: string) => void; renameProject: (id: string, label: string) => void;
updateProjectMeta: (id: string, meta: { label?: string; icon?: string | null; color?: string | null; iconBackground?: string | null }) => void; updateProjectMeta: (id: string, meta: {
label?: string;
icon?: string | null;
color?: string | null;
iconBackground?: string | null;
defaultModel?: string | null;
}) => void;
uploadProjectIcon: (id: string, file: File) => Promise<{ ok: boolean; error?: string }>; uploadProjectIcon: (id: string, file: File) => Promise<{ ok: boolean; error?: string }>;
removeProjectIcon: (id: string) => Promise<{ ok: boolean; error?: string }>; removeProjectIcon: (id: string) => Promise<{ ok: boolean; error?: string }>;
discoverProjectIcon: (id: string, options?: { force?: boolean }) => Promise<{ ok: boolean; skipped?: boolean; reason?: string; error?: string }>; discoverProjectIcon: (id: string, options?: { force?: boolean }) => Promise<{ ok: boolean; skipped?: boolean; reason?: string; error?: string }>;
@@ -116,6 +122,21 @@ const resolveTildePath = (value: string, homeDir?: string | null): string => {
const HEX_COLOR_PATTERN = /^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/; const HEX_COLOR_PATTERN = /^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/;
const normalizeDefaultModel = (value: unknown): string | undefined => {
if (typeof value !== 'string') {
return undefined;
}
const trimmed = value.trim();
if (!trimmed) {
return undefined;
}
const separatorIndex = trimmed.indexOf('/');
if (separatorIndex <= 0 || separatorIndex >= trimmed.length - 1) {
return undefined;
}
return trimmed;
};
const normalizeIconBackground = (value: unknown): string | null => { const normalizeIconBackground = (value: unknown): string | null => {
if (typeof value !== 'string') { if (typeof value !== 'string') {
return null; return null;
@@ -254,6 +275,10 @@ const sanitizeProjects = (value: unknown): ProjectEntry[] => {
if (typeof candidate.color === 'string' && candidate.color.trim().length > 0) { if (typeof candidate.color === 'string' && candidate.color.trim().length > 0) {
project.color = candidate.color.trim(); project.color = candidate.color.trim();
} }
const defaultModel = normalizeDefaultModel(candidate.defaultModel);
if (defaultModel) {
project.defaultModel = defaultModel;
}
if (candidate.iconBackground === null) { if (candidate.iconBackground === null) {
project.iconBackground = null; project.iconBackground = null;
} else { } else {
@@ -470,6 +495,7 @@ const vscodeWorkspaceProjectsEqual = (left: ProjectEntry[], right: ProjectEntry[
&& leftProject.icon === rightProject.icon && leftProject.icon === rightProject.icon
&& leftProject.color === rightProject.color && leftProject.color === rightProject.color
&& leftProject.iconBackground === rightProject.iconBackground && leftProject.iconBackground === rightProject.iconBackground
&& leftProject.defaultModel === rightProject.defaultModel
&& leftProject.addedAt === rightProject.addedAt && leftProject.addedAt === rightProject.addedAt
&& leftProject.lastOpenedAt === rightProject.lastOpenedAt && leftProject.lastOpenedAt === rightProject.lastOpenedAt
&& leftProject.sidebarCollapsed === rightProject.sidebarCollapsed && leftProject.sidebarCollapsed === rightProject.sidebarCollapsed
@@ -666,7 +692,13 @@ export const useProjectsStore = create<ProjectsStore>()(
persistProjects(nextProjects, activeProjectId); persistProjects(nextProjects, activeProjectId);
}, },
updateProjectMeta: (id: string, meta: { label?: string; icon?: string | null; color?: string | null; iconBackground?: string | null }) => { updateProjectMeta: (id: string, meta: {
label?: string;
icon?: string | null;
color?: string | null;
iconBackground?: string | null;
defaultModel?: string | null;
}) => {
if (isVSCodeProjectsRuntime) { if (isVSCodeProjectsRuntime) {
return; return;
} }
@@ -683,6 +715,14 @@ export const useProjectsStore = create<ProjectsStore>()(
if (meta.iconBackground !== undefined) { if (meta.iconBackground !== undefined) {
updated.iconBackground = normalizeIconBackground(meta.iconBackground); updated.iconBackground = normalizeIconBackground(meta.iconBackground);
} }
if (meta.defaultModel !== undefined) {
const normalized = normalizeDefaultModel(meta.defaultModel);
if (normalized) {
updated.defaultModel = normalized;
} else {
delete updated.defaultModel;
}
}
return updated; return updated;
}); });
set({ projects: nextProjects }); set({ projects: nextProjects });
+3 -1
View File
@@ -769,7 +769,9 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
// (a fresh draft must start from defaults, not inherit the previous session's selection). // (a fresh draft must start from defaults, not inherit the previous session's selection).
const configDirectory = normalizePath(selectedProject?.path ?? null) ?? directory const configDirectory = normalizePath(selectedProject?.path ?? null) ?? directory
void activateConfigForDirectory(configDirectory).then(() => { void activateConfigForDirectory(configDirectory).then(() => {
useConfigStore.getState().applyDefaultModelAgentSelection() useConfigStore.getState().applyDefaultModelAgentSelection({
projectDefaultModel: selectedProject?.defaultModel,
})
}) })
if (directory && directory !== useDirectoryStore.getState().currentDirectory) { if (directory && directory !== useDirectoryStore.getState().currentDirectory) {
@@ -139,6 +139,7 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
: null; : null;
const iconBackground = normalizeIconBackground(candidate.iconBackground); const iconBackground = normalizeIconBackground(candidate.iconBackground);
const color = typeof candidate.color === 'string' ? candidate.color.trim() : ''; const color = typeof candidate.color === 'string' ? candidate.color.trim() : '';
const defaultModel = typeof candidate.defaultModel === 'string' ? candidate.defaultModel.trim() : '';
const addedAt = Number.isFinite(candidate.addedAt) ? Number(candidate.addedAt) : null; const addedAt = Number.isFinite(candidate.addedAt) ? Number(candidate.addedAt) : null;
const lastOpenedAt = Number.isFinite(candidate.lastOpenedAt) const lastOpenedAt = Number.isFinite(candidate.lastOpenedAt)
? Number(candidate.lastOpenedAt) ? Number(candidate.lastOpenedAt)
@@ -158,6 +159,7 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
...(icon ? { icon } : {}), ...(icon ? { icon } : {}),
...(iconBackground ? { iconBackground } : {}), ...(iconBackground ? { iconBackground } : {}),
...(color ? { color } : {}), ...(color ? { color } : {}),
...(defaultModel && defaultModel.includes('/') ? { defaultModel } : {}),
...(Number.isFinite(addedAt) && addedAt >= 0 ? { addedAt } : {}), ...(Number.isFinite(addedAt) && addedAt >= 0 ? { addedAt } : {}),
...(Number.isFinite(lastOpenedAt) && lastOpenedAt >= 0 ? { lastOpenedAt } : {}), ...(Number.isFinite(lastOpenedAt) && lastOpenedAt >= 0 ? { lastOpenedAt } : {}),
}; };