Skip to content

Commit 2881d5e

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 284dbc7 commit 2881d5e

File tree

5 files changed

+126
-58
lines changed

5 files changed

+126
-58
lines changed

src/browser/components/WorkspaceListItem.tsx

Lines changed: 55 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
4141
onToggleUnread,
4242
}) => {
4343
// Destructure metadata for convenience
44-
const { id: workspaceId, name: workspaceName, namedWorkspacePath } = metadata;
44+
const { id: workspaceId, name: workspaceName, namedWorkspacePath, status } = metadata;
45+
const isCreating = status === "creating";
4546
const gitStatus = useGitStatus(workspaceId);
4647

4748
// Get rename context
@@ -103,18 +104,23 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
103104
<React.Fragment>
104105
<div
105106
className={cn(
106-
"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",
107-
isSelected && "bg-hover border-l-blue-400"
107+
"py-1.5 pl-4 pr-2 border-l-[3px] border-transparent transition-all duration-150 text-[13px] relative flex gap-2",
108+
isCreating
109+
? "cursor-default opacity-70"
110+
: "cursor-pointer hover:bg-hover [&:hover_button]:opacity-100",
111+
isSelected && !isCreating && "bg-hover border-l-blue-400"
108112
)}
109-
onClick={() =>
113+
onClick={() => {
114+
if (isCreating) return; // Disable click while creating
110115
onSelectWorkspace({
111116
projectPath,
112117
projectName,
113118
namedWorkspacePath,
114119
workspaceId,
115-
})
116-
}
120+
});
121+
}}
117122
onKeyDown={(e) => {
123+
if (isCreating) return; // Disable keyboard while creating
118124
if (e.key === "Enter" || e.key === " ") {
119125
e.preventDefault();
120126
onSelectWorkspace({
@@ -126,9 +132,12 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
126132
}
127133
}}
128134
role="button"
129-
tabIndex={0}
135+
tabIndex={isCreating ? -1 : 0}
130136
aria-current={isSelected ? "true" : undefined}
131-
aria-label={`Select workspace ${displayName}`}
137+
aria-label={
138+
isCreating ? `Creating workspace ${displayName}` : `Select workspace ${displayName}`
139+
}
140+
aria-disabled={isCreating}
132141
data-workspace-path={namedWorkspacePath}
133142
data-workspace-id={workspaceId}
134143
>
@@ -156,14 +165,18 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
156165
/>
157166
) : (
158167
<span
159-
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"
168+
className={cn(
169+
"text-foreground -mx-1 min-w-0 flex-1 truncate rounded-sm px-1 text-left text-[14px] transition-colors duration-200",
170+
!isCreating && "cursor-pointer hover:bg-white/5"
171+
)}
160172
onDoubleClick={(e) => {
173+
if (isCreating) return; // Disable rename while creating
161174
e.stopPropagation();
162175
startRenaming();
163176
}}
164-
title="Double-click to rename"
177+
title={isCreating ? "Creating workspace..." : "Double-click to rename"}
165178
>
166-
{canInterrupt ? (
179+
{canInterrupt || isCreating ? (
167180
<Shimmer className="w-full truncate" colorClass="var(--color-foreground)">
168181
{displayName}
169182
</Shimmer>
@@ -174,33 +187,39 @@ const WorkspaceListItemInner: React.FC<WorkspaceListItemProps> = ({
174187
)}
175188

176189
<div className="ml-auto flex items-center gap-1">
177-
<GitStatusIndicator
178-
gitStatus={gitStatus}
179-
workspaceId={workspaceId}
180-
tooltipPosition="right"
181-
/>
182-
183-
<TooltipWrapper inline>
184-
<button
185-
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"
186-
onClick={(e) => {
187-
e.stopPropagation();
188-
void onRemoveWorkspace(workspaceId, e.currentTarget);
189-
}}
190-
aria-label={`Remove workspace ${displayName}`}
191-
data-workspace-id={workspaceId}
192-
>
193-
×
194-
</button>
195-
<Tooltip className="tooltip" align="right">
196-
Remove workspace
197-
</Tooltip>
198-
</TooltipWrapper>
190+
{!isCreating && (
191+
<>
192+
<GitStatusIndicator
193+
gitStatus={gitStatus}
194+
workspaceId={workspaceId}
195+
tooltipPosition="right"
196+
/>
197+
198+
<TooltipWrapper inline>
199+
<button
200+
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"
201+
onClick={(e) => {
202+
e.stopPropagation();
203+
void onRemoveWorkspace(workspaceId, e.currentTarget);
204+
}}
205+
aria-label={`Remove workspace ${displayName}`}
206+
data-workspace-id={workspaceId}
207+
>
208+
×
209+
</button>
210+
<Tooltip className="tooltip" align="right">
211+
Remove workspace
212+
</Tooltip>
213+
</TooltipWrapper>
214+
</>
215+
)}
199216
</div>
200217
</div>
201-
<div className="min-w-0">
202-
<WorkspaceStatusIndicator workspaceId={workspaceId} />
203-
</div>
218+
{!isCreating && (
219+
<div className="min-w-0">
220+
<WorkspaceStatusIndicator workspaceId={workspaceId} />
221+
</div>
222+
)}
204223
</div>
205224
</div>
206225
{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)