Skip to content

Commit 112ba9c

Browse files
committed
🤖 feat: show pending workspace states in sidebar
- Add status?: 'creating' field to WorkspaceMetadata for pending workspaces - Backend emits pending metadata immediately before slow AI title generation - generatePlaceholderName() creates git-safe placeholder from user's message - Frontend shows shimmer on workspace name during creation - Disable selection/remove actions while workspace is being created - Clear pending state on error by emitting null metadata This provides immediate visual feedback when creating workspaces instead of the UI appearing frozen during title generation (2-5s).
1 parent 894a0d4 commit 112ba9c

File tree

5 files changed

+134
-66
lines changed

5 files changed

+134
-66
lines changed

src/browser/components/WorkspaceListItem.tsx

Lines changed: 63 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
4343
onToggleUnread,
4444
}) => {
4545
// Destructure metadata for convenience
46-
const { id: workspaceId, name: workspaceName, namedWorkspacePath } = metadata;
46+
const { id: workspaceId, name: workspaceName, namedWorkspacePath, status } = metadata;
47+
const isCreating = status === "creating";
4748
const gitStatus = useGitStatus(workspaceId);
4849

4950
// Get rename context
@@ -105,19 +106,24 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
105106
<React.Fragment>
106107
<div
107108
className={cn(
108-
"py-1.5 pl-4 pr-2 cursor-pointer border-l-[3px] border-transparent transition-all duration-150 text-[13px] relative hover:bg-hover [&:hover_button]:opacity-100 flex gap-2",
109-
isSelected && "bg-hover border-l-blue-400",
110-
isDeleting && "opacity-50 pointer-events-none"
109+
"py-1.5 pl-4 pr-2 border-l-[3px] border-transparent transition-all duration-150 text-[13px] relative flex gap-2",
110+
isCreating || isDeleting
111+
? "cursor-default opacity-70"
112+
: "cursor-pointer hover:bg-hover [&:hover_button]:opacity-100",
113+
isSelected && !isCreating && "bg-hover border-l-blue-400",
114+
isDeleting && "pointer-events-none"
111115
)}
112-
onClick={() =>
116+
onClick={() => {
117+
if (isCreating) return; // Disable click while creating
113118
onSelectWorkspace({
114119
projectPath,
115120
projectName,
116121
namedWorkspacePath,
117122
workspaceId,
118-
})
119-
}
123+
});
124+
}}
120125
onKeyDown={(e) => {
126+
if (isCreating) return; // Disable keyboard while creating
121127
if (e.key === "Enter" || e.key === " ") {
122128
e.preventDefault();
123129
onSelectWorkspace({
@@ -129,9 +135,12 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
129135
}
130136
}}
131137
role="button"
132-
tabIndex={0}
138+
tabIndex={isCreating ? -1 : 0}
133139
aria-current={isSelected ? "true" : undefined}
134-
aria-label={`Select workspace ${displayName}`}
140+
aria-label={
141+
isCreating ? `Creating workspace ${displayName}` : `Select workspace ${displayName}`
142+
}
143+
aria-disabled={isCreating}
135144
data-workspace-path={namedWorkspacePath}
136145
data-workspace-id={workspaceId}
137146
>
@@ -159,14 +168,18 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
159168
/>
160169
) : (
161170
<span
162-
className="text-foreground -mx-1 min-w-0 flex-1 cursor-pointer truncate rounded-sm px-1 text-left text-[14px] transition-colors duration-200 hover:bg-white/5"
171+
className={cn(
172+
"text-foreground -mx-1 min-w-0 flex-1 truncate rounded-sm px-1 text-left text-[14px] transition-colors duration-200",
173+
!isCreating && "cursor-pointer hover:bg-white/5"
174+
)}
163175
onDoubleClick={(e) => {
176+
if (isCreating) return; // Disable rename while creating
164177
e.stopPropagation();
165178
startRenaming();
166179
}}
167-
title="Double-click to rename"
180+
title={isCreating ? "Creating workspace..." : "Double-click to rename"}
168181
>
169-
{canInterrupt ? (
182+
{canInterrupt || isCreating ? (
170183
<Shimmer className="w-full truncate" colorClass="var(--color-foreground)">
171184
{displayName}
172185
</Shimmer>
@@ -177,40 +190,46 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
177190
)}
178191

179192
<div className="ml-auto flex items-center gap-1">
180-
<GitStatusIndicator
181-
gitStatus={gitStatus}
182-
workspaceId={workspaceId}
183-
tooltipPosition="right"
184-
/>
185-
186-
<TooltipWrapper inline>
187-
<button
188-
className="text-muted hover:text-foreground col-start-1 flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center border-none bg-transparent p-0 text-base opacity-0 transition-all duration-200 hover:rounded-sm hover:bg-white/10"
189-
onClick={(e) => {
190-
e.stopPropagation();
191-
void onRemoveWorkspace(workspaceId, e.currentTarget);
192-
}}
193-
aria-label={`Remove workspace ${displayName}`}
194-
data-workspace-id={workspaceId}
195-
>
196-
×
197-
</button>
198-
<Tooltip className="tooltip" align="right">
199-
Remove workspace
200-
</Tooltip>
201-
</TooltipWrapper>
193+
{!isCreating && (
194+
<>
195+
<GitStatusIndicator
196+
gitStatus={gitStatus}
197+
workspaceId={workspaceId}
198+
tooltipPosition="right"
199+
/>
200+
201+
<TooltipWrapper inline>
202+
<button
203+
className="text-muted hover:text-foreground col-start-1 flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center border-none bg-transparent p-0 text-base opacity-0 transition-all duration-200 hover:rounded-sm hover:bg-white/10"
204+
onClick={(e) => {
205+
e.stopPropagation();
206+
void onRemoveWorkspace(workspaceId, e.currentTarget);
207+
}}
208+
aria-label={`Remove workspace ${displayName}`}
209+
data-workspace-id={workspaceId}
210+
>
211+
×
212+
</button>
213+
<Tooltip className="tooltip" align="right">
214+
Remove workspace
215+
</Tooltip>
216+
</TooltipWrapper>
217+
</>
218+
)}
202219
</div>
203220
</div>
204-
<div className="min-w-0">
205-
{isDeleting ? (
206-
<div className="text-muted flex min-w-0 items-center gap-1.5 text-xs">
207-
<span className="-mt-0.5 shrink-0 text-[10px]">🗑️</span>
208-
<span className="min-w-0 truncate">Deleting...</span>
209-
</div>
210-
) : (
211-
<WorkspaceStatusIndicator workspaceId={workspaceId} />
212-
)}
213-
</div>
221+
{!isCreating && (
222+
<div className="min-w-0">
223+
{isDeleting ? (
224+
<div className="text-muted flex min-w-0 items-center gap-1.5 text-xs">
225+
<span className="-mt-0.5 shrink-0 text-[10px]">🗑️</span>
226+
<span className="min-w-0 truncate">Deleting...</span>
227+
</div>
228+
) : (
229+
<WorkspaceStatusIndicator workspaceId={workspaceId} />
230+
)}
231+
</div>
232+
)}
214233
</div>
215234
</div>
216235
{renameError && isEditing && (

src/common/types/workspace.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ export interface WorkspaceMetadata {
5454

5555
/** Runtime configuration for this workspace (always set, defaults to local on load) */
5656
runtimeConfig: RuntimeConfig;
57+
58+
/**
59+
* Workspace creation status. When 'creating', the workspace is being set up
60+
* (title generation, git operations). Undefined or absent means ready.
61+
* Pending workspaces are ephemeral (not persisted to config).
62+
*/
63+
status?: "creating";
5764
}
5865

5966
/**

src/node/services/agentSession.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type { AIService } from "@/node/services/aiService";
88
import type { HistoryService } from "@/node/services/historyService";
99
import type { PartialService } from "@/node/services/partialService";
1010
import type { InitStateManager } from "@/node/services/initStateManager";
11-
import type { WorkspaceMetadata } from "@/common/types/workspace";
11+
import type { FrontendWorkspaceMetadata } from "@/common/types/workspace";
1212
import { DEFAULT_RUNTIME_CONFIG } from "@/common/constants/workspace";
1313
import type {
1414
WorkspaceChatMessage,
@@ -33,7 +33,7 @@ export interface AgentSessionChatEvent {
3333

3434
export interface AgentSessionMetadataEvent {
3535
workspaceId: string;
36-
metadata: WorkspaceMetadata | null;
36+
metadata: FrontendWorkspaceMetadata | null;
3737
}
3838

3939
interface AgentSessionOptions {
@@ -135,7 +135,7 @@ export class AgentSession {
135135
await this.emitHistoricalEvents(listener);
136136
}
137137

138-
emitMetadata(metadata: WorkspaceMetadata | null): void {
138+
emitMetadata(metadata: FrontendWorkspaceMetadata | null): void {
139139
this.assertNotDisposed("emitMetadata");
140140
this.emitter.emit("metadata-event", {
141141
workspaceId: this.workspaceId,
@@ -239,11 +239,12 @@ export class AgentSession {
239239
: PlatformPaths.basename(normalizedWorkspacePath) || "unknown";
240240
}
241241

242-
const metadata: WorkspaceMetadata = {
242+
const metadata: FrontendWorkspaceMetadata = {
243243
id: this.workspaceId,
244244
name: workspaceName,
245245
projectName: derivedProjectName,
246246
projectPath: derivedProjectPath,
247+
namedWorkspacePath: normalizedWorkspacePath,
247248
runtimeConfig: DEFAULT_RUNTIME_CONFIG,
248249
};
249250

src/node/services/ipcMain.ts

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import type {
2626
import { Ok, Err, type Result } from "@/common/types/result";
2727
import { validateWorkspaceName } from "@/common/utils/validation/workspaceValidation";
2828
import type {
29-
WorkspaceMetadata,
3029
FrontendWorkspaceMetadata,
3130
WorkspaceActivitySnapshot,
3231
} from "@/common/types/workspace";
@@ -106,7 +105,7 @@ async function createWorkspaceWithCollisionRetry(
106105
throw new Error("Unexpected: workspace creation loop completed without return");
107106
}
108107

109-
import { generateWorkspaceName } from "./workspaceTitleGenerator";
108+
import { generateWorkspaceName, generatePlaceholderName } from "./workspaceTitleGenerator";
110109
/**
111110
* IpcMain - Manages all IPC handlers and service coordination
112111
*
@@ -304,15 +303,43 @@ export class IpcMain {
304303
| { success: true; workspaceId: string; metadata: FrontendWorkspaceMetadata }
305304
| Result<void, SendMessageError>
306305
> {
306+
// Generate IDs and placeholder upfront for immediate UI feedback
307+
const workspaceId = this.config.generateStableId();
308+
const placeholderName = generatePlaceholderName(message);
309+
const projectName = projectPath.split("/").pop() ?? projectPath.split("\\").pop() ?? "unknown";
310+
const createdAt = new Date().toISOString();
311+
312+
// Prepare runtime config early for pending metadata
313+
const finalRuntimeConfig: RuntimeConfig = options.runtimeConfig ?? {
314+
type: "local",
315+
srcBaseDir: this.config.srcDir,
316+
};
317+
318+
// Create session and emit pending metadata IMMEDIATELY
319+
// This allows the sidebar to show the workspace while we do slow operations
320+
const session = this.getOrCreateSession(workspaceId);
321+
session.emitMetadata({
322+
id: workspaceId,
323+
name: placeholderName,
324+
projectName,
325+
projectPath,
326+
namedWorkspacePath: "", // Not yet created
327+
createdAt,
328+
runtimeConfig: finalRuntimeConfig,
329+
status: "creating",
330+
});
331+
307332
try {
308-
// 1. Generate workspace branch name using AI (use same model as message)
333+
// 1. Generate workspace branch name using AI (SLOW - but user sees pending state)
309334
let branchName: string;
310335
{
311336
const isErrLike = (v: unknown): v is { type: string } =>
312337
typeof v === "object" && v !== null && "type" in v;
313338
const nameResult = await generateWorkspaceName(message, options.model, this.aiService);
314339
if (!nameResult.success) {
315340
const err = nameResult.error;
341+
// Clear pending state on error
342+
session.emitMetadata(null);
316343
if (isErrLike(err)) {
317344
return Err(err);
318345
}
@@ -337,14 +364,7 @@ export class IpcMain {
337364
const recommendedTrunk =
338365
options.trunkBranch ?? (await detectDefaultTrunkBranch(projectPath, branches)) ?? "main";
339366

340-
// 3. Create workspace
341-
const finalRuntimeConfig: RuntimeConfig = options.runtimeConfig ?? {
342-
type: "local",
343-
srcBaseDir: this.config.srcDir,
344-
};
345-
346-
const workspaceId = this.config.generateStableId();
347-
367+
// 3. Resolve runtime paths
348368
let runtime;
349369
let resolvedSrcBaseDir: string;
350370
try {
@@ -361,12 +381,12 @@ export class IpcMain {
361381
}
362382
} catch (error) {
363383
const errorMsg = error instanceof Error ? error.message : String(error);
384+
// Clear pending state on error
385+
session.emitMetadata(null);
364386
return Err({ type: "unknown", raw: `Failed to prepare runtime: ${errorMsg}` });
365387
}
366388

367-
const session = this.getOrCreateSession(workspaceId);
368389
this.initStateManager.startInit(workspaceId, projectPath);
369-
370390
const initLogger = this.createInitLogger(workspaceId);
371391

372392
// Create workspace with automatic collision retry
@@ -378,21 +398,20 @@ export class IpcMain {
378398
);
379399

380400
if (!createResult.success || !createResult.workspacePath) {
401+
// Clear pending state on error
402+
session.emitMetadata(null);
381403
return Err({ type: "unknown", raw: createResult.error ?? "Failed to create workspace" });
382404
}
383405

384406
// Use the final branch name (may have suffix if collision occurred)
385407
branchName = finalBranchName;
386408

387-
const projectName =
388-
projectPath.split("/").pop() ?? projectPath.split("\\").pop() ?? "unknown";
389-
390409
const metadata = {
391410
id: workspaceId,
392411
name: branchName,
393412
projectName,
394413
projectPath,
395-
createdAt: new Date().toISOString(),
414+
createdAt,
396415
};
397416

398417
await this.config.editConfig((config) => {
@@ -414,9 +433,12 @@ export class IpcMain {
414433
const allMetadata = await this.config.getAllWorkspaceMetadata();
415434
const completeMetadata = allMetadata.find((m) => m.id === workspaceId);
416435
if (!completeMetadata) {
436+
// Clear pending state on error
437+
session.emitMetadata(null);
417438
return Err({ type: "unknown", raw: "Failed to retrieve workspace metadata" });
418439
}
419440

441+
// Emit final metadata (no status = ready)
420442
session.emitMetadata(completeMetadata);
421443

422444
void runtime
@@ -445,6 +467,8 @@ export class IpcMain {
445467
} catch (error) {
446468
const errorMessage = error instanceof Error ? error.message : String(error);
447469
log.error("Unexpected error in createWorkspaceForFirstMessage:", error);
470+
// Clear pending state on error
471+
session.emitMetadata(null);
448472
return Err({ type: "unknown", raw: `Failed to create workspace: ${errorMessage}` });
449473
}
450474
}
@@ -1000,11 +1024,12 @@ export class IpcMain {
10001024
}
10011025

10021026
// Initialize workspace metadata
1003-
const metadata: WorkspaceMetadata = {
1027+
const metadata: FrontendWorkspaceMetadata = {
10041028
id: newWorkspaceId,
10051029
name: newName,
10061030
projectName,
10071031
projectPath: foundProjectPath,
1032+
namedWorkspacePath: runtime.getWorkspacePath(foundProjectPath, newName),
10081033
createdAt: new Date().toISOString(),
10091034
runtimeConfig: DEFAULT_RUNTIME_CONFIG,
10101035
};

src/node/services/workspaceTitleGenerator.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,19 @@ function validateBranchName(name: string): string {
5757
.replace(/-+/g, "-")
5858
.substring(0, 50);
5959
}
60+
61+
/**
62+
* Generate a placeholder name from the user's message for immediate display
63+
* while the AI generates the real title. This is git-safe and human-readable.
64+
*/
65+
export function generatePlaceholderName(message: string): string {
66+
// Take first ~40 chars, sanitize for git branch name
67+
const truncated = message.slice(0, 40).trim();
68+
const sanitized = truncated
69+
.toLowerCase()
70+
.replace(/[^a-z0-9]+/g, "-")
71+
.replace(/^-+|-+$/g, "")
72+
.replace(/-+/g, "-")
73+
.substring(0, 30);
74+
return sanitized || "new-workspace";
75+
}

0 commit comments

Comments
 (0)